@aranova/tracking-next 0.24.1 → 0.26.0

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../tracking-core/src/phone.ts","../../tracking-core/src/user-data.ts","../../tracking-core/src/consent.ts","../../tracking-core/src/capabilities.ts","../../tracking-core/src/tracking.ts","../../tracking-core/src/gtag.ts","../../tracking-core/src/fbq.ts","../../tracking-core/src/landing.ts","../../tracking-core/src/payloads.ts","../../tracking-core/src/resources/conversion-firing.ts","../../tracking-core/src/resources/conversion-config.ts","../../tracking-core/src/resources/automatic-transaction.ts","../../tracking-core/src/resources/automatic-trigger.ts","../../tracking-core/src/resources/intl/date.ts","../../tracking-core/src/resources/sales/money.ts","../../tracking-core/src/resources/tracking-config-runtime.ts","../../tracking-core/src/resources/conversion-autofire.ts","../../tracking-core/src/session.ts","../../tracking-core/src/events/page-view.ts","../../tracking-core/src/page-view.ts","../../tracking-core/src/heartbeat.ts","../../tracking-core/src/ingest.ts","../../tracking-core/src/events/cta-click.ts","../../tracking-core/src/events/sdk-heartbeat.ts","../../tracking-core/src/events/form-start.ts","../../tracking-core/src/events/form-submit.ts","../../tracking-core/src/events/multi-page-session.ts","../../tracking-core/src/events/page-exit.ts","../../tracking-core/src/events/phone-click.ts","../../tracking-core/src/events/scroll-depth.ts","../../tracking-core/src/events/specific-page-visit.ts","../../tracking-core/src/events/time-on-site.ts","../../tracking-core/src/events/semantics.ts","../../tracking-core/src/events/registry.ts","../../tracking-core/src/ingest-typed.ts","../../tracking-core/src/triggers/time-on-site.ts","../../tracking-core/src/triggers/navigation.ts","../../tracking-core/src/triggers/scroll-measurement.ts","../../tracking-core/src/triggers/scroll-depth.ts","../../tracking-core/src/triggers/form-start.ts","../../tracking-core/src/triggers/page-exit.ts","../../tracking-core/src/triggers/cta-click-capture.ts","../../tracking-core/src/triggers/phone-click-capture.ts","../../tracking-core/src/resources/http/errors.ts","../../tracking-core/src/resources/http/request.ts","../../tracking-core/src/resources/sales/transport.ts","../../tracking-core/src/resources/sales/client.ts","../../tracking-core/src/resources/sales/schema.ts","../../tracking-core/src/resources/services.ts","../../tracking-core/src/phone-field.ts","../src/ConsentBanner.tsx","../src/hooks.ts","../src/AdPlatformTracking.tsx","../src/GoogleAdsTracking.tsx","../src/factory.tsx","../package.json","../../tracking-core/src/phone-react.tsx","../../tracking-core/src/resources/calendar/transport.ts","../../tracking-core/src/resources/calendar/time.ts","../../tracking-core/src/resources/calendar/read-client.ts","../../tracking-core/src/resources/calendar/schema.ts","../../tracking-core/src/resources/calendar/slots.ts","../../tracking-core/src/calendar-react.tsx"],"sourcesContent":["// Framework-agnostic phone-number utilities — isomorphic (browser + Node/RSC),\n// zero React. Bundled `libphonenumber-js` (standard metadata) so clients add no\n// dependency. The transmitted value is ALWAYS E.164; display is the only knob.\n\nimport { AsYouType, parsePhoneNumberFromString, type CountryCode } from \"libphonenumber-js\";\n\nexport type { CountryCode };\n\n/**\n * How a phone number is shown in the UI. The transmitted value is always E.164\n * and is deliberately NOT part of this — only the display format is configurable.\n * A function form covers the long tail (`(parsed) => string`).\n */\nexport type PhoneDisplayFormat =\n | \"national\"\n | \"international\"\n | \"e164\"\n | ((parsed: ParsedPhone) => string);\n\nexport interface ParsedPhone {\n /** E.164 (`\"+14165550199\"`) or `null` when the input isn't a valid number. This is what gets transmitted. */\n e164: string | null;\n /** National display form (`\"(416) 555-0199\"`); empty string when unparseable. */\n national: string;\n /** International display form (`\"+1 416 555 0199\"`); empty string when unparseable. */\n international: string;\n /** ISO-3166 country resolved by libphonenumber, or `null`. */\n country: CountryCode | null;\n isValid: boolean;\n}\n\n/** Region assumed for numbers typed without a country code. */\nexport const DEFAULT_PHONE_COUNTRY: CountryCode = \"CA\";\n\n/** Parse a raw/display string into every representation at once (one parse → display + wire never drift). */\nexport function parsePhone(raw: string, country?: CountryCode): ParsedPhone {\n const region = country ?? DEFAULT_PHONE_COUNTRY;\n const parsed = parsePhoneNumberFromString(raw ?? \"\", region);\n if (!parsed) {\n return { e164: null, national: \"\", international: \"\", country: region, isValid: false };\n }\n const isValid = parsed.isValid();\n return {\n // E.164 is only surfaced for a *valid* number — a possible-but-invalid input\n // (e.g. too few digits) still parses but must not be transmitted.\n e164: isValid ? parsed.number : null,\n national: parsed.formatNational(),\n international: parsed.formatInternational(),\n country: parsed.country ?? region,\n isValid,\n };\n}\n\n/** Normalize any raw/display value to E.164, or `null` if it isn't a valid number. */\nexport function toE164(raw: string, country?: CountryCode): string | null {\n return parsePhone(raw, country).e164;\n}\n\n/** Format a value for display. Defaults to `'national'`. Never affects the wire value. */\nexport function formatPhone(\n value: string,\n format: PhoneDisplayFormat = \"national\",\n country?: CountryCode,\n): string {\n const parsed = parsePhone(value, country);\n if (typeof format === \"function\") return format(parsed);\n switch (format) {\n case \"international\":\n return parsed.international || value;\n case \"e164\":\n return parsed.e164 ?? value;\n case \"national\":\n default:\n return parsed.national || value;\n }\n}\n\n/** Live, incremental formatting for an `<input>` as the user types (`AsYouType`). */\nexport function formatPhoneAsTyped(raw: string, country?: CountryCode): string {\n return new AsYouType(country ?? DEFAULT_PHONE_COUNTRY).input(raw ?? \"\");\n}\n","// Enhanced-conversions user_data bridge (Google Ads \"user-provided data\").\n//\n// Why this exists: Google's automatic user-provided-data capture demonstrably\n// misses phone fields on client sites (verified live: a filled tel input never\n// produced a `pn` hit parameter), and our offline sale uploads are phone-hash\n// keyed — without a phone↔click pairing built at conversion time, none of them\n// can match. This module makes the SDK the deterministic capture path: it\n// extracts the visitor's own email/phone from `form_submit` fields (or an\n// explicit override / a recorded sale's customer fields), normalizes them\n// (E.164 phone, lowercased email), and sets them as PLAINTEXT\n// `gtag('set','user_data', …)` immediately before a conversion fires. gtag.js\n// normalizes further and SHA-256 hashes IN THE BROWSER — plaintext never\n// leaves the page, and we never own Google's hashing contract.\n//\n// Privacy posture: the stash is module-level memory only — never persisted to\n// any storage, never added to our own ingest payloads (the form fields were\n// already part of the site's `form_submit` metadata; we only read them).\n// Consent gating happens at the egress in `fireConversionWithConsent` (the\n// same gate every conversion already passes through); an explicit consent\n// denial additionally clears the stash and nulls gtag's page state (see\n// consent.ts). This module must NOT import consent.ts — consent.ts imports us\n// for that clearing hook, and the reverse edge would be a cycle.\n\nimport { toE164, type CountryCode } from \"./phone\";\n\n/** Raw identifiers a caller may hand us (normalized before use). */\nexport interface ConversionUserData {\n email?: string | null;\n phone?: string | null;\n}\n\n/** Normalized identifiers as gtag's `user_data` expects them. */\nexport interface NormalizedUserData {\n email: string | null;\n /** E.164 (`\"+16477836797\"`) — the format Google's parser reliably accepts. */\n phoneNumber: string | null;\n}\n\nconst EMAIL_SHAPE = /^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/;\nconst EMAIL_NAME_HINT = /e[-_]?mail/i;\n// `\\b` won't do: underscores are word chars, so `customer_phone` would miss.\n// The leading guard keeps bare \"tel\" from matching e.g. \"hotel\".\nconst PHONE_NAME_HINT = /(^|[^a-z])(phone|tel|mobile|cell)/i;\n\n// Page-lifetime, memory-only. Freshest non-null value wins per identifier.\nlet stash: NormalizedUserData = { email: null, phoneNumber: null };\n\n/**\n * Trim + lowercase + shape-check. Deliberately NO gmail dot/plus\n * canonicalization — gtag.js applies Google's own normalization before\n * hashing, and owning that contract here would be drift waiting to happen.\n */\nexport function normalizeEmail(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const cleaned = raw.trim().toLowerCase();\n return EMAIL_SHAPE.test(cleaned) ? cleaned : null;\n}\n\ninterface FieldLike {\n name?: unknown;\n type?: unknown;\n label?: unknown;\n value?: unknown;\n}\n\nfunction fieldText(field: FieldLike, key: \"name\" | \"type\" | \"label\"): string {\n const value = field[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/**\n * Deterministic extraction from `form_submit` `fields[]`: for each identifier,\n * a typed field (`type=\"email\"` / `type=\"tel\"`) wins over a name/label match\n * (`user_email`, `customer_phone`, …), in document order. A field whose value\n * fails normalization does NOT consume the slot — scanning continues, so one\n * malformed phone field can't mask a later valid one. Never throws.\n */\nexport function extractUserDataFromFormFields(\n fields: unknown,\n country?: CountryCode,\n): NormalizedUserData {\n const result: NormalizedUserData = { email: null, phoneNumber: null };\n if (!Array.isArray(fields)) return result;\n const passes: Array<(field: FieldLike, hint: RegExp, type: string) => boolean> = [\n (field, _hint, type) => fieldText(field, \"type\").toLowerCase() === type,\n (field, hint) => hint.test(fieldText(field, \"name\")) || hint.test(fieldText(field, \"label\")),\n ];\n for (const matches of passes) {\n for (const raw of fields) {\n if (raw === null || typeof raw !== \"object\") continue;\n const field = raw as FieldLike;\n if (typeof field.value !== \"string\" || field.value.length === 0) continue;\n if (result.email === null && matches(field, EMAIL_NAME_HINT, \"email\")) {\n result.email = normalizeEmail(field.value);\n }\n if (result.phoneNumber === null && matches(field, PHONE_NAME_HINT, \"tel\")) {\n try {\n result.phoneNumber = toE164(field.value, country);\n } catch {\n // libphonenumber choked on garbage — leave the slot open\n }\n }\n }\n if (result.email !== null && result.phoneNumber !== null) break;\n }\n return result;\n}\n\n/** Normalize + merge into the stash (non-null values win over existing). */\nexport function stashUserData(data: ConversionUserData, country?: CountryCode): void {\n const email = normalizeEmail(data.email);\n let phoneNumber: string | null = null;\n if (typeof data.phone === \"string\" && data.phone.length > 0) {\n try {\n phoneNumber = toE164(data.phone, country);\n } catch {\n phoneNumber = null;\n }\n }\n stash = {\n email: email ?? stash.email,\n phoneNumber: phoneNumber ?? stash.phoneNumber,\n };\n}\n\n/** Extract from `form_submit` fields and merge into the stash. Never throws. */\nexport function stashUserDataFromFormFields(fields: unknown, country?: CountryCode): void {\n try {\n const extracted = extractUserDataFromFormFields(fields, country);\n stash = {\n email: extracted.email ?? stash.email,\n phoneNumber: extracted.phoneNumber ?? stash.phoneNumber,\n };\n } catch {\n // extraction must never break event tracking\n }\n}\n\n/** Snapshot of the current stash (copy — mutations don't leak back). */\nexport function getStashedUserData(): NormalizedUserData {\n return { ...stash };\n}\n\n/** Drop everything (consent denial, tests). */\nexport function clearStashedUserData(): void {\n stash = { email: null, phoneNumber: null };\n}\n\n/**\n * Set gtag's per-page `user_data` right before a conversion fires: explicit\n * values win per-key over the stash; an empty merge sets nothing at all.\n * Browser-gated and throw-proof — the conversion must fire regardless.\n * NOT consent-checked here: the single caller (`fireConversionWithConsent`)\n * has already returned on denial before reaching this.\n *\n * Returns whether a `gtag('set','user_data', …)` call was made.\n */\nexport function applyUserDataForConversion(\n explicit?: ConversionUserData | null,\n country?: CountryCode,\n): boolean {\n if (typeof window === \"undefined\" || typeof window.gtag !== \"function\") return false;\n let email = stash.email;\n let phoneNumber = stash.phoneNumber;\n if (explicit) {\n const normalizedEmail = normalizeEmail(explicit.email);\n if (normalizedEmail) email = normalizedEmail;\n if (typeof explicit.phone === \"string\" && explicit.phone.length > 0) {\n try {\n phoneNumber = toE164(explicit.phone, country) ?? phoneNumber;\n } catch {\n // keep the stashed phone\n }\n }\n }\n if (email === null && phoneNumber === null) return false;\n try {\n window.gtag(\"set\", \"user_data\", {\n ...(email !== null ? { email } : {}),\n ...(phoneNumber !== null ? { phone_number: phoneNumber } : {}),\n });\n return true;\n } catch {\n return false;\n }\n}\n","import type { ConsentState } from \"./types\";\nimport { clearStashedUserData } from \"./user-data\";\n\n/**\n * localStorage key for the visitor's explicit consent choice.\n */\nexport const CONSENT_STATE_KEY = \"consent_state\";\n\n/**\n * localStorage key for the ISO timestamp when consent was last changed.\n */\nexport const CONSENT_TIMESTAMP_KEY = \"consent_timestamp\";\n\n/**\n * localStorage key for the ISO timestamp when an explicit decline expires.\n *\n * Written alongside a `denied` choice; absent for grants (they never expire).\n * Computed at WRITE time so every reader — including the inline\n * `beforeInteractive` scripts that can't import this module — only has to\n * compare a stored ISO string against the clock.\n */\nexport const CONSENT_EXPIRES_AT_KEY = \"consent_expires_at\";\n\n/**\n * How long an explicit decline is honored before the visitor reverts to the\n * default-granted state. Explicit grants never expire.\n */\nexport const DEFAULT_DECLINE_TTL_DAYS = 90;\n\nconst DAY_MS = 86_400_000;\n\n/**\n * Google Consent Mode value sent to `gtag('consent', 'update', ...)`.\n */\nexport type GtagConsentValue = \"granted\" | \"denied\";\n\n/**\n * Consent Mode v2 payload sent to Google Ads when consent changes.\n */\nexport interface ConsentUpdatePayload {\n ad_storage: GtagConsentValue;\n ad_user_data: GtagConsentValue;\n ad_personalization: GtagConsentValue;\n analytics_storage: GtagConsentValue;\n}\n\n/** Effective consent state — the opt-out model has no \"pending\". */\nexport type ConsentChoiceState = \"granted\" | \"denied\";\n\n/**\n * Where the effective state came from: `explicit` when the visitor made a\n * stored, still-valid choice; `default` otherwise (no choice, expired decline,\n * storage blocked, SSR).\n */\nexport type ConsentSource = \"default\" | \"explicit\";\n\n/**\n * The effective consent decision plus its provenance.\n */\nexport interface ConsentChoice {\n state: ConsentChoiceState;\n source: ConsentSource;\n /** ISO timestamp of the explicit choice; null for the default state. */\n updatedAt: string | null;\n /** ISO expiry of an unexpired decline; null for grants and the default state. */\n expiresAt: string | null;\n}\n\n/** Options for explicit consent writes. */\nexport interface SetConsentOptions {\n /** Days an explicit decline is honored. Defaults to {@link DEFAULT_DECLINE_TTL_DAYS}. */\n declineTtlDays?: number;\n}\n\nconst DEFAULT_CHOICE: ConsentChoice = {\n state: \"granted\",\n source: \"default\",\n updatedAt: null,\n expiresAt: null,\n};\n\ntype ConsentChangeListener = (choice: ConsentChoice) => void;\nconst changeListeners = new Set<ConsentChangeListener>();\n\n/**\n * Subscribe to consent changes (opt-in, opt-out, reset) made in THIS tab.\n * Cross-tab changes surface via the browser's `storage` event instead.\n * Returns an unsubscribe function.\n */\nexport function onConsentChange(listener: ConsentChangeListener): () => void {\n changeListeners.add(listener);\n return () => {\n changeListeners.delete(listener);\n };\n}\n\n// Takes the intended choice rather than re-reading storage: when localStorage\n// is blocked, a re-read would report default-granted right after an opt-out\n// click even though the live gtag/fbq revoke DID apply for this page load.\nfunction notifyConsentChanged(choice: ConsentChoice): void {\n for (const listener of changeListeners) {\n try {\n listener(choice);\n } catch {\n // a listener must never break the consent flow\n }\n }\n}\n\n/**\n * Build the Google Consent Mode v2 update payload for a single consent state.\n */\nexport function buildConsentPayload(state: GtagConsentValue): ConsentUpdatePayload {\n return {\n ad_storage: state,\n ad_user_data: state,\n ad_personalization: state,\n analytics_storage: state,\n };\n}\n\n/**\n * Resolve the visitor's effective consent (opt-out model).\n *\n * Default is GRANTED. Only a stored, unexpired explicit decline yields\n * `denied`. SSR, blocked storage, and expired declines all resolve to the\n * default. A legacy decline stored by the opt-in-era SDK (no expiry key) stays\n * denied and gets a fresh 90-day expiry backfilled, keeping this reader\n * consistent with the inline scripts (which treat a missing expiry as denied).\n */\nexport function getConsentChoice(): ConsentChoice {\n if (typeof window === \"undefined\") return DEFAULT_CHOICE;\n\n try {\n const stored = window.localStorage.getItem(CONSENT_STATE_KEY);\n const updatedAt = window.localStorage.getItem(CONSENT_TIMESTAMP_KEY);\n\n if (stored === \"granted\")\n return { state: \"granted\", source: \"explicit\", updatedAt, expiresAt: null };\n\n if (stored === \"denied\") {\n let expiresAt = window.localStorage.getItem(CONSENT_EXPIRES_AT_KEY);\n if (!expiresAt) {\n expiresAt = new Date(Date.now() + DEFAULT_DECLINE_TTL_DAYS * DAY_MS).toISOString();\n try {\n window.localStorage.setItem(CONSENT_EXPIRES_AT_KEY, expiresAt);\n } catch {\n // backfill is best-effort; the decline is still honored this read\n }\n }\n // A garbled expiry parses to NaN, the comparison is false, and the decline\n // stays honored (fail closed on the decliner's side). Only a parseable\n // expiry in the past reverts to the default.\n if (!(Date.parse(expiresAt) <= Date.now()))\n return { state: \"denied\", source: \"explicit\", updatedAt, expiresAt };\n }\n } catch {\n // localStorage blocked (sandboxed iframe / storage disabled) — default\n }\n\n return DEFAULT_CHOICE;\n}\n\n/**\n * Read the visitor's effective consent state.\n *\n * Opt-out model: returns `granted` unless a stored, unexpired explicit decline\n * exists. Never returns `pending` — that value survives in {@link ConsentState}\n * only so pre-v2 call sites keep compiling.\n */\nexport function getConsentState(): ConsentState {\n return getConsentChoice().state;\n}\n\nfunction pushConsentToPlatforms(state: GtagConsentValue): void {\n if (typeof window === \"undefined\") return;\n\n if (typeof window.gtag === \"function\")\n window.gtag(\"consent\", \"update\", buildConsentPayload(state));\n\n // Mirror to the Meta Pixel so one control gates both ad platforms.\n if (typeof window.fbq === \"function\")\n window.fbq(\"consent\", state === \"granted\" ? \"grant\" : \"revoke\");\n}\n\n/**\n * Persist an explicit visitor consent choice and push it live to Google\n * Consent Mode and the Meta Pixel.\n *\n * Declines expire after {@link DEFAULT_DECLINE_TTL_DAYS} days (override via\n * `options.declineTtlDays`); grants never expire.\n */\nexport function setConsentState(state: GtagConsentValue, options?: SetConsentOptions): void {\n if (typeof window === \"undefined\") return;\n\n // Compute the full intended choice BEFORE touching storage so (a) a garbage\n // TTL can't throw mid-write (state written, expiry not), and (b) listeners\n // get the visitor's actual choice even when storage is blocked.\n const requestedTtl = options?.declineTtlDays;\n const ttlDays =\n typeof requestedTtl === \"number\" && Number.isFinite(requestedTtl) && requestedTtl > 0\n ? requestedTtl\n : DEFAULT_DECLINE_TTL_DAYS;\n const updatedAt = new Date().toISOString();\n const expiresAt =\n state === \"denied\" ? new Date(Date.now() + ttlDays * DAY_MS).toISOString() : null;\n\n try {\n window.localStorage.setItem(CONSENT_STATE_KEY, state);\n window.localStorage.setItem(CONSENT_TIMESTAMP_KEY, updatedAt);\n if (expiresAt !== null) {\n window.localStorage.setItem(CONSENT_EXPIRES_AT_KEY, expiresAt);\n } else {\n window.localStorage.removeItem(CONSENT_EXPIRES_AT_KEY);\n }\n } catch {\n // localStorage blocked — still push the live consent update below so the\n // visitor's click takes effect for this page load even if it can't persist\n }\n\n pushConsentToPlatforms(state);\n if (state === \"denied\") {\n // A mid-session revoke also scrubs enhanced-conversions page state: drop\n // the stashed identifiers and best-effort null gtag's user_data.\n clearStashedUserData();\n try {\n if (typeof window.gtag === \"function\") window.gtag(\"set\", \"user_data\", null);\n } catch {\n // scrubbing is best-effort; the consent update above already gates fires\n }\n }\n notifyConsentChanged({ state, source: \"explicit\", updatedAt, expiresAt });\n}\n\n/**\n * Explicitly opt the visitor in to ad tracking (never expires).\n */\nexport function optIn(): void {\n setConsentState(\"granted\");\n}\n\n/**\n * Explicitly opt the visitor out of ad tracking for\n * {@link DEFAULT_DECLINE_TTL_DAYS} days (override via `options.declineTtlDays`).\n *\n * This is the primitive a client site's footer \"cookie preferences\" control\n * should call — the packages ship no consent UI of their own.\n */\nexport function optOut(options?: SetConsentOptions): void {\n setConsentState(\"denied\", options);\n}\n\n/**\n * Clear the stored explicit choice, returning the visitor to the\n * default-granted state, and push that state live to gtag + Meta.\n *\n * Power a \"Cookie preferences\" reset in a footer:\n *\n * ```tsx\n * const { reset } = useCookiePreferences();\n * <button onClick={reset}>Reset cookie preferences</button>\n * ```\n */\nexport function resetConsent(): void {\n if (typeof window === \"undefined\") return;\n\n try {\n window.localStorage.removeItem(CONSENT_STATE_KEY);\n window.localStorage.removeItem(CONSENT_TIMESTAMP_KEY);\n window.localStorage.removeItem(CONSENT_EXPIRES_AT_KEY);\n } catch {\n // localStorage blocked — nothing to clear\n }\n\n pushConsentToPlatforms(\"granted\");\n notifyConsentChanged(DEFAULT_CHOICE);\n}\n\n/**\n * Re-apply a stored explicit consent choice to Google Consent Mode + Meta.\n *\n * @deprecated The v2 consent-default path ({@link applyDefaultConsentState} /\n * `createConsentDefaultScript`) already applies the effective state at\n * bootstrap, making this redundant. Pushes platform updates directly — it must\n * NOT route through {@link setConsentState}, which would renew the decline's\n * 90-day expiry on every page load.\n */\nexport function restoreStoredConsent(): ConsentState {\n const choice = getConsentChoice();\n\n if (choice.source === \"explicit\") pushConsentToPlatforms(choice.state);\n\n return choice.state;\n}\n\n/**\n * Inline-JS fragment that resolves the effective consent value into\n * `var aranovaConsent = 'granted' | 'denied'`.\n *\n * Single source of the expiry logic for every inline `<script>` builder (gtag\n * and Meta), so the runtime reader and the inline readers can't drift. Must\n * stay dependency-free ES5 and never throw (localStorage access throws in\n * sandboxed iframes).\n */\nexport function createEffectiveConsentSnippet(): string {\n // IIFE keeps the temporaries off the page's global scope — only\n // `aranovaConsent` (the value consumed by the rest of the script) leaks.\n return `\nvar aranovaConsent = (function () {\n try {\n if (window.localStorage.getItem('${CONSENT_STATE_KEY}') === 'denied') {\n var exp = window.localStorage.getItem('${CONSENT_EXPIRES_AT_KEY}');\n var expMs = exp ? Date.parse(exp) : NaN;\n if (!(expMs <= Date.now())) return 'denied';\n }\n } catch (e) {}\n return 'granted';\n})();\n`.trim();\n}\n","// Capability self-report registry.\n//\n// Every SDK construct registers itself here at construction time, and the\n// registered set rides out on `TrackingClientContext.capabilities`, which the\n// backend persists on the session row. The dashboard derives what a client site\n// ACTUALLY has installed from those sessions, rather than trusting an operator\n// checkbox — see contracts/tracking-capabilities.json, which pins this id list\n// against the backend enum and the dashboard type union.\n//\n// Browser-only by design: a server-side client (calendar bookings) emits no\n// session, and its artifact is better evidence than a self-report anyway.\n//\n// This module deliberately imports nothing: it is the one thing every other\n// resource can import without adding an edge that could close a cycle.\n\n/**\n * Every capability an install can report. Pinned by\n * `contracts/tracking-capabilities.json` — adding one here without a catalog\n * entry fails the drift test.\n */\nexport const TRACKING_CAPABILITIES = [\n \"ad_tags_google\",\n \"ad_tags_meta\",\n \"base_tracking\",\n \"blog_rendering\",\n \"calendar_read\",\n \"calendar_write\",\n \"consent_controls\",\n \"conversion_goals_auto\",\n \"conversion_goals_manual\",\n \"cta_click_capture\",\n \"form_capture\",\n \"phone_click_capture\",\n \"phone_fields\",\n] as const;\n\nexport type TrackingCapability = (typeof TRACKING_CAPABILITIES)[number];\n\n/**\n * DOM attribute a server-rendered surface stamps to report itself.\n *\n * Blog rendering never calls the Aranova API — it reads the CDN directly — so\n * neither the ingest payload nor the request-header path can see it. The\n * renderer stamps this attribute instead and the browser context collector\n * picks it up on the next batch.\n */\nexport const CAPABILITY_DOM_ATTRIBUTE = \"data-aranova-capability\";\n\nconst registered = new Set<TrackingCapability>();\n\n/**\n * Record that a capability is present in this runtime.\n *\n * Idempotent and side-effect free — safe to call on every construction,\n * including React strict-mode double mounts.\n */\nexport function registerCapability(capability: TrackingCapability): void {\n registered.add(capability);\n}\n\n/**\n * Capabilities registered so far in this runtime, sorted for a stable wire\n * value (so the backend can hash the array to skip redundant writes).\n *\n * Also collects `data-aranova-capability` markers from the DOM, which is how\n * server-rendered surfaces that never call our API report themselves.\n */\nexport function getRegisteredCapabilities(): TrackingCapability[] {\n const all = new Set<TrackingCapability>(registered);\n for (const marker of readDomMarkers()) all.add(marker);\n return Array.from(all).sort();\n}\n\nfunction readDomMarkers(): TrackingCapability[] {\n if (typeof document === \"undefined\") return [];\n const known = new Set<string>(TRACKING_CAPABILITIES);\n const found: TrackingCapability[] = [];\n // Unknown values are dropped rather than forwarded: the backend rejects ids\n // outside its enum, and a stray attribute on a client's page must never be\n // able to fail an otherwise-valid ingest batch.\n for (const node of document.querySelectorAll(`[${CAPABILITY_DOM_ATTRIBUTE}]`)) {\n const value = node.getAttribute(CAPABILITY_DOM_ATTRIBUTE);\n if (value && known.has(value)) found.push(value as TrackingCapability);\n }\n return found;\n}\n\n/** Test-only: drop everything registered so far. */\nexport function resetRegisteredCapabilitiesForTests(): void {\n registered.clear();\n}\n","import type { TrackingParams } from \"./types\";\n\n/**\n * Default attribution cookie lifetime: 90 days.\n */\nexport const TRACKING_COOKIE_MAX_AGE_SECONDS = 7_776_000;\n\n/**\n * Attribution query/cookie keys captured by the SDK.\n */\nexport const TRACKING_PARAM_KEYS = [\n \"gclid\",\n // Google's iOS/Safari replacement click IDs — issued when privacy features\n // withhold gclid (wbraid: web-to-web, gbraid: app-to-web). First-class\n // citizens: captured, persisted, and attributed exactly like gclid.\n \"wbraid\",\n \"gbraid\",\n // Yelp Ads click id (40 hex chars), appended to ad-click URLs.\n \"ylpcid\",\n \"fbclid\",\n \"utm_source\",\n \"utm_medium\",\n \"utm_campaign\",\n \"utm_term\",\n \"utm_content\",\n] as const;\n\nexport type TrackingParamKey = (typeof TRACKING_PARAM_KEYS)[number];\n\n/**\n * Create an all-null attribution parameter object.\n */\nexport function createEmptyTrackingParams(): TrackingParams {\n return {\n gclid: null,\n wbraid: null,\n gbraid: null,\n ylpcid: null,\n fbclid: null,\n utm_source: null,\n utm_medium: null,\n utm_campaign: null,\n utm_term: null,\n utm_content: null,\n };\n}\n\n/**\n * Normalize a raw cookie value into a tracking value.\n *\n * Empty strings and non-string values become `null`.\n */\nexport function normalizeTrackingCookieValue(value: unknown): string | null {\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\n/**\n * Read all tracking params using the provided cookie reader.\n *\n * This is shared by browser, React, and Next server integrations.\n */\nexport function getTrackingParamsFromCookieReader(\n readCookie: (key: TrackingParamKey) => unknown,\n): TrackingParams {\n return TRACKING_PARAM_KEYS.reduce<TrackingParams>((params, key) => {\n params[key] = normalizeTrackingCookieValue(readCookie(key));\n return params;\n }, createEmptyTrackingParams());\n}\n\n/**\n * Extract tracking params from URL search params.\n *\n * Only non-empty values are returned.\n */\nexport function getTrackingQueryValues(\n searchParams: Pick<URLSearchParams, \"get\">,\n): Partial<Record<TrackingParamKey, string>> {\n return TRACKING_PARAM_KEYS.reduce<Partial<Record<TrackingParamKey, string>>>((params, key) => {\n const value = searchParams.get(key);\n\n if (typeof value === \"string\" && value.trim().length > 0) {\n params[key] = value;\n }\n\n return params;\n }, {});\n}\n\n/**\n * localStorage fallback prefix. Meta/Facebook in-app browsers (Instagram / FB\n * webviews) frequently block `document.cookie`; when a cookie write can't be\n * confirmed we mirror the value here so attribution (and `_fbc`) survives the\n * session and subsequent in-webview reloads instead of being silently lost.\n */\nconst FALLBACK_STORAGE_PREFIX = \"_aranova_track_\";\n\nfunction fallbackKey(name: string): string {\n return `${FALLBACK_STORAGE_PREFIX}${name}`;\n}\n\n/**\n * Persist a cookie value AND mirror it to localStorage. Generic over the cookie\n * name so it serves the attribution params AND the Meta `_fbc` cookie. Never\n * throws.\n *\n * The localStorage mirror is written UNCONDITIONALLY — it is NOT gated on a\n * cookie read-back. Meta/Instagram in-app webviews partition cookies: the write\n * is visible to a same-page read (so a verify-after-write would falsely pass)\n * yet is silently dropped on the next navigation/reload. Gating the fallback on\n * that read-back would leave the value unrecoverable in exactly the case it\n * exists for; a stale same-name cookie from a prior visit would also mask a\n * blocked write. So we always write both. {@link readCookieValue} prefers the\n * cookie when present, which keeps the mirror harmless when cookies work and\n * load-bearing when they don't survive navigation.\n */\nexport function persistCookieValue(\n name: string,\n value: string,\n maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS,\n): void {\n const encoded = encodeURIComponent(value);\n if (typeof document !== \"undefined\") {\n try {\n document.cookie = `${name}=${encoded}; Max-Age=${maxAgeSeconds}; Path=/; SameSite=Lax`;\n } catch {\n // cookie blocked — the localStorage mirror below is the fallback\n }\n }\n if (typeof window !== \"undefined\") {\n try {\n window.localStorage.setItem(fallbackKey(name), encoded);\n } catch {\n // both blocked — give up silently, never break the host site\n }\n }\n}\n\n/**\n * Read a cookie value, falling back to the localStorage mirror written by\n * {@link persistCookieValue} when the cookie is absent (blocked webview).\n */\nexport function readCookieValue(name: string): string | null {\n if (typeof document !== \"undefined\") {\n const cookies = document.cookie ? document.cookie.split(\"; \") : [];\n const match = cookies.find((cookie) => cookie.startsWith(`${name}=`));\n if (match) {\n const [, rawValue = \"\"] = match.split(\"=\");\n return normalizeTrackingCookieValue(decodeURIComponent(rawValue));\n }\n }\n if (typeof window !== \"undefined\") {\n try {\n const stored = window.localStorage.getItem(fallbackKey(name));\n if (stored) return normalizeTrackingCookieValue(decodeURIComponent(stored));\n } catch {\n // ignore\n }\n }\n return null;\n}\n\n/**\n * Read a tracking cookie from `document.cookie` (or the localStorage fallback).\n *\n * Returns `null` during SSR or when neither source has the value.\n */\nexport function getCookieValueFromDocument(key: TrackingParamKey): string | null {\n return readCookieValue(key);\n}\n\n/**\n * Persist one attribution value as a first-party cookie (localStorage fallback\n * when cookies are blocked).\n */\nexport function setTrackingCookie(\n key: TrackingParamKey,\n value: string,\n maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS,\n): void {\n persistCookieValue(key, value, maxAgeSeconds);\n}\n\n/**\n * Merge two attribution param sets, preferring `primary`'s non-null values and\n * filling the gaps from `fallback`. Used to combine the cookie-backed read with\n * the synchronous init-time snapshot so a value captured before an SPA router\n * stripped the URL (or before a webview blocked the cookie) still wins.\n */\nexport function mergeTrackingParams(\n primary: TrackingParams,\n fallback: TrackingParams,\n): TrackingParams {\n return TRACKING_PARAM_KEYS.reduce<TrackingParams>((merged, key) => {\n merged[key] = primary[key] ?? fallback[key];\n return merged;\n }, createEmptyTrackingParams());\n}\n\n/**\n * Capture any tracking params present in a URL search parameter source and\n * persist them to first-party cookies.\n *\n * Returns the subset of params that were found and persisted.\n */\nexport function persistTrackingParamsFromSearchParams(\n searchParams: Pick<URLSearchParams, \"get\">,\n maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS,\n): Partial<Record<TrackingParamKey, string>> {\n const trackingValues = getTrackingQueryValues(searchParams);\n\n Object.entries(trackingValues).forEach(([key, value]) => {\n setTrackingCookie(key as TrackingParamKey, value, maxAgeSeconds);\n });\n\n return trackingValues;\n}\n\n/**\n * Capture tracking params from a URL, persist them to first-party cookies, and\n * return the current cookie-backed attribution state.\n *\n * Defaults to `window.location.href` in the browser.\n */\nexport function captureTrackingParamsFromLocation(\n url = typeof window === \"undefined\" ? \"\" : window.location.href,\n maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS,\n): TrackingParams {\n const resolvedUrl =\n typeof window === \"undefined\"\n ? new URL(url || \"https://example.invalid\")\n : new URL(url, window.location.origin);\n persistTrackingParamsFromSearchParams(resolvedUrl.searchParams, maxAgeSeconds);\n return getTrackingParamsFromCookieReader(getCookieValueFromDocument);\n}\n","// This module loads the Google tag (gtag.js), applies Consent Mode, and fires\n// `gtag('config', …)` (remarketing) plus real-time `gtag('event','conversion')`\n// via `fireGtagConversion` (GAP28). Consent v2 is OPT-OUT: the effective state\n// is granted unless the visitor stored an explicit, unexpired decline, so tags\n// run from first paint for the default visitor.\n// See docs/google-ads-deployment/gtags-and-conversion-tracking.md.\n\nimport { buildConsentPayload, createEffectiveConsentSnippet, getConsentState } from \"./consent\";\nimport type { GtagEnvironmentMap } from \"./types\";\n\n/**\n * Google Tag Manager script host used for gtag loading.\n */\nexport const GTAG_SCRIPT_HOST = \"https://www.googletagmanager.com/gtag/js\";\n\n/**\n * Attribute used to mark scripts inserted by the tracking SDK.\n */\nexport const TRACKING_SCRIPT_ATTRIBUTE = \"data-aranova-tracking\";\n\nfunction getScriptMarker(id: string): string {\n return `aranova-${id}`;\n}\n\n/**\n * Pattern matching valid Google Ads / GA4 tag IDs.\n *\n * Accepted formats: `AW-123456789`, `G-XXXXXXXXXX`, `GT-XXXXXXX`, `DC-XXXXXXX`.\n * IDs that don't match are silently dropped to prevent script injection when\n * interpolated into inline `<script>` content.\n */\nconst GTAG_ID_PATTERN = /^[A-Z]{1,3}-[A-Za-z0-9_-]+$/;\n\nexport function isValidGtagId(id: string): boolean {\n return GTAG_ID_PATTERN.test(id);\n}\n\n/**\n * Create an inline script that initializes gtag with the visitor's EFFECTIVE\n * consent as the Consent Mode default (opt-out model).\n *\n * Resolves granted/denied synchronously from localStorage in one shot — a\n * decliner never gets a granted window and the default visitor never gets a\n * denied one, so no `wait_for_update` and no follow-up restore script is\n * needed. Run it `beforeInteractive` so the default lands before gtag.js.\n */\nexport function createConsentDefaultScript(): string {\n return `\nwindow.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\nwindow.gtag = gtag;\n${createEffectiveConsentSnippet()}\ngtag('consent', 'default', {\n ad_storage: aranovaConsent,\n ad_user_data: aranovaConsent,\n ad_personalization: aranovaConsent,\n analytics_storage: aranovaConsent\n});\n`.trim();\n}\n\n/**\n * Create an inline script that initializes gtag for a Google Ads tag id.\n */\nexport function createGtagInitScript(gtagId: string): string {\n if (!isValidGtagId(gtagId)) return \"\";\n return `\nwindow.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\nwindow.gtag = gtag;\ngtag('js', new Date());\ngtag('config', '${gtagId}');\n`.trim();\n}\n\n/**\n * Create an inline script that pushes the effective consent as an update.\n *\n * @deprecated Redundant since consent v2 — `createConsentDefaultScript()`\n * already resolves the effective state (including decline expiry) into the\n * Consent Mode default, so no restore pass is needed. Kept expiry-aware for\n * integrations that still render it.\n */\nexport function createConsentRestoreScript(): string {\n return `\n${createEffectiveConsentSnippet()}\nif (window.gtag) {\n window.gtag('consent', 'update', {\n ad_storage: aranovaConsent,\n ad_user_data: aranovaConsent,\n ad_personalization: aranovaConsent,\n analytics_storage: aranovaConsent\n });\n}\n`.trim();\n}\n\n/**\n * Ensure `window.gtag` and `window.dataLayer` exist and return the gtag shim.\n */\nexport function ensureGtagFunction(): NonNullable<Window[\"gtag\"]> {\n window.dataLayer = window.dataLayer || [];\n\n if (typeof window.gtag === \"function\") return window.gtag;\n\n // CRITICAL: push the `arguments` object, NOT a rest-param array. gtag.js only\n // treats the canonical `dataLayer.push(arguments)` form as a command — a plain\n // array pushed to the dataLayer is ignored. With the array form, every\n // gtag('config' | 'consent' | 'event') call silently no-ops: the account never\n // registers, consent mode never applies, and conversions never fire (verified\n // live — the array form sends zero network hits; the arguments form sends the\n // pagead/conversion ping). Mirror Google's canonical inline snippet exactly.\n function gtag(): void {\n // eslint-disable-next-line prefer-rest-params\n window.dataLayer?.push(arguments);\n }\n window.gtag = gtag;\n\n return window.gtag;\n}\n\nconst SEND_TO_RE = /^AW-[A-Za-z0-9]+\\/[A-Za-z0-9_-]+$/;\n\n/** A gtag `send_to` target, e.g. `AW-123456789/AbC-D_efg`. */\nexport function isValidSendTo(sendTo: string): boolean {\n return SEND_TO_RE.test(sendTo);\n}\n\nexport interface GtagConversionInput {\n /** `AW-<id>/<label>` — the conversion action's firing target. */\n sendTo: string;\n /** Conversion value in MAJOR units; omit to let Google apply the action's default. */\n value?: number | null;\n currency?: string | null;\n transactionId?: string | null;\n}\n\n/**\n * Fire a real-time on-site conversion — `gtag('event','conversion',{ send_to, … })`\n * (GAP28). Browser-gated and never throws: `record()` is isomorphic and runs server-side\n * under a secret key where `window`/`gtag` are absent, so this no-ops there. Consent\n * gating + de-dup are the caller's responsibility (see `fireConversionWithConsent`).\n * Returns whether the event was actually pushed.\n */\nexport function fireGtagConversion(input: GtagConversionInput): boolean {\n if (typeof window === \"undefined\" || typeof window.gtag !== \"function\") return false;\n if (!isValidSendTo(input.sendTo)) return false;\n const params: Record<string, unknown> = { send_to: input.sendTo };\n if (input.value != null) params.value = input.value;\n if (input.currency) params.currency = input.currency;\n if (input.transactionId) params.transaction_id = input.transactionId;\n try {\n window.gtag(\"event\", \"conversion\", params);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Apply the visitor's EFFECTIVE consent as the Consent Mode default\n * (opt-out model): granted unless a stored, unexpired decline exists.\n *\n * Reading via `getConsentState()` also backfills the expiry key for\n * legacy opt-in-era declines, keeping later inline reads consistent.\n */\nexport function applyDefaultConsentState(): void {\n const gtag = ensureGtagFunction();\n gtag(\n \"consent\",\n \"default\",\n buildConsentPayload(getConsentState() === \"denied\" ? \"denied\" : \"granted\"),\n );\n}\n\n/**\n * Load the external gtag script once for the provided Google Ads tag id.\n */\nexport function loadGtagScript(gtagId: string): void {\n if (typeof document === \"undefined\") return;\n\n const marker = getScriptMarker(\"gtag-loader\");\n const existingScript = document.querySelector<HTMLScriptElement>(\n `script[${TRACKING_SCRIPT_ATTRIBUTE}=\"${marker}\"]`,\n );\n if (existingScript) return;\n\n const script = document.createElement(\"script\");\n script.async = true;\n script.src = `${GTAG_SCRIPT_HOST}?id=${encodeURIComponent(gtagId)}`;\n script.setAttribute(TRACKING_SCRIPT_ATTRIBUTE, marker);\n document.head.append(script);\n}\n\n/**\n * Send the initial `gtag('js')` and `gtag('config')` calls.\n */\nexport function initializeGtag(gtagId: string): void {\n const gtag = ensureGtagFunction();\n gtag(\"js\", new Date());\n gtag(\"config\", gtagId);\n}\n\n/**\n * Push the current effective consent to gtag as an update.\n *\n * @deprecated Redundant since consent v2 — `applyDefaultConsentState()`\n * already applies the effective state at bootstrap. Pushes directly (no\n * storage writes), so it never renews a decline's expiry.\n */\nexport function restoreConsentState(): void {\n if (typeof window === \"undefined\") return;\n\n const consentState = getConsentState();\n if (consentState === \"granted\" || consentState === \"denied\")\n window.gtag?.(\"consent\", \"update\", buildConsentPayload(consentState));\n}\n\n/**\n * Load and initialize Google Ads tracking with Consent Mode support.\n *\n * Used by framework components and browser-script initialization.\n */\nexport function bootstrapGoogleAdsTracking(gtagId: string): void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n if (!isValidGtagId(gtagId)) return;\n\n applyDefaultConsentState();\n loadGtagScript(gtagId);\n initializeGtag(gtagId);\n}\n\n/**\n * Load and initialize Google Ads tracking for ALL labelled gtag IDs.\n *\n * Every ID in the map gets a `gtag('config', ...)` call — gtag natively\n * supports multiple configured tags on the same page. The script loader\n * only runs once (for the first ID); subsequent IDs reuse the shared\n * `dataLayer`.\n */\nexport function bootstrapMultipleGtags(gtagIds: GtagEnvironmentMap): void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n\n const ids = Object.values(gtagIds).filter(\n (id): id is string => typeof id === \"string\" && isValidGtagId(id),\n );\n if (ids.length === 0) return;\n\n applyDefaultConsentState();\n loadGtagScript(ids[0]!);\n\n // Call gtag('js') once, then gtag('config') per ID. initializeGtag\n // calls both, but gtag('js') should only fire once per page load.\n const gtag = ensureGtagFunction();\n gtag(\"js\", new Date());\n for (const id of ids) {\n gtag(\"config\", id);\n }\n}\n\n/**\n * Create an inline script that initializes gtag for multiple Google Ads tag ids.\n *\n * Used by the Next.js `GoogleAdsTracking` component when rendering `<Script>`\n * tags for a multi-gtag configuration.\n */\nexport function createGtagInitScriptMulti(gtagIds: string[]): string {\n const safeIds = gtagIds.filter(isValidGtagId);\n const configs = safeIds.map((id) => `gtag('config', '${id}');`).join(\"\\n\");\n return `\nwindow.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\nwindow.gtag = gtag;\ngtag('js', new Date());\n${configs}\n`.trim();\n}\n","// The Meta Pixel (`fbq`) loader — the Facebook analogue of `gtag.ts`. It loads\n// fbevents.js and fires `fbq('init', …)` + `fbq('track','PageView')` to build Meta\n// remarketing / custom audiences (and let Meta optimize delivery + attribute).\n// Consent v2 is OPT-OUT: the pixel runs from first paint unless the visitor\n// stored an explicit, unexpired decline. This is NOT our in-house analytics\n// (that's the event ingest pipeline); it's the ad-platform tag, exactly like the\n// Google tag is for Google Ads.\n//\n// It also forms the Conversions-API-canonical `_fbc` cookie from the landing\n// `fbclid` (and reads the Pixel-set `_fbp`) so a future server-side Meta\n// Conversions API writeback has everything it needs.\n\nimport { createEffectiveConsentSnippet, getConsentState } from \"./consent\";\nimport { persistCookieValue, readCookieValue, TRACKING_COOKIE_MAX_AGE_SECONDS } from \"./tracking\";\nimport { TRACKING_SCRIPT_ATTRIBUTE } from \"./gtag\";\nimport type { MetaPixelEnvironmentMap } from \"./types\";\n\n/** Meta Pixel script host. */\nexport const FB_EVENTS_SCRIPT_HOST = \"https://connect.facebook.net/en_US/fbevents.js\";\n\n/** Cookie names Meta uses for the Conversions API. */\nexport const FBC_COOKIE = \"_fbc\";\nexport const FBP_COOKIE = \"_fbp\";\n\n/**\n * Valid Meta Pixel ID: a 15-16 digit number. IDs that don't match are dropped to\n * prevent script injection when interpolated into inline `<script>` content\n * (mirrors GTAG_ID_PATTERN).\n */\nconst META_PIXEL_ID_PATTERN = /^\\d{15,16}$/;\n\nexport function isValidMetaPixelId(id: string): boolean {\n return META_PIXEL_ID_PATTERN.test(id);\n}\n\n// ---------------------------------------------------------------------------\n// _fbc / _fbp cookie formation\n// ---------------------------------------------------------------------------\n\n/**\n * subdomainIndex for the `_fbc` value: `com` → 0, `example.com` → 1,\n * `www.example.com` → 2 (dot-label count minus one).\n */\nexport function computeFbSubdomainIndex(hostname: string): number {\n const labels = hostname.split(\".\").filter(Boolean);\n return Math.max(0, labels.length - 1);\n}\n\n/**\n * Build the CAPI-canonical `_fbc` value: `fb.<subdomainIndex>.<creationMs>.<fbclid>`.\n * Never hashed.\n */\nexport function buildFbc(fbclid: string, now: number, hostname?: string): string {\n const host = hostname ?? (typeof window === \"undefined\" ? \"\" : window.location.hostname);\n return `fb.${computeFbSubdomainIndex(host)}.${now}.${fbclid}`;\n}\n\n/** Current `_fbc` cookie (or localStorage fallback), if any. */\nexport function getFbcCookie(): string | null {\n return readCookieValue(FBC_COOKIE);\n}\n\n/** Current `_fbp` cookie — set by the Meta Pixel; we only ever read it. */\nexport function getFbpCookie(): string | null {\n return readCookieValue(FBP_COOKIE);\n}\n\nfunction readFbclidFromUrl(): string | null {\n if (typeof window === \"undefined\") return null;\n try {\n const value = new URL(window.location.href).searchParams.get(\"fbclid\");\n return value && value.trim().length > 0 ? value : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Form and persist `_fbc` from the landing `fbclid` when the Pixel hasn't already\n * set it. Reads the fbclid from the URL first, then the captured attribution\n * cookie. No-ops when there's no fbclid or `_fbc` already exists. `_fbp` is\n * Pixel-only — never written here.\n */\nexport function captureFbc(now = typeof Date === \"undefined\" ? 0 : Date.now()): void {\n if (typeof window === \"undefined\") return;\n // A Pixel-set `_fbc` is canonical — don't overwrite it.\n if (getFbcCookie()) return;\n const fbclid = readFbclidFromUrl() ?? readCookieValue(\"fbclid\");\n if (!fbclid) return;\n persistCookieValue(FBC_COOKIE, buildFbc(fbclid, now), TRACKING_COOKIE_MAX_AGE_SECONDS);\n}\n\n// ---------------------------------------------------------------------------\n// fbq loader (mirrors gtag.ts)\n// ---------------------------------------------------------------------------\n\ntype FbqStub = ((...args: unknown[]) => void) & {\n callMethod?: (...args: unknown[]) => void;\n queue: unknown[][];\n push: unknown;\n loaded: boolean;\n version: string;\n};\n\nfunction getScriptMarker(id: string): string {\n return `aranova-${id}`;\n}\n\n/**\n * Ensure `window.fbq` exists (the standard fbevents bootstrap stub) and return\n * it. Safe to call repeatedly — it only initializes once.\n */\nexport function ensureFbqFunction(): NonNullable<Window[\"fbq\"]> {\n const w = window as Window & { fbq?: FbqStub; _fbq?: FbqStub };\n if (typeof w.fbq === \"function\") return w.fbq;\n\n const fbq = function (this: unknown, ...args: unknown[]) {\n if (fbq.callMethod) fbq.callMethod.apply(fbq, args);\n else fbq.queue.push(args);\n } as FbqStub;\n\n fbq.push = fbq;\n fbq.loaded = true;\n fbq.version = \"2.0\";\n fbq.queue = [];\n\n w.fbq = fbq;\n if (!w._fbq) w._fbq = fbq;\n return fbq;\n}\n\n/**\n * Apply the visitor's EFFECTIVE consent to the Meta Pixel (opt-out model):\n * grant unless a stored, unexpired decline exists.\n */\nexport function applyDefaultMetaConsentState(): void {\n ensureFbqFunction()(\"consent\", getConsentState() === \"denied\" ? \"revoke\" : \"grant\");\n}\n\n/** Load fbevents.js once. */\nexport function loadFbeventsScript(): void {\n if (typeof document === \"undefined\") return;\n const marker = getScriptMarker(\"fbq-loader\");\n const existing = document.querySelector<HTMLScriptElement>(\n `script[${TRACKING_SCRIPT_ATTRIBUTE}=\"${marker}\"]`,\n );\n if (existing) return;\n\n const script = document.createElement(\"script\");\n script.async = true;\n script.src = FB_EVENTS_SCRIPT_HOST;\n script.setAttribute(TRACKING_SCRIPT_ATTRIBUTE, marker);\n document.head.append(script);\n}\n\n/** `fbq('init', id)` + the initial PageView. */\nexport function initializeMetaPixel(pixelId: string): void {\n const fbq = ensureFbqFunction();\n fbq(\"init\", pixelId);\n fbq(\"track\", \"PageView\");\n}\n\n/**\n * Push the current effective consent to fbq.\n *\n * @deprecated Redundant since consent v2 — `applyDefaultMetaConsentState()`\n * already applies the effective state at bootstrap. Pushes directly (no\n * storage writes), so it never renews a decline's expiry.\n */\nexport function restoreMetaConsentState(): void {\n if (typeof window === \"undefined\") return;\n const state = getConsentState();\n if (state === \"granted\") window.fbq?.(\"consent\", \"grant\");\n else if (state === \"denied\") window.fbq?.(\"consent\", \"revoke\");\n}\n\n/**\n * Load + initialize one Meta Pixel with Consent Mode support, and form `_fbc`.\n */\nexport function bootstrapMetaPixel(pixelId: string): void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n if (!isValidMetaPixelId(pixelId)) return;\n\n applyDefaultMetaConsentState();\n loadFbeventsScript();\n initializeMetaPixel(pixelId);\n captureFbc();\n}\n\n/**\n * Load + initialize ALL labelled Meta Pixel IDs (script loads once; `fbq('init')`\n * fires per id — the Pixel supports multiple pixels on one page).\n */\nexport function bootstrapMultiplePixels(pixelIds: MetaPixelEnvironmentMap): void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n const ids = Object.values(pixelIds).filter(\n (id): id is string => typeof id === \"string\" && isValidMetaPixelId(id),\n );\n if (ids.length === 0) return;\n\n applyDefaultMetaConsentState();\n loadFbeventsScript();\n const fbq = ensureFbqFunction();\n for (const id of ids) {\n fbq(\"init\", id);\n }\n fbq(\"track\", \"PageView\");\n captureFbc();\n}\n\n// ---------------------------------------------------------------------------\n// Inline <script> builders for the Next.js <Script> path (mirror gtag.ts)\n// ---------------------------------------------------------------------------\n\n/** The standard fbevents stub as an inline string. */\nfunction fbqStubScript(): string {\n return `\n!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?\nn.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;\nn.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;\nt.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,\ndocument,'script','${FB_EVENTS_SCRIPT_HOST}');`.trim();\n}\n\n/**\n * Inline script that loads the fbevents stub and applies the visitor's\n * EFFECTIVE consent (opt-out model) before any `init`/`PageView` fires.\n */\nexport function createMetaConsentDefaultScript(): string {\n return `${fbqStubScript()}\n${createEffectiveConsentSnippet()}\nfbq('consent', aranovaConsent === 'denied' ? 'revoke' : 'grant');`;\n}\n\n/** Inline script that inits one pixel + PageView. */\nexport function createMetaPixelInitScript(pixelId: string): string {\n if (!isValidMetaPixelId(pixelId)) return \"\";\n return `fbq('init', '${pixelId}');\\nfbq('track', 'PageView');`;\n}\n\n/** Inline script that inits multiple pixels + a single PageView. */\nexport function createMetaPixelInitScriptMulti(pixelIds: string[]): string {\n const inits = pixelIds.filter(isValidMetaPixelId).map((id) => `fbq('init', '${id}');`);\n if (inits.length === 0) return \"\";\n return `${inits.join(\"\\n\")}\\nfbq('track', 'PageView');`;\n}\n\n/**\n * Inline script that pushes the effective consent into fbq.\n *\n * @deprecated Redundant since consent v2 — `createMetaConsentDefaultScript()`\n * already applies the effective state (including decline expiry) before the\n * pixel initializes. Kept expiry-aware for integrations that still render it.\n */\nexport function createMetaConsentRestoreScript(): string {\n return `\n${createEffectiveConsentSnippet()}\nif (window.fbq) {\n window.fbq('consent', aranovaConsent === 'denied' ? 'revoke' : 'grant');\n}`.trim();\n}\n","// Session-scoped LANDING attribution (ADR-016).\n//\n// The carried attribution channel (tracking.ts) persists gclid/fbclid/utm_*\n// for 90 days so journey stitching and conversion writeback keep working\n// across sessions. This module answers a different question — \"what did THIS\n// session's landing URL actually carry?\" — so the dashboard's source label is\n// never poisoned by a click from an earlier session.\n//\n// One localStorage record, keyed to the current session id and overwritten\n// whenever a new session is minted: self-cleaning, O(1) storage, survives\n// in-webview reloads (localStorage, not cookies — Meta/IG webviews silently\n// drop cookie writes, the exact failure mode the carried channel already\n// engineers around). An in-memory mirror covers storage-blocked environments.\n\nimport { getTrackingQueryValues, TRACKING_PARAM_KEYS, type TrackingParamKey } from \"./tracking\";\n\n/**\n * localStorage key for the landing-params record (same `_aranova_track_`\n * family as the carried-channel cookie mirrors).\n */\nexport const LANDING_STORAGE_KEY = \"_aranova_track_landing\";\n\n/**\n * Serialized landing record: the params present in the landing URL of the\n * session identified by `session_id`.\n */\nexport interface StoredLandingRecord {\n session_id: string;\n params: Partial<Record<TrackingParamKey, string>>;\n}\n\nlet memoryRecord: StoredLandingRecord | null = null;\n\nfunction sanitizeParams(value: unknown): Partial<Record<TrackingParamKey, string>> {\n if (typeof value !== \"object\" || value === null) return {};\n const source = value as Record<string, unknown>;\n return TRACKING_PARAM_KEYS.reduce<Partial<Record<TrackingParamKey, string>>>((params, key) => {\n const entry = source[key];\n if (typeof entry === \"string\" && entry.length > 0) params[key] = entry;\n return params;\n }, {});\n}\n\nfunction readStoredRecord(): StoredLandingRecord | null {\n try {\n const raw = window.localStorage.getItem(LANDING_STORAGE_KEY);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as Partial<StoredLandingRecord>;\n if (typeof parsed.session_id !== \"string\" || parsed.session_id.length === 0) return null;\n return { session_id: parsed.session_id, params: sanitizeParams(parsed.params) };\n } catch {\n return null;\n }\n}\n\nfunction writeRecord(record: StoredLandingRecord): void {\n memoryRecord = record;\n try {\n window.localStorage.setItem(LANDING_STORAGE_KEY, JSON.stringify(record));\n } catch {\n // Storage blocked — the in-memory mirror above still serves this page.\n }\n}\n\nfunction captureFromUrl(url?: string): Partial<Record<TrackingParamKey, string>> {\n try {\n const resolved = new URL(url ?? window.location.href, window.location.origin);\n return getTrackingQueryValues(resolved.searchParams);\n } catch {\n return {};\n }\n}\n\n/**\n * Return the landing params for `sessionId`, capturing them from the current\n * URL when no record for that session exists yet.\n *\n * First-wins: a record whose `session_id` matches is returned as-is (a second\n * tab's URL never clobbers the session's true landing). A missing or\n * mismatched record means a new session just started — the current URL IS that\n * session's landing, so it is captured and persisted. Read-only with respect\n * to the carried channel: never touches cookies. Never throws; returns `{}`\n * during SSR.\n */\nexport function getOrCaptureLandingParams(\n sessionId: string,\n url?: string,\n): Partial<Record<TrackingParamKey, string>> {\n if (typeof window === \"undefined\") return {};\n\n const stored = readStoredRecord();\n if (stored && stored.session_id === sessionId) {\n memoryRecord = stored;\n return stored.params;\n }\n if (memoryRecord && memoryRecord.session_id === sessionId) {\n return memoryRecord.params;\n }\n\n const record: StoredLandingRecord = { session_id: sessionId, params: captureFromUrl(url) };\n writeRecord(record);\n return record.params;\n}\n\n/**\n * The 10 landing wire fields, null-filled. Key PRESENCE tells the backend the\n * landing is explicitly known; when it is NOT known the keys must be omitted\n * entirely so the backend falls back to parsing first_page.\n */\nexport interface LandingPayloadFields {\n landing_gclid: string | null;\n landing_wbraid: string | null;\n landing_gbraid: string | null;\n landing_ylpcid: string | null;\n landing_fbclid: string | null;\n landing_utm_source: string | null;\n landing_utm_medium: string | null;\n landing_utm_campaign: string | null;\n landing_utm_term: string | null;\n landing_utm_content: string | null;\n}\n\n/**\n * Build the landing portion of a session payload — the single place the\n * \"present iff known\" wire contract is enforced. Returns `{}` (omit the keys)\n * when there is no landing knowledge: during SSR the session's landing URL is\n * simply not observable, and sending explicit nulls would wrongly tell the\n * backend \"this session landed with no params\", suppressing its fallback.\n */\nexport function buildLandingPayloadFields(\n sessionId: string,\n override?: Partial<Record<TrackingParamKey, string>>,\n): Partial<LandingPayloadFields> {\n const params =\n override ?? (typeof window === \"undefined\" ? null : getOrCaptureLandingParams(sessionId));\n if (params === null) return {};\n return {\n landing_gclid: params.gclid ?? null,\n landing_wbraid: params.wbraid ?? null,\n landing_gbraid: params.gbraid ?? null,\n landing_ylpcid: params.ylpcid ?? null,\n landing_fbclid: params.fbclid ?? null,\n landing_utm_source: params.utm_source ?? null,\n landing_utm_medium: params.utm_medium ?? null,\n landing_utm_campaign: params.utm_campaign ?? null,\n landing_utm_term: params.utm_term ?? null,\n landing_utm_content: params.utm_content ?? null,\n };\n}\n\n/**\n * Drop the landing record (localStorage + memory). Paired with\n * `resetTrackingIdentity()`; also used by tests.\n */\nexport function clearLandingRecord(): void {\n memoryRecord = null;\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.removeItem(LANDING_STORAGE_KEY);\n } catch {\n // ignored\n }\n}\n","import { getRegisteredCapabilities } from \"./capabilities\";\nimport { getFbcCookie, getFbpCookie } from \"./fbq\";\nimport { buildLandingPayloadFields } from \"./landing\";\nimport type { TrackingParamKey } from \"./tracking\";\nimport type {\n TrackingClientContext,\n TrackingEnvironment,\n TrackingEventCreatePayload,\n TrackingInstallSurface,\n TrackingParams,\n TrackingSessionUpsertPayload,\n} from \"./types\";\n\ninterface TrackingContextInput {\n packageName?: string | null;\n pageTitle?: string | null;\n referrer?: string | null;\n sdkVersion?: string | null;\n siteOrigin?: string | null;\n environment?: TrackingEnvironment;\n activeGtagIds?: Record<string, string> | null;\n}\n\ninterface TrackingEventInput {\n eventType: string;\n metadata?: Record<string, unknown> | null;\n pageUrl?: string | null;\n sessionId: string;\n}\n\ninterface TrackingSessionInput {\n consentState?: Record<string, unknown> | null;\n firstPage?: string | null;\n sessionId: string;\n visitorId?: string | null;\n /**\n * Landing attribution override (ADR-016). When omitted, the session's\n * persisted landing record is used (captured from the current URL if the\n * session has none yet).\n */\n landingParams?: Partial<Record<TrackingParamKey, string>>;\n}\n\n/**\n * Build runtime context attached to tracking sessions and events.\n */\nexport function createTrackingClientContext(\n surface: TrackingInstallSurface,\n input: TrackingContextInput = {},\n): TrackingClientContext {\n return {\n surface,\n sdk_version: input.sdkVersion ?? null,\n package_name: input.packageName ?? null,\n site_origin:\n input.siteOrigin ?? (typeof window === \"undefined\" ? null : window.location.origin),\n page_title:\n input.pageTitle ?? (typeof document === \"undefined\" ? null : document.title || null),\n referrer:\n input.referrer ?? (typeof document === \"undefined\" ? null : document.referrer || null),\n environment: input.environment ?? \"production\",\n active_gtag_ids: input.activeGtagIds ?? null,\n capabilities: getRegisteredCapabilities(),\n };\n}\n\n/**\n * Build the session portion of a tracking ingest request.\n */\nexport function createTrackingSessionUpsertPayload(\n trackingParams: TrackingParams,\n input: TrackingSessionInput,\n context: TrackingClientContext,\n): TrackingSessionUpsertPayload {\n return {\n session_id: input.sessionId,\n visitor_id: input.visitorId ?? null,\n gclid: trackingParams.gclid,\n wbraid: trackingParams.wbraid,\n gbraid: trackingParams.gbraid,\n ylpcid: trackingParams.ylpcid,\n fbclid: trackingParams.fbclid,\n fbc: getFbcCookie(),\n fbp: getFbpCookie(),\n utm_source: trackingParams.utm_source,\n utm_medium: trackingParams.utm_medium,\n utm_campaign: trackingParams.utm_campaign,\n utm_term: trackingParams.utm_term,\n utm_content: trackingParams.utm_content,\n // Omitted entirely when the landing isn't observable (SSR, no override) —\n // present-as-null would wrongly tell the backend \"landed with no params\".\n ...buildLandingPayloadFields(input.sessionId, input.landingParams),\n first_page: input.firstPage ?? null,\n consent_state: input.consentState ?? null,\n context,\n };\n}\n\n/**\n * Build one event payload before it is batched into a tracking ingest request.\n */\nexport function createTrackingEventCreatePayload(\n trackingParams: TrackingParams,\n input: TrackingEventInput,\n context: TrackingClientContext,\n): TrackingEventCreatePayload {\n return {\n session_id: input.sessionId,\n event_type: input.eventType,\n gclid: trackingParams.gclid,\n wbraid: trackingParams.wbraid,\n gbraid: trackingParams.gbraid,\n ylpcid: trackingParams.ylpcid,\n fbclid: trackingParams.fbclid,\n fbc: getFbcCookie(),\n fbp: getFbpCookie(),\n page_url: input.pageUrl ?? (typeof window === \"undefined\" ? null : window.location.href),\n metadata: input.metadata ?? null,\n context,\n };\n}\n","// Consent-gated, de-duped orchestration around the raw `fireGtagConversion` (GAP28).\n//\n// Consent v2 (opt-out model): fire unless the visitor's effective consent is an\n// explicit, unexpired decline. There is no \"pending\" state and therefore no\n// queue — the default visitor converts in real time.\n//\n// `fireGtagConversion` is itself browser-gated and never throws, so this is safe to call\n// from the isomorphic sales `record()` — server-side it simply no-ops.\n\nimport { getConsentState } from \"../consent\";\nimport { fireGtagConversion, isValidSendTo, type GtagConversionInput } from \"../gtag\";\nimport { applyUserDataForConversion, type ConversionUserData } from \"../user-data\";\n\nconst DEDUP_PREFIX = \"_aranova_conv_\";\n\nexport type ConversionFireOutcome = \"fired\" | \"denied\" | \"duplicate\" | \"invalid\" | \"retryable\";\n\nfunction dedupKey(input: GtagConversionInput): string {\n return `${DEDUP_PREFIX}${input.transactionId ?? \"\"}:${input.sendTo}`;\n}\n\n// Has this (transaction_id, send_to) already fired? Read-only — the key is written ONLY\n// after a successful fire (see `fireOnce`), so a fire that never happened (e.g. gtag not\n// ready yet) is never suppressed on retry. Best-effort: a blocked sessionStorage reads as\n// \"not fired\" so the conversion still gets a chance.\nfunction alreadyFired(input: GtagConversionInput): boolean {\n if (!input.transactionId || typeof window === \"undefined\") return false;\n try {\n return window.sessionStorage.getItem(dedupKey(input)) !== null;\n } catch {\n return false;\n }\n}\n\nfunction markFired(input: GtagConversionInput): void {\n if (!input.transactionId || typeof window === \"undefined\") return;\n try {\n window.sessionStorage.setItem(dedupKey(input), \"1\");\n } catch {\n // sessionStorage unavailable — Google's counting_type is the authoritative backstop\n }\n}\n\n/**\n * Fire a conversion through the consent gate + de-dup guard.\n *\n * Enhanced conversions: right before the fire (past the consent gate AND the\n * de-dup guard — a duplicate that won't emit an event must not mutate gtag's\n * page-level user_data either), gtag's `user_data` is set from the explicit\n * `options.userData` merged over the form-submit stash — this is the single\n * choke point all firing paths (recordSale, trackConversion, autofire) flow\n * through, so every conversion hit carries the visitor's hashed identifiers\n * when any are known. Re-setting before each fire is idempotent (gtag scopes\n * user_data to the page), so a later autofire on the same page matches too.\n * The de-dup key is written only AFTER a successful fire, so a fire that\n * never happened (gtag not ready) is never suppressed on retry.\n */\nexport function fireConversionWithConsent(\n input: GtagConversionInput,\n options?: { userData?: ConversionUserData | null },\n): ConversionFireOutcome {\n if (getConsentState() === \"denied\") return \"denied\";\n if (alreadyFired(input)) return \"duplicate\";\n if (!isValidSendTo(input.sendTo)) return \"invalid\";\n try {\n applyUserDataForConversion(options?.userData);\n if (!fireGtagConversion(input)) return \"retryable\";\n markFired(input);\n return \"fired\";\n } catch {\n return \"retryable\";\n }\n}\n\n/**\n * Flush conversions queued while consent was pending.\n *\n * @deprecated No-op since consent v2 — there is no \"pending\" state, so nothing\n * is ever queued. Kept exported so pre-v2 integrations keep compiling.\n */\nexport function flushPendingConversions(): void {\n // intentionally empty\n}\n","// The client tracking config the SDK reads at runtime (GAP28 / ENG-46).\n//\n// The browser fetches the per-business object published to R2/CDN. This module is a\n// TOLERANT reader — it ignores unknown fields, defaults every field, and never throws — so\n// the backend can add fields freely (additive-only within the `v1` schema major) without\n// breaking an older SDK, and a newer object never breaks an older reader. See\n// docs/tracking-package/conversion-config-schema.md for the contract.\n\nexport interface ServiceFiring {\n send_to: string;\n /** Action's configured default value (cents); the SDK fires it only when a sale has no amount. */\n value_cents?: number | null;\n currency?: string | null;\n}\n\n/** Serializable on-page trigger (owned by tracking-core/src/events/trigger-spec.ts). The shape\n * varies by `event_type`; only the parameter for that type is set. */\nexport interface ConfigTriggerSpec {\n event_type: string;\n threshold_percent?: number;\n threshold_seconds?: number;\n page_threshold?: number;\n page_name?: string;\n}\n\n/** One unified conversion goal: a revenue `sale` or an on-page `event`. */\nexport interface ConversionGoal {\n key: string;\n label?: string;\n kind: \"sale\" | \"event\";\n /** Structured fire-when for event-goals; null for sales. */\n trigger: ConfigTriggerSpec | null;\n firing: ServiceFiring | null;\n}\n\nexport interface ConversionConfig {\n schema_version: number;\n config_version: number;\n business_id?: string;\n customer_id?: string | null;\n environment?: string;\n google_tracking_state: \"active\" | \"disabled\";\n gtag_ids: Record<string, string>;\n meta_pixel_ids: Record<string, string>;\n /** LEGACY: sale-goals only (for pre-unified-goal readers). */\n services: Array<{\n key: string;\n label?: string;\n firing: ServiceFiring | null;\n }>;\n /** Unified goal list (sales + on-page events). Superset of `services`. */\n goals: ConversionGoal[];\n}\n\nexport interface ConversionConfigStore {\n /** Firing config for a goal/service key, or null when it doesn't fire on-site. */\n getFiring(key: string): ServiceFiring | null;\n /** The full goal for a key, or null when unknown. */\n getGoal(key: string): ConversionGoal | null;\n /** Every adopted goal (sales + events). */\n listGoals(): ConversionGoal[];\n /** The currently adopted config (baked / cached fallback until the fetch lands). */\n current(): ConversionConfig | null;\n /** True once a config is adopted (seeded synchronously from cache/baked, or fetched). */\n isReady(): boolean;\n /**\n * Run `listener` when a config first becomes available — immediately if already\n * ready, otherwise on the first adopt. Lets auto-fire replay automatic events that\n * occurred before the async CDN fetch resolved. Returns an unsubscribe fn.\n */\n onResolve(listener: () => void): () => void;\n /** Force a background revalidate against the CDN object. */\n revalidate(): Promise<void>;\n}\n\nfunction isStringMap(value: unknown): value is Record<string, string> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.values(value).every((v) => typeof v === \"string\")\n );\n}\n\nfunction parseFiring(value: unknown): ServiceFiring | null {\n if (!value || typeof value !== \"object\") return null;\n const f = value as Record<string, unknown>;\n if (typeof f.send_to !== \"string\") return null;\n return {\n send_to: f.send_to,\n value_cents: typeof f.value_cents === \"number\" ? f.value_cents : null,\n currency: typeof f.currency === \"string\" ? f.currency : null,\n };\n}\n\nfunction parseTrigger(value: unknown): ConfigTriggerSpec | null {\n if (!value || typeof value !== \"object\") return null;\n const t = value as Record<string, unknown>;\n if (typeof t.event_type !== \"string\") return null;\n const spec: ConfigTriggerSpec = { event_type: t.event_type };\n if (typeof t.threshold_percent === \"number\") spec.threshold_percent = t.threshold_percent;\n if (typeof t.threshold_seconds === \"number\") spec.threshold_seconds = t.threshold_seconds;\n if (typeof t.page_threshold === \"number\") spec.page_threshold = t.page_threshold;\n if (typeof t.page_name === \"string\") spec.page_name = t.page_name;\n return spec;\n}\n\n/** Tolerant parse of a raw config object — never throws; returns null only when unusable. */\nexport function parseConversionConfig(raw: unknown): ConversionConfig | null {\n if (!raw || typeof raw !== \"object\") return null;\n const obj = raw as Record<string, unknown>;\n const servicesRaw = Array.isArray(obj.services) ? obj.services : [];\n const services = servicesRaw.flatMap((entry) => {\n if (!entry || typeof entry !== \"object\") return [];\n const s = entry as Record<string, unknown>;\n if (typeof s.key !== \"string\") return [];\n return [\n {\n key: s.key,\n label: typeof s.label === \"string\" ? s.label : undefined,\n firing: parseFiring(s.firing),\n },\n ];\n });\n const goalsRaw = Array.isArray(obj.goals) ? obj.goals : null;\n // Back-compat: an object from a pre-unified-goal backend has no `goals` — derive them from\n // the legacy `services` (all sale-goals) so the store always has a unified list.\n const goals: ConversionGoal[] = goalsRaw\n ? goalsRaw.flatMap((entry) => {\n if (!entry || typeof entry !== \"object\") return [];\n const g = entry as Record<string, unknown>;\n if (typeof g.key !== \"string\") return [];\n return [\n {\n key: g.key,\n label: typeof g.label === \"string\" ? g.label : undefined,\n kind: g.kind === \"event\" ? \"event\" : \"sale\",\n trigger: parseTrigger(g.trigger),\n firing: parseFiring(g.firing),\n },\n ];\n })\n : services.map((s) => ({\n key: s.key,\n label: s.label,\n kind: \"sale\" as const,\n trigger: null,\n firing: s.firing,\n }));\n return {\n schema_version: typeof obj.schema_version === \"number\" ? obj.schema_version : 1,\n config_version: typeof obj.config_version === \"number\" ? obj.config_version : 0,\n business_id: typeof obj.business_id === \"string\" ? obj.business_id : undefined,\n customer_id: typeof obj.customer_id === \"string\" ? obj.customer_id : null,\n environment: typeof obj.environment === \"string\" ? obj.environment : undefined,\n google_tracking_state: obj.google_tracking_state === \"active\" ? \"active\" : \"disabled\",\n gtag_ids: isStringMap(obj.gtag_ids) ? obj.gtag_ids : {},\n meta_pixel_ids: isStringMap(obj.meta_pixel_ids) ? obj.meta_pixel_ids : {},\n services,\n goals,\n };\n}\n\n// --- stale-while-revalidate cache (sessionStorage) -----------------------------------------\n\nconst CACHE_PREFIX = \"_aranova_cfg_\";\n\ninterface CachedEntry {\n etag: string | null;\n config: ConversionConfig;\n}\n\nfunction cacheKey(url: string): string {\n return `${CACHE_PREFIX}${url}`;\n}\n\nfunction readCache(url: string): CachedEntry | null {\n if (typeof window === \"undefined\") return null;\n try {\n const raw = window.sessionStorage.getItem(cacheKey(url));\n if (!raw) return null;\n const parsed = JSON.parse(raw) as { etag?: unknown; config?: unknown };\n const config = parseConversionConfig(parsed.config);\n if (!config) return null;\n return {\n etag: typeof parsed.etag === \"string\" ? parsed.etag : null,\n config,\n };\n } catch {\n return null;\n }\n}\n\nfunction writeCache(url: string, entry: CachedEntry): void {\n if (typeof window === \"undefined\") return;\n try {\n window.sessionStorage.setItem(cacheKey(url), JSON.stringify(entry));\n } catch {\n // sessionStorage unavailable — runtime adoption still works, just not across inits\n }\n}\n\nexport interface ResolveConversionConfigOptions {\n /** Full URL of the per-business CDN object. */\n cdnUrl: string;\n /** Offline-correct fallback (e.g. the CLI-baked snapshot). */\n baked?: ConversionConfig | null;\n /** Injectable for tests / non-global-fetch runtimes. */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Resolve the config with stale-while-revalidate: seed synchronously from the\n * sessionStorage cache (or the baked fallback), then conditionally re-fetch the CDN object\n * with `If-None-Match`. A fetched object is adopted only if its `config_version` is strictly\n * greater than what's cached, so a reordered edge copy can't downgrade fresher state.\n * Non-blocking and browser-only; a failed fetch leaves the seed in place.\n */\nexport function resolveConversionConfig(\n options: ResolveConversionConfigOptions,\n): ConversionConfigStore {\n const cached = readCache(options.cdnUrl);\n let current: ConversionConfig | null = cached?.config ?? options.baked ?? null;\n let etag: string | null = cached?.etag ?? null;\n const goalsByKey = new Map<string, ConversionGoal>();\n const resolveListeners = new Set<() => void>();\n\n function rebuildIndex(): void {\n goalsByKey.clear();\n for (const goal of current?.goals ?? []) {\n goalsByKey.set(goal.key, goal);\n }\n }\n\n function notifyResolved(): void {\n // One-shot: only the FIRST adoption matters for replay. Snapshot then clear so a\n // listener that re-subscribes inside its callback isn't double-run.\n const listeners = [...resolveListeners];\n resolveListeners.clear();\n // Isolate each listener: the set is already cleared, so one throwing subscriber\n // must not drop the others' buffered replays. Swallow (best-effort) to match the\n // SDK's policy of never surfacing tracking errors to the host page.\n for (const listener of listeners) {\n try {\n listener();\n } catch {\n // never let one subscriber break conversion replay\n }\n }\n }\n\n function adopt(next: ConversionConfig | null, nextEtag: string | null): void {\n if (!next) return;\n if (current && next.config_version <= current.config_version) return;\n const wasEmpty = current === null;\n current = next;\n etag = nextEtag;\n rebuildIndex();\n writeCache(options.cdnUrl, { etag, config: next });\n if (wasEmpty) notifyResolved();\n }\n\n async function revalidate(): Promise<void> {\n if (typeof window === \"undefined\") return;\n try {\n const doFetch = options.fetchImpl ?? globalThis.fetch;\n if (!doFetch) return;\n const headers: Record<string, string> = {};\n if (etag) headers[\"If-None-Match\"] = etag;\n const response = await doFetch(options.cdnUrl, {\n method: \"GET\",\n headers,\n });\n if (response.status === 304 || !response.ok) return;\n adopt(parseConversionConfig(await response.json()), response.headers.get(\"ETag\"));\n } catch {\n // best-effort; the cached / baked fallback stays in place\n }\n }\n\n rebuildIndex();\n void revalidate();\n\n return {\n getFiring: (key) => goalsByKey.get(key)?.firing ?? null,\n getGoal: (key) => goalsByKey.get(key) ?? null,\n listGoals: () => [...goalsByKey.values()],\n current: () => current,\n isReady: () => current !== null,\n onResolve: (listener) => {\n if (current !== null) {\n listener();\n return () => {};\n }\n resolveListeners.add(listener);\n return () => resolveListeners.delete(listener);\n },\n revalidate,\n };\n}\n","const STORAGE_KEY = \"_aranova_auto_txn_map\";\nconst transactionIds = new Map<string, string>();\nlet legacyCounter = 0;\n\ninterface StoredTransactionMap {\n sessionId: string;\n entries: Record<string, string>;\n}\n\nfunction scopeKey(sessionId: string, goalKey: string, path: string): string {\n return JSON.stringify([sessionId, goalKey, path]);\n}\n\nfunction randomId(): string {\n const cryptoApi = globalThis.crypto;\n if (typeof cryptoApi?.randomUUID === \"function\") return cryptoApi.randomUUID();\n if (typeof cryptoApi?.getRandomValues === \"function\") {\n const bytes = cryptoApi.getRandomValues(new Uint8Array(16));\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n }\n // Ancient-browser fallback. Keep fixed-length opaque shape; modern browsers\n // always use Web Crypto above.\n legacyCounter = (legacyCounter + 1) % 0x1_0000_0000;\n const timestamp = Date.now().toString(16).padStart(12, \"0\");\n const counter = legacyCounter.toString(16).padStart(8, \"0\");\n const random = Math.floor(Math.random() * 0xffffffffffff)\n .toString(16)\n .padStart(12, \"0\");\n return `${timestamp}${counter}${random}`.slice(0, 32);\n}\n\nfunction isValidTransactionId(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n /^auto:(?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/i.test(\n value,\n ) &&\n value.length <= 64\n );\n}\n\nfunction readStoredMap(sessionId: string): StoredTransactionMap {\n if (typeof window === \"undefined\") return { sessionId, entries: {} };\n try {\n const raw = window.localStorage.getItem(STORAGE_KEY);\n if (!raw) return { sessionId, entries: {} };\n const parsed = JSON.parse(raw) as Partial<StoredTransactionMap>;\n if (\n parsed.sessionId !== sessionId ||\n !parsed.entries ||\n typeof parsed.entries !== \"object\" ||\n Array.isArray(parsed.entries)\n ) {\n return { sessionId, entries: {} };\n }\n return { sessionId, entries: parsed.entries };\n } catch {\n return { sessionId, entries: {} };\n }\n}\n\nfunction writeStoredMap(stored: StoredTransactionMap): void {\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.setItem(STORAGE_KEY, JSON.stringify(stored));\n } catch {\n // Storage unavailable; page-lifetime stability is still preserved.\n }\n}\n\n/**\n * Return one opaque, bounded Google transaction ID per session/goal/path.\n *\n * The raw session id and URL path stay in first-party local storage and are\n * never sent to Google. The one-current-session map preserves deduplication\n * across tabs while discarding prior-session mappings.\n */\nexport function getAutomaticTransactionId(\n sessionId: string,\n goalKey: string,\n path: string,\n): string {\n const key = scopeKey(sessionId, goalKey, path);\n const existing = transactionIds.get(key);\n if (existing) return existing;\n\n const stored = readStoredMap(sessionId);\n const storedId = stored.entries[key];\n if (isValidTransactionId(storedId)) {\n transactionIds.set(key, storedId);\n return storedId;\n }\n\n const transactionId = `auto:${randomId()}`;\n transactionIds.set(key, transactionId);\n // Re-read before write so another tab that won the race remains authoritative.\n const latest = readStoredMap(sessionId);\n const concurrentId = latest.entries[key];\n if (isValidTransactionId(concurrentId)) {\n transactionIds.set(key, concurrentId);\n return concurrentId;\n }\n latest.entries[key] = transactionId;\n writeStoredMap(latest);\n return transactionId;\n}\n\nexport function resetAutomaticTransactionIdsForTests(): void {\n transactionIds.clear();\n legacyCounter = 0;\n}\n","import type { ConversionGoal } from \"./conversion-config\";\n\nfunction hasNumberField<K extends string>(\n metadata: Readonly<Record<string, unknown>>,\n key: K,\n): metadata is Readonly<Record<string, unknown> & Record<K, number>> {\n return typeof metadata[key] === \"number\";\n}\n\nfunction hasStringField<K extends string>(\n metadata: Readonly<Record<string, unknown>>,\n key: K,\n): metadata is Readonly<Record<string, unknown> & Record<K, string>> {\n return typeof metadata[key] === \"string\";\n}\n\n/** Shared automatic-goal matcher used by every SDK runtime. */\nexport function automaticThresholdMet(\n goal: ConversionGoal,\n eventType: string,\n metadata: Readonly<Record<string, unknown>>,\n): boolean {\n const trigger = goal.trigger;\n if (!trigger || trigger.event_type !== eventType) return false;\n switch (eventType) {\n case \"scroll_depth\":\n return (\n hasNumberField(metadata, \"depth_percent\") &&\n trigger.threshold_percent != null &&\n metadata.depth_percent >= trigger.threshold_percent\n );\n case \"time_on_site\":\n return (\n hasNumberField(metadata, \"duration_ms\") &&\n trigger.threshold_seconds != null &&\n metadata.duration_ms >= trigger.threshold_seconds * 1000\n );\n case \"multi_page_session\":\n return (\n hasNumberField(metadata, \"page_count\") &&\n trigger.page_threshold != null &&\n metadata.page_count >= trigger.page_threshold\n );\n case \"specific_page_visit\":\n return hasStringField(metadata, \"page_name\") && metadata.page_name === trigger.page_name;\n case \"page_view\":\n case \"form_start\":\n case \"phone_click\":\n return true;\n default:\n return false;\n }\n}\n","/**\n * Format an ISO timestamp in a specific IANA time zone (e.g. `America/Toronto`),\n * so dashboards stop hand-rolling `Intl`. Defaults to a short date-time; pass\n * `opts` to override fields. The `timeZone` is always forced to the argument.\n */\nexport function formatDateInTz(\n iso: string,\n timeZone: string,\n opts?: Intl.DateTimeFormatOptions,\n locale?: string,\n): string {\n const date = new Date(iso);\n // Guard malformed input: Intl.format(Invalid Date) throws a RangeError.\n if (Number.isNaN(date.getTime())) return iso;\n return new Intl.DateTimeFormat(locale, {\n year: \"numeric\",\n month: \"short\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n ...opts,\n timeZone,\n }).format(date);\n}\n","import type { SupportedCurrency } from \"./schema\";\n\n/**\n * Money conversion helpers.\n *\n * The API speaks **integer minor units (cents)** exclusively. These helpers move\n * between a human-facing major amount (dollars) and cents, and format cents for\n * display — so a consumer always has both representations without float math.\n */\n\n// Minor-unit exponent per supported currency (USD/CAD = 2 decimal places).\nconst MINOR_UNIT_EXPONENT: Record<SupportedCurrency, number> = {\n USD: 2,\n CAD: 2,\n};\n\nfunction exponentFor(currency: SupportedCurrency): number {\n return MINOR_UNIT_EXPONENT[currency] ?? 2;\n}\n\n/**\n * Convert a major amount (dollars `250.5`) to integer minor units (`25050`).\n *\n * Convenience only — the wire is always integer cents. Uses float multiply +\n * `Math.round`, so values that aren't exactly representable in binary float\n * (e.g. `1.005`) can round to the neighbouring cent. If you already hold an\n * exact cents integer, pass it straight through and skip this helper.\n */\nexport function toMinor(amount: number, currency: SupportedCurrency): number {\n return Math.round(amount * 10 ** exponentFor(currency));\n}\n\n/** Convert integer minor units (`25050`) to a major amount (`250.5`). */\nexport function fromMinor(cents: number, currency: SupportedCurrency): number {\n return cents / 10 ** exponentFor(currency);\n}\n\n/**\n * Format integer minor units as a localized currency string (e.g. `\"$250.50\"`).\n * Uses the built-in `Intl.NumberFormat` — no extra dependency.\n */\nexport function formatMoney(cents: number, currency: SupportedCurrency, locale?: string): string {\n return new Intl.NumberFormat(locale, { style: \"currency\", currency }).format(\n fromMinor(cents, currency),\n );\n}\n\n// Hoisted to `resources/intl/date` so the calendar resource shares the same\n// binding; still public API via `sales-public.ts`.\nexport { formatDateInTz } from \"../intl/date\";\n","import { applyDefaultConsentState, isValidGtagId, loadGtagScript } from \"../gtag\";\nimport {\n parseConversionConfig,\n type ConversionConfig,\n type ConversionGoal,\n} from \"./conversion-config\";\nimport { fireConversionWithConsent } from \"./conversion-firing\";\nimport { getAutomaticTransactionId } from \"./automatic-transaction\";\nimport { automaticThresholdMet } from \"./automatic-trigger\";\nimport { fromMinor } from \"./sales/money\";\nimport type { SupportedCurrency } from \"./sales/schema\";\n\n/**\n * Where a business's published tracking config lives.\n *\n * `businessId` + `environment` are the stable identity; the ORIGIN it is fetched\n * from is deployment-specific (production CDN vs. a local object store), which is\n * why `cdnBaseUrl` exists. Codegen bakes only the identity, so one committed\n * generated file works in every environment and only an env var changes.\n *\n * `cdnUrl` remains supported and WINS when present — every client repo generated\n * before `cdnBaseUrl` passes one, and those must keep working untouched.\n */\nexport interface TrackingConfigReference {\n /**\n * Fully-resolved object URL. Optional: omit it and pass `cdnBaseUrl` (or rely\n * on the production default) to have it composed from the identity below.\n */\n cdnUrl?: string;\n /**\n * Origin (optionally with a path prefix) the config object is served from, e.g.\n * `https://demos.aranova.io` in production or\n * `http://localhost:9100/aranova-demos` against a local MinIO. Ignored when\n * `cdnUrl` is set; blank or omitted falls back to {@link DEFAULT_CDN_BASE_URL}.\n * `tracking-cli gen` wires this to an env var so retargeting is config, not code.\n */\n cdnBaseUrl?: string;\n businessId: string;\n environment: \"production\" | \"test\";\n}\n\n/** Production object-storage origin — the default when nothing overrides it. */\nexport const DEFAULT_CDN_BASE_URL = \"https://demos.aranova.io\";\n\n/**\n * Object key for a business's config, mirroring the backend's\n * `core/storage.py::tracking_config_key`. The backend stays the authority: it\n * publishes at this key and returns the absolute URL, which is what the CLI bakes\n * as the legacy `cdnUrl`. This is the composition path for references that carry\n * identity instead of a URL — the `v1` prefix is the schema MAJOR and must move in\n * lockstep with the backend if it is ever cut to `v2`.\n */\nfunction trackingConfigKey(businessId: string, environment: \"production\" | \"test\"): string {\n return `tracking-config/v1/${businessId}-${environment}.json`;\n}\n\n/**\n * The URL a reference resolves to. An explicit `cdnUrl` wins (back-compat);\n * otherwise compose from `cdnBaseUrl` (or the production default).\n *\n * A blank/whitespace `cdnBaseUrl` is treated as UNSET rather than composed: the\n * generated module reads it from an env var, and a var that is present-but-empty\n * (a stray `NEXT_PUBLIC_ARANOVA_CDN_BASE_URL=` line) would otherwise produce\n * `/tracking-config/...` — a same-origin request to the client's own site.\n */\nexport function resolveTrackingConfigUrl(ref: TrackingConfigReference): string {\n if (ref.cdnUrl) return ref.cdnUrl;\n const configured = ref.cdnBaseUrl?.trim();\n const base = (configured || DEFAULT_CDN_BASE_URL).replace(/\\/+$/, \"\");\n return `${base}/${trackingConfigKey(ref.businessId, ref.environment)}`;\n}\n\ntype RuntimeState = \"unconfirmed\" | \"active\" | \"tombstone\";\n\ninterface CachedEntry {\n etag: string | null;\n config: ConversionConfig;\n}\n\ninterface QueuedConversion {\n key: string;\n value?: number | null;\n currency?: string | null;\n transactionId?: string | null;\n}\n\nexport type TrackingConfigConversionOptions = Omit<QueuedConversion, \"key\">;\n\ninterface QueuedPageView {\n href: string;\n title: string | null;\n referrer: string | null;\n}\n\ninterface QueuedAutomaticEvent {\n eventType: string;\n metadata: Record<string, unknown>;\n transactionPath: string;\n transactionScope: string;\n}\n\nconst CACHE_PREFIX = \"_aranova_cfg_runtime_\";\nconst AUTHORITY_TTL_MS = 60_000;\n// Queues are bounded rather than cleared while authority is unconfirmed: the\n// config can appear at any time (a first publish, or R2 recovering), and the\n// most recent items are still worth firing when it does. Unbounded, a site whose\n// config 404s accumulates an entry per page view for the life of the tab.\nconst MAX_QUEUE_LENGTH = 50;\n// While unconfirmed, revalidation is spaced by a growing delay instead of riding\n// every queued item. Without it a missing config produces one no-cache request\n// per page view, forever. `focus` / `visibilitychange` still revalidate, so\n// recovery stays prompt once the object exists.\nconst RETRY_BASE_MS = 5_000;\nconst RETRY_MAX_MS = 5 * 60_000;\n\nconst runtimes = new Map<string, TrackingConfigRuntime>();\nconst configuredIds = new Set<string>();\nlet scriptLoad: Promise<void> | null = null;\nlet jsInitialized = false;\n\nfunction cacheKey(url: string): string {\n return `${CACHE_PREFIX}${url}`;\n}\n\n/** Append, dropping the oldest entry once the cap is reached. */\nfunction pushBounded<T>(queue: T[], item: T): void {\n queue.push(item);\n if (queue.length > MAX_QUEUE_LENGTH) queue.splice(0, queue.length - MAX_QUEUE_LENGTH);\n}\n\nfunction readCache(url: string): CachedEntry | null {\n if (typeof window === \"undefined\") return null;\n try {\n const raw = window.sessionStorage.getItem(cacheKey(url));\n if (!raw) return null;\n const parsed = JSON.parse(raw) as { etag?: unknown; config?: unknown };\n const config = parseConversionConfig(parsed.config);\n if (!config) return null;\n return {\n etag: typeof parsed.etag === \"string\" ? parsed.etag : null,\n config,\n };\n } catch {\n return null;\n }\n}\n\nfunction writeCache(url: string, entry: CachedEntry): void {\n if (typeof window === \"undefined\") return;\n try {\n window.sessionStorage.setItem(cacheKey(url), JSON.stringify(entry));\n } catch {\n // sessionStorage unavailable — runtime still works, just without a conditional candidate\n }\n}\n\nfunction isTombstone(config: ConversionConfig): boolean {\n return config.google_tracking_state === \"disabled\" || Object.keys(config.gtag_ids).length === 0;\n}\n\nfunction validateConfig(config: ConversionConfig, ref: TrackingConfigReference): boolean {\n return (\n config.business_id === ref.businessId &&\n config.environment === ref.environment &&\n (config.google_tracking_state === \"active\" || config.google_tracking_state === \"disabled\")\n );\n}\n\nfunction pageViewSnapshot(): QueuedPageView | null {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return null;\n return {\n href: window.location.href,\n title: document.title || null,\n referrer: document.referrer || null,\n };\n}\n\nfunction ensureScript(gtagId: string): Promise<void> {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return Promise.resolve();\n applyDefaultConsentState();\n loadGtagScript(gtagId);\n if (scriptLoad) return scriptLoad;\n scriptLoad = new Promise((resolve) => {\n const script = document.querySelector<HTMLScriptElement>(\n 'script[data-aranova-tracking=\"aranova-gtag-loader\"]',\n );\n if (!script) {\n resolve();\n return;\n }\n if ((script as HTMLScriptElement & { dataset: DOMStringMap }).dataset.loaded === \"true\") {\n resolve();\n return;\n }\n window.setTimeout(resolve, 0);\n script.addEventListener(\n \"load\",\n () => {\n script.dataset.loaded = \"true\";\n resolve();\n },\n { once: true },\n );\n script.addEventListener(\"error\", () => resolve(), { once: true });\n });\n return scriptLoad;\n}\n\nexport class TrackingConfigRuntime {\n private readonly fetchImpl: typeof fetch;\n /** Resolved config URL — see the constructor for why it is computed once. */\n private readonly url: string;\n private current: ConversionConfig | null = null;\n private etag: string | null = null;\n private stateValue: RuntimeState = \"unconfirmed\";\n private confirmedAt = 0;\n private authorityGeneration = 0;\n private inFlight: Promise<void> | null = null;\n private flushInFlight: Promise<void> | null = null;\n private flushRequested = false;\n private retryTimer: number | null = null;\n private started = false;\n /** Consecutive failed authority attempts — drives the revalidate backoff. */\n private authorityFailures = 0;\n /** Epoch ms before which `ensureAuthority` must not issue another request. */\n private nextAuthorityAttemptAt = 0;\n private readonly conversionQueue: QueuedConversion[] = [];\n private readonly automaticQueue: QueuedAutomaticEvent[] = [];\n private readonly pageQueue: QueuedPageView[] = [];\n private readonly listeners = new Set<() => void>();\n\n constructor(\n readonly ref: TrackingConfigReference,\n fetchImpl: typeof fetch = globalThis.fetch,\n ) {\n // Native browser fetch requires Window/WorkerGlobalScope as its receiver.\n // Calling an unbound native fetch stored on `this` throws \"Illegal invocation\".\n this.fetchImpl = fetchImpl.bind(globalThis);\n // Resolved once: the cache key, the fetch target, and the write-back key must\n // all be the same string, or a reference that composes its URL would read a\n // cache entry it never writes.\n this.url = resolveTrackingConfigUrl(ref);\n const cached = readCache(this.url);\n this.current = cached?.config ?? null;\n this.etag = cached?.etag ?? null;\n this.start();\n }\n\n /** The URL this runtime actually fetches (composed or explicit). */\n configUrl(): string {\n return this.url;\n }\n\n /**\n * Explicitly start authority resolution and Google-tag bootstrap.\n *\n * Idempotent so framework effects can call it after hydration without\n * depending on constructor timing.\n */\n start(): void {\n if (this.started) {\n void this.flush();\n return;\n }\n this.started = true;\n void this.revalidate();\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"visibilitychange\", () => {\n if (document.visibilityState === \"visible\") void this.revalidate();\n });\n window.addEventListener(\"focus\", () => void this.revalidate());\n }\n }\n\n state(): RuntimeState {\n return this.stateValue;\n }\n\n config(): ConversionConfig | null {\n return this.stateValue === \"active\" || this.stateValue === \"tombstone\" ? this.current : null;\n }\n\n __unsafeExpireAuthorityForTests(): void {\n this.confirmedAt = Number.NEGATIVE_INFINITY;\n this.nextAuthorityAttemptAt = 0;\n }\n\n /** Queue depths — asserted by tests to pin the bound. */\n __queueDepthsForTests(): { conversions: number; automatic: number; pages: number } {\n return {\n conversions: this.conversionQueue.length,\n automatic: this.automaticQueue.length,\n pages: this.pageQueue.length,\n };\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n async ensureAuthority(): Promise<boolean> {\n if (this.stateValue !== \"unconfirmed\" && Date.now() - this.confirmedAt < AUTHORITY_TTL_MS) {\n return true;\n }\n // Backoff applies only to this implicit path (driven by queued work). An\n // explicit `revalidate()` — the visibility/focus listeners, or a caller —\n // always goes to the network so recovery is never delayed by the timer.\n if (Date.now() < this.nextAuthorityAttemptAt) return false;\n await this.revalidateAuthority();\n return this.stateValue !== \"unconfirmed\" && Date.now() - this.confirmedAt < AUTHORITY_TTL_MS;\n }\n\n async revalidate(): Promise<void> {\n this.nextAuthorityAttemptAt = 0;\n await this.revalidateAuthority();\n await this.flush();\n }\n\n private async revalidateAuthority(): Promise<void> {\n if (typeof window === \"undefined\" || !this.fetchImpl) return;\n if (this.inFlight) return this.inFlight;\n this.inFlight = this.revalidateNow().finally(() => {\n this.inFlight = null;\n });\n return this.inFlight;\n }\n\n queuePageView(snapshot: QueuedPageView | null = pageViewSnapshot()): void {\n if (!snapshot) return;\n pushBounded(this.pageQueue, snapshot);\n void this.flush();\n }\n\n fireConversion(key: string, options?: TrackingConfigConversionOptions): void {\n pushBounded(this.conversionQueue, { key, ...options });\n void this.flush();\n }\n\n queueAutomaticEvent(\n eventType: string,\n metadata: Record<string, unknown>,\n transactionPath: string,\n transactionScope: string,\n ): void {\n pushBounded(this.automaticQueue, {\n eventType,\n metadata,\n transactionPath,\n transactionScope,\n });\n void this.flush();\n }\n\n listGoals(): ConversionGoal[] {\n return this.current?.goals ?? [];\n }\n\n private async revalidateNow(): Promise<void> {\n try {\n const headers: Record<string, string> = {};\n if (this.etag) headers[\"If-None-Match\"] = this.etag;\n const response = await this.fetchImpl(this.url, {\n method: \"GET\",\n headers,\n cache: \"no-cache\",\n });\n if (response.status === 304 && this.current && validateConfig(this.current, this.ref)) {\n this.confirm(this.current, this.etag);\n return;\n }\n if (!response.ok) {\n this.expireAuthority();\n return;\n }\n const next = parseConversionConfig(await response.json());\n if (!next || !validateConfig(next, this.ref)) {\n this.expireAuthority();\n return;\n }\n if (this.current && next.config_version < this.current.config_version) {\n this.expireAuthority();\n return;\n }\n this.confirm(next, response.headers.get(\"ETag\"));\n } catch {\n this.expireAuthority();\n }\n }\n\n private expireAuthority(): void {\n this.authorityGeneration += 1;\n if (this.stateValue !== \"unconfirmed\") this.stateValue = \"unconfirmed\";\n // Exponential, capped. Queued work keeps accumulating (bounded), so the\n // config appearing later still fires the most recent items.\n this.authorityFailures += 1;\n const delay = Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** (this.authorityFailures - 1));\n this.nextAuthorityAttemptAt = Date.now() + delay;\n }\n\n private confirm(config: ConversionConfig, etag: string | null): void {\n this.authorityGeneration += 1;\n this.current = config;\n this.etag = etag;\n this.confirmedAt = Date.now();\n this.authorityFailures = 0;\n this.nextAuthorityAttemptAt = 0;\n this.stateValue = isTombstone(config) ? \"tombstone\" : \"active\";\n writeCache(this.url, { etag, config });\n if (this.stateValue === \"tombstone\") {\n if (this.retryTimer !== null) {\n window.clearTimeout(this.retryTimer);\n this.retryTimer = null;\n }\n this.conversionQueue.length = 0;\n this.automaticQueue.length = 0;\n this.pageQueue.length = 0;\n }\n for (const listener of this.listeners) listener();\n }\n\n private async flush(): Promise<void> {\n if (this.flushInFlight) {\n this.flushRequested = true;\n return this.flushInFlight;\n }\n this.flushRequested = false;\n this.flushInFlight = this.flushNow().finally(() => {\n this.flushInFlight = null;\n if (this.flushRequested && this.stateValue === \"active\") void this.flush();\n });\n return this.flushInFlight;\n }\n\n private scheduleRetry(): void {\n if (this.retryTimer !== null || typeof window === \"undefined\") return;\n this.retryTimer = window.setTimeout(() => {\n this.retryTimer = null;\n void this.flush();\n }, 1000);\n }\n\n private async flushNow(): Promise<void> {\n if (!(await this.ensureAuthority())) return;\n if (this.stateValue !== \"active\" || !this.current) return;\n const config = this.current;\n const generation = this.authorityGeneration;\n const ids = Object.values(config.gtag_ids).filter(\n (id): id is string => typeof id === \"string\" && isValidGtagId(id),\n );\n if (ids.length === 0) return;\n await ensureScript(ids[0]!);\n if (\n this.authorityGeneration !== generation ||\n this.stateValue !== \"active\" ||\n this.current !== config\n ) {\n return;\n }\n const gtag = window.gtag;\n if (typeof gtag !== \"function\") return;\n try {\n if (!jsInitialized) {\n gtag(\"js\", new Date());\n jsInitialized = true;\n }\n for (const id of ids) {\n if (configuredIds.has(id)) continue;\n gtag(\"config\", id, { send_page_view: false });\n configuredIds.add(id);\n }\n } catch {\n this.scheduleRetry();\n return;\n }\n while (this.pageQueue.length > 0) {\n const page = this.pageQueue[0]!;\n try {\n gtag(\"event\", \"page_view\", {\n page_location: page.href,\n page_title: page.title ?? undefined,\n page_referrer: page.referrer ?? undefined,\n });\n this.pageQueue.shift();\n } catch {\n this.scheduleRetry();\n return;\n }\n }\n while (this.automaticQueue.length > 0) {\n const event = this.automaticQueue[0]!;\n for (const goal of config.goals) {\n if (goal.kind !== \"event\" || !goal.firing) continue;\n if (!automaticThresholdMet(goal, event.eventType, event.metadata)) continue;\n pushBounded(this.conversionQueue, {\n key: goal.key,\n transactionId: getAutomaticTransactionId(\n event.transactionScope,\n goal.key,\n event.transactionPath,\n ),\n });\n }\n this.automaticQueue.shift();\n }\n while (this.conversionQueue.length > 0) {\n const item = this.conversionQueue[0]!;\n const goal = config.goals.find((g) => g.key === item.key);\n const firing = goal?.firing;\n if (!firing) {\n this.conversionQueue.shift();\n continue;\n }\n const currency = item.currency ?? firing.currency ?? null;\n const value =\n item.value ??\n (firing.value_cents != null && currency\n ? fromMinor(firing.value_cents, currency as SupportedCurrency)\n : null);\n const outcome = fireConversionWithConsent({\n sendTo: firing.send_to,\n value,\n currency,\n transactionId: item.transactionId ?? null,\n });\n if (outcome === \"retryable\") {\n this.scheduleRetry();\n return;\n }\n this.conversionQueue.shift();\n }\n }\n}\n\nexport function getTrackingConfigRuntime(\n ref: TrackingConfigReference,\n fetchImpl?: typeof fetch,\n): TrackingConfigRuntime {\n // Keyed on the RESOLVED url: `{cdnUrl}` and an equivalent\n // `{cdnBaseUrl,businessId,environment}` name the same object and must share one\n // runtime, or each would keep its own authority state and gtag bootstrap.\n const key = `${resolveTrackingConfigUrl(ref)}|${ref.businessId}|${ref.environment}`;\n const existing = runtimes.get(key);\n if (existing) return existing;\n const runtime = new TrackingConfigRuntime(ref, fetchImpl ?? globalThis.fetch);\n runtimes.set(key, runtime);\n return runtime;\n}\n\nexport function resetTrackingConfigRuntimesForTests(): void {\n runtimes.clear();\n configuredIds.clear();\n scriptLoad = null;\n jsInitialized = false;\n}\n","// Auto-fire on-page conversions for AUTOMATIC event-goals (GAP28 / unified-goal ADR).\n//\n// The SDK's automatic detectors (scroll_depth, time_on_site, multi_page_session,\n// specific_page_visit, page_view, form_start) already emit analytics events via\n// `client.trackEvent`. This layer observes those events and ALSO fires a\n// `gtag('event','conversion')` when a published EVENT-goal's trigger threshold is met — so the\n// consumer writes ZERO conversion code for automatic goals (the config drives everything).\n//\n// `phone_click` is the one manual event we ALSO auto-fire: a `tel:` tap (captured by\n// `attachPhoneClickCapture`) is an unambiguous on-site conversion, so a linked phone_click\n// event-goal fires with zero consumer code (see thresholdMet). The other manual event-goals\n// (form_submit/cta_click) are NOT auto-fired — the consumer fires them via `trackConversion`.\n// Sales fire via `recordSale`.\n\nimport type { TrackingClient, TrackEventInput } from \"../ingest\";\nimport { getAutomaticTransactionId } from \"./automatic-transaction\";\nimport { automaticThresholdMet } from \"./automatic-trigger\";\nimport type { ConversionConfigStore } from \"./conversion-config\";\nimport { fireConversionWithConsent } from \"./conversion-firing\";\nimport { fromMinor } from \"./sales/money\";\nimport type { SupportedCurrency } from \"./sales/schema\";\nimport type { TrackingConfigRuntime } from \"./tracking-config-runtime\";\n\nfunction currentPath(): string {\n return typeof window === \"undefined\" ? \"\" : window.location.pathname;\n}\n\nexport interface ConversionAutoFire {\n /** Fire any matching automatic event-goal's conversion for a just-emitted detector event. */\n onAutomaticEvent(\n eventType: string,\n metadata: Record<string, unknown>,\n transactionScope: string,\n ): void;\n}\n\n// Bound the pre-config buffer so a page that never resolves its config (offline, bad\n// URL) can't grow it without limit.\nconst MAX_BUFFERED_EVENTS = 50;\n\n/** Build the auto-fire matcher bound to a config store. */\nexport function createConversionAutoFire(\n store:\n | Pick<ConversionConfigStore, \"listGoals\" | \"isReady\" | \"onResolve\">\n | Pick<TrackingConfigRuntime, \"listGoals\" | \"fireConversion\" | \"queueAutomaticEvent\">,\n): ConversionAutoFire {\n // Detectors fire synchronously, but the CDN config resolves async. A detector can emit\n // before a cold-cache fetch lands (an early real scroll, a fast time_on_site threshold,\n // the initial page_view) and won't re-emit on the same page. Buffer events that arrive\n // before the config is ready and replay them on the first resolve, so an early trigger\n // still converts (a beat late) instead of being silently dropped.\n const pending: Array<{\n eventType: string;\n metadata: Record<string, unknown>;\n transactionScope: string;\n }> = [];\n let subscribed = false;\n\n function fireMatching(\n eventType: string,\n metadata: Record<string, unknown>,\n transactionScope: string,\n ): void {\n for (const goal of store.listGoals()) {\n if (goal.kind !== \"event\" || !goal.firing) continue;\n if (!automaticThresholdMet(goal, eventType, metadata)) continue;\n const transactionId = getAutomaticTransactionId(transactionScope, goal.key, currentPath());\n if (\"queueAutomaticEvent\" in store) {\n store.fireConversion(goal.key, {\n transactionId,\n });\n continue;\n }\n const firing = goal.firing;\n const cents = firing.value_cents ?? null;\n const currency = firing.currency ?? null;\n fireConversionWithConsent({\n sendTo: firing.send_to,\n value: cents != null && currency ? fromMinor(cents, currency as SupportedCurrency) : null,\n currency,\n transactionId,\n });\n }\n }\n\n return {\n onAutomaticEvent(eventType, metadata, transactionScope) {\n if (\"queueAutomaticEvent\" in store) {\n store.queueAutomaticEvent(eventType, metadata, currentPath(), transactionScope);\n return;\n }\n if (store.isReady()) {\n fireMatching(eventType, metadata, transactionScope);\n return;\n }\n // Config still loading — buffer (bounded) and replay on the first resolve.\n if (pending.length < MAX_BUFFERED_EVENTS) {\n pending.push({ eventType, metadata, transactionScope });\n }\n if (!subscribed) {\n subscribed = true;\n store.onResolve(() => {\n const buffered = pending.splice(0);\n for (const event of buffered) {\n fireMatching(event.eventType, event.metadata, event.transactionScope);\n }\n });\n }\n },\n };\n}\n\n/**\n * Wrap a {@link TrackingClient} so every automatic event it tracks ALSO drives conversion\n * auto-fire. Pass the wrapped client to the `attach*` detectors. The auto-fire is best-effort\n * and never breaks ingest.\n */\nexport function withConversionAutoFire(\n client: TrackingClient,\n autoFire: ConversionAutoFire,\n): TrackingClient {\n return {\n ...client,\n trackEvent: (input: TrackEventInput) => {\n client.trackEvent(input);\n try {\n autoFire.onAutomaticEvent(input.eventType, input.metadata ?? {}, client.getSessionId());\n } catch {\n // never let conversion firing break analytics ingest\n }\n },\n };\n}\n","// Visitor + session identity for the tracking SDK.\n//\n// Visitor: persistent localStorage UUID, never expires until the user clears\n// browser storage. Used for cross-session correlation.\n//\n// Session: rolling 30-minute idle window. Regenerated when more than\n// SESSION_IDLE_MS has passed since the last event. Matches the behavior of\n// GA4, PostHog, Mixpanel, etc., so analytics is comparable.\n\nimport { clearLandingRecord } from \"./landing\";\n\n/**\n * localStorage key for the persistent visitor id.\n */\nexport const VISITOR_STORAGE_KEY = \"aranova_tracking_visitor\";\n\n/**\n * localStorage key for the rolling session id state.\n */\nexport const SESSION_STORAGE_KEY = \"aranova_tracking_session\";\n\n/**\n * Idle window before a new session id is created.\n */\nexport const SESSION_IDLE_MS = 30 * 60 * 1000;\n\n/**\n * Serialized session state stored in localStorage.\n */\nexport interface StoredSession {\n /** Client-generated session UUID. */\n id: string;\n /** Unix timestamp in milliseconds for the most recent event/session touch. */\n last_event_at: number;\n}\n\nfunction safeUuid(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\")\n return crypto.randomUUID();\n // Fallback for ancient browsers — not cryptographically perfect but unique enough.\n return `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}-${Math.random().toString(16).slice(2)}`;\n}\n\nfunction readLocalStorage(key: string): string | null {\n try {\n return window.localStorage.getItem(key);\n } catch {\n return null;\n }\n}\n\nfunction writeLocalStorage(key: string, value: string): void {\n try {\n window.localStorage.setItem(key, value);\n } catch {\n // Storage may be denied (private mode, blocked cookies, quota). Caller is\n // responsible for degrading gracefully.\n }\n}\n\n/**\n * Return the persistent visitor id for this browser profile.\n *\n * Creates and stores a new id when one does not already exist. During SSR,\n * returns an ephemeral id because browser storage is unavailable.\n */\nexport function getVisitorId(): string {\n if (typeof window === \"undefined\") return safeUuid();\n\n const existing = readLocalStorage(VISITOR_STORAGE_KEY);\n if (existing && existing.length > 0) return existing;\n\n const fresh = safeUuid();\n writeLocalStorage(VISITOR_STORAGE_KEY, fresh);\n return fresh;\n}\n\n/**\n * Result from `getOrRotateSessionId()`.\n */\nexport interface SessionIdResult {\n /** Current session id. */\n id: string;\n /** Whether this call created a new session. */\n isNew: boolean;\n}\n\n/**\n * Return the current session id, rotating it after the idle window expires.\n *\n * Also refreshes `last_event_at` for active sessions.\n */\nexport function getOrRotateSessionId(now: number = Date.now()): SessionIdResult {\n if (typeof window === \"undefined\") return { id: safeUuid(), isNew: true };\n\n const raw = readLocalStorage(SESSION_STORAGE_KEY);\n if (raw) {\n try {\n const parsed = JSON.parse(raw) as Partial<StoredSession>;\n if (typeof parsed.id === \"string\" && typeof parsed.last_event_at === \"number\") {\n if (now - parsed.last_event_at <= SESSION_IDLE_MS) {\n const refreshed: StoredSession = { id: parsed.id, last_event_at: now };\n writeLocalStorage(SESSION_STORAGE_KEY, JSON.stringify(refreshed));\n return { id: parsed.id, isNew: false };\n }\n }\n } catch {\n // Fall through to a fresh session.\n }\n }\n\n const fresh: StoredSession = { id: safeUuid(), last_event_at: now };\n writeLocalStorage(SESSION_STORAGE_KEY, JSON.stringify(fresh));\n return { id: fresh.id, isNew: true };\n}\n\n/**\n * Clear visitor and session identity from localStorage, including the\n * session-scoped landing record (a landing must never outlive its session).\n *\n * Intended for tests, debugging, and explicit user reset flows.\n */\nexport function resetTrackingIdentity(): void {\n clearLandingRecord();\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.removeItem(VISITOR_STORAGE_KEY);\n window.localStorage.removeItem(SESSION_STORAGE_KEY);\n } catch {\n // ignored\n }\n}\n","import { z } from \"zod\";\n\n/**\n * Metadata for the automatic `page_view` event.\n *\n * The SDK emits this on initial load, SPA route changes, and bfcache restores.\n * Consumers do not call `trackEvent('page_view', ...)`; registering\n * `automatic: { page_view: {} }` enables the SDK-owned trigger.\n */\nexport const pageViewMetadataSchema = z\n .object({\n page: z\n .object({\n title: z.string().nullable(),\n path: z.string(),\n search: z.string(),\n hash: z.string(),\n })\n .strict(),\n referrer: z.string().nullable(),\n // `.nullable().optional()` — absent (undefined) OR explicit null OR a\n // real viewport object. Mirrors Pydantic's `_Viewport | None = None`\n // on the backend side so the drift test stays clean.\n viewport: z\n .object({\n w: z.number(),\n h: z.number(),\n })\n .strict()\n .nullable()\n .optional(),\n })\n .strict();\n\nexport type PageViewMetadata = z.infer<typeof pageViewMetadataSchema>;\n\n/**\n * Registration config for automatic `page_view`.\n *\n * `page_view` is required in every trigger registry and currently has no\n * options. Use `{ page_view: {} }`.\n */\nexport const pageViewConfigSchema = z.object({}).strict();\nexport type PageViewConfig = z.infer<typeof pageViewConfigSchema>;\n","// Auto page_view emission. Fires once on attach, then again on every SPA\n// navigation. Detects navigation via three signals:\n// - history.pushState (patched)\n// - history.replaceState (patched)\n// - popstate event (back/forward buttons)\n// - pageshow with event.persisted === true (back-forward cache restore)\n//\n// The Next.js provider can opt out of this and use `usePathname` instead so\n// it picks up App Router transitions reliably without monkey-patching globals.\n\nimport { pageViewMetadataSchema, type PageViewMetadata } from \"./events/page-view\";\nimport type { TrackingClient } from \"./ingest\";\n\n// Re-export so existing callers that import `PageViewMetadata` from\n// `./page-view` keep compiling. The canonical definition now lives in\n// `events/page-view.ts` and is derived from a Zod schema.\nexport type { PageViewMetadata } from \"./events/page-view\";\n\n/**\n * Session-storage key used to maintain the in-tab SPA referrer chain.\n */\nexport const LAST_FIRED_URL_STORAGE_KEY = \"aranova_tracking_last_fired_url\";\n\n// Tracks the previous in-session URL we fired a page_view for. SPA\n// navigation never updates `document.referrer` (the document is never\n// reloaded), so all events would otherwise share the same stale referrer\n// value. We track it ourselves: the referrer for an event at URL X is the\n// last URL we fired a page_view for, falling back to document.referrer for\n// the very first event of the session.\n//\n// Hybrid storage: the in-memory variable is the runtime source of truth\n// (cheap reads, no quota concerns), and sessionStorage is the durability\n// layer (survives full-page reloads and bfcache restoration). On first\n// read per JS context we lazily hydrate from sessionStorage; on every\n// write we update both layers. If sessionStorage is unavailable (private\n// mode, blocked extensions, quota errors) we silently fall back to\n// memory-only — the SDK stays functional, just loses cross-reload\n// referrer continuity in that one tab.\nlet lastFiredUrl: string | null = null;\nlet lastFiredUrlHydrated = false;\n\nfunction readSessionStorage(key: string): string | null {\n try {\n if (typeof window === \"undefined\") return null;\n return window.sessionStorage.getItem(key);\n } catch {\n return null;\n }\n}\n\nfunction writeSessionStorage(key: string, value: string): void {\n try {\n if (typeof window === \"undefined\") return;\n window.sessionStorage.setItem(key, value);\n } catch {\n // private mode / blocked / quota — memory-only is fine\n }\n}\n\nfunction deleteSessionStorage(key: string): void {\n try {\n if (typeof window === \"undefined\") return;\n window.sessionStorage.removeItem(key);\n } catch {\n // ignore\n }\n}\n\nfunction getLastFiredUrl(): string | null {\n if (!lastFiredUrlHydrated) {\n lastFiredUrlHydrated = true;\n const stored = readSessionStorage(LAST_FIRED_URL_STORAGE_KEY);\n if (stored !== null) lastFiredUrl = stored;\n }\n return lastFiredUrl;\n}\n\nfunction setLastFiredUrl(url: string): void {\n lastFiredUrl = url;\n lastFiredUrlHydrated = true;\n writeSessionStorage(LAST_FIRED_URL_STORAGE_KEY, url);\n}\n\n/**\n * Clear the in-session URL tracking. Primarily an escape hatch for tests\n * so each test starts with a fresh referrer chain; production code\n * doesn't need this — the singleton client lives for the page lifetime.\n */\nexport function resetPageViewState(): void {\n lastFiredUrl = null;\n lastFiredUrlHydrated = false;\n deleteSessionStorage(LAST_FIRED_URL_STORAGE_KEY);\n}\n\n/**\n * Build canonical `page_view` metadata from the current browser document.\n *\n * Returns `null` outside the browser.\n */\nexport function buildPageViewMetadata(referrerOverride?: string | null): PageViewMetadata | null {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return null;\n // Run the constructed object through the Zod schema so the shape is\n // validated even when the SDK itself is the one building it. If the\n // schema ever drifts from what buildPageViewMetadata emits, the parse\n // throws here and the event is dropped rather than being sent malformed.\n return pageViewMetadataSchema.parse({\n page: {\n title: document.title || null,\n path: window.location.pathname,\n search: window.location.search,\n hash: window.location.hash,\n },\n referrer: referrerOverride !== undefined ? referrerOverride : document.referrer || null,\n viewport: { w: window.innerWidth, h: window.innerHeight },\n });\n}\n\n/**\n * Fire a `page_view` event through the low-level client.\n *\n * Used internally by automatic page view triggers and bfcache restore\n * handling.\n */\nexport function fireManualPageView(client: TrackingClient): void {\n if (typeof window === \"undefined\") return;\n\n const currentHref = window.location.href;\n const previousFiredUrl = getLastFiredUrl();\n\n // Internal SPA referrer: the previous URL we fired a page_view for in this\n // tab. Only counts when it differs from the current URL (a same-URL re-fire\n // — e.g. React StrictMode double-mount in dev, or a bfcache restore to the\n // same page — should not produce a self-referencing referrer).\n const internalReferrer =\n previousFiredUrl !== null && previousFiredUrl !== currentHref ? previousFiredUrl : null;\n\n // External referrer: where the user came from before loading the app.\n // Used as the fallback for the very first page_view of the session.\n const externalReferrer = typeof document !== \"undefined\" ? document.referrer || null : null;\n\n const referrer = internalReferrer ?? externalReferrer;\n\n const metadata = buildPageViewMetadata(referrer);\n client.trackEvent({\n eventType: \"page_view\",\n pageUrl: currentHref,\n metadata: metadata as unknown as Record<string, unknown> | null,\n });\n\n // Only advance the in-session pointer when the URL actually changed, so a\n // same-URL re-fire never poisons the next event's referrer.\n if (currentHref !== previousFiredUrl) {\n setLastFiredUrl(currentHref);\n }\n}\n\n/**\n * Attach a back-forward cache restore listener in isolation. Used by\n * surfaces that have their own SPA detection (e.g. the Next.js provider\n * uses `usePathname`) but still want to capture bfcache restores, which\n * don't go through any router state change.\n *\n * Returns a detach function that removes the listener.\n */\nexport function attachBfcacheRestore(client: TrackingClient): () => void {\n if (typeof window === \"undefined\") return () => {};\n\n function handlePageShow(event: PageTransitionEvent): void {\n if (!event.persisted) return;\n fireManualPageView(client);\n }\n\n window.addEventListener(\"pageshow\", handlePageShow);\n return () => {\n window.removeEventListener(\"pageshow\", handlePageShow);\n };\n}\n\nexport interface AttachAutoPageViewOptions {\n /** Skip the initial fire on attach (useful when the host already fired one). */\n skipInitial?: boolean;\n}\n\n/**\n * Attach automatic page view tracking for a browser SPA.\n *\n * Patches history navigation, listens to `popstate`, fires the initial\n * page view unless disabled, and returns a detach function.\n */\nexport function attachAutoPageView(\n client: TrackingClient,\n options: AttachAutoPageViewOptions = {},\n): () => void {\n if (typeof window === \"undefined\" || typeof history === \"undefined\") {\n return () => {};\n }\n\n let lastPath = window.location.pathname + window.location.search;\n\n function maybeFire(): void {\n const current = window.location.pathname + window.location.search;\n if (current === lastPath) return;\n lastPath = current;\n fireManualPageView(client);\n }\n\n const originalPushState = history.pushState.bind(history);\n const originalReplaceState = history.replaceState.bind(history);\n\n function patchedPushState(this: History, ...args: Parameters<History[\"pushState\"]>): void {\n originalPushState(...args);\n // Defer one tick so the URL is settled before we read it.\n setTimeout(maybeFire, 0);\n }\n function patchedReplaceState(this: History, ...args: Parameters<History[\"replaceState\"]>): void {\n originalReplaceState(...args);\n setTimeout(maybeFire, 0);\n }\n\n // bfcache restore: when the user clicks an external link and hits the\n // back button, the browser can restore the page from its back-forward\n // cache without re-running any JS lifecycles. `popstate` does NOT fire\n // for bfcache restores, but `pageshow` does, with event.persisted === true.\n // When that happens we fire a fresh page_view so the session reflects\n // the re-entry.\n function handlePageShow(event: PageTransitionEvent): void {\n if (!event.persisted) return;\n fireManualPageView(client);\n }\n\n history.pushState = patchedPushState as History[\"pushState\"];\n history.replaceState = patchedReplaceState as History[\"replaceState\"];\n window.addEventListener(\"popstate\", maybeFire);\n window.addEventListener(\"pageshow\", handlePageShow);\n\n if (!options.skipInitial) fireManualPageView(client);\n\n return () => {\n history.pushState = originalPushState;\n history.replaceState = originalReplaceState;\n window.removeEventListener(\"popstate\", maybeFire);\n window.removeEventListener(\"pageshow\", handlePageShow);\n };\n}\n","// Builds the metadata payload for the sdk_heartbeat event. Called once per\n// new session to report the SDK version and registered trigger configuration\n// back to the Aranova API.\n\nimport type { SdkHeartbeatMetadata } from \"./events/sdk-heartbeat\";\nimport type { TriggerRegistryConfig } from \"./events/registry\";\nimport type { TrackingInstallSurface } from \"./types\";\n\n/**\n * Recursively serialize a value into a JSON-safe form. Converts RegExp\n * instances to their `.source` string so the trigger config can survive\n * `JSON.stringify` without losing information.\n */\nfunction serializeValue(value: unknown): unknown {\n if (value instanceof RegExp) return value.source;\n if (Array.isArray(value)) return value.map(serializeValue);\n if (value !== null && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n out[k] = serializeValue(v);\n }\n return out;\n }\n return value;\n}\n\n/**\n * Build metadata for the SDK-internal `sdk_heartbeat` event.\n *\n * The heartbeat reports package version, install surface, registered trigger\n * names, and non-empty trigger config so the dashboard can show site coverage.\n */\nexport function buildHeartbeatMetadata(\n surface: TrackingInstallSurface,\n sdkVersion: string | null,\n packageName: string | null,\n triggers: TriggerRegistryConfig | null,\n gtagIds: Record<string, string> | null = null,\n): SdkHeartbeatMetadata {\n const automaticNames = triggers ? Object.keys(triggers.automatic) : [];\n const manualNames = triggers?.manual ? Object.keys(triggers.manual) : [];\n\n // Build trigger_config: the init params per event, with RegExp values\n // converted to strings. Skip events with empty config objects.\n let triggerConfig: Record<string, Record<string, unknown>> | null = null;\n if (triggers) {\n const cfg: Record<string, Record<string, unknown>> = {};\n for (const [name, config] of Object.entries(triggers.automatic)) {\n const serialized = serializeValue(config) as Record<string, unknown>;\n if (Object.keys(serialized).length > 0) {\n cfg[name] = serialized;\n }\n }\n if (triggers.manual) {\n for (const [name, config] of Object.entries(triggers.manual)) {\n if (config === undefined) continue;\n const serialized = serializeValue(config) as Record<string, unknown>;\n if (Object.keys(serialized).length > 0) {\n cfg[name] = serialized;\n }\n }\n }\n if (Object.keys(cfg).length > 0) {\n triggerConfig = cfg;\n }\n }\n\n return {\n sdk_version: sdkVersion ?? \"unknown\",\n package_name: packageName,\n surface,\n triggers: {\n automatic: automaticNames,\n manual: manualNames,\n },\n trigger_config: triggerConfig,\n configured_gtag_ids: gtagIds,\n };\n}\n","// Tracking ingest client. Queues events, debounce-flushes them to the\n// /tracking/events endpoint, and degrades silently on errors so a broken\n// network never breaks the host site.\n\nimport { getRegisteredCapabilities } from \"./capabilities\";\nimport { getConsentChoice, getConsentState } from \"./consent\";\nimport { resetPageViewState } from \"./page-view\";\nimport type { PhoneConfig } from \"./phone-field\";\nimport { captureFbc, getFbcCookie, getFbpCookie } from \"./fbq\";\nimport {\n captureTrackingParamsFromLocation,\n createEmptyTrackingParams,\n getCookieValueFromDocument,\n getTrackingParamsFromCookieReader,\n mergeTrackingParams,\n} from \"./tracking\";\nimport type { TriggerRegistryConfig } from \"./events/registry\";\nimport { buildHeartbeatMetadata } from \"./heartbeat\";\nimport { buildLandingPayloadFields, getOrCaptureLandingParams } from \"./landing\";\nimport { getOrRotateSessionId, getVisitorId } from \"./session\";\nimport { stashUserDataFromFormFields } from \"./user-data\";\nimport type {\n TrackingClientContext,\n TrackingEnvironment,\n TrackingInstallSurface,\n TrackingParams,\n TrackingSessionUpsertPayload,\n} from \"./types\";\n\n/**\n * Default debounce window before queued events are flushed.\n */\nexport const DEFAULT_FLUSH_INTERVAL_MS = 2000;\n\n/**\n * Default queue size that triggers an immediate flush.\n */\nexport const DEFAULT_MAX_QUEUE_SIZE = 10;\n\n/**\n * Hard server-side maximum event count per request body.\n */\nexport const HARD_MAX_BATCH = 50;\n\n/**\n * Ceiling on the exponential backoff between failed delivery attempts.\n */\nexport const MAX_RETRY_BACKOFF_MS = 60_000;\n\n/**\n * Cap on events held in the durable retry buffer. Oldest batches are dropped\n * first once this is exceeded — an unbounded buffer would eventually blow the\n * localStorage quota and take the whole SDK down with it.\n */\nexport const MAX_BUFFERED_EVENTS = 200;\n\n/**\n * localStorage key prefix for the durable retry buffer. Versioned so a future\n * shape change can't be misread as the current one.\n */\nexport const RETRY_BUFFER_KEY_PREFIX = \"aranova_tracking_pending_v1\";\n\n/**\n * What to do with a batch after an attempted delivery.\n *\n * `retry` covers the transport failing and the server saying \"later\" (408, 429,\n * 5xx). `drop` covers a permanent rejection — a 422 from a malformed payload\n * will never succeed, and retrying it forever would wedge every batch behind it.\n */\ntype DeliveryOutcome = \"ok\" | \"retry\" | \"drop\";\n\n/**\n * Header used to authenticate public tracking ingest requests.\n */\nexport const API_KEY_HEADER = \"X-Aranova-Api-Key\";\n\n/**\n * Identity headers stamped on every ingest request. Duplicate fields already\n * present in `session.context` but survive body-parse failures so the backend\n * can attribute 422s to the offending SDK install.\n */\nexport const SDK_VERSION_HEADER = \"X-Aranova-Sdk-Version\";\nexport const SDK_PACKAGE_HEADER = \"X-Aranova-Sdk-Package\";\nexport const SDK_SURFACE_HEADER = \"X-Aranova-Sdk-Surface\";\nexport const SDK_ENVIRONMENT_HEADER = \"X-Aranova-Sdk-Environment\";\n\n/**\n * Configuration for the low-level ingest client.\n *\n * Framework packages usually create this for you through `createTracking()`.\n */\nexport interface TrackingClientConfig {\n /** Public tracking API key issued for the business. */\n apiKey: string;\n /** Tracking endpoint base URL, usually ending in `/tracking`. */\n endpoint: string;\n /** SDK surface creating this client. */\n surface: TrackingInstallSurface;\n /** Package version reported in session context and heartbeat metadata. */\n sdkVersion?: string;\n /** Package name reported in session context and heartbeat metadata. */\n packageName?: string;\n /** Trigger registry so the heartbeat can report registered events. */\n triggers?: TriggerRegistryConfig;\n /** Override the default 2s debounce window. */\n flushIntervalMs?: number;\n /** Override the default 10-event batch trigger. */\n maxQueueSize?: number;\n /** Deployment environment label reported in session context. */\n environment?: TrackingEnvironment;\n /** All active gtag IDs, keyed by label. Included in session context. */\n activeGtagIds?: Record<string, string>;\n /** When true, swallow nothing — useful for tests. */\n debug?: boolean;\n /** Phone-field config, carried for parity; the React hook reads it via context. */\n phone?: PhoneConfig;\n}\n\n/**\n * Input accepted by the low-level stringly-typed client.\n *\n * Prefer the typed `trackEvent(eventName, metadata)` facade exposed by\n * `useTracking()` in React/Next integrations.\n */\nexport interface TrackEventInput {\n /** Event name to enqueue. */\n eventType: string;\n /** URL associated with the event. Defaults to the current page URL. */\n pageUrl?: string | null;\n /** Event-specific metadata. */\n metadata?: Record<string, unknown> | null;\n /** Timestamp override. Defaults to queue time. */\n occurredAt?: Date | string | null;\n}\n\ninterface QueuedEvent {\n event_type: string;\n page_url: string | null;\n metadata: Record<string, unknown> | null;\n occurred_at: string | null;\n}\n\n/**\n * Low-level tracking client responsible for queueing and flushing events.\n */\nexport interface TrackingClient {\n /** Enqueue an event for batched delivery. */\n trackEvent: (input: TrackEventInput) => void;\n /** Flush queued events immediately (fetch, non-keepalive). */\n flush: () => Promise<void>;\n /**\n * Flush queued events through the keepalive transport so the request\n * survives document unload. Use from `pagehide`/`visibilitychange:hidden`\n * handlers — a plain `flush()` there is aborted by the browser on unload.\n */\n flushBeacon: () => void;\n /** Return the current rolling session id. */\n getSessionId: () => string;\n /** Return the persistent visitor id. */\n getVisitorId: () => string;\n /** Remove timers/listeners and prevent future flushes. */\n destroy: () => void;\n}\n\ninterface IngestRequestBody {\n session: TrackingSessionUpsertPayload;\n events: Array<{\n event_type: string;\n page_url: string | null;\n metadata: Record<string, unknown> | null;\n occurred_at: string | null;\n }>;\n}\n\nfunction buildContext(\n surface: TrackingInstallSurface,\n sdkVersion: string | null,\n packageName: string | null,\n environment: TrackingEnvironment,\n activeGtagIds: Record<string, string> | null,\n): TrackingClientContext {\n return {\n surface,\n sdk_version: sdkVersion,\n package_name: packageName,\n site_origin: typeof window === \"undefined\" ? null : window.location.origin,\n page_title: typeof document === \"undefined\" ? null : document.title || null,\n referrer: typeof document === \"undefined\" ? null : document.referrer || null,\n environment,\n active_gtag_ids: activeGtagIds,\n // Rebuilt per flush (this runs inside the payload builder), so a client\n // constructed later on a deeper route still gets reported.\n capabilities: getRegisteredCapabilities(),\n };\n}\n\nfunction readTrackingParams(): TrackingParams {\n if (typeof window === \"undefined\") return createEmptyTrackingParams();\n // Capture from URL on every read so the first event in a session reflects the\n // landing-page params even if the cookie helper hasn't run yet.\n try {\n captureTrackingParamsFromLocation();\n } catch {\n // ignore\n }\n return getTrackingParamsFromCookieReader(getCookieValueFromDocument);\n}\n\nfunction consentSnapshot(): Record<string, unknown> | null {\n try {\n // Effective consent + provenance so the dashboard can tell default-granted\n // (opt-out model, no interaction) apart from an explicit choice.\n const choice = getConsentChoice();\n return {\n state: choice.state,\n source: choice.source,\n updated_at: choice.updatedAt,\n expires_at: choice.expiresAt,\n };\n } catch {\n return null;\n }\n}\n\ninterface IdentityHeaders {\n sdkVersion: string;\n packageName: string;\n surface: string;\n environment: string;\n}\n\nasync function postWithFetch(\n url: string,\n body: string,\n apiKey: string,\n identity: IdentityHeaders,\n keepalive: boolean,\n): Promise<DeliveryOutcome> {\n // No fetch at all (a non-browser runtime): there is nothing to retry against,\n // and scheduling one would spin a timer forever. Give up on the batch.\n if (typeof fetch !== \"function\") return \"drop\";\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n [API_KEY_HEADER]: apiKey,\n [SDK_VERSION_HEADER]: identity.sdkVersion,\n [SDK_PACKAGE_HEADER]: identity.packageName,\n [SDK_SURFACE_HEADER]: identity.surface,\n [SDK_ENVIRONMENT_HEADER]: identity.environment,\n },\n body,\n keepalive,\n // CORS is open on the tracking endpoint; never send cookies.\n credentials: \"omit\",\n mode: \"cors\",\n });\n if (response.ok) return \"ok\";\n if (response.status === 408 || response.status === 429 || response.status >= 500) {\n return \"retry\";\n }\n // 401/403/422 and friends: the payload or the key is wrong, and will still\n // be wrong in 30 seconds.\n return \"drop\";\n } catch {\n // Network-level failure (offline, DNS, CORS preflight, aborted). Never\n // throws to the host site; the batch stays buffered for the next attempt.\n return \"retry\";\n }\n}\n\n/**\n * A batch awaiting delivery. Each one carries its OWN session snapshot: a batch\n * can outlive the session that produced it (buffered across a reload), and\n * re-sending it under whatever session is current would silently misattribute\n * those events.\n */\ninterface PendingBatch {\n session: TrackingSessionUpsertPayload;\n events: QueuedEvent[];\n}\n\nfunction retryBufferKey(apiKey: string, endpoint: string): string {\n return `${RETRY_BUFFER_KEY_PREFIX}:${apiKey}:${endpoint}`;\n}\n\nfunction readPendingBatches(key: string): PendingBatch[] {\n if (typeof window === \"undefined\") return [];\n try {\n const raw = window.localStorage.getItem(key);\n if (!raw) return [];\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter(\n (entry): entry is PendingBatch =>\n typeof entry === \"object\" &&\n entry !== null &&\n \"session\" in entry &&\n Array.isArray((entry as PendingBatch).events),\n );\n } catch {\n // Storage blocked, or a corrupt/foreign value — start clean rather than\n // letting a bad read break the host site.\n return [];\n }\n}\n\n/**\n * Mirror the buffer to storage unconditionally.\n *\n * Deliberately no read-back verification: under partitioned storage a write can\n * succeed for this document and still not be visible to a verifying read, so a\n * verify-gate false-negatives exactly where durability matters most.\n */\nfunction writePendingBatches(key: string, batches: PendingBatch[]): void {\n if (typeof window === \"undefined\") return;\n try {\n if (batches.length === 0) window.localStorage.removeItem(key);\n else window.localStorage.setItem(key, JSON.stringify(batches));\n } catch {\n // Quota exceeded or storage blocked — in-memory retry still works.\n }\n}\n\n/** Drop the oldest batches until the buffer is back under the event cap. */\nfunction trimToBufferCap(batches: PendingBatch[]): PendingBatch[] {\n let total = batches.reduce((sum, batch) => sum + batch.events.length, 0);\n const trimmed = batches.slice();\n while (total > MAX_BUFFERED_EVENTS && trimmed.length > 1) {\n const dropped = trimmed.shift();\n total -= dropped ? dropped.events.length : 0;\n }\n return trimmed;\n}\n\nlet globalClient: TrackingClient | null = null;\nlet globalClientKey: string | null = null;\n\nfunction clientConfigKey(config: TrackingClientConfig): string {\n return `${config.apiKey}@${config.endpoint}#${config.surface}`;\n}\n\n/**\n * Return a page-level singleton tracking client. Creating the client anew on\n * every component mount is wrong — React StrictMode double-mounts dev-only,\n * and destroying+recreating the client between the cleanup and re-run strips\n * away the pushState patch that SPA auto page view relies on. A singleton\n * survives all of that: the client lives for the entire page, and providers\n * just attach/detach auto page view against it.\n *\n * If `apiKey` / `endpoint` / `surface` change between calls, the previous\n * singleton is destroyed and a new one replaces it. This covers hot-config\n * changes without leaking state.\n */\nexport function getOrCreateTrackingClient(config: TrackingClientConfig): TrackingClient {\n const key = clientConfigKey(config);\n if (globalClient !== null && globalClientKey === key) {\n return globalClient;\n }\n if (globalClient !== null) {\n globalClient.destroy();\n }\n globalClient = createTrackingClient(config);\n globalClientKey = key;\n return globalClient;\n}\n\n// Global/delegated captures (document/window listeners: page_exit, scroll_depth,\n// time_on_site, form_start, cta_click, phone_click, bfcache restore) must attach ONCE\n// per page-singleton client — NOT once per React provider mount. A page can mount several\n// <TrackingProvider>s (a supported island pattern: a global provider for page-level\n// triggers plus per-component providers so `useSearchParams()` doesn't opt the whole tree\n// out of static rendering). Since the client is a singleton but each provider runs its own\n// attach effect, N mounts would stack N document listeners and every interaction would emit\n// its event N times. We ref-count attaches against the singleton client's identity: the\n// first mount attaches, later mounts are no-ops, and the last unmount detaches.\ninterface ClientCaptureEntry {\n detach: () => void;\n refCount: number;\n}\nconst clientCaptureRegistry = new WeakMap<TrackingClient, ClientCaptureEntry>();\n\n/**\n * Attach a set of global/delegated captures against a singleton `client` exactly once,\n * ref-counted across provider mounts. `build` performs the actual `document`/`window`\n * listener attachment and returns a single detacher for all of them; it runs only on the\n * first mount for a given client. The returned release decrements the ref-count and runs\n * `build`'s detacher when the last holder releases. Release is idempotent — React\n * StrictMode invokes an effect's cleanup twice in dev, and a double release must not\n * double-decrement.\n */\nexport function attachClientCapturesOnce(\n client: TrackingClient,\n build: () => () => void,\n): () => void {\n let entry = clientCaptureRegistry.get(client);\n if (entry === undefined) {\n entry = { detach: build(), refCount: 0 };\n clientCaptureRegistry.set(client, entry);\n }\n entry.refCount += 1;\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const current = clientCaptureRegistry.get(client);\n if (current === undefined) return;\n current.refCount -= 1;\n if (current.refCount <= 0) {\n current.detach();\n clientCaptureRegistry.delete(client);\n }\n };\n}\n\n/**\n * Tear down the singleton if any. Primarily an escape hatch for tests where\n * each test should see a fresh client; production code rarely needs this.\n * Also clears the in-session SPA referrer so the next test starts with a\n * fresh referrer chain.\n */\nexport function resetGlobalTrackingClient(): void {\n if (globalClient !== null) {\n // Force-detach any captures still attached to this client so their document/window\n // listeners can't leak into the next test even if a provider didn't unmount.\n const entry = clientCaptureRegistry.get(globalClient);\n if (entry !== undefined) {\n entry.detach();\n clientCaptureRegistry.delete(globalClient);\n }\n globalClient.destroy();\n }\n globalClient = null;\n globalClientKey = null;\n resetPageViewState();\n}\n\n/**\n * Create a low-level ingest client.\n *\n * The client queues events, debounces network flushes, sends an SDK heartbeat\n * once per new session, and swallows network errors so analytics never break\n * the host site.\n */\nexport function createTrackingClient(config: TrackingClientConfig): TrackingClient {\n const flushIntervalMs = config.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;\n const maxQueueSize = Math.min(config.maxQueueSize ?? DEFAULT_MAX_QUEUE_SIZE, HARD_MAX_BATCH);\n const sdkVersion = config.sdkVersion ?? null;\n const packageName = config.packageName ?? null;\n // Default to 'production' so the wire payload always carries a valid enum\n // value. Sending null would fail the backend's strict enum validation.\n const environment: TrackingEnvironment = config.environment ?? \"production\";\n const activeGtagIds = config.activeGtagIds ?? null;\n const endpointBase = config.endpoint.replace(/\\/$/, \"\");\n const eventsUrl = `${endpointBase}/events`;\n const identityHeaders: IdentityHeaders = {\n sdkVersion: sdkVersion ?? \"\",\n packageName: packageName ?? \"\",\n surface: config.surface,\n environment,\n };\n\n let queue: QueuedEvent[] = [];\n let flushTimer: ReturnType<typeof setTimeout> | null = null;\n // Batches that have been handed to the network at least once and not yet\n // acknowledged. Mirrored to localStorage so a reload — or a deploy window that\n // 5xxs every request — costs latency instead of data.\n const bufferKey = retryBufferKey(config.apiKey, endpointBase);\n let pending: PendingBatch[] = readPendingBatches(bufferKey);\n // Flushes are serialized through one chain. Batches are no longer removed from\n // the buffer before the response arrives, so two overlapping flushes would\n // send the same batch twice. Chaining (rather than a \"busy\" flag that returns\n // early) keeps `await flush()` meaning \"flushed\" for the caller.\n let flushChain: Promise<void> = Promise.resolve();\n let retryAttempt = 0;\n let firstPage: string | null = null;\n // Attribution captured synchronously at client creation (before any SPA router\n // can strip the query string). Merged into every session payload as a fallback\n // so a blocked-cookie webview or a stripped URL still attributes.\n let initialParams = createEmptyTrackingParams();\n let destroyed = false;\n\n // Initialize identity early so the first POST has stable values.\n const visitorId = getVisitorId();\n const initialSession = getOrRotateSessionId();\n let sessionId = initialSession.id;\n\n if (typeof window !== \"undefined\") {\n firstPage = window.location.href;\n try {\n initialParams = captureTrackingParamsFromLocation();\n } catch {\n // ignore — never break the host site\n }\n // Pin this session's LANDING params now, before any SPA router strips the\n // query string (reuses the stored record when the session already has one).\n getOrCaptureLandingParams(sessionId);\n try {\n captureFbc();\n } catch {\n // ignore\n }\n }\n\n // Queue an sdk_heartbeat event at the start of every new session.\n function enqueueHeartbeat(): void {\n const metadata = buildHeartbeatMetadata(\n config.surface,\n sdkVersion,\n packageName,\n config.triggers ?? null,\n activeGtagIds,\n );\n queue.push({\n event_type: \"sdk_heartbeat\",\n page_url: typeof window === \"undefined\" ? null : window.location.href,\n metadata: metadata as unknown as Record<string, unknown>,\n occurred_at: new Date().toISOString(),\n });\n }\n\n if (initialSession.isNew) {\n enqueueHeartbeat();\n }\n\n // Anything left buffered by a previous page load goes out on the normal\n // debounce, ahead of whatever this page produces.\n if (pending.length > 0) {\n scheduleFlush();\n }\n\n function buildSessionPayload(): TrackingSessionUpsertPayload {\n const rotated = getOrRotateSessionId();\n if (rotated.isNew && rotated.id !== sessionId) {\n // Session rotated mid-page (idle > 30min then user returned).\n enqueueHeartbeat();\n }\n sessionId = rotated.id;\n // Prefer the live cookie/localStorage read; fall back to the init-time\n // snapshot (covers a webview that blocked the cookie AND a router that\n // already stripped the landing URL by flush time).\n const params = mergeTrackingParams(readTrackingParams(), initialParams);\n const context = buildContext(\n config.surface,\n sdkVersion,\n packageName,\n environment,\n activeGtagIds,\n );\n return {\n session_id: sessionId,\n visitor_id: visitorId,\n gclid: params.gclid,\n wbraid: params.wbraid,\n gbraid: params.gbraid,\n ylpcid: params.ylpcid,\n fbclid: params.fbclid,\n fbc: getFbcCookie(),\n fbp: getFbpCookie(),\n utm_source: params.utm_source,\n utm_medium: params.utm_medium,\n utm_campaign: params.utm_campaign,\n utm_term: params.utm_term,\n utm_content: params.utm_content,\n // Landing params for the CURRENT session id — captured on the spot when\n // the session just rotated (the current URL is the rotated session's\n // landing), reused from the stored record otherwise. Keys are omitted\n // entirely when the landing isn't observable (SSR).\n ...buildLandingPayloadFields(sessionId),\n first_page: firstPage,\n consent_state: consentSnapshot(),\n context,\n };\n }\n\n function scheduleFlush(delayMs: number = flushIntervalMs): void {\n if (flushTimer !== null || destroyed) return;\n flushTimer = setTimeout(() => {\n flushTimer = null;\n void flush();\n }, delayMs);\n }\n\n function clearScheduledFlush(): void {\n if (flushTimer !== null) {\n clearTimeout(flushTimer);\n flushTimer = null;\n }\n }\n\n /** Move everything currently queued into the durable buffer. */\n function bufferQueued(): void {\n if (queue.length === 0) return;\n const events = queue.slice(0, HARD_MAX_BATCH);\n queue = queue.slice(events.length);\n pending = trimToBufferCap([...pending, { session: buildSessionPayload(), events }]);\n writePendingBatches(bufferKey, pending);\n }\n\n /**\n * Drain the durable buffer, oldest batch first.\n *\n * A batch leaves the buffer only on `ok` (acknowledged) or `drop` (permanently\n * rejected). Anything else keeps it, so a 5xx window costs latency, not data.\n *\n * Delivery is at-least-once: with no event-level idempotency key on the wire,\n * a response lost after the server committed will re-send that batch. That\n * window is far narrower than the \"every 5xx is permanent loss\" it replaces —\n * closing it needs a client-generated event id plus a backend uniqueness\n * constraint, which is a schema change and its own release.\n */\n function flush(): Promise<void> {\n // `.catch` keeps one unexpected throw from poisoning every later flush.\n flushChain = flushChain.then(runFlush).catch(() => {});\n return flushChain;\n }\n\n async function runFlush(): Promise<void> {\n if (destroyed) return;\n clearScheduledFlush();\n bufferQueued();\n if (pending.length === 0) return;\n\n try {\n while (pending.length > 0) {\n const batch = pending[0]!;\n const body: IngestRequestBody = { session: batch.session, events: batch.events };\n // keepalive=false: this runs on a live page, where a plain fetch\n // completes normally and its failure is observable. The unload path\n // (flushOnUnload) passes true instead — pagehide tears the document down\n // and aborts a plain fetch mid-flight, while keepalive hands the request\n // to the browser to finish after teardown.\n const outcome = await postWithFetch(\n eventsUrl,\n JSON.stringify(body),\n config.apiKey,\n identityHeaders,\n false,\n );\n if (outcome === \"retry\") {\n retryAttempt += 1;\n // Exponential from the normal flush interval, capped. Scheduling\n // happens after `flushing` is cleared, below.\n return;\n }\n pending = pending.slice(1);\n writePendingBatches(bufferKey, pending);\n retryAttempt = 0;\n }\n } finally {\n if (pending.length > 0) {\n const backoff = Math.min(flushIntervalMs * 2 ** retryAttempt, MAX_RETRY_BACKOFF_MS);\n scheduleFlush(backoff);\n } else if (queue.length > 0) {\n // `bufferQueued` takes at most HARD_MAX_BATCH per pass, so a burst\n // larger than one batch still has events waiting.\n scheduleFlush();\n }\n }\n }\n\n function trackEvent(input: TrackEventInput): void {\n if (destroyed) return;\n if (!input || typeof input.eventType !== \"string\" || input.eventType.length === 0) return;\n\n // Enhanced conversions: a form submit is the one moment the visitor's own\n // email/phone pass through the SDK — stash them (memory only) so the\n // conversion that fires next carries user_data. NOT done for phone_click:\n // its metadata holds the BUSINESS's number, not the visitor's. An explicit\n // consent decline also skips the stash entirely — egress is already gated,\n // but a decliner's identifiers shouldn't sit in page memory either.\n if (input.eventType === \"form_submit\" && getConsentState() !== \"denied\") {\n try {\n const fields = (input.metadata as { form?: { fields?: unknown } } | null)?.form?.fields;\n if (fields) stashUserDataFromFormFields(fields, config.phone?.defaultCountry);\n } catch {\n // user-data capture must never break ingest\n }\n }\n\n const occurredAt =\n input.occurredAt instanceof Date\n ? input.occurredAt.toISOString()\n : typeof input.occurredAt === \"string\"\n ? input.occurredAt\n : new Date().toISOString();\n\n queue.push({\n event_type: input.eventType,\n page_url: input.pageUrl ?? (typeof window === \"undefined\" ? null : window.location.href),\n metadata: input.metadata ?? null,\n occurred_at: occurredAt,\n });\n\n if (queue.length >= maxQueueSize) {\n void flush();\n } else {\n scheduleFlush();\n }\n }\n\n /**\n * Last-gasp send on pagehide/visibilitychange.\n *\n * The keepalive request outlives the document, so its outcome can never be\n * observed. The batch it carries is therefore removed from the buffer\n * optimistically: keeping it would re-send on the next page load every time\n * the send actually worked, which is almost always. Any batch behind it stays\n * buffered and is retried on the next load.\n */\n function flushOnUnload(): void {\n bufferQueued();\n clearScheduledFlush();\n if (pending.length === 0) return;\n\n const batch = pending[0]!;\n pending = pending.slice(1);\n writePendingBatches(bufferKey, pending);\n\n const body: IngestRequestBody = { session: batch.session, events: batch.events };\n void postWithFetch(eventsUrl, JSON.stringify(body), config.apiKey, identityHeaders, true);\n }\n\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"pagehide\", flushOnUnload);\n window.addEventListener(\"visibilitychange\", () => {\n if (document.visibilityState === \"hidden\") flushOnUnload();\n });\n }\n\n return {\n trackEvent,\n flush,\n flushBeacon: flushOnUnload,\n getSessionId: () => sessionId,\n getVisitorId: () => visitorId,\n destroy: () => {\n destroyed = true;\n // Fire any pending events through the keepalive path before tearing\n // down. Critical for React StrictMode in dev, where the provider's\n // first mount is immediately unmounted and its 2s debounce would\n // otherwise drop the initial page_view on the floor. Uses fetch\n // keepalive so the request survives the component tearing down.\n if (queue.length > 0) {\n flushOnUnload();\n }\n clearScheduledFlush();\n queue = [];\n if (typeof window !== \"undefined\") {\n window.removeEventListener(\"pagehide\", flushOnUnload);\n }\n },\n };\n}\n","import { z } from \"zod\";\n\n/**\n * Metadata for a manually fired `cta_click` event.\n *\n * Use this for non-phone calls to action such as directions, appointment\n * buttons, downloads, or external booking links.\n */\nexport const ctaClickMetadataSchema = z\n .object({\n cta_name: z.string(),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n section: z.string().nullable().optional(),\n destination_url: z.string().nullable().optional(),\n // Set by auto-capture (and available to manual callers): the link target\n // and a short element descriptor (tag#id) for tying clicks to specific UI.\n href: z.string().nullable().optional(),\n element: z.string().nullable().optional(),\n })\n .strict();\n\nexport type CtaClickMetadata = z.infer<typeof ctaClickMetadataSchema>;\n\n/**\n * Registration config for `cta_click`.\n *\n * The event stays manually fireable; `autoCapture` additionally attaches a\n * delegated click listener that fires it for any element matching `selector`\n * (default `[data-aranova-cta]`) — tag your CTAs, get analytics for free.\n */\nexport const ctaClickConfigSchema = z\n .object({\n autoCapture: z\n .object({\n selector: z.string().optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\nexport type CtaClickConfig = z.infer<typeof ctaClickConfigSchema>;\n","import { z } from \"zod\";\n\n/**\n * Registered trigger names reported by the SDK heartbeat.\n */\nexport const sdkHeartbeatTriggersSchema = z\n .object({\n automatic: z.array(z.string()),\n manual: z.array(z.string()),\n })\n .strict();\n\n/**\n * Metadata for the SDK-internal `sdk_heartbeat` event.\n *\n * The SDK fires this once per new session so the dashboard can show which SDK\n * version, install surface, and trigger registry a client site is running.\n * Consumers do not manually register or fire this event.\n */\nexport const sdkHeartbeatMetadataSchema = z\n .object({\n sdk_version: z.string(),\n package_name: z.string().nullable(),\n surface: z.enum([\"next\", \"react\", \"script\"]),\n triggers: sdkHeartbeatTriggersSchema,\n trigger_config: z.record(z.string(), z.record(z.string(), z.unknown())).nullable().optional(),\n configured_gtag_ids: z.record(z.string(), z.string()).nullable().optional(),\n })\n .strict();\n\nexport type SdkHeartbeatMetadata = z.infer<typeof sdkHeartbeatMetadataSchema>;\n\n/**\n * Internal registration config for `sdk_heartbeat`.\n *\n * This event has no consumer-facing options.\n */\nexport const sdkHeartbeatConfigSchema = z.object({}).strict();\nexport type SdkHeartbeatConfig = z.infer<typeof sdkHeartbeatConfigSchema>;\n","import { z } from \"zod\";\n\n/**\n * Metadata for the automatic `form_start` event.\n *\n * The SDK emits this once per form when the visitor first focuses a field.\n */\nexport const formStartMetadataSchema = z\n .object({\n form: z\n .object({\n id: z.string(),\n action: z.string().nullable(),\n })\n .strict(),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n })\n .strict();\n\nexport type FormStartMetadata = z.infer<typeof formStartMetadataSchema>;\n\n/**\n * Registration config for automatic `form_start`.\n *\n * Use `selector` to narrow which forms can trigger the event. When omitted,\n * the SDK observes all `<form>` elements.\n */\nexport const formStartConfigSchema = z\n .object({\n selector: z.string().optional(),\n })\n .strict();\n\nexport type FormStartConfig = z.infer<typeof formStartConfigSchema>;\n","import { z } from \"zod\";\n\n// form_submit is manual — the SDK never auto-fires this. Consumer code calls\n// `tracking.trackEvent('form_submit', { form, page })` from their own submit\n// handler. Registering it enables the type-level permission; omitting it\n// turns manual calls into a compile error.\n//\n// The optional `fields` array captures submitted form field metadata and JSON\n// values. Consumers explicitly build the fields array themselves so they\n// control exactly what is sent.\n\n/**\n * JSON-serializable value accepted by `form_submit.fields[].value`.\n *\n * This intentionally excludes `undefined`, functions, symbols, `Date`\n * instances, and non-finite numbers. Values are stored in PostgreSQL JSONB, so\n * consumers should send only data that has a stable JSON representation.\n */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nexport const jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>\n z.union([\n z.string(),\n z.number().finite(),\n z.boolean(),\n z.null(),\n z.array(jsonValueSchema),\n z.record(jsonValueSchema),\n ]),\n);\n\n/**\n * Metadata for a manually fired `form_submit` event.\n *\n * Register the event with `manual: { form_submit: {} }`, then call\n * `trackEvent('form_submit', metadata)` from the host site's submit handler.\n *\n * `fields` is optional. If present, each value must be JSON-serializable. Client\n * integrations may intentionally capture raw submitted lead data (including name,\n * email, phone, address, selections, and free text) for first-party analytics and\n * lead operations. Submitted file data is supported after conversion to a\n * JSON-serializable representation; upload larger files separately and send a storage\n * reference. Never include credentials, authentication tokens, payment-card or bank\n * secrets, or private keys.\n *\n * No byte limit is enforced on this metadata, here or on the server — `fields` and its\n * values are unbounded. Keep inlined payloads small anyway: a submit fired just before\n * navigation flushes over `keepalive`, which browsers cap near 64 KB and drop silently.\n *\n * @example\n * ```ts\n * tracking.trackEvent('form_submit', {\n * form: {\n * id: 'lead-form',\n * action: '/api/lead',\n * fields: [\n * {\n * name: 'service_interest',\n * type: 'select',\n * label: 'Service interest',\n * value: 'teeth_whitening',\n * },\n * ],\n * },\n * page: { path: window.location.pathname },\n * });\n * ```\n */\nexport const formSubmitMetadataSchema = z\n .object({\n form: z\n .object({\n id: z.string(),\n action: z.string().nullable(),\n fields: z\n .array(\n z\n .object({\n name: z.string(),\n type: z.string(),\n label: z.string().nullable(),\n value: jsonValueSchema,\n })\n .strict(),\n )\n .optional(),\n })\n .strict(),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n })\n .strict();\n\nexport type FormSubmitMetadata = z.infer<typeof formSubmitMetadataSchema>;\n\n/**\n * Registration config for `form_submit`.\n *\n * This event is manual-only and currently has no registration options. The\n * empty object enables typed `trackEvent('form_submit', ...)` calls.\n */\nexport const formSubmitConfigSchema = z.object({}).strict();\nexport type FormSubmitConfig = z.infer<typeof formSubmitConfigSchema>;\n","import { z } from \"zod\";\n\n/**\n * Metadata for the automatic `multi_page_session` event.\n *\n * Fired when the visitor reaches the configured distinct-page threshold in a\n * single tracking session.\n */\nexport const multiPageSessionMetadataSchema = z\n .object({\n page_count: z.number().int().min(2),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n })\n .strict();\n\nexport type MultiPageSessionMetadata = z.infer<typeof multiPageSessionMetadataSchema>;\n\n/**\n * Registration config for automatic `multi_page_session`.\n */\nexport const multiPageSessionConfigSchema = z\n .object({\n pageThreshold: z.number().int().min(2),\n })\n .strict();\n\nexport type MultiPageSessionConfig = z.infer<typeof multiPageSessionConfigSchema>;\n","import { z } from \"zod\";\n\n/**\n * Metadata for the automatic `page_exit` event.\n *\n * Fired when the user leaves a page (SPA navigation away, tab hidden, or\n * pagehide). `dwell_ms` is the ACTIVE (visible) time spent on the page segment\n * being closed — hidden time never counts, matching `time_on_site` semantics.\n * A page revisited after being hidden emits another `page_exit` for the next\n * visible segment, so summing `dwell_ms` per page/session yields total active\n * dwell without double counting.\n */\nexport const pageExitMetadataSchema = z\n .object({\n dwell_ms: z.number().int().min(0),\n // null = left without any scroll signal; floor is 0 so a valid 0% is never\n // rejected (a single bad field 422s the whole keepalive beacon batch).\n max_scroll_percent: z.number().int().min(0).max(100).nullable(),\n // The gating baseline: the fraction of the page visible at load with\n // zero scrolling — or, for pages that grew after the post-paint snapshot\n // (skeleton/streaming renders), the first-scroll position that\n // established it. null = page had no scrollable range, or the segment\n // ended before the snapshot. `.optional()` is load-bearing: SDK builds\n // predating this field keep POSTing page_exit without the key —\n // requiring it would 422 whole keepalive beacon batches.\n scroll_baseline_percent: z.number().int().min(0).max(100).nullable().optional(),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n })\n .strict();\n\nexport type PageExitMetadata = z.infer<typeof pageExitMetadataSchema>;\n\n/**\n * Registration config for automatic `page_exit`.\n *\n * SDK-internal: attached unconditionally (like `sdk_heartbeat`), so there are\n * no registration options.\n */\nexport const pageExitConfigSchema = z.object({}).strict();\nexport type PageExitConfig = z.infer<typeof pageExitConfigSchema>;\n","import { z } from \"zod\";\n\n/**\n * Metadata for a manually fired `phone_click` event.\n *\n * `phone_number` should be the business phone number from the clicked `tel:`\n * link, not a visitor-entered phone number. `section` can distinguish header,\n * footer, hero, or contact-page links.\n */\nexport const phoneClickMetadataSchema = z\n .object({\n phone_number: z.string(),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n section: z.string().nullable().optional(),\n })\n .strict();\n\nexport type PhoneClickMetadata = z.infer<typeof phoneClickMetadataSchema>;\n\n/**\n * Registration config for `phone_click`.\n *\n * The event stays manually fireable; `autoCapture` additionally attaches a\n * delegated click listener that fires it for any `tel:` link matching\n * `selector` (default `a[href^=\"tel:\"]`) — link your phone number, get the\n * analytics event (and, for a linked phone-click goal, the conversion) for free.\n */\nexport const phoneClickConfigSchema = z\n .object({\n autoCapture: z\n .object({\n selector: z.string().optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\nexport type PhoneClickConfig = z.infer<typeof phoneClickConfigSchema>;\n","import { z } from \"zod\";\n\n/**\n * Metadata for the automatic `scroll_depth` event.\n *\n * Fired once per configured threshold per page.\n */\nexport const scrollDepthMetadataSchema = z\n .object({\n depth_percent: z.number().int().min(1).max(100),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n })\n .strict();\n\nexport type ScrollDepthMetadata = z.infer<typeof scrollDepthMetadataSchema>;\n\n/**\n * Registration config for automatic `scroll_depth`.\n *\n * `thresholds` are integer percentages from 1 to 100.\n */\nexport const scrollDepthConfigSchema = z\n .object({\n thresholds: z.array(z.number().int().min(1).max(100)).min(1),\n })\n .strict();\n\nexport type ScrollDepthConfig = z.infer<typeof scrollDepthConfigSchema>;\n","import { z } from \"zod\";\n\nexport const PAGE_IDENTITY_MAX_LENGTH = 64;\nexport const PAGE_IDENTITY_PATTERN = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;\n\n/** Common page identities offered as presets by operator tooling. */\nexport const SPECIFIC_PAGE_NAMES = [\n \"contact_page\",\n \"about_page\",\n \"services_page\",\n \"booking_page\",\n \"location_page\",\n \"pricing_page\",\n \"faq_page\",\n \"testimonials_page\",\n] as const;\n\nexport const pageIdentitySchema = z\n .string()\n .max(PAGE_IDENTITY_MAX_LENGTH)\n .regex(PAGE_IDENTITY_PATTERN, {\n message:\n \"page identity must be lowercase snake_case, start with a letter, and contain at most 64 characters\",\n });\n\nexport type PageIdentity = z.infer<typeof pageIdentitySchema>;\n\n/** @deprecated Use PageIdentity. Kept as a compatibility alias for existing consumers. */\nexport type SpecificPageName = PageIdentity;\n\n/** @deprecated Use pageIdentitySchema. Kept for source compatibility. */\nexport const specificPageNameSchema = pageIdentitySchema;\n\n/**\n * Metadata for the automatic `specific_page_visit` event.\n *\n * The SDK emits this when the current pathname matches one of the configured\n * named page patterns.\n */\nexport const specificPageVisitMetadataSchema = z\n .object({\n page_name: specificPageNameSchema,\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n })\n .strict();\n\nexport type SpecificPageVisitMetadata = z.infer<typeof specificPageVisitMetadataSchema>;\n\n/**\n * Registration config for automatic `specific_page_visit`.\n *\n * Each page entry pairs a stable, validated identity with a `RegExp` that\n * matches the pathname. The identity can use a preset above or a client-specific\n * lowercase snake-case slug.\n */\nexport const specificPageVisitConfigSchema = z\n .object({\n pages: z\n .array(\n z\n .object({\n name: specificPageNameSchema,\n pathPattern: z.custom<RegExp>((value) => value instanceof RegExp, {\n message: \"pathPattern must be a RegExp\",\n }),\n })\n .strict(),\n )\n .min(1),\n })\n .strict();\n\nexport type SpecificPageVisitConfig = z.infer<typeof specificPageVisitConfigSchema>;\n","import { z } from \"zod\";\n\n/**\n * Metadata for the automatic `time_on_site` event.\n *\n * The SDK starts a visibility-aware timer and fires once when visible\n * engagement crosses the configured threshold.\n */\nexport const timeOnSiteMetadataSchema = z\n .object({\n duration_ms: z.number().int().nonnegative(),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n })\n .strict();\n\nexport type TimeOnSiteMetadata = z.infer<typeof timeOnSiteMetadataSchema>;\n\n/**\n * Registration config for automatic `time_on_site`.\n */\nexport const timeOnSiteConfigSchema = z\n .object({\n thresholdSeconds: z.number().int().positive(),\n })\n .strict();\nexport type TimeOnSiteConfig = z.infer<typeof timeOnSiteConfigSchema>;\n","export type EventOutcomeRole = \"lead\" | \"engagement\" | \"navigation\" | \"diagnostic\";\nexport type EventCategory = \"page\" | \"engagement\" | \"lead\" | \"commerce\" | \"system\";\nexport type EventClientVisibility = \"simple\" | \"detailed\" | \"hidden\";\n\nexport interface EventSemantics {\n label: string;\n category: EventCategory;\n outcomeRole: EventOutcomeRole;\n clientVisibility: EventClientVisibility;\n}\n\n/**\n * Lightweight runtime event metadata. This module intentionally imports no\n * Zod schemas so dashboards and framework adapters can consume it without\n * pulling the validation registry into their bundles.\n */\nexport const EVENT_SEMANTICS = {\n page_view: {\n label: \"Page view\",\n category: \"page\",\n outcomeRole: \"navigation\",\n clientVisibility: \"simple\",\n },\n time_on_site: {\n label: \"Time on site\",\n category: \"engagement\",\n outcomeRole: \"engagement\",\n clientVisibility: \"detailed\",\n },\n specific_page_visit: {\n label: \"Key page visit\",\n category: \"engagement\",\n outcomeRole: \"engagement\",\n clientVisibility: \"detailed\",\n },\n scroll_depth: {\n label: \"Scroll depth\",\n category: \"engagement\",\n outcomeRole: \"engagement\",\n clientVisibility: \"detailed\",\n },\n multi_page_session: {\n label: \"Multi-page session\",\n category: \"engagement\",\n outcomeRole: \"engagement\",\n clientVisibility: \"detailed\",\n },\n form_start: {\n label: \"Form started\",\n category: \"engagement\",\n outcomeRole: \"engagement\",\n clientVisibility: \"simple\",\n },\n sdk_heartbeat: {\n label: \"SDK heartbeat\",\n category: \"system\",\n outcomeRole: \"diagnostic\",\n clientVisibility: \"hidden\",\n },\n page_exit: {\n label: \"Page exit\",\n category: \"engagement\",\n outcomeRole: \"diagnostic\",\n clientVisibility: \"detailed\",\n },\n form_submit: {\n label: \"Form submitted\",\n category: \"lead\",\n outcomeRole: \"lead\",\n clientVisibility: \"simple\",\n },\n phone_click: {\n label: \"Phone click\",\n category: \"lead\",\n outcomeRole: \"lead\",\n clientVisibility: \"simple\",\n },\n cta_click: {\n label: \"CTA click\",\n category: \"engagement\",\n outcomeRole: \"engagement\",\n clientVisibility: \"simple\",\n },\n} as const satisfies Record<string, EventSemantics>;\n\nexport type EventName = keyof typeof EVENT_SEMANTICS;\n\nexport function getEventSemantics(eventName: string): EventSemantics | null {\n return eventName in EVENT_SEMANTICS ? EVENT_SEMANTICS[eventName as EventName] : null;\n}\n","import type { z } from \"zod\";\n\nimport {\n ctaClickConfigSchema,\n ctaClickMetadataSchema,\n type CtaClickConfig,\n type CtaClickMetadata,\n} from \"./cta-click\";\nimport {\n sdkHeartbeatConfigSchema,\n sdkHeartbeatMetadataSchema,\n type SdkHeartbeatConfig,\n type SdkHeartbeatMetadata,\n} from \"./sdk-heartbeat\";\nimport {\n formStartConfigSchema,\n formStartMetadataSchema,\n type FormStartConfig,\n type FormStartMetadata,\n} from \"./form-start\";\nimport {\n formSubmitConfigSchema,\n formSubmitMetadataSchema,\n type FormSubmitConfig,\n type FormSubmitMetadata,\n} from \"./form-submit\";\nimport {\n multiPageSessionConfigSchema,\n multiPageSessionMetadataSchema,\n type MultiPageSessionConfig,\n type MultiPageSessionMetadata,\n} from \"./multi-page-session\";\nimport {\n pageExitConfigSchema,\n pageExitMetadataSchema,\n type PageExitConfig,\n type PageExitMetadata,\n} from \"./page-exit\";\nimport {\n pageViewConfigSchema,\n pageViewMetadataSchema,\n type PageViewConfig,\n type PageViewMetadata,\n} from \"./page-view\";\nimport {\n phoneClickConfigSchema,\n phoneClickMetadataSchema,\n type PhoneClickConfig,\n type PhoneClickMetadata,\n} from \"./phone-click\";\nimport {\n scrollDepthConfigSchema,\n scrollDepthMetadataSchema,\n type ScrollDepthConfig,\n type ScrollDepthMetadata,\n} from \"./scroll-depth\";\nimport {\n specificPageVisitConfigSchema,\n specificPageVisitMetadataSchema,\n type SpecificPageVisitConfig,\n type SpecificPageVisitMetadata,\n} from \"./specific-page-visit\";\nimport {\n timeOnSiteConfigSchema,\n timeOnSiteMetadataSchema,\n type TimeOnSiteConfig,\n type TimeOnSiteMetadata,\n} from \"./time-on-site\";\nimport { EVENT_SEMANTICS, type EventName, type EventSemantics } from \"./semantics\";\n\nexport { EVENT_SEMANTICS, getEventSemantics } from \"./semantics\";\nexport type {\n EventCategory,\n EventClientVisibility,\n EventName,\n EventOutcomeRole,\n EventSemantics,\n} from \"./semantics\";\n\n// Event kind — automatic events are fired by the SDK itself when their\n// client-side signal fires (page_view on navigation, time_on_site on timer,\n// etc). Manual events are only fireable via explicit consumer code.\nexport type EventKind = \"automatic\" | \"manual\";\n\n// The registry is the single client-side source of truth for \"what events\n// exist, what shape does their metadata take, and what kind are they\". The\n// backend mirror lives in apps/api/src/schemas/tracking_events.py and is\n// kept in sync via the drift test in apps/api/tests/test_event_schema_drift.py.\nexport const EVENT_REGISTRY = {\n // --- automatic triggers ---\n page_view: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.page_view,\n metadataSchema: pageViewMetadataSchema,\n configSchema: pageViewConfigSchema,\n },\n time_on_site: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.time_on_site,\n metadataSchema: timeOnSiteMetadataSchema,\n configSchema: timeOnSiteConfigSchema,\n },\n specific_page_visit: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.specific_page_visit,\n metadataSchema: specificPageVisitMetadataSchema,\n configSchema: specificPageVisitConfigSchema,\n },\n scroll_depth: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.scroll_depth,\n metadataSchema: scrollDepthMetadataSchema,\n configSchema: scrollDepthConfigSchema,\n },\n multi_page_session: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.multi_page_session,\n metadataSchema: multiPageSessionMetadataSchema,\n configSchema: multiPageSessionConfigSchema,\n },\n form_start: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.form_start,\n metadataSchema: formStartMetadataSchema,\n configSchema: formStartConfigSchema,\n },\n // --- SDK-internal automatic (not consumer-configurable) ---\n sdk_heartbeat: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.sdk_heartbeat,\n metadataSchema: sdkHeartbeatMetadataSchema,\n configSchema: sdkHeartbeatConfigSchema,\n },\n page_exit: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.page_exit,\n metadataSchema: pageExitMetadataSchema,\n configSchema: pageExitConfigSchema,\n },\n // --- manual triggers ---\n form_submit: {\n kind: \"manual\",\n semantics: EVENT_SEMANTICS.form_submit,\n metadataSchema: formSubmitMetadataSchema,\n configSchema: formSubmitConfigSchema,\n },\n phone_click: {\n kind: \"manual\",\n semantics: EVENT_SEMANTICS.phone_click,\n metadataSchema: phoneClickMetadataSchema,\n configSchema: phoneClickConfigSchema,\n },\n cta_click: {\n kind: \"manual\",\n semantics: EVENT_SEMANTICS.cta_click,\n metadataSchema: ctaClickMetadataSchema,\n configSchema: ctaClickConfigSchema,\n },\n} as const satisfies Record<\n EventName,\n {\n kind: EventKind;\n semantics: EventSemantics;\n metadataSchema: z.ZodTypeAny;\n configSchema: z.ZodTypeAny;\n }\n>;\n\n/**\n * Event names that are fired by the SDK when their configured signal occurs.\n *\n * Automatic events are not accepted by the typed `trackEvent()` API.\n */\nexport type AutomaticEventName = {\n [K in EventName]: (typeof EVENT_REGISTRY)[K][\"kind\"] extends \"automatic\" ? K : never;\n}[EventName];\n\n/**\n * Event names that consumer code can fire manually after registering them.\n */\nexport type ManualEventName = {\n [K in EventName]: (typeof EVENT_REGISTRY)[K][\"kind\"] extends \"manual\" ? K : never;\n}[EventName];\n\n// Map an event name to its explicit metadata / config TS type. We pull the\n// inferred types directly from the per-event files rather than deriving\n// via `z.infer<typeof EVENT_REGISTRY[K]['metadataSchema']>` so that error\n// messages name the event-specific type (PageViewMetadata, not an\n// anonymous zod inference).\ntype MetadataByName = {\n page_view: PageViewMetadata;\n time_on_site: TimeOnSiteMetadata;\n specific_page_visit: SpecificPageVisitMetadata;\n scroll_depth: ScrollDepthMetadata;\n multi_page_session: MultiPageSessionMetadata;\n form_start: FormStartMetadata;\n sdk_heartbeat: SdkHeartbeatMetadata;\n page_exit: PageExitMetadata;\n form_submit: FormSubmitMetadata;\n phone_click: PhoneClickMetadata;\n cta_click: CtaClickMetadata;\n};\n\ntype ConfigByName = {\n page_view: PageViewConfig;\n time_on_site: TimeOnSiteConfig;\n specific_page_visit: SpecificPageVisitConfig;\n scroll_depth: ScrollDepthConfig;\n multi_page_session: MultiPageSessionConfig;\n form_start: FormStartConfig;\n sdk_heartbeat: SdkHeartbeatConfig;\n page_exit: PageExitConfig;\n form_submit: FormSubmitConfig;\n phone_click: PhoneClickConfig;\n cta_click: CtaClickConfig;\n};\n\n/**\n * Metadata payload type for a specific tracking event.\n *\n * @example\n * ```ts\n * type SubmitMetadata = EventMetadata<'form_submit'>;\n * ```\n */\nexport type EventMetadata<K extends EventName> = MetadataByName[K];\n\n/**\n * Trigger registration config type for a specific tracking event.\n */\nexport type EventConfig<K extends EventName> = ConfigByName[K];\n\n// Runtime constant arrays for iteration at consumer / factory time.\n/**\n * Runtime list of automatic event names.\n */\nexport const ALL_AUTOMATIC_EVENT_NAMES: readonly AutomaticEventName[] = (\n Object.entries(EVENT_REGISTRY) as Array<[EventName, (typeof EVENT_REGISTRY)[EventName]]>\n)\n .filter(([, def]) => def.kind === \"automatic\")\n .map(([name]) => name) as AutomaticEventName[];\n\n/**\n * Runtime list of manual event names.\n */\nexport const ALL_MANUAL_EVENT_NAMES: readonly ManualEventName[] = (\n Object.entries(EVENT_REGISTRY) as Array<[EventName, (typeof EVENT_REGISTRY)[EventName]]>\n)\n .filter(([, def]) => def.kind === \"manual\")\n .map(([name]) => name) as ManualEventName[];\n\n/**\n * Events that represent a lead/outcome in first-party tracking projections.\n */\nexport const ALL_LEAD_EVENT_NAMES: readonly EventName[] = (\n Object.entries(EVENT_REGISTRY) as Array<[EventName, (typeof EVENT_REGISTRY)[EventName]]>\n)\n .filter(([, def]) => def.semantics.outcomeRole === \"lead\")\n .map(([name]) => name);\n\n/**\n * Trigger registry passed to `createTracking({ triggers })`.\n *\n * `automatic.page_view` is required because every install should capture page\n * views. Other automatic events are opt-in. Manual events must be registered\n * here before the typed client accepts `trackEvent()` calls for them.\n *\n * @example\n * ```ts\n * createTracking({\n * apiKey,\n * endpoint,\n * triggers: {\n * automatic: {\n * page_view: {},\n * time_on_site: { thresholdSeconds: 60 },\n * },\n * manual: {\n * form_submit: {},\n * phone_click: {},\n * },\n * },\n * });\n * ```\n */\nexport type TriggerRegistryConfig = {\n automatic: {\n page_view: EventConfig<\"page_view\">;\n } & Partial<{\n time_on_site: EventConfig<\"time_on_site\">;\n specific_page_visit: EventConfig<\"specific_page_visit\">;\n scroll_depth: EventConfig<\"scroll_depth\">;\n multi_page_session: EventConfig<\"multi_page_session\">;\n form_start: EventConfig<\"form_start\">;\n }>;\n manual?: Partial<{\n form_submit: EventConfig<\"form_submit\">;\n phone_click: EventConfig<\"phone_click\">;\n cta_click: EventConfig<\"cta_click\">;\n }>;\n};\n\n/**\n * Manual event names registered in a concrete trigger registry.\n *\n * Used by `TypedTrackingClient` so `trackEvent()` only accepts events the\n * consumer explicitly enabled.\n */\nexport type RegisteredManualEvents<TRegistry extends TriggerRegistryConfig> = Extract<\n keyof NonNullable<TRegistry[\"manual\"]>,\n ManualEventName\n>;\n\n/**\n * Automatic event names registered in a concrete trigger registry.\n */\nexport type RegisteredAutomaticEvents<TRegistry extends TriggerRegistryConfig> = Extract<\n keyof TRegistry[\"automatic\"],\n AutomaticEventName\n>;\n\n/**\n * Discriminated union of valid manual tracking calls for a registry.\n */\nexport type TrackableEvent<TRegistry extends TriggerRegistryConfig> = {\n [K in RegisteredManualEvents<TRegistry>]: {\n eventType: K;\n metadata: EventMetadata<K>;\n };\n}[RegisteredManualEvents<TRegistry>];\n\n// Runtime helper: look up a schema pair by name. Cast through `unknown`\n// because the registry is `as const` and TS loses the specific schema type\n// when indexing via a dynamic key.\nexport function getEventDefinition(name: EventName): {\n kind: EventKind;\n semantics: EventSemantics;\n metadataSchema: z.ZodTypeAny;\n configSchema: z.ZodTypeAny;\n} {\n return EVENT_REGISTRY[name] as unknown as {\n kind: EventKind;\n semantics: EventSemantics;\n metadataSchema: z.ZodTypeAny;\n configSchema: z.ZodTypeAny;\n };\n}\n","// Typed facade over the low-level TrackingClient.\n//\n// The raw TrackingClient in ingest.ts is non-generic and accepts a\n// stringly-typed `TrackEventInput`. The typed facade wraps it to add:\n//\n// 1. A discriminated `trackEvent(eventType, metadata, options?)` signature\n// that only accepts manually-fireable events the consumer registered\n// via `createTracking({ triggers: { manual: { ... } } })`.\n// 2. Optional runtime validation that parses the metadata through the\n// event's Zod schema before forwarding to the raw client. Off by\n// default so prod pays zero cost, on when the factory is given\n// `debug: true`.\n//\n// Automatic events (page_view, time_on_site, specific_page_visit, etc.) are NOT\n// exposed through the typed facade — they're fired by the SDK internally\n// via the raw client, so consumer code that tries `trackEvent('page_view')`\n// is a compile error.\n\nimport { registerCapability } from \"./capabilities\";\nimport { getEventDefinition } from \"./events/registry\";\nimport type {\n EventMetadata,\n RegisteredManualEvents,\n TriggerRegistryConfig,\n} from \"./events/registry\";\nimport type { TrackingClient } from \"./ingest\";\n\nexport interface TypedTrackEventOptions {\n /**\n * Override the page URL associated with this event.\n *\n * Omit this for normal browser usage; the SDK captures `window.location.href`.\n */\n pageUrl?: string | null;\n /**\n * Override the event timestamp.\n *\n * Defaults to the time the event is queued. Accepts a `Date` or ISO string.\n */\n occurredAt?: Date | string | null;\n}\n\n/**\n * Typed tracking client returned by `useTracking()`.\n *\n * The accepted event names and metadata shapes are narrowed from the concrete\n * trigger registry supplied to `createTracking()`.\n */\nexport interface TypedTrackingClient<TRegistry extends TriggerRegistryConfig> {\n /**\n * Fire a manually-registered event. The event name must be present in\n * the registry's `manual` map and the metadata must match that event's\n * canonical Zod-derived shape.\n */\n trackEvent<K extends RegisteredManualEvents<TRegistry>>(\n eventType: K,\n metadata: EventMetadata<K>,\n options?: TypedTrackEventOptions,\n ): void;\n\n /**\n * Immediately flush queued events to the ingest endpoint.\n *\n * Normal consumers rarely need this because the SDK flushes on a debounce,\n * when the queue reaches the batch threshold, and on `pagehide`.\n */\n flush(): Promise<void>;\n /**\n * Return the current rolling session id.\n */\n getSessionId(): string;\n /**\n * Return the persistent visitor id for this browser profile.\n */\n getVisitorId(): string;\n}\n\n/**\n * Options for `createTypedClient()`.\n */\nexport interface CreateTypedClientOptions {\n /**\n * When true, every `trackEvent` call runs the metadata through the Zod\n * schema via `.parse()` before forwarding. Parse failures throw loudly,\n * which is what you want in dev. Prod should leave this off so a single\n * analytics event can never take down the host site.\n */\n debug?: boolean;\n}\n\n/**\n * Wrap a low-level `TrackingClient` with registry-aware TypeScript types.\n *\n * Framework packages call this internally; application code usually accesses\n * the result through the scoped `useTracking()` hook returned by\n * `createTracking()`.\n */\nexport function createTypedClient<TRegistry extends TriggerRegistryConfig>(\n raw: TrackingClient,\n registry: TRegistry,\n options: CreateTypedClientOptions = {},\n): TypedTrackingClient<TRegistry> {\n const debug = options.debug ?? false;\n\n // Reported from the registry, not from the first firing: a site whose form\n // gets a handful of submissions a month is still fully wired, and keying the\n // capability on a real submit would let the presence window mark it removed\n // between them. One registration site covers next/react/browser.\n if (registry.manual?.form_submit) registerCapability(\"form_capture\");\n\n return {\n trackEvent<K extends RegisteredManualEvents<TRegistry>>(\n eventType: K,\n metadata: EventMetadata<K>,\n opts?: TypedTrackEventOptions,\n ): void {\n // Runtime validation in dev only. Since `trackEvent` is typed at the\n // caller site, the TS compiler already guarantees the metadata shape\n // for well-behaved consumers — this parse() catches runtime bugs in\n // SDK-internal code that bypasses the types (e.g. dynamic payloads\n // passed from a JS-only consumer, or a string coming from localStorage).\n if (debug) {\n const def = getEventDefinition(eventType);\n def.metadataSchema.parse(metadata);\n }\n\n raw.trackEvent({\n eventType: eventType as string,\n metadata: metadata as unknown as Record<string, unknown> | null,\n pageUrl: opts?.pageUrl ?? null,\n occurredAt: opts?.occurredAt ?? null,\n });\n },\n\n flush: raw.flush.bind(raw),\n getSessionId: raw.getSessionId.bind(raw),\n getVisitorId: raw.getVisitorId.bind(raw),\n };\n}\n","// time_on_site automatic trigger.\n//\n// Fires a single `time_on_site` event once the user has been actively\n// engaged with the tab for at least `thresholdSeconds`. The timer is\n// visibility-aware — when the tab goes hidden (other tab focused, app\n// backgrounded) we pause the counter, and resume when it comes back. This\n// stops the \"user opened the tab in the background and walked away\"\n// scenario from artificially inflating engagement.\n//\n// The event fires at most once per page load.\n\nimport type { TimeOnSiteConfig } from \"../events/time-on-site\";\nimport type { TrackingClient } from \"../ingest\";\n\n/**\n * Attach the automatic `time_on_site` trigger.\n *\n * Starts a visibility-aware timer and returns a detach function that clears\n * timers/listeners.\n */\nexport function attachTimeOnSite(client: TrackingClient, config: TimeOnSiteConfig): () => void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n return () => {};\n }\n\n const thresholdMs = config.thresholdSeconds * 1000;\n let accumulatedMs = 0;\n let activeSince: number | null = document.visibilityState === \"visible\" ? Date.now() : null;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let fired = false;\n\n function fire(): void {\n if (fired) return;\n fired = true;\n client.trackEvent({\n eventType: \"time_on_site\",\n metadata: {\n duration_ms: thresholdMs,\n page: { path: window.location.pathname },\n } as unknown as Record<string, unknown>,\n pageUrl: window.location.href,\n occurredAt: null,\n });\n }\n\n function scheduleNext(): void {\n if (fired || activeSince === null) return;\n const remaining = thresholdMs - accumulatedMs;\n if (remaining <= 0) {\n fire();\n return;\n }\n timer = setTimeout(fire, remaining);\n }\n\n function clearTimer(): void {\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n }\n\n function onVisibilityChange(): void {\n if (fired) return;\n if (document.visibilityState === \"hidden\") {\n // Pause — drain the current interval into accumulatedMs.\n if (activeSince !== null) {\n accumulatedMs += Date.now() - activeSince;\n activeSince = null;\n }\n clearTimer();\n } else {\n // Resume.\n activeSince = Date.now();\n scheduleNext();\n }\n }\n\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n scheduleNext();\n\n return () => {\n clearTimer();\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n };\n}\n","// Shared SPA-navigation signal for triggers.\n//\n// history.pushState/replaceState can only be observed by monkeypatching, and\n// per-trigger patches don't compose: each trigger captured the originals at\n// attach and blindly restored them at detach, so a non-LIFO detach order\n// stomped the other trigger's patch (it silently stopped seeing SPA\n// navigations). This module installs ONE ref-counted patch: it goes in with\n// the first subscriber and is restored with the last unsubscribe, making\n// detach order irrelevant.\n//\n// Notification timing preserves the previous per-trigger behavior:\n// pushState/replaceState notify via setTimeout(0) (the URL updates\n// synchronously but frameworks render after), popstate notifies\n// synchronously. Listeners are expected to read window.location themselves\n// and pathname-guard (query-only changes are their no-op, not ours).\n\ntype HistoryChangeListener = () => void;\n\nconst listeners = new Set<HistoryChangeListener>();\nlet restorePatch: (() => void) | null = null;\n\nfunction notify(): void {\n // Set iteration tolerates concurrent delete: a listener that unsubscribes\n // itself (or another) mid-notification is simply skipped if not yet visited.\n for (const listener of listeners) listener();\n}\n\nfunction notifyDeferred(): void {\n setTimeout(notify, 0);\n}\n\nfunction installPatch(): void {\n // Keep the exact original references (no .bind) so restore reinstates the\n // identical functions — a bound copy would change identity and stack a new\n // bind wrapper on every install/restore cycle.\n const originalPushState = history.pushState;\n const originalReplaceState = history.replaceState;\n\n function patchedPushState(this: History, ...args: Parameters<History[\"pushState\"]>): void {\n originalPushState.apply(this, args);\n notifyDeferred();\n }\n function patchedReplaceState(this: History, ...args: Parameters<History[\"replaceState\"]>): void {\n originalReplaceState.apply(this, args);\n notifyDeferred();\n }\n\n history.pushState = patchedPushState as History[\"pushState\"];\n history.replaceState = patchedReplaceState as History[\"replaceState\"];\n window.addEventListener(\"popstate\", notify);\n\n restorePatch = () => {\n history.pushState = originalPushState;\n history.replaceState = originalReplaceState;\n window.removeEventListener(\"popstate\", notify);\n restorePatch = null;\n };\n}\n\n/**\n * Subscribe to SPA navigations (pushState / replaceState / popstate).\n * Returns an unsubscribe function. Callers must be browser-guarded\n * (`typeof window !== \"undefined\"`) before subscribing.\n */\nexport function onHistoryChange(listener: HistoryChangeListener): () => void {\n if (listeners.size === 0) installPatch();\n listeners.add(listener);\n return () => {\n if (!listeners.delete(listener)) return;\n if (listeners.size === 0) restorePatch?.();\n };\n}\n","// Shared scroll-depth measurement for the scroll_depth and page_exit triggers.\n//\n// The metric is \"percent of page content the bottom of the viewport has\n// passed\": (scrollTop + viewportHeight) / pageHeight. Crucially, a page with\n// no scrollable range (it fits the viewport) measures as `null`, NOT 100 —\n// scroll depth is undefined there, and treating it as 100 is what used to\n// fire every threshold on short pages without any user scrolling.\n\n// Pixels of slack at the true bottom: fractional scroll positions under\n// browser zoom / DPR scaling can leave scrollTop + clientHeight 1-2px short\n// of scrollHeight, which would make 100% unreachable.\nexport const BOTTOM_EPSILON_PX = 2;\n\n/**\n * Current scroll percent of the page, or `null` when the page has no\n * scrollable range (`scrollHeight <= clientHeight`) or the metrics are\n * degenerate. scrollTop is clamped to the scrollable range so iOS\n * rubber-band overscroll can't produce out-of-range values.\n */\nexport function measureScrollPercent(): number | null {\n const root = document.scrollingElement ?? document.documentElement;\n const scrollHeight = root.scrollHeight;\n const clientHeight = root.clientHeight;\n if (scrollHeight <= 0 || clientHeight <= 0) return null;\n // Effectively unscrollable includes pages within the bottom epsilon of the\n // viewport: at scrollTop 0 the epsilon check below would already report 100,\n // turning a 1-2px-taller page into a phantom full read on any stray scroll.\n if (scrollHeight <= clientHeight + BOTTOM_EPSILON_PX) return null;\n const maxTop = scrollHeight - clientHeight;\n const scrollTop = Math.min(Math.max(root.scrollTop, 0), maxTop);\n if (scrollTop + clientHeight >= scrollHeight - BOTTOM_EPSILON_PX) return 100;\n return Math.max(1, Math.min(100, Math.round(((scrollTop + clientHeight) / scrollHeight) * 100)));\n}\n\n/**\n * Snapshot the baseline scroll percent — the fraction of the page already\n * visible with zero scrolling — once the page has actually painted.\n *\n * Double requestAnimationFrame: on attach and especially on SPA navigation\n * the new page's content and the framework's scroll-to-top haven't settled\n * yet when our code runs; measuring after two frames reads the settled\n * layout. Returns a cancel function — call it on detach or when scheduling\n * a replacement snapshot (re-navigation).\n */\nexport function scheduleBaselineSnapshot(\n onSnapshot: (baselinePercent: number | null) => void,\n): () => void {\n let rafId = requestAnimationFrame(() => {\n rafId = requestAnimationFrame(() => {\n onSnapshot(measureScrollPercent());\n });\n });\n return () => cancelAnimationFrame(rafId);\n}\n\nexport interface BaselineGate {\n /** Discard state and schedule a fresh post-paint snapshot (attach / SPA nav). */\n rebaseline(): void;\n /** Cancel any pending snapshot without touching state (call on detach). */\n cancel(): void;\n /**\n * The gating baseline, or null while the snapshot is pending or when the\n * page had no scrollable range. For pages that grow after the snapshot\n * (skeleton/streaming renders) this is the position of the first scroll\n * that found a scrollable page, not the at-load fraction.\n */\n baseline(): number | null;\n /**\n * Sample the current scroll percent through the gate. Returns null when the\n * scroll event must be ignored: the snapshot hasn't landed (SPA\n * scroll-to-top / restoration noise), the page is unscrollable, or this\n * very sample established the lazy baseline (depth counts from the NEXT\n * scroll). A non-null return guarantees baseline() is non-null.\n */\n sample(): number | null;\n}\n\n/**\n * The baseline machinery shared by the scroll_depth and page_exit triggers —\n * one implementation so the two can't drift.\n */\nexport function createBaselineGate(): BaselineGate {\n let baselinePercent: number | null = null;\n let ready = false;\n let cancelSnapshot: (() => void) | null = null;\n\n return {\n rebaseline() {\n cancelSnapshot?.();\n ready = false;\n baselinePercent = null;\n cancelSnapshot = scheduleBaselineSnapshot((b) => {\n baselinePercent = b;\n ready = true;\n });\n },\n cancel() {\n cancelSnapshot?.();\n },\n baseline() {\n return ready ? baselinePercent : null;\n },\n sample() {\n if (!ready) return null;\n if (baselinePercent === null) {\n // Lazy re-baseline: the page wasn't scrollable at snapshot time.\n baselinePercent = measureScrollPercent();\n return null;\n }\n return measureScrollPercent();\n },\n };\n}\n","// scroll_depth automatic trigger.\n//\n// Fires once per configured threshold per page, but only for depth the user\n// actually earned by scrolling:\n//\n// - A baseline percent (the fraction of the page visible with zero\n// scrolling) is snapshotted after the page paints (double-rAF, via the\n// shared BaselineGate). Thresholds at or below the baseline were \"free\"\n// at load and are suppressed for the whole pageview — a page that fits\n// the viewport (baseline null) never fires at all. This scales across\n// viewports automatically: the same page has a lower baseline on a\n// phone, so more thresholds become earnable there.\n// - Thresholds are only evaluated from scroll events, and scroll events\n// are ignored until the baseline snapshot lands — so SPA scroll-to-top /\n// popstate scroll restoration during a navigation can't fire anything.\n// Restoration that lands AFTER the snapshot (browsers defer it on\n// incrementally-rendered pages) is indistinguishable from a user scroll\n// and re-emits threshold events for depth reached on a prior visit to\n// the path; the linked gtag conversions stay deduped (session-scoped\n// per goal+path) and backend evaluation takes the session max, so the\n// cost is a duplicate analytics event, not a duplicate conversion.\n// - Lazy re-baseline: if the page wasn't scrollable at snapshot time\n// (skeleton/streaming render), the first scroll event that finds a\n// scrollable page establishes the baseline instead of firing.\n//\n// Suppression is deliberately permanent per pageview: content that grows\n// after the snapshot can't un-suppress a threshold (conservative — every\n// timing race under-counts rather than false-fires).\n//\n// The fired set resets on SPA navigation when the pathname actually changes\n// (pushState / replaceState / popstate); same-path replaceState (query param\n// updates) is a no-op via the pathname guard.\n\nimport type { ScrollDepthConfig } from \"../events/scroll-depth\";\nimport type { TrackingClient } from \"../ingest\";\nimport { onHistoryChange } from \"./navigation\";\nimport { createBaselineGate } from \"./scroll-measurement\";\n\n/**\n * Attach the automatic `scroll_depth` trigger.\n *\n * Installs a throttled scroll listener, fires each configured threshold once\n * per page (baseline-gated, real scrolls only), and returns a detach function.\n */\nexport function attachScrollDepth(client: TrackingClient, config: ScrollDepthConfig): () => void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n return () => {};\n }\n\n const thresholds = new Set(config.thresholds);\n let firedForPath = new Set<number>();\n let currentPath = window.location.pathname;\n let rafId: number | null = null;\n const gate = createBaselineGate();\n\n function checkThresholds(): void {\n const percent = gate.sample();\n if (percent === null) return;\n const baseline = gate.baseline();\n if (baseline === null) return; // unreachable when percent !== null; keeps the types honest\n for (const threshold of thresholds) {\n if (threshold <= baseline) continue; // visible at load — never earnable this pageview\n if (percent >= threshold && !firedForPath.has(threshold)) {\n firedForPath.add(threshold);\n client.trackEvent({\n eventType: \"scroll_depth\",\n metadata: {\n depth_percent: threshold,\n page: { path: currentPath },\n } as unknown as Record<string, unknown>,\n pageUrl: window.location.href,\n occurredAt: null,\n });\n }\n }\n }\n\n function onScroll(): void {\n if (rafId !== null) return;\n rafId = requestAnimationFrame(() => {\n rafId = null;\n checkThresholds();\n });\n }\n\n function resetIfPathChanged(): void {\n const newPath = window.location.pathname;\n if (newPath === currentPath) return;\n currentPath = newPath;\n firedForPath = new Set();\n gate.rebaseline();\n }\n\n const unsubscribeNav = onHistoryChange(resetIfPathChanged);\n window.addEventListener(\"scroll\", onScroll, { passive: true });\n\n gate.rebaseline();\n\n return () => {\n if (rafId !== null) cancelAnimationFrame(rafId);\n gate.cancel();\n unsubscribeNav();\n window.removeEventListener(\"scroll\", onScroll);\n };\n}\n","// form_start automatic trigger.\n//\n// Uses focusin event delegation on document to detect the first field\n// interaction inside a <form>. Fires once per form per page lifecycle.\n// Dedupes via a Set keyed on form id/action. Resets on SPA navigation.\n\nimport type { FormStartConfig } from \"../events/form-start\";\nimport type { TrackingClient } from \"../ingest\";\n\n/**\n * Attach the automatic `form_start` trigger.\n *\n * Uses `focusin` event delegation to detect the first interaction with each\n * matching form and returns a detach function.\n */\nexport function attachFormStart(client: TrackingClient, config: FormStartConfig): () => void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n return () => {};\n }\n\n const selector = config.selector ?? \"form\";\n let firedForms = new Set<string>();\n let currentPath = window.location.pathname;\n\n function getFormKey(form: HTMLFormElement): string {\n if (form.id) return `id:${form.id}`;\n // Use getAttribute — the DOM property always returns a resolved URL,\n // never \"\" or null, so it can't distinguish \"no action\" from \"action=current page\".\n const explicitAction = form.getAttribute(\"action\");\n if (explicitAction) return `action:${explicitAction}`;\n const forms = Array.from(document.querySelectorAll(selector));\n return `index:${forms.indexOf(form)}`;\n }\n\n function onFocusIn(event: FocusEvent): void {\n const target = event.target;\n if (!(target instanceof HTMLElement)) return;\n\n // Walk up to the nearest matching <form>.\n const form = target.closest(selector) as HTMLFormElement | null;\n if (!form || form.tagName !== \"FORM\") return;\n\n const key = getFormKey(form);\n if (firedForms.has(key)) return;\n firedForms.add(key);\n\n client.trackEvent({\n eventType: \"form_start\",\n metadata: {\n form: {\n id: form.id || \"\",\n action: form.getAttribute(\"action\") ?? null,\n },\n page: { path: window.location.pathname },\n } as unknown as Record<string, unknown>,\n pageUrl: window.location.href,\n occurredAt: null,\n });\n }\n\n function resetIfPathChanged(): void {\n const newPath = window.location.pathname;\n if (newPath === currentPath) return;\n currentPath = newPath;\n firedForms = new Set();\n }\n\n const originalPushState = history.pushState.bind(history);\n const originalReplaceState = history.replaceState.bind(history);\n\n function patchedPushState(this: History, ...args: Parameters<History[\"pushState\"]>): void {\n originalPushState(...args);\n setTimeout(resetIfPathChanged, 0);\n }\n function patchedReplaceState(this: History, ...args: Parameters<History[\"replaceState\"]>): void {\n originalReplaceState(...args);\n setTimeout(resetIfPathChanged, 0);\n }\n\n history.pushState = patchedPushState as History[\"pushState\"];\n history.replaceState = patchedReplaceState as History[\"replaceState\"];\n window.addEventListener(\"popstate\", resetIfPathChanged);\n document.addEventListener(\"focusin\", onFocusIn);\n\n return () => {\n history.pushState = originalPushState;\n history.replaceState = originalReplaceState;\n window.removeEventListener(\"popstate\", resetIfPathChanged);\n document.removeEventListener(\"focusin\", onFocusIn);\n };\n}\n","// page_exit automatic trigger (SDK-internal — attached unconditionally).\n//\n// Emits one `page_exit` per visible page segment with the ACTIVE dwell time\n// and the max scroll depth reached, on three leave signals:\n// - SPA navigation away (pushState / replaceState / popstate, pathname change)\n// - the tab going hidden (visibilitychange — the reliable mobile signal)\n// - pagehide (tab close / hard navigation)\n//\n// Dwell is visibility-aware like time_on_site: hidden time never counts. When\n// a hidden tab becomes visible again, the accumulator resets and the next\n// leave emits another segment — the backend sums segments per session.\n//\n// CRITICAL: on pagehide/hidden this trigger flushes the client itself via\n// `flushBeacon()` (keepalive transport). The ingest client's own\n// flush-on-pagehide listener is registered at client creation — BEFORE this\n// trigger attaches — so it fires first, sending the queue WITHOUT our\n// just-enqueued page_exit. We must therefore push it ourselves, and a plain\n// `flush()` is aborted by the browser on unload — only the keepalive beacon\n// survives, so `flushBeacon` (not `flush`) is load-bearing here.\n\nimport type { TrackingClient } from \"../ingest\";\nimport { onHistoryChange } from \"./navigation\";\nimport { createBaselineGate } from \"./scroll-measurement\";\n\n// Visible segments shorter than this are noise (no human reads a page for tens\n// of ms) and, load-bearingly, this drops the phantom emit from the\n// pagehide/visibilitychange double-fire. See emitSegment.\nconst MIN_SEGMENT_MS = 50;\n\nexport function attachPageExit(client: TrackingClient): () => void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n return () => {};\n }\n\n let currentPath = window.location.pathname;\n let activeSince: number | null = document.visibilityState === \"visible\" ? Date.now() : null;\n let accumulatedMs = 0;\n let maxScrollPercent: number | null = null;\n let rafId: number | null = null;\n // Shared baseline machinery with the scroll_depth trigger: scroll events\n // are gated until the post-paint snapshot lands (SPA scroll-to-top noise\n // can't register as depth), and a page with no scrollable range keeps\n // max_scroll_percent null instead of the old phantom 100.\n const gate = createBaselineGate();\n\n function onScroll(): void {\n if (rafId !== null) return;\n rafId = requestAnimationFrame(() => {\n rafId = null;\n const percent = gate.sample();\n if (percent !== null && (maxScrollPercent === null || percent > maxScrollPercent)) {\n maxScrollPercent = percent;\n }\n });\n }\n\n function settledDwellMs(): number {\n let total = accumulatedMs;\n if (activeSince !== null) {\n total += Date.now() - activeSince;\n }\n return Math.max(0, Math.round(total));\n }\n\n function emitSegment(path: string, flush: boolean): void {\n const dwell = settledDwellMs();\n // A segment shorter than this carries no signal — skip it. This also\n // absorbs the phantom emit when pagehide and visibilitychange:hidden both\n // fire on the same unload: the first emits the real segment and closes it\n // (activeSince = null below), so the second computes ~0ms and is dropped.\n if (dwell < MIN_SEGMENT_MS) return;\n client.trackEvent({\n eventType: \"page_exit\",\n metadata: {\n dwell_ms: dwell,\n max_scroll_percent: maxScrollPercent,\n // Lets the backend tell \"scrolled to the bottom\" apart from \"the page\n // was barely scrollable\". null = unscrollable page or the segment\n // ended before the post-paint snapshot landed. For pages that grew\n // after the snapshot this is the first-scroll position, not the\n // at-load fraction (see BaselineGate.baseline).\n scroll_baseline_percent: gate.baseline(),\n page: { path },\n } as unknown as Record<string, unknown>,\n pageUrl: window.location.href,\n occurredAt: null,\n });\n if (flush) {\n // The client's own pagehide flush already ran without this event — push\n // it through the keepalive beacon so it survives unload.\n client.flushBeacon();\n }\n // Close the segment. A new one only begins on an explicit visible/navigate\n // (both set activeSince themselves) — NOT here: at pagehide the document is\n // often still \"visible\", so restarting a segment would make the following\n // visibilitychange:hidden emit a phantom ~0ms duplicate.\n accumulatedMs = 0;\n activeSince = null;\n }\n\n function onNavigate(): void {\n const newPath = window.location.pathname;\n if (newPath === currentPath) return;\n emitSegment(currentPath, false);\n currentPath = newPath;\n maxScrollPercent = null;\n gate.rebaseline();\n accumulatedMs = 0;\n activeSince = document.visibilityState === \"visible\" ? Date.now() : null;\n }\n\n function onVisibilityChange(): void {\n if (document.visibilityState === \"hidden\") {\n emitSegment(currentPath, true);\n } else {\n // Back from hidden: a fresh segment starts accruing.\n activeSince = Date.now();\n }\n }\n\n function onPageHide(): void {\n emitSegment(currentPath, true);\n }\n\n const unsubscribeNav = onHistoryChange(onNavigate);\n window.addEventListener(\"scroll\", onScroll, { passive: true });\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n window.addEventListener(\"pagehide\", onPageHide);\n\n gate.rebaseline();\n\n return () => {\n if (rafId !== null) cancelAnimationFrame(rafId);\n gate.cancel();\n unsubscribeNav();\n window.removeEventListener(\"scroll\", onScroll);\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n window.removeEventListener(\"pagehide\", onPageHide);\n };\n}\n","// cta_click auto-capture (opt-in via the cta_click registration config).\n//\n// A single delegated click listener fires `cta_click` for any element matching\n// the configured selector (default `[data-aranova-cta]`). The event itself\n// stays `manual` in the registry — consumers can still fire it from code; this\n// trigger just removes the need to hand-instrument every button.\n//\n// CTA identity: the `data-aranova-cta` attribute value when present, else the\n// element's trimmed text (capped). `href` and a short `element` descriptor\n// (tag#id) ride along so the dashboard can tie clicks to concrete UI.\n\nimport { registerCapability } from \"../capabilities\";\nimport type { CtaClickConfig } from \"../events/cta-click\";\nimport type { TrackingClient } from \"../ingest\";\n\nexport const DEFAULT_CTA_SELECTOR = \"[data-aranova-cta]\";\n\nconst CTA_NAME_MAX_LENGTH = 120;\n\nfunction describeElement(el: Element): string {\n const tag = el.tagName.toLowerCase();\n return el.id ? `${tag}#${el.id}` : tag;\n}\n\nfunction resolveCtaName(el: Element): string {\n const explicit = el.getAttribute(\"data-aranova-cta\");\n if (explicit && explicit.trim().length > 0) return explicit.trim();\n const text = (el.textContent ?? \"\").trim().replaceAll(/\\s+/g, \" \");\n if (text.length > 0) return text.slice(0, CTA_NAME_MAX_LENGTH);\n return describeElement(el);\n}\n\n/**\n * Attach the delegated cta_click auto-capture listener. Returns a detach\n * function. No-ops (returns a noop detacher) when `autoCapture` is absent.\n */\nexport function attachCtaClickCapture(client: TrackingClient, config: CtaClickConfig): () => void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n return () => {};\n }\n const autoCapture = config.autoCapture;\n if (!autoCapture) {\n return () => {};\n }\n // Registered past the guard, so the capability means \"the listener is\n // attached\", not \"the option was passed\".\n registerCapability(\"cta_click_capture\");\n const selector = autoCapture.selector ?? DEFAULT_CTA_SELECTOR;\n\n function onClick(event: MouseEvent): void {\n const target = event.target;\n if (!(target instanceof Element)) return;\n let matched: Element | null = null;\n try {\n matched = target.closest(selector);\n } catch {\n return; // invalid selector — never break the host site\n }\n if (matched === null) return;\n const href =\n matched instanceof HTMLAnchorElement ? matched.href || null : matched.getAttribute(\"href\");\n client.trackEvent({\n eventType: \"cta_click\",\n metadata: {\n cta_name: resolveCtaName(matched),\n page: { path: window.location.pathname },\n section: matched.getAttribute(\"data-aranova-section\"),\n destination_url: href,\n href,\n element: describeElement(matched),\n } as unknown as Record<string, unknown>,\n pageUrl: window.location.href,\n occurredAt: null,\n });\n }\n\n // Capture phase so navigations that stop propagation still get counted.\n document.addEventListener(\"click\", onClick, true);\n return () => {\n document.removeEventListener(\"click\", onClick, true);\n };\n}\n","// phone_click auto-capture (opt-in via the phone_click registration config).\n//\n// A single delegated click listener fires `phone_click` for any `tel:` link\n// matching the configured selector (default `a[href^=\"tel:\"]`). The event\n// itself stays `manual` in the registry — consumers can still fire it from\n// code; this trigger just removes the need to hand-instrument every call link.\n//\n// Unlike cta_click, a captured phone_click ALSO drives conversion auto-fire: a\n// `tel:` tap is an unambiguous on-site conversion, so `conversion-autofire`\n// fires a linked `phone_click` event-goal (see thresholdMet). The number rides\n// along as E.164 (`toE164`, falling back to the raw href value) so the\n// dashboard can tie clicks to a concrete number.\n//\n// Overlap caveat: the default selectors don't collide (`a[href^=\"tel:\"]` vs\n// cta_click's `[data-aranova-cta]`). If an operator tags a `tel:` link with\n// `data-aranova-cta` AND enables both auto-captures, one tap emits two analytics\n// events — but only phone_click auto-fires a conversion (cta_click is fire-on-\n// demand via trackConversion), so there's no double-count of the conversion.\n\nimport { registerCapability } from \"../capabilities\";\nimport type { PhoneClickConfig, PhoneClickMetadata } from \"../events/phone-click\";\nimport type { TrackingClient } from \"../ingest\";\nimport { toE164 } from \"../phone\";\n\nexport const DEFAULT_TEL_SELECTOR = 'a[href^=\"tel:\"]';\n\n/** decodeURIComponent throws `URIError` on a malformed `%` sequence (e.g. `tel:+1%`),\n * which a `tel:` href can legitimately carry — return the raw value instead of letting\n * it escape the click listener (the module's no-throw contract). */\nfunction safeDecodeURIComponent(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/** The dialable number from a `tel:` href, normalized to E.164 when possible. */\nfunction resolvePhoneNumber(el: Element): string {\n const href = el instanceof HTMLAnchorElement ? el.href : (el.getAttribute(\"href\") ?? \"\");\n // Strip the scheme (and any `;`-suffixed params like `tel:+123;ext=9`) before normalizing.\n const raw = safeDecodeURIComponent(href.replace(/^tel:/i, \"\").split(\";\")[0]).trim();\n return toE164(raw) ?? raw;\n}\n\n/**\n * Attach the delegated phone_click auto-capture listener. Returns a detach\n * function. No-ops (returns a noop detacher) when `autoCapture` is absent.\n */\nexport function attachPhoneClickCapture(\n client: TrackingClient,\n config: PhoneClickConfig,\n): () => void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n return () => {};\n }\n const autoCapture = config.autoCapture;\n if (!autoCapture) {\n return () => {};\n }\n // Registered past the guard, so the capability means \"the listener is\n // attached\", not \"the option was passed\".\n registerCapability(\"phone_click_capture\");\n const selector = autoCapture.selector ?? DEFAULT_TEL_SELECTOR;\n\n function onClick(event: MouseEvent): void {\n const target = event.target;\n if (!(target instanceof Element)) return;\n let matched: Element | null = null;\n try {\n matched = target.closest(selector);\n } catch {\n return; // invalid selector — never break the host site\n }\n if (matched === null) return;\n // Typed so the emitted shape is checked against the schema (not an opaque cast).\n const metadata: PhoneClickMetadata = {\n phone_number: resolvePhoneNumber(matched),\n page: { path: window.location.pathname },\n section: matched.getAttribute(\"data-aranova-section\"),\n };\n client.trackEvent({\n eventType: \"phone_click\",\n metadata,\n pageUrl: window.location.href,\n occurredAt: null,\n });\n }\n\n // Capture phase so navigations that stop propagation still get counted.\n document.addEventListener(\"click\", onClick, true);\n return () => {\n document.removeEventListener(\"click\", onClick, true);\n };\n}\n","/**\n * Thrown on a non-2xx from any awaited Aranova API call.\n *\n * Lives here rather than inside one resource because more than one resource\n * needs it, and a duplicate class would be a genuine hazard: a name star-exported\n * from two modules is silently dropped unless both resolve to the same binding.\n */\nexport class AranovaApiError extends Error {\n readonly status: number;\n readonly code: string | undefined;\n readonly requestId: string | undefined;\n\n constructor(message: string, options: { status: number; code?: string; requestId?: string }) {\n super(message);\n this.name = \"AranovaApiError\";\n this.status = options.status;\n this.code = options.code;\n this.requestId = options.requestId;\n }\n}\n","import {\n API_KEY_HEADER,\n SDK_ENVIRONMENT_HEADER,\n SDK_PACKAGE_HEADER,\n SDK_SURFACE_HEADER,\n SDK_VERSION_HEADER,\n} from \"../../ingest\";\nimport { AranovaApiError } from \"./errors\";\n\n/** Shared config for every awaited (non fire-and-forget) API helper. */\nexport interface ApiTransportConfig {\n /** Public (`aranv_pk_…`) or secret (`aranv_sk_…`) API key. */\n apiKey: string;\n /** Base tracking endpoint, e.g. `https://aranovainternal-production.up.railway.app/tracking`. */\n endpoint: string;\n /** Optional SDK identity headers (mirrors the event ingest client). */\n sdkVersion?: string;\n packageName?: string;\n surface?: string;\n environment?: string;\n}\n\nfunction identityHeaders(config: ApiTransportConfig): Record<string, string> {\n const headers: Record<string, string> = { [API_KEY_HEADER]: config.apiKey };\n if (config.sdkVersion) headers[SDK_VERSION_HEADER] = config.sdkVersion;\n if (config.packageName) headers[SDK_PACKAGE_HEADER] = config.packageName;\n if (config.surface) headers[SDK_SURFACE_HEADER] = config.surface;\n if (config.environment) headers[SDK_ENVIRONMENT_HEADER] = config.environment;\n return headers;\n}\n\nfunction joinUrl(endpoint: string, path: string): string {\n return `${endpoint.replace(/\\/$/, \"\")}${path}`;\n}\n\n/**\n * Single awaited request. Unlike the event queue, this surfaces failures: any\n * non-2xx rejects with an {@link AranovaApiError}. Returns `undefined` for 204.\n */\nexport async function apiRequest<T>(\n config: ApiTransportConfig,\n method: string,\n path: string,\n body?: unknown,\n extraHeaders?: Record<string, string>,\n): Promise<T> {\n const headers = { ...identityHeaders(config), ...extraHeaders };\n if (body !== undefined) headers[\"Content-Type\"] = \"application/json\";\n\n const response = await fetch(joinUrl(config.endpoint, path), {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n\n if (!response.ok) {\n let detail: string | undefined;\n let code: string | undefined;\n try {\n const parsed: unknown = await response.json();\n if (parsed && typeof parsed === \"object\") {\n const record = parsed as Record<string, unknown>;\n if (typeof record.detail === \"string\") detail = record.detail;\n if (typeof record.code === \"string\") code = record.code;\n }\n } catch {\n // non-JSON error body — fall back to status text\n }\n throw new AranovaApiError(detail ?? response.statusText ?? \"Request failed\", {\n status: response.status,\n code,\n requestId: response.headers.get(\"x-request-id\") ?? undefined,\n });\n }\n\n if (response.status === 204) return undefined as T;\n return (await response.json()) as T;\n}\n","// Hoisted to `resources/http/request`. Both names below are public API via\n// `sales-public.ts`, so they keep their original spellings.\nimport type { ApiTransportConfig } from \"../http/request\";\nimport { apiRequest } from \"../http/request\";\n\nexport type SalesTransportConfig = ApiTransportConfig;\nexport const salesRequest = apiRequest;\n","import type {\n BusinessConfig,\n CustomerGetOptions,\n CustomerGetResult,\n CustomerKpis,\n CustomerListPage,\n CustomerListQuery,\n CustomerSummaryQuery,\n Sale,\n SaleCursorPage,\n SaleInput,\n SaleListQueryV2,\n SaleSummaryQueryV2,\n SaleSummaryV2,\n SaleUpdateInput,\n SupportedCurrency,\n} from \"./schema\";\nimport { registerCapability } from \"../../capabilities\";\nimport type { ConversionConfigStore } from \"../conversion-config\";\nimport { fireConversionWithConsent } from \"../conversion-firing\";\nimport type { TrackingConfigRuntime } from \"../tracking-config-runtime\";\nimport { getConsentState } from \"../../consent\";\nimport { stashUserData, type ConversionUserData } from \"../../user-data\";\nimport { salesRequest, type SalesTransportConfig } from \"./transport\";\nimport { fromMinor } from \"./money\";\n\n/** Config for {@link createSalesClient}. */\nexport interface SalesClientConfig extends SalesTransportConfig {\n /** Applied when an individual `record()` call omits `currency`. */\n defaultCurrency?: SupportedCurrency;\n /**\n * GAP28: when present, `record()` ALSO fires a real-time on-site conversion\n * (`gtag('event','conversion')`) for any recorded service that has a `firing` send_to in\n * the resolved config. Consent-gated + de-duped; no-ops server-side. Wire it from\n * `resolveConversionConfig(...)`.\n */\n firing?: Pick<ConversionConfigStore, \"getFiring\"> | TrackingConfigRuntime;\n}\n\n// Fire the on-site conversion(s) for a just-recorded sale. Per-service value = the sale's\n// amount when present, else the action's configured default from config (Google applies\n// its own default when neither is sent). transaction_id ties the gtag fire to the sale so\n// retries/reloads de-dup within the WEBPAGE action.\nfunction fireRecordedConversions(\n firing: Pick<ConversionConfigStore, \"getFiring\"> | TrackingConfigRuntime | undefined,\n input: {\n external_id?: string | null;\n amount_total_cents?: number | null;\n customer_email?: string | null;\n customer_phone?: string | null;\n },\n recorded: { service?: string | null; amount_cents: number | null }[],\n sale: Sale,\n currency: SupportedCurrency,\n): void {\n if (!firing) return;\n // Enhanced conversions: the sale's own customer identifiers are the\n // strongest possible user_data signal — pass them into every per-service\n // fire, and refresh the stash so later same-page event-goal fires match too.\n const userData: ConversionUserData | null =\n input.customer_email || input.customer_phone\n ? { email: input.customer_email ?? null, phone: input.customer_phone ?? null }\n : null;\n // Denied consent: the fires below no-op anyway, so don't retain the\n // identifiers in page memory either.\n if (userData && getConsentState() !== \"denied\") stashUserData(userData);\n const txnBase = input.external_id ?? sale.id;\n for (const item of recorded) {\n if (!item.service) continue;\n if (\"fireConversion\" in firing) {\n firing.fireConversion(item.service, {\n value: item.amount_cents != null ? fromMinor(item.amount_cents, currency) : undefined,\n currency,\n transactionId: `${txnBase}:${item.service}`,\n });\n continue;\n }\n const config = firing.getFiring(item.service);\n if (!config) continue;\n const cents = item.amount_cents ?? config.value_cents ?? null;\n fireConversionWithConsent(\n {\n sendTo: config.send_to,\n value: cents != null ? fromMinor(cents, currency) : null,\n currency: config.currency ?? currency,\n transactionId: `${txnBase}:${item.service}`,\n },\n { userData },\n );\n }\n}\n\n/** Phone-keyed customer rollups (sk-only; a public key gets a `403`). */\nexport interface SalesCustomersClient {\n list(query?: CustomerListQuery): Promise<CustomerListPage>;\n /** `id` is the customer's E.164 phone. */\n get(id: string, options?: CustomerGetOptions): Promise<CustomerGetResult>;\n summary(query?: CustomerSummaryQuery): Promise<CustomerKpis>;\n}\n\n/** Business config (low-sensitivity — accepts a public or secret key). */\nexport interface SalesBusinessClient {\n config(): Promise<BusinessConfig>;\n}\n\n/**\n * One isomorphic sales client — what a key may *do* is enforced by the backend,\n * not by hiding methods. A **public** key (`aranv_pk_…`) may `record` (the\n * backend rejects reads/CRUD from it with a `403`); a **secret** key\n * (`aranv_sk_…`), used **server-side only**, gets full read/list/update/delete.\n * Never ship a secret key in a browser bundle.\n *\n * Generic over the service-key union `TService` and the manual-conversion key union\n * `TConversion`: bind the types emitted by `@aranova/tracking-cli gen` (`AranovaService`\n * and `AranovaConversion`) for compile-time-checked `service` / `trackConversion` keys.\n */\nexport interface SalesClient<\n TService extends string = string,\n TConversion extends string = string,\n> {\n record(\n input: Omit<SaleInput, \"currency\" | \"occurred_at\" | \"service\" | \"services\"> & {\n service?: TService | null;\n // XOR with `service`: record multiple services in one sale, each priced\n // individually. `amount_total_cents` is then optional (the backend derives\n // it as the sum). Keys are checked against the codegen `TService` union.\n services?: Array<{ service: TService; amount_cents: number }>;\n currency?: SupportedCurrency;\n occurred_at?: string;\n },\n ): Promise<Sale>;\n /**\n * Record a revenue sale — the intent-revealing alias of {@link record} in the unified-goal\n * API. POSTs `/sales` and ALSO fires the on-site conversion when the sale-goal is\n * WEBPAGE-mapped. Use this for anything with real revenue; use {@link trackConversion} for a\n * non-revenue on-page event.\n */\n recordSale(\n input: Omit<SaleInput, \"currency\" | \"occurred_at\" | \"service\" | \"services\"> & {\n service?: TService | null;\n services?: Array<{ service: TService; amount_cents: number }>;\n currency?: SupportedCurrency;\n occurred_at?: string;\n },\n ): Promise<Sale>;\n /**\n * Fire ONLY the on-site conversion for an event-goal `key` — for MANUAL event-goals\n * (`form_submit`, `phone_click`, `cta_click`) the consumer triggers explicitly. No `/sales`\n * write. No-ops when the goal isn't WEBPAGE-mapped (no resolved `send_to`) or the config\n * isn't wired. Consent-gated + de-duped. (Automatic event-goals fire themselves — no call.)\n */\n trackConversion(\n key: TConversion,\n options?: {\n transactionId?: string | null;\n value?: number | null;\n currency?: SupportedCurrency;\n /**\n * Enhanced conversions override: the visitor's own email/phone for this\n * conversion. Wins per-key over the automatic form-submit stash — the\n * escape hatch when a form's fields defeat the extraction heuristics.\n */\n userData?: ConversionUserData | null;\n },\n ): void;\n /** Keyset list with optional server sort + opt-in `total_count`. */\n list(query?: SaleListQueryV2): Promise<SaleCursorPage>;\n /**\n * Currency-grouped aggregations for the key's business. Additive v2 options:\n * calendar/custom ranges, IANA `timezone`, `granularity`, and `compare_to`.\n * Legacy `24h/7d/30d` keep their exact prior numbers. Secret key only.\n */\n summary(query: SaleSummaryQueryV2): Promise<SaleSummaryV2>;\n get(id: string): Promise<Sale>;\n update(\n id: string,\n patch: Omit<SaleUpdateInput, \"service\" | \"services\"> & {\n service?: TService | null;\n // Present ⇒ replaces the whole service set (XOR with `service`); the\n // backend recomputes `amount_total_cents` from the sum.\n services?: Array<{ service: TService; amount_cents: number }>;\n },\n ): Promise<Sale>;\n delete(id: string): Promise<void>;\n /** Phone-keyed customer rollups (sk-only). */\n customers: SalesCustomersClient;\n /** Business config (pk or sk). */\n business: SalesBusinessClient;\n}\n\nexport function createSalesClient<\n TService extends string = string,\n TConversion extends string = string,\n>(config: SalesClientConfig): SalesClient<TService, TConversion> {\n // `firing` is what makes trackConversion do anything at all — without it the\n // method returns immediately, so its presence IS the manual-goal capability.\n // The sales LEDGER verbs are not reported: they are moving to the internal\n // app and are not a client-site capability.\n if (config.firing) registerCapability(\"conversion_goals_manual\");\n\n type RecordInput = Parameters<SalesClient<TService, TConversion>[\"record\"]>[0];\n\n async function record(input: RecordInput): Promise<Sale> {\n const currency = input.currency ?? config.defaultCurrency;\n if (!currency) {\n throw new Error(\n \"record: `currency` is required (pass it on the sale or set config.defaultCurrency)\",\n );\n }\n const body: SaleInput = {\n ...input,\n currency,\n occurred_at: input.occurred_at ?? new Date().toISOString(),\n };\n const sale = await salesRequest<Sale>(config, \"POST\", \"/sales\", body);\n // GAP28: fire the real-time on-site conversion(s) AFTER the sale is recorded, so the\n // gtag transaction_id and the offline path agree. Never throws (best-effort fire).\n const recorded = input.services?.length\n ? input.services.map((s) => ({\n service: s.service,\n amount_cents: s.amount_cents,\n }))\n : [\n {\n service: input.service,\n amount_cents: input.amount_total_cents ?? null,\n },\n ];\n fireRecordedConversions(config.firing, input, recorded, sale, currency);\n return sale;\n }\n\n return {\n record,\n // recordSale is the intent-revealing alias — same behavior, clearer call site.\n recordSale: record,\n\n trackConversion(key, options) {\n // Manual event-goal: fire the WEBPAGE conversion only (no /sales). No-op when the goal\n // isn't WEBPAGE-mapped or the config isn't wired.\n if (config.firing && \"fireConversion\" in config.firing) {\n // Enhanced conversions on the runtime path: the drain fires gtag\n // itself, reading user_data from the stash — persist the explicit\n // override there so it isn't lost to the queue.\n if (options?.userData && getConsentState() !== \"denied\") stashUserData(options.userData);\n config.firing.fireConversion(key, {\n value: options?.value ?? undefined,\n currency: options?.currency ?? config.defaultCurrency ?? undefined,\n transactionId: options?.transactionId ?? null,\n });\n return;\n }\n const firing = config.firing?.getFiring(key);\n if (!firing) return;\n const currency = firing.currency ?? options?.currency ?? config.defaultCurrency ?? null;\n const cents = firing.value_cents ?? null;\n const value =\n options?.value ??\n (cents != null && currency ? fromMinor(cents, currency as SupportedCurrency) : null);\n fireConversionWithConsent(\n {\n sendTo: firing.send_to,\n value,\n currency,\n transactionId: options?.transactionId ?? null,\n },\n { userData: options?.userData },\n );\n },\n\n async list(query) {\n // Pagination + sort travel at the top level; everything else is a filter.\n const { cursor, limit, sort, order, want_total, ...filters } = query ?? {};\n return salesRequest<SaleCursorPage>(config, \"POST\", \"/sales/query\", {\n filters,\n ...(limit !== undefined ? { limit } : {}),\n ...(cursor !== undefined ? { cursor } : {}),\n ...(sort !== undefined ? { sort } : {}),\n ...(order !== undefined ? { order } : {}),\n ...(want_total !== undefined ? { want_total } : {}),\n });\n },\n\n async summary(query) {\n const {\n range,\n include_categories,\n include_deleted_services,\n top_n,\n since,\n until,\n timezone,\n granularity,\n compare_to,\n ...filters\n } = query;\n return salesRequest<SaleSummaryV2>(config, \"POST\", \"/sales/summary\", {\n filters,\n ...(range !== undefined ? { range } : {}),\n ...(include_categories !== undefined ? { include_categories } : {}),\n ...(include_deleted_services !== undefined ? { include_deleted_services } : {}),\n ...(top_n !== undefined ? { top_n } : {}),\n ...(since !== undefined ? { since } : {}),\n ...(until !== undefined ? { until } : {}),\n ...(timezone !== undefined ? { timezone } : {}),\n ...(granularity !== undefined ? { granularity } : {}),\n ...(compare_to !== undefined ? { compare_to } : {}),\n });\n },\n\n async get(id) {\n return salesRequest<Sale>(config, \"GET\", `/sales/${id}`);\n },\n\n async update(id, patch) {\n return salesRequest<Sale>(config, \"PATCH\", `/sales/${id}`, patch);\n },\n\n async delete(id) {\n await salesRequest<void>(config, \"DELETE\", `/sales/${id}`);\n },\n\n customers: {\n async list(query) {\n const { segment, sort, order, cursor, limit, want_total, ...filters } = query ?? {};\n return salesRequest<CustomerListPage>(config, \"POST\", \"/customers/query\", {\n filters,\n ...(segment !== undefined ? { segment } : {}),\n ...(sort !== undefined ? { sort } : {}),\n ...(order !== undefined ? { order } : {}),\n ...(cursor !== undefined ? { cursor } : {}),\n ...(limit !== undefined ? { limit } : {}),\n ...(want_total !== undefined ? { want_total } : {}),\n });\n },\n async get(id, options) {\n const params = new URLSearchParams();\n if (options?.include_sales !== undefined)\n params.set(\"include_sales\", String(options.include_sales));\n if (options?.limit !== undefined) params.set(\"limit\", String(options.limit));\n if (options?.cursor != null) params.set(\"cursor\", options.cursor);\n const qs = params.toString();\n // `id` is the E.164 phone (`+1…`) — must be URL-encoded.\n return salesRequest<CustomerGetResult>(\n config,\n \"GET\",\n `/customers/${encodeURIComponent(id)}${qs ? `?${qs}` : \"\"}`,\n );\n },\n async summary(query) {\n const { range, since, until, timezone, compare_to, ...filters } = query ?? {};\n return salesRequest<CustomerKpis>(config, \"POST\", \"/customers/summary\", {\n filters,\n ...(range !== undefined ? { range } : {}),\n ...(since !== undefined ? { since } : {}),\n ...(until !== undefined ? { until } : {}),\n ...(timezone !== undefined ? { timezone } : {}),\n ...(compare_to !== undefined ? { compare_to } : {}),\n });\n },\n },\n\n business: {\n async config() {\n return salesRequest<BusinessConfig>(config, \"GET\", \"/business/config\");\n },\n },\n };\n}\n","import { z } from \"zod\";\n\n/**\n * Sales / Conversions wire schemas — the client-side source of truth.\n *\n * `saleCreateSchema` is mirrored by `SaleCreateSchema` in\n * `apps/api/src/schemas/tracking_sales.py` and enforced by the backend drift\n * test (the `resources` section of `events.schema.json`). Keep them in lockstep.\n *\n * Money is **integer minor units (cents)**; `quantity` is a decimal string;\n * `currency` is the required `SupportedCurrency` enum.\n */\n\nexport const SUPPORTED_CURRENCIES = [\"USD\", \"CAD\"] as const;\nexport type SupportedCurrency = (typeof SUPPORTED_CURRENCIES)[number];\n\nconst TRACKING_ENVIRONMENTS = [\"production\", \"development\"] as const;\n\nconst currencySchema = z.enum(SUPPORTED_CURRENCIES);\nconst centsSchema = z.number().int().nonnegative();\nconst quantitySchema = z.string().regex(/^\\d+(\\.\\d{1,3})?$/);\n// Free-form JSON object — the sale's extensibility escape hatch. Mirrors the\n// Pydantic `dict[str, Any]` (`additionalProperties: true`) on the wire.\nconst metadataSchema = z.record(z.unknown());\n\nexport const saleItemSchema = z\n .object({\n external_item_id: z.string().nullable().optional(),\n name: z.string().nullable().optional(),\n category: z.string().nullable().optional(),\n quantity: quantitySchema,\n unit_price_cents: centsSchema,\n // Non-negativity validated on the wire — same contract as the other cents\n // fields — and backstopped by the DB CHECK.\n unit_cost_cents: centsSchema.nullable().optional(),\n })\n .strict();\n\n// One service covered by a sale, at its own price. `service` is the per-business\n// service key, validated against the taxonomy by the backend at write time.\nexport const saleServiceSchema = z\n .object({\n service: z.string(),\n amount_cents: centsSchema,\n })\n .strict();\n\n// Raw customer identity. Stored as-is on the backend for human display in\n// dashboards; hashing happens at writeback-upload time in the future Google\n// Ads reconciliation worker (see docs/tracking-package/conversion-writeback.md).\n// The SDK never hashes — pass values straight through.\nconst customerNameSchema = z.string().max(200);\nconst customerPhoneSchema = z.string().max(64);\nconst customerEmailSchema = z.string().max(320).email();\n\n// The singular `service` (priced by `amount_total_cents`) and the plural\n// `services` (each priced individually) are mutually exclusive. When `services`\n// is present, `amount_total_cents` is optional and the backend derives it as the\n// sum; otherwise it is required. Shared by create + update.\nfunction refineServiceXor(\n val: {\n service?: string | null;\n services?: ReadonlyArray<{ service: string; amount_cents: number }> | null;\n amount_total_cents?: number | null;\n },\n ctx: z.RefinementCtx,\n { requireAmount }: { requireAmount: boolean },\n): void {\n if (val.services != null) {\n if (val.service != null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"pass either `service` or `services`, not both\",\n path: [\"services\"],\n });\n }\n if (val.services.length === 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"`services` must not be empty\",\n path: [\"services\"],\n });\n }\n const keys = val.services.map((s) => s.service);\n if (new Set(keys).size !== keys.length) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"`services` must not list the same service more than once\",\n path: [\"services\"],\n });\n }\n if (val.amount_total_cents != null) {\n const sum = val.services.reduce((acc, s) => acc + s.amount_cents, 0);\n if (val.amount_total_cents !== sum) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message:\n \"amount_total_cents must equal the sum of the services amounts \" +\n \"(omit it to derive it automatically)\",\n path: [\"amount_total_cents\"],\n });\n }\n }\n } else if (requireAmount && val.amount_total_cents == null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"amount_total_cents is required unless `services` is provided\",\n path: [\"amount_total_cents\"],\n });\n }\n}\n\nexport const saleCreateSchema = z\n .object({\n external_id: z.string().nullable().optional(),\n description: z.string().nullable().optional(),\n service: z.string().nullable().optional(),\n services: z.array(saleServiceSchema).nullable().optional(),\n currency: currencySchema,\n // Optional only because the plural `services` form derives it from the sum\n // (see refineServiceXor); the singular/serviceless path still requires it.\n amount_total_cents: centsSchema.nullable().optional(),\n occurred_at: z.string().datetime(),\n environment: z.enum(TRACKING_ENVIRONMENTS).default(\"production\"),\n items: z.array(saleItemSchema).default([]),\n metadata: metadataSchema.nullable().optional(),\n customer_name: customerNameSchema.nullable().optional(),\n customer_phone: customerPhoneSchema.nullable().optional(),\n customer_email: customerEmailSchema.nullable().optional(),\n // CASL consent attestation: the customer agreed to receive SMS. Recorded\n // with a timestamp server-side; every SMS send path gates on it.\n //\n // Tri-state: omit it (or send null) to let the server apply the business's\n // configured default-opt-in policy, honouring a returning customer's\n // remembered preference. Send an explicit boolean to assert consent state\n // yourself — `false` records a deliberate opt-out.\n sms_consent: z.boolean().nullable().optional(),\n })\n .strict()\n .superRefine((val, ctx) => refineServiceXor(val, ctx, { requireAmount: true }));\n\nexport const saleUpdateSchema = z\n .object({\n description: z.string().nullable().optional(),\n service: z.string().nullable().optional(),\n services: z.array(saleServiceSchema).nullable().optional(),\n currency: currencySchema.optional(),\n amount_total_cents: centsSchema.optional(),\n occurred_at: z.string().datetime().optional(),\n items: z.array(saleItemSchema).optional(),\n metadata: metadataSchema.nullable().optional(),\n customer_name: customerNameSchema.nullable().optional(),\n // Re-attest when changing a filler-looking name; the server clears the\n // prior attestation whenever `customer_name` changes.\n customer_name_placeholder_confirmed: z.boolean().optional(),\n customer_phone: customerPhoneSchema.nullable().optional(),\n customer_email: customerEmailSchema.nullable().optional(),\n // NOT NULL server-side: omit to leave unchanged (explicit null is rejected).\n sms_consent: z.boolean().optional(),\n })\n .strict()\n .superRefine((val, ctx) => refineServiceXor(val, ctx, { requireAmount: false }));\n\nexport type SaleItemInput = z.input<typeof saleItemSchema>;\nexport type SaleServiceInput = z.input<typeof saleServiceSchema>;\n// Use the INPUT type so fields with Zod defaults (environment, items) and\n// occurred_at are optional for callers — the sales client fills them in.\nexport type SaleInput = z.input<typeof saleCreateSchema>;\nexport type SaleUpdateInput = z.input<typeof saleUpdateSchema>;\n\n// ---------------------------------------------------------------------------\n// Read shapes (server responses; not validated on the client)\n// ---------------------------------------------------------------------------\n\nexport interface SaleItem {\n id: string;\n external_item_id: string | null;\n name: string | null;\n category: string | null;\n quantity: string;\n unit_price_cents: number;\n unit_cost_cents: number | null;\n}\n\nexport interface SaleService {\n id: string;\n service_id: string;\n service_key: string;\n service_label: string;\n amount_cents: number;\n}\n\nexport interface Sale {\n id: string;\n business_id: string;\n business_name?: string | null;\n external_id: string | null;\n currency: SupportedCurrency;\n amount_total_cents: number;\n description: string | null;\n // Singular service fields are populated only for single-service sales (kept\n // for backwards compatibility); `services` is always the full set.\n service_id: string | null;\n service_key?: string | null;\n service_label?: string | null;\n services: SaleService[];\n occurred_at: string;\n environment: (typeof TRACKING_ENVIRONMENTS)[number];\n metadata: Record<string, unknown> | null;\n customer_name: string | null;\n /** Operator attestation that a filler-looking `customer_name` is genuine. */\n customer_name_placeholder_confirmed: boolean;\n /** Server timestamp for when the name attestation was recorded. */\n customer_name_placeholder_confirmed_at: string | null;\n customer_phone: string | null;\n customer_email: string | null;\n /** CASL consent attestation stored on the sale; SMS send paths gate on it server-side. */\n sms_consent: boolean;\n /** Server timestamp for when the consent attestation was recorded. */\n sms_consent_granted_at: string | null;\n created_at: string;\n updated_at: string;\n items: SaleItem[];\n}\n\nexport interface SaleListPage {\n items: Sale[];\n total: number;\n}\n\nexport interface SaleCursorPage {\n items: Sale[];\n next_cursor: string | null;\n /** Populated only when `want_total` was requested (a single indexed COUNT). */\n total_count?: number;\n has_more?: boolean;\n}\n\n/**\n * Sortable columns on the secret-key (keyset) and admin (offset) list endpoints.\n * `business_name` only applies to the cross-business admin list — it sorts the\n * joined `businesses.name` column.\n */\nexport type SaleSortField =\n | \"occurred_at\"\n | \"created_at\"\n | \"amount_total_cents\"\n | \"customer_name\"\n | \"business_name\";\n\nexport type SaleSortOrder = \"asc\" | \"desc\";\n\n/**\n * Comprehensive filter shape mirrored from the backend's `SaleQueryFilters`.\n *\n * `search` runs case-insensitively across `customer_name`, `customer_phone`,\n * `customer_email`, `description`, and `external_id` — the human-facing\n * columns. `service_id` is the resolved per-business service UUID (different\n * from the create-time `service` *key*).\n */\nexport interface SaleFilters {\n business_id?: string;\n external_id?: string;\n service_id?: string;\n /** E.164 phone — the canonical customer key; filters sales for one customer. */\n customer_phone?: string;\n currency?: SupportedCurrency;\n environment?: (typeof TRACKING_ENVIRONMENTS)[number];\n since?: string;\n until?: string;\n min_amount_cents?: number;\n max_amount_cents?: number;\n search?: string;\n}\n\n/**\n * Full query input for `SalesClient.list()` — filters + pagination.\n *\n * Pagination is **keyset (cursor)**: `next_cursor` returned by one page is\n * passed back as `cursor` on the next. `null` / undefined cursor = first page.\n *\n * Ordering on this endpoint is fixed at **`occurred_at DESC, id DESC`** — the\n * cursor encodes a position in that index, so a different sort would\n * invalidate cursors mid-pagination. For ad-hoc sorted reads use the\n * dashboard admin endpoint, which is offset-paginated.\n */\nexport interface SaleListQuery extends SaleFilters {\n limit?: number;\n cursor?: string | null;\n}\n\n/** Keyset-safe sort columns (NOT-NULL, indexed). */\nexport type SaleKeysetSortField = \"occurred_at\" | \"created_at\" | \"amount_total_cents\";\n\n/** v2 list query — adds server sort + opt-in total. */\nexport interface SaleListQueryV2 extends SaleListQuery {\n sort?: SaleKeysetSortField;\n order?: SaleSortOrder;\n /** Opt-in: a single indexed COUNT over the filtered set. */\n want_total?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Sales summary (aggregations). Read by `SalesClient.summary()`. Every monetary\n// figure is grouped **by currency** — USD and CAD cents are never summed into a\n// single total. Money stays integer cents; only `quantity` is a decimal string.\n// ---------------------------------------------------------------------------\n\nexport const TRACKING_RANGES = [\"24h\", \"7d\", \"30d\"] as const;\nexport type TrackingOverviewRange = (typeof TRACKING_RANGES)[number];\n\n/** Query input for `SalesClient.summary()` — filters + range + options. */\nexport interface SaleSummaryQuery extends SaleFilters {\n range: TrackingOverviewRange;\n /** Include the per-category line-item breakdown (extra join; default false). */\n include_categories?: boolean;\n /** Surface soft-deleted services individually (flagged \"(deleted)\") instead of\n * rolling them into a single \"Deleted services\" bucket. Default false. */\n include_deleted_services?: boolean;\n /** Cap on the by-service / by-category rows (1–50, default 10). */\n top_n?: number;\n}\n\nexport interface CurrencyRevenue {\n currency: SupportedCurrency;\n sale_count: number;\n revenue_cents: number;\n average_order_value_cents: number;\n}\n\nexport interface SalesServiceBreakdown {\n service_id: string | null;\n service_key: string | null;\n /** \"Unassigned\" when the sale has no service. */\n service_label: string | null;\n currency: SupportedCurrency;\n sale_count: number;\n revenue_cents: number;\n}\n\nexport interface SalesCategoryBreakdown {\n category: string | null;\n currency: SupportedCurrency;\n /** sum(unit_price_cents * quantity) — advisory, not authoritative. */\n revenue_cents: number;\n /** Decimal string. */\n quantity: string;\n}\n\nexport interface SalesTrendPoint {\n bucket_start: string;\n currency: SupportedCurrency;\n sale_count: number;\n revenue_cents: number;\n}\n\nexport interface SaleSummary {\n range: TrackingOverviewRange;\n business_id: string | null;\n metrics: {\n sale_count: number;\n distinct_customers: number;\n by_currency: CurrencyRevenue[];\n };\n by_service: SalesServiceBreakdown[];\n by_currency: CurrencyRevenue[];\n by_category: SalesCategoryBreakdown[];\n series: SalesTrendPoint[];\n}\n\n// ---------------------------------------------------------------------------\n// v2 dashboard surface (additive, back-compat). Reads only → plain interfaces,\n// not drift-checked. Legacy `24h/7d/30d` callers get the same numbers; new\n// ranges/options layer on tz-correct calendar windows + comparisons.\n// ---------------------------------------------------------------------------\n\nexport const NAMED_RANGES = [\n \"today\",\n \"yesterday\",\n \"wtd\",\n \"mtd\",\n \"qtd\",\n \"ytd\",\n \"24h\",\n \"7d\",\n \"30d\",\n \"90d\",\n \"custom\",\n] as const;\n/** Superset of `TrackingOverviewRange` (`24h`/`7d`/`30d` stay valid). */\nexport type NamedRange = (typeof NAMED_RANGES)[number];\nexport type Granularity = \"hour\" | \"day\" | \"week\" | \"month\" | \"auto\";\nexport type CompareTo = \"previous_period\" | \"previous_year\" | \"none\";\n\nexport interface DistinctCustomersByCurrency {\n currency: SupportedCurrency;\n distinct_customers: number;\n}\n\nexport interface SummaryWindow {\n since: string;\n until: string;\n}\n\nexport interface SummaryCurrencyDelta {\n currency: SupportedCurrency;\n revenue_cents_delta: number;\n /** Ratio (0.12 = +12%); null when previous revenue was 0. */\n revenue_pct_delta: number | null;\n sale_count_delta: number;\n}\n\nexport interface SummaryDeltas {\n by_currency: SummaryCurrencyDelta[];\n sale_count_delta: number;\n distinct_customers_delta: number;\n}\n\nexport interface SaleSummaryPrevious {\n window: SummaryWindow;\n metrics: SaleSummaryV2[\"metrics\"];\n by_currency: CurrencyRevenue[];\n series: SalesTrendPoint[];\n}\n\n/** Query input for `SalesClient.summary()` v2 — widened range + tz/compare options. */\nexport interface SaleSummaryQueryV2 extends SaleFilters {\n range?: NamedRange;\n /** Required when `range === 'custom'`. */\n since?: string;\n until?: string;\n /** IANA tz, e.g. `America/Toronto`. Default = business tz. */\n timezone?: string;\n granularity?: Granularity;\n compare_to?: CompareTo;\n include_categories?: boolean;\n include_deleted_services?: boolean;\n top_n?: number;\n}\n\n/** Superset of `SaleSummary` (assignable to it). */\nexport interface SaleSummaryV2 extends Omit<SaleSummary, \"range\" | \"metrics\"> {\n range: NamedRange;\n metrics: SaleSummary[\"metrics\"] & {\n distinct_customers_by_currency: DistinctCustomersByCurrency[];\n };\n timezone: string | null;\n window: SummaryWindow | null;\n granularity: string | null;\n previous: SaleSummaryPrevious | null;\n deltas: SummaryDeltas | null;\n}\n\n// ---------------------------------------------------------------------------\n// Customers — phone-keyed (a customer IS their E.164 phone). `customer_id` is\n// the E.164 string. Money is per-currency, never summed.\n// ---------------------------------------------------------------------------\n\nexport type CustomerSegment = \"new\" | \"returning\" | \"repeat\" | \"lapsed\";\nexport type CustomerSortField = \"total_spent\" | \"last_purchase\" | \"purchases\" | \"first_purchase\";\n\nexport interface CustomerCurrencyTotal {\n currency: SupportedCurrency;\n revenue_cents: number;\n sale_count: number;\n average_order_value_cents: number;\n}\n\nexport interface CustomerSummary {\n /** The E.164 phone — the canonical customer id. */\n customer_id: string;\n display_name: string | null;\n email: string | null;\n phone: string;\n first_purchase_at: string;\n last_purchase_at: string;\n purchase_count: number;\n segment: CustomerSegment;\n totals: CustomerCurrencyTotal[];\n}\n\nexport type CustomerProfile = CustomerSummary;\n\nexport interface CustomerListQuery extends Omit<SaleFilters, \"external_id\"> {\n segment?: CustomerSegment;\n sort?: CustomerSortField;\n order?: SaleSortOrder;\n cursor?: string | null;\n limit?: number;\n want_total?: boolean;\n}\n\nexport interface CustomerListPage {\n items: CustomerSummary[];\n next_cursor: string | null;\n total_count: number | null;\n}\n\nexport interface CustomerGetOptions {\n include_sales?: boolean;\n limit?: number;\n cursor?: string | null;\n}\n\nexport interface CustomerGetResult {\n customer: CustomerProfile;\n /** Present only when `include_sales: true` (and a business-scoped key). */\n sales?: SaleCursorPage | null;\n}\n\nexport interface CustomerSummaryQuery extends SaleFilters {\n range?: NamedRange;\n since?: string;\n until?: string;\n timezone?: string;\n compare_to?: CompareTo;\n}\n\nexport interface CustomerSegmentCount {\n segment: CustomerSegment;\n count: number;\n}\n\nexport interface CustomerCurrencyDelta {\n currency: SupportedCurrency;\n revenue_cents_delta: number;\n /** Ratio (0.12 = +12%); null when previous revenue was 0. */\n revenue_pct_delta: number | null;\n}\n\nexport interface CustomerKpisDeltas {\n total_customers_delta: number;\n new_customers_delta: number;\n returning_customers_delta: number;\n repeat_rate_delta: number;\n ltv_by_currency: CustomerCurrencyDelta[];\n}\n\nexport interface CustomerKpisPrevious {\n window_since: string;\n window_until: string;\n total_customers: number;\n new_customers: number;\n returning_customers: number;\n repeat_rate: number;\n ltv_by_currency: CustomerCurrencyTotal[];\n}\n\nexport interface CustomerKpis {\n range: NamedRange;\n timezone: string;\n window_since: string;\n window_until: string;\n total_customers: number;\n new_customers: number;\n returning_customers: number;\n repeat_rate: number;\n by_segment: CustomerSegmentCount[];\n ltv_by_currency: CustomerCurrencyTotal[];\n /** Present only when `compare_to` is set. */\n previous?: CustomerKpisPrevious | null;\n deltas?: CustomerKpisDeltas | null;\n}\n\n// ---------------------------------------------------------------------------\n// Business config — supersets `fetchServices()`.\n// ---------------------------------------------------------------------------\n\nexport interface BusinessConfigService {\n key: string;\n label: string;\n archived: boolean;\n}\n\nexport interface BusinessConfigFeatures {\n customers: boolean;\n comparisons: boolean;\n retention: boolean;\n}\n\nexport interface BusinessConfig {\n business_id: string;\n display_name: string;\n timezone: string;\n primary_currency: SupportedCurrency;\n currencies: SupportedCurrency[];\n default_phone_country: string | null;\n services: BusinessConfigService[];\n features: BusinessConfigFeatures;\n}\n","import { salesRequest, type SalesTransportConfig } from \"./sales/transport\";\n\n/** A business's active service, as returned by `GET /tracking/services`. */\nexport interface PublicServiceItem {\n key: string;\n label: string;\n}\n\n/**\n * Fetch the caller's business's active service taxonomy. Accepts a public or\n * secret key (the taxonomy is low-sensitivity category names). Powers the\n * `@aranova/tracking-cli gen` codegen.\n */\nexport async function fetchServices(config: SalesTransportConfig): Promise<PublicServiceItem[]> {\n return salesRequest<PublicServiceItem[]>(config, \"GET\", \"/services\");\n}\n","// Layer 0 (init config) + Layer 3 (tracking integration) for phone fields.\n// Kept in core so both the React and Next packages share identical types, and\n// the `phoneField` helper stays isomorphic.\n\nimport type { JsonValue } from \"./events/form-submit\";\nimport { toE164, type CountryCode, type PhoneDisplayFormat } from \"./phone\";\n\n/**\n * Init-time phone config (`createTracking({ phone })`). The transmitted value is\n * ALWAYS E.164 and is deliberately not configurable here — only display is.\n */\nexport interface PhoneConfig {\n /** Region assumed for numbers typed without a country code. Default `'CA'`. */\n defaultCountry?: CountryCode;\n /** How the input DISPLAYS to the user. Default `'national'`. Does not affect the wire. */\n display?: PhoneDisplayFormat;\n}\n\n/** A single tracked form field destined for `form_submit.fields[]`. */\nexport interface TrackedField {\n name: string;\n type: string;\n value: JsonValue;\n label?: string | null;\n}\n\n/**\n * Build a tracked field whose wire value is ALWAYS E.164. The client keeps its\n * own display value for UI/email; this puts `+E.164` on the wire (or `null` when\n * the input isn't a valid number).\n */\nexport function phoneField(name: string, raw: string, country?: CountryCode): TrackedField {\n return { name, type: \"phone\", value: toE164(raw, country) };\n}\n","\"use client\";\n\nimport { useEffect, useState, type CSSProperties, type ReactNode } from \"react\";\n\nimport { useConsent } from \"./hooks\";\n\n/**\n * Legacy opt-in-era consent banner.\n *\n * @deprecated PERMANENTLY INERT since consent v2 (opt-out model): it renders\n * only while consent is `pending`, and the effective state is never `pending`\n * anymore, so this component always returns `null`. Tracking is on by default;\n * replace the banner with a footer \"cookie preferences\" control built on\n * {@link useCookiePreferences} (see the package README). Kept exported so\n * existing integrations keep compiling; scheduled for removal.\n */\nexport interface ConsentBannerProps {\n /** Body text. Defaults to the standard cookies-for-ad-performance message. */\n message?: ReactNode;\n /** Optional bold title above the body text. */\n title?: ReactNode;\n /** Label for the accept button. Default: `\"Accept\"`. */\n acceptLabel?: string;\n /** Label for the decline button. Default: `\"Decline\"`. */\n declineLabel?: string;\n /** Optional link inline with the message (e.g. to a privacy policy). */\n policyHref?: string;\n /** Visible text for {@link policyHref}. Default: `\"Learn more\"`. */\n policyLabel?: string;\n /**\n * Fires after the consent state is persisted + propagated to gtag. Useful\n * for emitting your own analytics event on the choice.\n */\n onAccept?: () => void;\n onDecline?: () => void;\n /** Where the banner docks. Default: `\"bottom\"`. */\n position?: \"top\" | \"bottom\";\n /**\n * Visual theme. `\"auto\"` follows `prefers-color-scheme`. Default: `\"light\"`.\n */\n theme?: \"light\" | \"dark\" | \"auto\";\n /** Class added to the outer wrapper for additional styling hooks. */\n className?: string;\n /** Inline style overrides applied to the outer wrapper after the defaults. */\n style?: CSSProperties;\n}\n\ninterface ThemeTokens {\n background: string;\n border: string;\n text: string;\n mutedText: string;\n acceptBg: string;\n acceptText: string;\n declineBg: string;\n declineText: string;\n declineBorder: string;\n shadow: string;\n linkColor: string;\n}\n\nconst LIGHT_THEME: ThemeTokens = {\n background: \"#ffffff\",\n border: \"#e5e7eb\",\n text: \"#111827\",\n mutedText: \"#4b5563\",\n acceptBg: \"#111827\",\n acceptText: \"#ffffff\",\n declineBg: \"transparent\",\n declineText: \"#111827\",\n declineBorder: \"#d1d5db\",\n shadow: \"0 -4px 16px -2px rgba(15, 23, 42, 0.08), 0 -2px 6px -1px rgba(15, 23, 42, 0.04)\",\n linkColor: \"#1f2937\",\n};\n\nconst DARK_THEME: ThemeTokens = {\n background: \"#0f172a\",\n border: \"#1e293b\",\n text: \"#f1f5f9\",\n mutedText: \"#cbd5e1\",\n acceptBg: \"#f1f5f9\",\n acceptText: \"#0f172a\",\n declineBg: \"transparent\",\n declineText: \"#f1f5f9\",\n declineBorder: \"#334155\",\n shadow: \"0 -4px 16px -2px rgba(0, 0, 0, 0.5), 0 -2px 6px -1px rgba(0, 0, 0, 0.3)\",\n linkColor: \"#e2e8f0\",\n};\n\nfunction useResolvedTheme(theme: ConsentBannerProps[\"theme\"]): ThemeTokens {\n const [prefersDark, setPrefersDark] = useState<boolean>(false);\n\n useEffect(() => {\n if (theme !== \"auto\" || typeof window === \"undefined\" || !window.matchMedia) return;\n const mql = window.matchMedia(\"(prefers-color-scheme: dark)\");\n setPrefersDark(mql.matches);\n const onChange = (e: MediaQueryListEvent): void => setPrefersDark(e.matches);\n mql.addEventListener(\"change\", onChange);\n return () => mql.removeEventListener(\"change\", onChange);\n }, [theme]);\n\n if (theme === \"dark\") return DARK_THEME;\n if (theme === \"auto\" && prefersDark) return DARK_THEME;\n return LIGHT_THEME;\n}\n\nconst DEFAULT_MESSAGE =\n \"We use cookies to understand ad performance and improve how our marketing works across visits. You can accept or decline this tracking.\";\n\n/**\n * @deprecated Permanently inert since consent v2 — always renders `null`\n * because the effective consent state is never `pending`. Use a footer\n * control built on {@link useCookiePreferences} instead. See\n * {@link ConsentBannerProps} for details.\n */\nexport function ConsentBanner({\n message,\n title,\n acceptLabel = \"Accept\",\n declineLabel = \"Decline\",\n policyHref,\n policyLabel = \"Learn more\",\n onAccept,\n onDecline,\n position = \"bottom\",\n theme = \"light\",\n className,\n style,\n}: ConsentBannerProps = {}): ReactNode {\n const { isPending, accept, decline } = useConsent();\n const tokens = useResolvedTheme(theme);\n const [hasMounted, setHasMounted] = useState(false);\n\n useEffect(() => {\n setHasMounted(true);\n }, []);\n\n if (!hasMounted || !isPending) return null;\n\n const wrapperStyle: CSSProperties = {\n position: \"fixed\",\n left: 0,\n right: 0,\n [position]: 0,\n zIndex: 2147483640,\n background: tokens.background,\n color: tokens.text,\n borderTop: position === \"bottom\" ? `1px solid ${tokens.border}` : \"none\",\n borderBottom: position === \"top\" ? `1px solid ${tokens.border}` : \"none\",\n boxShadow: tokens.shadow,\n padding: \"16px 20px\",\n boxSizing: \"border-box\",\n animation: `${ANIMATION_NAME}-${position} 200ms ease-out`,\n fontFamily:\n 'system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif',\n ...style,\n };\n\n const innerStyle: CSSProperties = {\n maxWidth: 1100,\n margin: \"0 auto\",\n display: \"flex\",\n flexWrap: \"wrap\",\n gap: 16,\n alignItems: \"center\",\n justifyContent: \"space-between\",\n };\n\n const messageStyle: CSSProperties = {\n flex: \"1 1 320px\",\n margin: 0,\n fontSize: 14,\n lineHeight: 1.5,\n color: tokens.mutedText,\n };\n\n const titleStyle: CSSProperties = {\n margin: \"0 0 4px 0\",\n fontSize: 14,\n fontWeight: 600,\n color: tokens.text,\n };\n\n const actionsStyle: CSSProperties = {\n display: \"flex\",\n gap: 8,\n flexShrink: 0,\n };\n\n const buttonBase: CSSProperties = {\n appearance: \"none\",\n fontFamily: \"inherit\",\n fontSize: 14,\n fontWeight: 500,\n padding: \"8px 16px\",\n borderRadius: 6,\n cursor: \"pointer\",\n border: \"1px solid transparent\",\n transition: \"opacity 120ms ease\",\n };\n\n const declineStyle: CSSProperties = {\n ...buttonBase,\n background: tokens.declineBg,\n color: tokens.declineText,\n borderColor: tokens.declineBorder,\n };\n\n const acceptStyle: CSSProperties = {\n ...buttonBase,\n background: tokens.acceptBg,\n color: tokens.acceptText,\n };\n\n const linkStyle: CSSProperties = {\n color: tokens.linkColor,\n textDecoration: \"underline\",\n textUnderlineOffset: 2,\n };\n\n const handleAccept = (): void => {\n accept();\n onAccept?.();\n };\n\n const handleDecline = (): void => {\n decline();\n onDecline?.();\n };\n\n return (\n <>\n <style>{ANIMATION_KEYFRAMES}</style>\n <div\n role=\"dialog\"\n aria-live=\"polite\"\n aria-label=\"Cookie consent\"\n className={className}\n style={wrapperStyle}\n >\n <div style={innerStyle}>\n <div style={{ flex: \"1 1 320px\" }}>\n {title ? <p style={titleStyle}>{title}</p> : null}\n <p style={messageStyle}>\n {message ?? DEFAULT_MESSAGE}\n {policyHref ? (\n <>\n {\" \"}\n <a href={policyHref} style={linkStyle}>\n {policyLabel}\n </a>\n </>\n ) : null}\n </p>\n </div>\n <div style={actionsStyle}>\n <button type=\"button\" onClick={handleDecline} style={declineStyle}>\n {declineLabel}\n </button>\n <button type=\"button\" onClick={handleAccept} style={acceptStyle}>\n {acceptLabel}\n </button>\n </div>\n </div>\n </div>\n </>\n );\n}\n\n// Single injected stylesheet for the slide-in animation. Keyframes can't be\n// expressed in inline `style`, so this is the one CSS dependency. Scoped to\n// the banner's own animation-name to avoid colliding with consumer styles.\nconst ANIMATION_NAME = \"aranova-consent-banner\";\nconst ANIMATION_KEYFRAMES = `\n@keyframes ${ANIMATION_NAME}-bottom {\n from { transform: translateY(100%); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n}\n@keyframes ${ANIMATION_NAME}-top {\n from { transform: translateY(-100%); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n}\n`;\n","\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\n\nimport {\n CONSENT_EXPIRES_AT_KEY,\n CONSENT_STATE_KEY,\n CONSENT_TIMESTAMP_KEY,\n createEmptyTrackingParams,\n getConsentChoice,\n getCookieValueFromDocument,\n getTrackingParamsFromCookieReader,\n onConsentChange,\n optIn,\n optOut,\n registerCapability,\n resetConsent,\n type ConsentChoice,\n type ConsentChoiceState,\n type ConsentSource,\n type ConsentState,\n type TrackingParams,\n} from \"../../tracking-core/src/index\";\n\n/**\n * Read the captured Google Ads click id from first-party cookies.\n *\n * Returns `null` during SSR and before the client has mounted.\n */\nexport function useGclid(): string | null {\n const [gclid, setGclid] = useState<string | null>(null);\n\n useEffect(() => {\n setGclid(getCookieValueFromDocument(\"gclid\"));\n }, []);\n\n return gclid;\n}\n\n/**\n * Read all captured attribution parameters from first-party cookies.\n *\n * Values are loaded after mount, so the initial render returns all `null`s.\n */\nexport function useTrackingParams(): TrackingParams {\n const [trackingParams, setTrackingParams] = useState<TrackingParams>(createEmptyTrackingParams());\n\n useEffect(() => {\n setTrackingParams(getTrackingParamsFromCookieReader(getCookieValueFromDocument));\n }, []);\n\n return trackingParams;\n}\n\n/** Options for {@link useCookiePreferences}. */\nexport interface UseCookiePreferencesOptions {\n /** Days an explicit decline is honored. Defaults to 90. */\n declineTtlDays?: number;\n}\n\n/**\n * The headless cookie-preferences surface returned by\n * {@link useCookiePreferences}.\n */\nexport interface UseCookiePreferencesResult {\n /** Effective consent — `granted` unless an unexpired explicit decline exists. */\n state: ConsentChoiceState;\n /** `default` = no valid explicit choice stored; `explicit` = visitor chose. */\n source: ConsentSource;\n /** True when the visitor has made no (valid, unexpired) explicit choice. */\n isDefault: boolean;\n isGranted: boolean;\n isDenied: boolean;\n /** ISO timestamp of the explicit choice; null for the default state. */\n updatedAt: string | null;\n /** ISO expiry of an unexpired decline; null otherwise. */\n expiresAt: string | null;\n /** Explicitly opt out of ad tracking (honored for 90 days by default). */\n optOut: () => void;\n /** Explicitly opt in (never expires). */\n optIn: () => void;\n /** Clear the explicit choice — back to default-granted. */\n reset: () => void;\n}\n\nconst DEFAULT_CHOICE: ConsentChoice = {\n state: \"granted\",\n source: \"default\",\n updatedAt: null,\n expiresAt: null,\n};\n\n/**\n * Headless cookie-preferences hook for the opt-out consent model (consent v2).\n *\n * Tracking is ON by default; this hook is how each client site wires its own\n * footer \"Cookie preferences\" control (button, dialog, toggle — the packages\n * ship no consent UI). State stays in sync with actions from other components\n * in the same tab (via `onConsentChange`) and other tabs (via `storage`\n * events).\n *\n * ```tsx\n * function CookiePreferences() {\n * const { isDenied, optOut, optIn } = useCookiePreferences();\n * return isDenied ? (\n * <button onClick={optIn}>Enable ad measurement</button>\n * ) : (\n * <button onClick={optOut}>Opt out of ad measurement</button>\n * );\n * }\n * ```\n */\nexport function useCookiePreferences(\n options?: UseCookiePreferencesOptions,\n): UseCookiePreferencesResult {\n // This hook is the only way a site can offer the mandatory footer opt-out\n // control, so its use is the signal that the control actually shipped.\n registerCapability(\"consent_controls\");\n // SSR/pre-mount value = the effective default; synced from storage on mount.\n const [choice, setChoice] = useState<ConsentChoice>(DEFAULT_CHOICE);\n const ttlDays = options?.declineTtlDays;\n\n useEffect(() => {\n const sync = (): void => setChoice(getConsentChoice());\n sync();\n\n // Cross-tab: storage events (key === null means storage.clear()). The\n // timestamp key matters too — a re-affirmed explicit choice in another tab\n // writes the same state value (no event for it), only a new timestamp.\n const handleStorage = (event: StorageEvent): void => {\n if (\n event.key === null ||\n event.key === CONSENT_STATE_KEY ||\n event.key === CONSENT_EXPIRES_AT_KEY ||\n event.key === CONSENT_TIMESTAMP_KEY\n )\n sync();\n };\n window.addEventListener(\"storage\", handleStorage);\n\n // Same-tab: another component's optIn/optOut/reset.\n const unsubscribe = onConsentChange(sync);\n\n return () => {\n window.removeEventListener(\"storage\", handleStorage);\n unsubscribe();\n };\n }, []);\n\n // State updates flow back through onConsentChange — actions never setState.\n const optOutAction = useCallback((): void => {\n optOut(ttlDays != null ? { declineTtlDays: ttlDays } : undefined);\n }, [ttlDays]);\n\n const optInAction = useCallback((): void => {\n optIn();\n }, []);\n\n const reset = useCallback((): void => {\n resetConsent();\n }, []);\n\n return {\n state: choice.state,\n source: choice.source,\n isDefault: choice.source === \"default\",\n isGranted: choice.state === \"granted\",\n isDenied: choice.state === \"denied\",\n updatedAt: choice.updatedAt,\n expiresAt: choice.expiresAt,\n optOut: optOutAction,\n optIn: optInAction,\n reset,\n };\n}\n\n/**\n * Read the current visitor consent state.\n *\n * @deprecated Since consent v2 (opt-out model) the state is never `pending`.\n * Use {@link useCookiePreferences} — it exposes the effective state plus\n * `source` so you can tell a default grant from an explicit one.\n */\nexport function useConsentState(): ConsentState {\n return useConsent().state;\n}\n\n/**\n * Result shape of the deprecated {@link useConsent} hook.\n *\n * @deprecated Use {@link UseCookiePreferencesResult} via\n * {@link useCookiePreferences}. `isPending` is always `false` since consent v2.\n */\nexport interface UseConsentResult {\n state: ConsentState;\n isPending: boolean;\n isGranted: boolean;\n isDenied: boolean;\n accept: () => void;\n decline: () => void;\n reset: () => void;\n}\n\n/**\n * Legacy opt-in-era consent hook.\n *\n * @deprecated Since consent v2 tracking defaults ON (opt-out model): the state\n * is never `pending`, so banner UIs gated on `isPending` never render. Use\n * {@link useCookiePreferences} for footer \"cookie preferences\" controls.\n * `accept` / `decline` still work and map to `optIn` / `optOut`.\n */\nexport function useConsent(): UseConsentResult {\n const {\n state,\n isGranted,\n isDenied,\n optIn: accept,\n optOut: decline,\n reset,\n } = useCookiePreferences();\n\n return {\n state,\n isPending: false,\n isGranted,\n isDenied,\n accept,\n decline,\n reset,\n };\n}\n","\"use client\";\n\nimport Script from \"next/script\";\nimport { useEffect } from \"react\";\n\nimport {\n createConsentDefaultScript,\n createGtagInitScript,\n createGtagInitScriptMulti,\n createMetaConsentDefaultScript,\n createMetaPixelInitScript,\n createMetaPixelInitScriptMulti,\n getTrackingConfigRuntime,\n registerCapability,\n resolveTrackingConfigUrl,\n type GtagEnvironmentMap,\n type MetaPixelEnvironmentMap,\n type TrackingConfigReference,\n} from \"../../tracking-core/src/index\";\n\n/**\n * Props for the combined Next.js ad-platform tag loader.\n *\n * Every field is optional and independent: pass the Google fields, the Meta\n * fields, or both. For each platform a labelled `*Ids` map (ALL loaded) takes\n * precedence over the single `*Id` shortcut.\n */\nexport interface AdPlatformTrackingProps {\n /** Single Google Ads tag id, e.g. `AW-123456789`. */\n gtagId?: string;\n /** Labelled Google Ads tag map — ALL loaded; wins over `gtagId`. */\n gtagIds?: GtagEnvironmentMap;\n /** R2-authoritative Google tracking config. When set, static gtagId(s) are ignored. */\n trackingConfig?: TrackingConfigReference;\n /** Fire a Google page view from this standalone loader. Leave false when using TrackingProvider. */\n standalonePageView?: boolean;\n /** Single Meta Pixel id, e.g. `123456789012345`. */\n metaPixelId?: string;\n /** Labelled Meta Pixel map — ALL loaded; wins over `metaPixelId`. */\n metaPixelIds?: MetaPixelEnvironmentMap;\n}\n\n/**\n * Next.js client component that loads the configured ad-platform tags — the\n * Google tag (`gtag`) and/or the Meta Pixel (`fbq`) — with Consent Mode, via\n * `next/script`. Render once in the root layout; omit a platform's props to\n * skip it. Renders no visible UI.\n */\nexport function AdPlatformTracking({\n gtagId,\n gtagIds,\n trackingConfig,\n standalonePageView = false,\n metaPixelId,\n metaPixelIds,\n}: AdPlatformTrackingProps) {\n const trackingConfigKey = trackingConfig\n ? `${resolveTrackingConfigUrl(trackingConfig)}:${trackingConfig.businessId}:${trackingConfig.environment}`\n : \"\";\n useEffect(() => {\n if (!trackingConfig) return;\n const runtime = getTrackingConfigRuntime(trackingConfig);\n if (standalonePageView) runtime.queuePageView();\n else runtime.start();\n // eslint-disable-next-line react-hooks/exhaustive-deps -- trackingConfigKey is the stable proxy for trackingConfig\n }, [trackingConfigKey, standalonePageView]);\n const gtagAll: string[] = trackingConfig\n ? []\n : gtagIds\n ? Object.values(gtagIds).filter((id): id is string => id != null)\n : gtagId\n ? [gtagId]\n : [];\n const metaAll: string[] = metaPixelIds\n ? Object.values(metaPixelIds).filter((id): id is string => id != null)\n : metaPixelId\n ? [metaPixelId]\n : [];\n\n // Reported from the resolved values, not the props: `trackingConfig` zeroes\n // `gtagAll` because the runtime loads gtag.js itself, and Meta is loaded\n // independently of Google either way.\n if (trackingConfig || gtagAll.length > 0) registerCapability(\"ad_tags_google\");\n if (metaAll.length > 0) registerCapability(\"ad_tags_meta\");\n\n const gtagLoaderId = gtagAll[0];\n const gtagInitScript =\n gtagAll.length === 1 ? createGtagInitScript(gtagAll[0]!) : createGtagInitScriptMulti(gtagAll);\n const metaInitScript =\n metaAll.length === 1\n ? createMetaPixelInitScript(metaAll[0]!)\n : createMetaPixelInitScriptMulti(metaAll);\n\n // Consent v2: the per-platform default scripts resolve the EFFECTIVE state\n // (granted unless an unexpired stored decline) synchronously before each tag\n // initializes, so no follow-up consent-restore scripts are needed. The Meta\n // base script now applies the correct consent BEFORE the init script's\n // PageView — pre-v2, a granted visitor's PageView fired while still revoked.\n return (\n <>\n {gtagLoaderId ? (\n <>\n <Script id=\"consent-default\" strategy=\"beforeInteractive\">\n {createConsentDefaultScript()}\n </Script>\n <Script\n src={`https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(gtagLoaderId)}`}\n strategy=\"afterInteractive\"\n />\n <Script id=\"gtag-init\" strategy=\"afterInteractive\">\n {gtagInitScript}\n </Script>\n </>\n ) : null}\n\n {metaAll.length > 0 ? (\n <>\n <Script id=\"meta-pixel-base\" strategy=\"afterInteractive\">\n {createMetaConsentDefaultScript()}\n </Script>\n <Script id=\"meta-pixel-init\" strategy=\"afterInteractive\">\n {metaInitScript}\n </Script>\n </>\n ) : null}\n </>\n );\n}\n","\"use client\";\n\nimport Script from \"next/script\";\n\nimport {\n createConsentDefaultScript,\n createGtagInitScript,\n createGtagInitScriptMulti,\n type GtagEnvironmentMap,\n} from \"../../tracking-core/src/index\";\n\n/**\n * Props for the Next.js Google Ads tracking component.\n *\n * Accepts either a single `gtagId` (legacy) or a labelled `gtagIds` map\n * where ALL entries are loaded simultaneously via `gtag('config', ...)`.\n */\nexport type GoogleAdsTrackingProps =\n | { gtagId: string; gtagIds?: undefined }\n | { gtagId?: undefined; gtagIds: GtagEnvironmentMap };\n\n/**\n * Next.js client component that loads Google Ads gtag with Consent Mode.\n *\n * Render in the root layout `<head>` when the client site runs paid Google\n * Ads. The component injects Next `<Script>` tags and renders no visible UI.\n */\nexport function GoogleAdsTracking(props: GoogleAdsTrackingProps) {\n const { gtagId, gtagIds } = props;\n\n // Resolve the set of IDs to configure and the loader ID (first in list).\n const allIds: string[] = gtagIds\n ? Object.values(gtagIds).filter((id): id is string => id != null)\n : gtagId\n ? [gtagId]\n : [];\n if (allIds.length === 0) return null;\n\n const loaderId = allIds[0]!;\n const initScript =\n allIds.length === 1 ? createGtagInitScript(loaderId) : createGtagInitScriptMulti(allIds);\n\n // Consent v2: the consent-default script resolves the EFFECTIVE state\n // (granted unless an unexpired stored decline) synchronously before gtag.js\n // loads, so no follow-up consent-restore script is needed.\n return (\n <>\n <Script id=\"consent-default\" strategy=\"beforeInteractive\">\n {createConsentDefaultScript()}\n </Script>\n <Script\n src={`https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(loaderId)}`}\n strategy=\"afterInteractive\"\n />\n <Script id=\"gtag-init\" strategy=\"afterInteractive\">\n {initScript}\n </Script>\n </>\n );\n}\n","\"use client\";\n\nimport { usePathname, useSearchParams } from \"next/navigation\";\nimport { version } from \"../package.json\";\nimport {\n createContext,\n Suspense,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n type ReactNode,\n} from \"react\";\n\nimport {\n attachBfcacheRestore,\n attachClientCapturesOnce,\n attachCtaClickCapture,\n attachFormStart,\n attachPageExit,\n attachPhoneClickCapture,\n attachScrollDepth,\n attachTimeOnSite,\n // Note: attachMultiPageSession is NOT imported here — Next uses a\n // usePathname-driven implementation instead of pushState patching.\n createConversionAutoFire,\n createTypedClient,\n fireManualPageView,\n getOrCreateTrackingClient,\n getOrRotateSessionId,\n getTrackingConfigRuntime,\n registerCapability,\n resolveConversionConfig,\n withConversionAutoFire,\n type ConversionConfig,\n type PhoneConfig,\n type TrackingConfigReference,\n type TrackingClient,\n type TrackingEnvironment,\n type TriggerRegistryConfig,\n type TypedTrackingClient,\n} from \"../../tracking-core/src/index\";\nimport { PhoneConfigProvider } from \"../../tracking-core/src/phone-react\";\n\nexport interface CreateTrackingOptions<TRegistry extends TriggerRegistryConfig> {\n /**\n * Public tracking API key issued for this business.\n *\n * This key is safe to expose via `NEXT_PUBLIC_*` env vars.\n */\n apiKey: string;\n /**\n * Tracking endpoint base URL, usually ending in `/tracking`.\n */\n endpoint: string;\n /**\n * Trigger registry that controls automatic events and typed manual events.\n */\n triggers: TRegistry;\n /**\n * Deployment environment label reported in session context.\n */\n environment?: TrackingEnvironment;\n /**\n * Labelled map of Google Ads tag IDs. Included in session context and\n * heartbeat metadata so the dashboard can show what's configured.\n *\n * This does NOT load the gtag scripts — use `<GoogleAdsTracking gtagIds={...} />`\n * in the root layout for that. This option only controls what's reported\n * in the tracking payload context.\n */\n gtagIds?: Record<string, string>;\n /**\n * Validate manual event metadata at runtime before queueing.\n *\n * Enable in development to catch shape bugs. Leave disabled in production so\n * analytics can never throw into the host app.\n */\n debug?: boolean;\n /**\n * Phone-field display + default-country config, read by `usePhoneField` /\n * `<PhoneField>`. Display is customizable; the transmitted value is always E.164.\n */\n phone?: PhoneConfig;\n /**\n * GAP28 / unified-goal: enable real-time on-site conversion firing. When set, the SDK\n * fetches the per-business config from `cdnUrl` (optional offline `baked` fallback) and\n * AUTOMATICALLY fires `gtag('event','conversion')` for any automatic event-goal whose\n * trigger threshold a detector crosses. Omit to keep events analytics-only.\n */\n conversionConfig?: { cdnUrl: string; baked?: ConversionConfig | null };\n /**\n * R2-authoritative config reference — `ARANOVA_TRACKING_CONFIG` from\n * `tracking-cli gen`. Wins over `conversionConfig`. The object URL is composed\n * from `businessId` + `environment` against the production CDN; spread in a\n * `cdnBaseUrl` to read it from somewhere else, e.g.\n * `{ ...ARANOVA_TRACKING_CONFIG, cdnBaseUrl: process.env.NEXT_PUBLIC_ARANOVA_CDN_BASE_URL }`.\n */\n trackingConfig?: TrackingConfigReference;\n}\n\nexport interface TrackingProviderProps {\n /**\n * Application subtree that should have access to the tracking client.\n */\n children: ReactNode;\n}\n\nexport interface CreateTrackingResult<TRegistry extends TriggerRegistryConfig> {\n /**\n * Client component provider for the Next.js App Router integration.\n */\n TrackingProvider: (props: TrackingProviderProps) => ReactNode;\n /**\n * Hook that returns the registry-typed tracking client.\n */\n useTracking: () => TypedTrackingClient<TRegistry>;\n}\n\n/**\n * Fires `page_view` on every route change — including a query-only change\n * under the same pathname (GA4 semantics: any full-URL change is a new view).\n *\n * This is the ONLY component that reads `useSearchParams()`. Next opts the\n * whole enclosing route out of static prerendering when `useSearchParams()`\n * is called without an enclosing `<Suspense>` boundary, so the provider\n * renders this component inside its own `<Suspense fallback={null}>`. The\n * bailout is thereby contained to a component that renders nothing — the\n * consumer's page content (rendered as `children`, a sibling of this\n * boundary) stays statically prerenderable with no consumer-side Suspense.\n *\n * Renders `null`. `fire` is expected to be referentially stable so the\n * effect re-runs only on an actual `pathname` / `searchParams` change — that\n * dependency array is the sole guard against duplicate `page_view`s (the\n * underlying `fireManualPageView` has no dedup of its own).\n */\nfunction PageViewTracker({ fire }: { fire: () => void }): null {\n const pathname = usePathname();\n const searchParams = useSearchParams();\n useEffect(() => {\n fire();\n }, [pathname, searchParams, fire]);\n return null;\n}\n\n/**\n * Next.js App Router version of the `createTracking()` factory. Uses\n * `usePathname` + `useSearchParams` from `next/navigation` for SPA route\n * detection rather than patching `history.pushState`, because Next's\n * router does not always go through the History API for transitions.\n *\n * Usage is identical to the React factory — call this once at app\n * startup and export the returned `TrackingProvider` + `useTracking`\n * from your own module, then import them everywhere else. `GoogleAdsTracking`\n * is still imported separately and placed in the root layout's `<head>`\n * when the client runs paid ads.\n */\nexport function createTracking<TRegistry extends TriggerRegistryConfig>(\n options: CreateTrackingOptions<TRegistry>,\n): CreateTrackingResult<TRegistry> {\n const {\n apiKey,\n endpoint,\n triggers,\n environment,\n gtagIds,\n debug,\n phone,\n conversionConfig,\n trackingConfig,\n } = options;\n\n registerCapability(\"base_tracking\");\n // The R2 config reference is what wires `createConversionAutoFire` below, so\n // passing it IS the automatic-goal capability — no sales client involved.\n if (trackingConfig) registerCapability(\"conversion_goals_auto\");\n\n if (!apiKey || !endpoint) {\n if (apiKey || endpoint) {\n // eslint-disable-next-line no-console\n console.warn(\n \"[AranovaTracking] createTracking() requires both `apiKey` and `endpoint`. \" +\n \"Tracking is disabled for this session.\",\n );\n }\n\n const noopClient = {\n trackEvent: () => {},\n flush: async () => {},\n getSessionId: () => \"\",\n getVisitorId: () => \"\",\n } as unknown as TypedTrackingClient<TRegistry>;\n\n return {\n TrackingProvider: ({ children }: TrackingProviderProps) => (\n <PhoneConfigProvider value={phone ?? null}>{children}</PhoneConfigProvider>\n ),\n useTracking: () => noopClient,\n };\n }\n\n const TrackingContext = createContext<TypedTrackingClient<TRegistry> | null>(null);\n\n const specificPageVisitConfig = triggers.automatic.specific_page_visit ?? null;\n const timeOnSiteConfig = triggers.automatic.time_on_site ?? null;\n\n function TrackingProvider({ children }: TrackingProviderProps): ReactNode {\n const pathname = usePathname();\n\n const rawClient = useMemo(\n () =>\n getOrCreateTrackingClient({\n apiKey,\n endpoint,\n surface: \"next\",\n packageName: \"@aranova/tracking-next\",\n sdkVersion: version,\n triggers,\n environment,\n activeGtagIds: gtagIds,\n debug,\n }),\n [],\n );\n\n // GAP28 / unified-goal: resolve the firing config once, then build a wrapper that makes\n // every automatic detector event ALSO auto-fire a matching event-goal's conversion\n // (best-effort, never breaks ingest). Identity wrapper when firing isn't enabled.\n const conversionStore = useMemo(\n () =>\n trackingConfig\n ? getTrackingConfigRuntime(trackingConfig)\n : conversionConfig\n ? resolveConversionConfig({\n cdnUrl: conversionConfig.cdnUrl,\n baked: conversionConfig.baked,\n })\n : null,\n [],\n );\n const wrapClient = useMemo(() => {\n const autoFire = conversionStore ? createConversionAutoFire(conversionStore) : null;\n return (c: TrackingClient): TrackingClient =>\n autoFire ? withConversionAutoFire(c, autoFire) : c;\n }, [conversionStore]);\n const client = useMemo(\n () => createTypedClient<TRegistry>(wrapClient(rawClient), triggers, { debug }),\n [rawClient, wrapClient],\n );\n\n useEffect(() => {\n if (trackingConfig && conversionStore && \"start\" in conversionStore) {\n conversionStore.start();\n }\n }, [conversionStore]);\n\n // Fire page_view on every route change (initial mount + each pathname or\n // query-only change). The pathname/searchParams signal lives in the\n // Suspense-isolated <PageViewTracker> below so `useSearchParams()` never\n // opts the consumer route out of static prerendering; this stable\n // callback is what it invokes.\n const firePageView = useCallback(() => {\n fireManualPageView(wrapClient(rawClient));\n if (trackingConfig) getTrackingConfigRuntime(trackingConfig).queuePageView();\n }, [rawClient, wrapClient]);\n\n // specific_page_visit for Next: piggybacks on the usePathname route\n // change signal rather than patching history.pushState, because Next's\n // router doesn't consistently use the History API. Dedupes per\n // (page_name, path) pair via a ref set.\n const firedPagesRef = useRef(new Set<string>());\n useEffect(() => {\n if (!specificPageVisitConfig || pathname === null) return;\n\n const detectorClient = wrapClient(rawClient);\n for (const { name, pathPattern } of specificPageVisitConfig.pages) {\n if (!pathPattern.test(pathname)) continue;\n const key = `${name}:${pathname}`;\n if (firedPagesRef.current.has(key)) continue;\n firedPagesRef.current.add(key);\n detectorClient.trackEvent({\n eventType: \"specific_page_visit\",\n metadata: {\n page_name: name,\n page: { path: pathname },\n } as unknown as Record<string, unknown>,\n pageUrl: null,\n occurredAt: null,\n });\n }\n }, [pathname, rawClient, wrapClient]);\n\n // bfcache restore + time_on_site are global document/window listeners — attached\n // in the consolidated \"global captures\" effect below, once per singleton client.\n\n // multi_page_session for Next: uses usePathname rather than pushState\n // patching, same as specific_page_visit and page_view, because Next's\n // App Router doesn't consistently fire pushState for client transitions.\n const multiPageSessionConfig = triggers.automatic.multi_page_session ?? null;\n const mpsLastPathRef = useRef<string | null>(null);\n useEffect(() => {\n if (!multiPageSessionConfig || pathname === null) return;\n if (pathname === mpsLastPathRef.current) return;\n mpsLastPathRef.current = pathname;\n\n // Session rotation check — clear state if session ID changed.\n const MPS_PATHS_KEY = \"aranova_tracking_mps_paths\";\n const MPS_SESSION_KEY = \"aranova_tracking_mps_session\";\n const MPS_FIRED_KEY = \"aranova_tracking_mps_fired\";\n\n try {\n const store = window.sessionStorage;\n const currentSession = getOrRotateSessionId().id;\n const storedSession = store.getItem(MPS_SESSION_KEY);\n if (storedSession !== currentSession) {\n store.setItem(MPS_SESSION_KEY, currentSession);\n store.removeItem(MPS_PATHS_KEY);\n store.removeItem(MPS_FIRED_KEY);\n }\n\n if (store.getItem(MPS_FIRED_KEY) === \"1\") return;\n\n const raw = store.getItem(MPS_PATHS_KEY);\n const paths: Set<string> = raw ? new Set(JSON.parse(raw) as string[]) : new Set();\n paths.add(pathname);\n store.setItem(MPS_PATHS_KEY, JSON.stringify([...paths]));\n\n if (paths.size >= multiPageSessionConfig.pageThreshold) {\n store.setItem(MPS_FIRED_KEY, \"1\");\n wrapClient(rawClient).trackEvent({\n eventType: \"multi_page_session\",\n metadata: {\n page_count: paths.size,\n page: { path: pathname },\n } as unknown as Record<string, unknown>,\n pageUrl: null,\n occurredAt: null,\n });\n }\n } catch {\n // sessionStorage unavailable — degrade gracefully.\n }\n }, [multiPageSessionConfig, pathname, rawClient, wrapClient]);\n\n // Global document/window captures: page_exit, bfcache restore, time_on_site,\n // scroll_depth, form_start, cta_click, phone_click. These attach ONCE per singleton\n // client (not per provider mount) via attachClientCapturesOnce — otherwise a page with\n // multiple <TrackingProvider>s stacks duplicate listeners and every interaction emits\n // its event N times. (The pathname-effect triggers above — page_view /\n // specific_page_visit / multi_page_session — stay per-mount; they key off usePathname.)\n useEffect(() => {\n return attachClientCapturesOnce(rawClient, () => {\n const detachers: Array<() => void> = [];\n const detectorClient = wrapClient(rawClient);\n\n // SDK-internal: always attached, so dwell/exit analytics need no config.\n detachers.push(attachPageExit(detectorClient));\n // usePathname doesn't fire on back-forward cache restore — needs a pageshow listener.\n detachers.push(attachBfcacheRestore(detectorClient));\n\n if (timeOnSiteConfig) {\n detachers.push(attachTimeOnSite(detectorClient, timeOnSiteConfig));\n }\n\n const scrollDepth = triggers.automatic.scroll_depth;\n if (scrollDepth) {\n detachers.push(attachScrollDepth(detectorClient, scrollDepth));\n }\n\n const formStart = triggers.automatic.form_start;\n if (formStart) {\n detachers.push(attachFormStart(detectorClient, formStart));\n }\n\n const ctaClick = triggers.manual?.cta_click;\n if (ctaClick) {\n // No-ops unless the config opts into autoCapture.\n detachers.push(attachCtaClickCapture(detectorClient, ctaClick));\n }\n\n const phoneClick = triggers.manual?.phone_click;\n if (phoneClick) {\n // No-ops unless the config opts into autoCapture. A captured tel: tap also\n // drives conversion auto-fire for a linked phone_click goal.\n detachers.push(attachPhoneClickCapture(detectorClient, phoneClick));\n }\n\n // IMPORTANT: Detach in reverse (LIFO) order — multiple triggers\n // patch history.pushState and the chain only restores cleanly when\n // unwound in the opposite order of attachment.\n return () => {\n for (let i = detachers.length - 1; i >= 0; i--) {\n detachers[i]();\n }\n };\n });\n }, [rawClient, wrapClient]);\n\n return (\n <TrackingContext.Provider value={client}>\n {/*\n Isolated behind its own boundary so the `useSearchParams()` read\n inside never opts the consumer route out of static prerendering.\n Renders null; `children` are a sibling, outside the boundary, so\n their static generation is unaffected — no consumer <Suspense> needed.\n */}\n <Suspense fallback={null}>\n <PageViewTracker fire={firePageView} />\n </Suspense>\n <PhoneConfigProvider value={phone ?? null}>{children}</PhoneConfigProvider>\n </TrackingContext.Provider>\n );\n }\n\n function useTracking(): TypedTrackingClient<TRegistry> {\n const client = useContext(TrackingContext);\n if (client === null) {\n throw new Error(\n \"useTracking must be called inside a <TrackingProvider> returned by createTracking()\",\n );\n }\n return client;\n }\n\n return { TrackingProvider, useTracking };\n}\n","{\n \"name\": \"@aranova/tracking-next\",\n \"version\": \"0.24.1\",\n \"private\": false,\n \"type\": \"commonjs\",\n \"description\": \"Next.js tracking utilities for Aranova client sites\",\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"sideEffects\": false,\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/AranovaIO/aranova_internal.git\",\n \"directory\": \"packages/tracking-next\"\n },\n \"homepage\": \"https://github.com/AranovaIO/aranova_internal/tree/master/packages/tracking-next\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.mts\",\n \"default\": \"./dist/index.mjs\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n }\n },\n \"./server\": {\n \"import\": {\n \"types\": \"./dist/server.d.mts\",\n \"default\": \"./dist/server.mjs\"\n },\n \"require\": {\n \"types\": \"./dist/server.d.ts\",\n \"default\": \"./dist/server.js\"\n }\n },\n \"./middleware\": {\n \"import\": {\n \"types\": \"./dist/middleware.d.mts\",\n \"default\": \"./dist/middleware.mjs\"\n },\n \"require\": {\n \"types\": \"./dist/middleware.d.ts\",\n \"default\": \"./dist/middleware.js\"\n }\n },\n \"./sales\": {\n \"import\": {\n \"types\": \"./dist/sales.d.mts\",\n \"default\": \"./dist/sales.mjs\"\n },\n \"require\": {\n \"types\": \"./dist/sales.d.ts\",\n \"default\": \"./dist/sales.js\"\n }\n },\n \"./calendar\": {\n \"import\": {\n \"types\": \"./dist/calendar.d.mts\",\n \"default\": \"./dist/calendar.mjs\"\n },\n \"require\": {\n \"types\": \"./dist/calendar.d.ts\",\n \"default\": \"./dist/calendar.js\"\n }\n },\n \"./calendar-server\": {\n \"import\": {\n \"types\": \"./dist/calendar-server.d.mts\",\n \"default\": \"./dist/calendar-server.mjs\"\n },\n \"require\": {\n \"types\": \"./dist/calendar-server.d.ts\",\n \"default\": \"./dist/calendar-server.js\"\n }\n },\n \"./phone\": {\n \"import\": {\n \"types\": \"./dist/phone.d.mts\",\n \"default\": \"./dist/phone.mjs\"\n },\n \"require\": {\n \"types\": \"./dist/phone.d.ts\",\n \"default\": \"./dist/phone.js\"\n }\n },\n \"./blog\": {\n \"import\": {\n \"types\": \"./dist/blog.d.mts\",\n \"default\": \"./dist/blog.mjs\"\n },\n \"require\": {\n \"types\": \"./dist/blog.d.ts\",\n \"default\": \"./dist/blog.js\"\n }\n },\n \"./blog-server\": {\n \"import\": {\n \"types\": \"./dist/blog-server.d.mts\",\n \"default\": \"./dist/blog-server.mjs\"\n },\n \"require\": {\n \"types\": \"./dist/blog-server.d.ts\",\n \"default\": \"./dist/blog-server.js\"\n }\n },\n \"./blog-client\": {\n \"import\": {\n \"types\": \"./dist/blog-client.d.mts\",\n \"default\": \"./dist/blog-client.mjs\"\n },\n \"require\": {\n \"types\": \"./dist/blog-client.d.ts\",\n \"default\": \"./dist/blog-client.js\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"test\": \"vitest\",\n \"test:run\": \"vitest run\",\n \"prepublishOnly\": \"npm run build\"\n },\n \"peerDependencies\": {\n \"next\": \">=14.0.0\",\n \"react\": \">=18.0.0\"\n },\n \"dependencies\": {\n \"github-slugger\": \"^2.0.0\",\n \"libphonenumber-js\": \"^1.11.0\",\n \"next-mdx-remote\": \"^6.0.0\",\n \"rehype-slug\": \"^6.0.0\",\n \"remark-gfm\": \"^4.0.1\",\n \"remark-mdx\": \"^3.1.1\",\n \"remark-parse\": \"^11.0.0\",\n \"server-only\": \"^0.0.1\",\n \"unified\": \"^11.0.5\",\n \"zod\": \"^3.24.1\"\n },\n \"devDependencies\": {\n \"@types/react\": \"^19.2.2\",\n \"@types/react-dom\": \"^19.2.2\",\n \"esbuild\": \"^0.27.7\",\n \"jsdom\": \"^29.0.1\",\n \"react\": \"^19.2.0\",\n \"react-dom\": \"^19.2.0\",\n \"tsup\": \"^8.5.1\",\n \"typescript\": \"^5.7.3\",\n \"vitest\": \"^4.1.4\"\n },\n \"publishConfig\": {\n \"registry\": \"https://registry.npmjs.org\",\n \"access\": \"public\"\n }\n}\n","\"use client\";\n\n// Layer 2 — React phone field. Authored ONCE here in core and re-exported by\n// tracking-react / tracking-next (the existing core→framework edge). This module\n// is a SEPARATE `'use client'` subpath and is intentionally NOT exported from\n// core's main `index.ts`, so non-React consumers (browser IIFE, server) never\n// pull React. `react` is an OPTIONAL peer dependency.\n\nimport {\n createContext,\n forwardRef,\n useCallback,\n useContext,\n useMemo,\n useState,\n type ChangeEvent,\n type Context,\n type FocusEvent,\n type InputHTMLAttributes,\n type ReactNode,\n} from \"react\";\n\nimport { registerCapability } from \"./capabilities\";\nimport {\n DEFAULT_PHONE_COUNTRY,\n formatPhone,\n formatPhoneAsTyped,\n parsePhone,\n type CountryCode,\n type ParsedPhone,\n type PhoneDisplayFormat,\n} from \"./phone\";\nimport type { PhoneConfig } from \"./phone-field\";\n\n/** Carries `createTracking({ phone })` config to `usePhoneField`. Separate from the\n * tracking client context so `useTracking()`'s type is untouched.\n *\n * Created lazily on first access — NOT at module scope — so that importing a\n * barrel which re-exports this module from a React Server Component graph has no\n * eval-time side effect. A module-scope `createContext()` runs during server\n * module evaluation and throws \"createContext only works in Client Components\"\n * (Next 15/16), even when the importer only wanted a server-safe symbol bundled\n * alongside it. Behind a getter the module stays inert until a client component\n * actually renders the provider/hook.\n *\n * Caveat: this module is bundled into BOTH `@aranova/tracking-react` and\n * `@aranova/tracking-next`, so each package has its own context instance at\n * runtime. Within one installed package the provider + hook share it (correct);\n * mixing `createTracking` from one package with `usePhoneField` from the other\n * won't share config (the hook falls back to the `CA`/`national` defaults). Use a\n * single tracking package per app. */\nlet _phoneConfigContext: Context<PhoneConfig | null> | undefined;\nfunction phoneConfigContext(): Context<PhoneConfig | null> {\n return (_phoneConfigContext ??= createContext<PhoneConfig | null>(null));\n}\n\n/** Provides `createTracking({ phone })` config to `usePhoneField` / `<PhoneField>`.\n * Wired internally by each package's `TrackingProvider`; consumers configure phone\n * via `createTracking({ phone })` rather than mounting this directly. Replaces the\n * former raw `PhoneConfigContext` export so the context is never created at module\n * load (see the getter above). */\nexport function PhoneConfigProvider({\n value,\n children,\n}: {\n value: PhoneConfig | null;\n children: ReactNode;\n}): ReactNode {\n const Ctx = phoneConfigContext();\n return <Ctx.Provider value={value}>{children}</Ctx.Provider>;\n}\n\n/** Resolve the effective phone config (provider value or built-in defaults). */\nexport function usePhoneConfig(): { defaultCountry: CountryCode; display: PhoneDisplayFormat } {\n const ctx = useContext(phoneConfigContext());\n return {\n defaultCountry: ctx?.defaultCountry ?? DEFAULT_PHONE_COUNTRY,\n display: ctx?.display ?? \"national\",\n };\n}\n\nexport interface UsePhoneFieldOptions {\n defaultValue?: string;\n /** Overrides the provider's `defaultCountry`. */\n country?: CountryCode;\n /** Overrides the provider's `display` (applied to the settled value on blur). */\n display?: PhoneDisplayFormat;\n /** Notified with the canonical E.164 (or `null`) on every change. */\n onValueChange?: (e164: string | null) => void;\n}\n\nexport interface PhoneInputProps {\n value: string;\n onChange: (event: ChangeEvent<HTMLInputElement>) => void;\n onBlur: (event: FocusEvent<HTMLInputElement>) => void;\n type: \"tel\";\n inputMode: \"tel\";\n autoComplete: \"tel\";\n}\n\nexport interface PhoneFieldApi {\n /** Display value for the `<input>` (live `AsYouType` while typing). */\n value: string;\n /** Canonical E.164 — what gets transmitted. `null` while invalid/incomplete. */\n e164: string | null;\n isValid: boolean;\n /** Validation message, surfaced only after blur with non-empty invalid input. */\n error: string | null;\n parsed: ParsedPhone;\n /** Spread onto an `<input>`: pre-wires value/onChange/onBlur/type/inputMode/autoComplete. */\n inputProps: PhoneInputProps;\n}\n\n/** Headless phone field — the client owns the markup. */\nexport function usePhoneField(opts: UsePhoneFieldOptions = {}): PhoneFieldApi {\n // Reported from the hook rather than from `createTracking({ phone })`:\n // config presence only says the option was set, not that a field renders.\n // `<PhoneField>` is built on this hook, so both surfaces are covered here.\n registerCapability(\"phone_fields\");\n const cfg = usePhoneConfig();\n const country = opts.country ?? cfg.defaultCountry;\n const display = opts.display ?? cfg.display;\n const { onValueChange } = opts;\n\n const [value, setValue] = useState(() => formatPhoneAsTyped(opts.defaultValue ?? \"\", country));\n const [touched, setTouched] = useState(false);\n\n const parsed = useMemo(() => parsePhone(value, country), [value, country]);\n\n const onChange = useCallback(\n (event: ChangeEvent<HTMLInputElement>) => {\n const next = formatPhoneAsTyped(event.target.value, country);\n setValue(next);\n onValueChange?.(parsePhone(next, country).e164);\n },\n [country, onValueChange],\n );\n\n const onBlur = useCallback(\n (_event: FocusEvent<HTMLInputElement>) => {\n setTouched(true);\n // Settle the field to the configured display format once it's valid.\n setValue((current) => {\n const p = parsePhone(current, country);\n return p.isValid ? formatPhone(current, display, country) : current;\n });\n },\n [country, display],\n );\n\n const error =\n touched && value.length > 0 && !parsed.isValid ? \"Enter a valid phone number\" : null;\n\n return {\n value,\n e164: parsed.e164,\n isValid: parsed.isValid,\n error,\n parsed,\n inputProps: { value, onChange, onBlur, type: \"tel\", inputMode: \"tel\", autoComplete: \"tel\" },\n };\n}\n\nexport interface PhoneFieldProps extends Omit<\n InputHTMLAttributes<HTMLInputElement>,\n \"type\" | \"value\" | \"onChange\"\n> {\n country?: CountryCode;\n /** Controlled display value. */\n value?: string;\n /** Uncontrolled initial value. */\n defaultValue?: string;\n /** Receives the native change event (RHF `register().onChange` or your own); the\n * event's `target.value` is already `AsYouType`-formatted. */\n onChange?: (event: ChangeEvent<HTMLInputElement>) => void;\n /** Receives the canonical E.164 (or `null`) on every change. */\n onE164Change?: (e164: string | null) => void;\n}\n\n/**\n * Batteries-included phone input. Composes identically with react-hook-form\n * `{...register('phone')}` and with controlled state — the `AsYouType` +\n * mutate-`e.target.value`-before-`onChange` technique lives inside, so RHF and\n * controlled parents both receive the formatted value, and the wire value stays\n * E.164.\n */\nexport const PhoneField = forwardRef<HTMLInputElement, PhoneFieldProps>(function PhoneField(\n { country, value, defaultValue, onChange, onE164Change, ...rest },\n ref,\n) {\n const cfg = usePhoneConfig();\n const resolvedCountry = country ?? cfg.defaultCountry;\n const isControlled = value !== undefined;\n const [internal, setInternal] = useState(() =>\n formatPhoneAsTyped(defaultValue ?? \"\", resolvedCountry),\n );\n\n const handleChange = (event: ChangeEvent<HTMLInputElement>): void => {\n const formatted = formatPhoneAsTyped(event.target.value, resolvedCountry);\n // Mutate the target BEFORE forwarding so RHF/controlled consumers see the\n // formatted value (and the input renders it).\n event.target.value = formatted;\n onE164Change?.(parsePhone(formatted, resolvedCountry).e164);\n if (!isControlled) setInternal(formatted);\n onChange?.(event);\n };\n\n const shown = isControlled ? formatPhoneAsTyped(value, resolvedCountry) : internal;\n\n return (\n <input\n {...rest}\n ref={ref}\n type=\"tel\"\n inputMode=\"tel\"\n autoComplete=\"tel\"\n value={shown}\n onChange={handleChange}\n />\n );\n});\n","import type { ApiTransportConfig } from \"../http/request\";\nimport { apiRequest } from \"../http/request\";\n\nexport type CalendarTransportConfig = ApiTransportConfig;\n\n/** Prefixes `/calendar` so callers pass resource-relative paths. */\nexport async function calendarRequest<T>(\n config: CalendarTransportConfig,\n method: string,\n path: string,\n body?: unknown,\n): Promise<T> {\n return apiRequest<T>(config, method, `/calendar${path}`, body);\n}\n","import { formatDateInTz } from \"../intl/date\";\n\nexport { formatDateInTz };\n\n/** The visitor's own zone, so a booking page defaults to their local times. */\nexport function resolveBrowserTimeZone(): string {\n try {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n } catch {\n return \"UTC\";\n }\n}\n\n/** Parts of an instant as seen in a specific zone. */\nfunction partsInTz(date: Date, timeZone: string): Record<string, number> {\n const formatter = new Intl.DateTimeFormat(\"en-US\", {\n timeZone,\n hour12: false,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n });\n const out: Record<string, number> = {};\n for (const part of formatter.formatToParts(date)) {\n if (part.type !== \"literal\") out[part.type] = Number(part.value);\n }\n // `hour` comes back as 24 at midnight under hour12:false in some engines.\n if (out.hour === 24) out.hour = 0;\n return out;\n}\n\n/** Offset in minutes between UTC and `timeZone` at a given instant. */\nexport function offsetMinutesAt(date: Date, timeZone: string): number {\n const p = partsInTz(date, timeZone);\n const asUtc = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second);\n return (asUtc - Math.floor(date.getTime() / 1000) * 1000) / 60_000;\n}\n\n/**\n * The instant matching a wall-clock time in `timeZone`.\n *\n * Two passes because the offset itself depends on the instant: guess with the\n * offset at the naive time, then re-solve with the offset that guess landed in.\n * That second pass is what makes DST-transition days come out right.\n */\nexport function instantFromWallClock(\n timeZone: string,\n year: number,\n month: number,\n day: number,\n hour = 0,\n minute = 0,\n): Date {\n const naive = Date.UTC(year, month - 1, day, hour, minute);\n const firstGuess = new Date(naive - offsetMinutesAt(new Date(naive), timeZone) * 60_000);\n const corrected = naive - offsetMinutesAt(firstGuess, timeZone) * 60_000;\n return new Date(corrected);\n}\n\n/** `YYYY-MM-DD` for an instant as seen in `timeZone`. */\nexport function localDateKey(iso: string, timeZone: string): string {\n const p = partsInTz(new Date(iso), timeZone);\n const pad = (n: number) => String(n).padStart(2, \"0\");\n return `${p.year}-${pad(p.month)}-${pad(p.day)}`;\n}\n\nexport function startOfDayInTz(dateKey: string, timeZone: string): Date {\n const [year, month, day] = dateKey.split(\"-\").map(Number);\n return instantFromWallClock(timeZone, year, month, day, 0, 0);\n}\n\nexport function endOfDayInTz(dateKey: string, timeZone: string): Date {\n const start = startOfDayInTz(dateKey, timeZone);\n // Add a calendar day rather than 24h: DST days are 23 or 25 hours long.\n const p = partsInTz(start, timeZone);\n return instantFromWallClock(timeZone, p.year, p.month, p.day + 1, 0, 0);\n}\n\nexport function durationMinutes(startIso: string, endIso: string): number {\n return Math.round((new Date(endIso).getTime() - new Date(startIso).getTime()) / 60_000);\n}\n\n/** `10:00 – 10:30` in the given zone. */\nexport function formatSlotRange(\n startIso: string,\n endIso: string,\n timeZone: string,\n locale?: string,\n): string {\n const opts: Intl.DateTimeFormatOptions = { hour: \"2-digit\", minute: \"2-digit\", timeZone };\n const fmt = new Intl.DateTimeFormat(locale, opts);\n return `${fmt.format(new Date(startIso))} – ${fmt.format(new Date(endIso))}`;\n}\n","import { registerCapability } from \"../../capabilities\";\nimport { AranovaApiError } from \"../http/errors\";\nimport type { BusyResponse, CalendarErrorCode, CalendarSummary } from \"./schema\";\nimport type { CalendarTransportConfig } from \"./transport\";\nimport { calendarRequest } from \"./transport\";\nimport { resolveBrowserTimeZone } from \"./time\";\n\n/**\n * The browser-side calendar client — reads only.\n *\n * There is deliberately no write verb on this type. A public key ships in a JS\n * bundle and its Origin allowlist is a browser-enforced header a script forges\n * trivially; a booking is not a database row but an event on a real person's\n * calendar that mails their contacts. Writes live in\n * `@aranova/tracking-next/calendar-server`, which is `server-only`.\n */\nexport interface CalendarReadClientConfig extends CalendarTransportConfig {\n /** Falls back to the visitor's own zone. */\n defaultTimeZone?: string;\n /** Required when the key is not already scoped to one business. */\n businessId?: string;\n}\n\nexport interface BusyQuery {\n /**\n * ISO 8601 instants WITH an offset — the API rejects a naive or date-only\n * value with a 400. `startOfDayInTz`/`endOfDayInTz` turn a picked date into\n * the right pair for a given zone.\n */\n since: string;\n until: string;\n timeZone?: string;\n}\n\nexport interface CalendarReadClient<TCalendarKey extends string = string> {\n /** Labels, timezones and status — everything a widget needs before booking. */\n listCalendars(): Promise<CalendarSummary[]>;\n /** Busy intervals only. Never the contents of the grantee's events. */\n busy(calendarKey: TCalendarKey, query: BusyQuery): Promise<BusyResponse>;\n}\n\nfunction withBusiness(config: CalendarReadClientConfig, path: string): string {\n if (!config.businessId) return path;\n const separator = path.includes(\"?\") ? \"&\" : \"?\";\n return `${path}${separator}business_id=${encodeURIComponent(config.businessId)}`;\n}\n\nexport function createCalendarReadClient<TCalendarKey extends string = string>(\n config: CalendarReadClientConfig,\n): CalendarReadClient<TCalendarKey> {\n registerCapability(\"calendar_read\");\n return {\n async listCalendars() {\n return calendarRequest<CalendarSummary[]>(config, \"GET\", withBusiness(config, \"/calendars\"));\n },\n async busy(calendarKey, query) {\n const params = new URLSearchParams({\n since: query.since,\n until: query.until,\n });\n const timeZone = query.timeZone ?? config.defaultTimeZone ?? resolveBrowserTimeZone();\n params.set(\"time_zone\", timeZone);\n return calendarRequest<BusyResponse>(\n config,\n \"GET\",\n withBusiness(config, `/${encodeURIComponent(calendarKey)}/busy?${params.toString()}`),\n );\n },\n };\n}\n\n/** Narrow an unknown error to a specific calendar failure code. */\nexport function isCalendarError(\n error: unknown,\n code?: CalendarErrorCode,\n): error is AranovaApiError {\n if (!(error instanceof AranovaApiError)) return false;\n return code === undefined || error.code === code;\n}\n","import { z } from \"zod\";\n\n// Mirrored by `apps/api/src/schemas/tracking_calendar.py` and pinned by the\n// event-schema drift test. Keep both sides in step.\n//\n// The location union is a plain `z.union`, deliberately: a discriminated union\n// emits `oneOf` + discriminator metadata on the Python side and `anyOf` here,\n// which would fail the drift snapshot. Both sides stay plain.\n\n/** Bumped when the durable `metadata` payload changes shape. */\nexport const CALENDAR_METADATA_SCHEMA_VERSION = 1;\n\nexport const MAX_ATTENDEES = 20;\nexport const MAX_REMINDER_OVERRIDES = 5;\n/** Google's ceiling for `reminders.overrides[].minutes`: four weeks. */\nexport const MAX_REMINDER_MINUTES = 40_320;\nexport const MAX_BOOKING_MINUTES = 1_440;\n\nexport const BOOKING_SOURCES = [\"website\", \"phone\", \"walk_in\", \"import\", \"operator\"] as const;\nexport const BOOKING_STATUSES = [\"pending\", \"confirmed\", \"cancelled\", \"no_show\"] as const;\nexport const GOOGLE_SYNC_STATES = [\"queued\", \"synced\", \"uncertain\", \"failed\", \"drifted\"] as const;\nexport const CALENDAR_SYNC_STATUSES = [\n \"pending_invite\",\n \"awaiting_calendar_selection\",\n \"connected\",\n \"needs_reconnect\",\n \"revoked\",\n \"disabled\",\n] as const;\n\n/** Every failure the calendar API can hand back, so a site can branch on it. */\nexport const CALENDAR_ERROR_CODES = [\n \"slot_unavailable\",\n \"calendar_not_connected\",\n \"calendar_disconnected\",\n \"booking_not_found\",\n \"outside_booking_window\",\n \"rate_limited\",\n \"google_error\",\n] as const;\nexport type CalendarErrorCode = (typeof CALENDAR_ERROR_CODES)[number];\n\nexport type BookingStatus = (typeof BOOKING_STATUSES)[number];\nexport type GoogleSyncState = (typeof GOOGLE_SYNC_STATES)[number];\nexport type CalendarSyncStatus = (typeof CALENDAR_SYNC_STATUSES)[number];\nexport type JsonScalar = string | number | boolean | null;\n\nconst isoInstant = z.string().datetime({ offset: true });\n\n/**\n * Does the runtime actually know this zone?\n *\n * `Intl.DateTimeFormat` rather than `Intl.supportedValuesOf(\"timeZone\")`: the\n * latter returns canonical zones only and omits live aliases (`Asia/Calcutta`,\n * `US/Pacific`, `Europe/Kiev`) that the API's `ZoneInfo` accepts. Validating\n * against it would reject values the server stores happily.\n */\nfunction isKnownTimeZone(timeZone: string): boolean {\n try {\n new Intl.DateTimeFormat(undefined, { timeZone });\n return true;\n } catch {\n return false;\n }\n}\n\n// The refinement is invisible to `zod-to-json-schema` — unrepresentable\n// constraints are dropped — so `events.schema.json` and the drift test against\n// the Pydantic mirror are unaffected while both sides gain the real check.\nconst ianaTz = z\n .string()\n .min(1)\n .max(64)\n .regex(/^[A-Za-z0-9_+\\-/]+$/)\n .refine(isKnownTimeZone, { message: \"unknown IANA time zone\" });\n\nexport const bookingAttendeeSchema = z\n .object({\n email: z.string().max(320).email(),\n display_name: z.string().max(200).nullable().optional(),\n optional: z.boolean().default(false),\n })\n .strict();\n\nexport const bookingReminderSchema = z\n .object({\n method: z.enum([\"email\", \"popup\"]),\n minutes_before: z.number().int().min(0).max(MAX_REMINDER_MINUTES),\n })\n .strict();\n\nexport const bookingRemindersSchema = z\n .object({\n use_calendar_defaults: z.boolean().default(true),\n overrides: z.array(bookingReminderSchema).max(MAX_REMINDER_OVERRIDES).default([]),\n })\n .strict();\n\nexport const bookingLocationSchema = z.union([\n z.object({ kind: z.literal(\"google_meet\") }).strict(),\n z.object({ kind: z.literal(\"physical\"), address: z.string().max(1024) }).strict(),\n z.object({ kind: z.literal(\"phone\"), phone: z.string().max(64) }).strict(),\n z.object({ kind: z.literal(\"custom\"), text: z.string().max(1024) }).strict(),\n]);\n\n/**\n * The nullable form, flattened.\n *\n * `bookingLocationSchema.nullable()` would nest one `anyOf` inside another,\n * while Pydantic's `BookingLocation | None` flattens to a single list — the\n * drift snapshot compares structure, so both sides emit the flat shape.\n */\nexport const bookingLocationNullableSchema = z.union([...bookingLocationSchema.options, z.null()]);\n\nexport const bookingCustomerSchema = z\n .object({\n // Required: Google needs an address to send the invite that confirms the\n // booking, and that invite is the whole confirmation mechanism.\n email: z.string().max(320).email(),\n name: z.string().max(200).nullable().optional(),\n phone: z.string().max(64).nullable().optional(),\n sms_consent: z.boolean().default(false),\n })\n .strict();\n\nconst jsonScalar = z.union([z.string(), z.number(), z.boolean(), z.null()]);\n\n/**\n * Named attribution keys plus a flat escape hatch.\n *\n * `custom` is flat and scalar-only on purpose: it mirrors trivially in Pydantic,\n * stays JSONB-queryable, and bounds what a caller can push. Only `custom` is\n * ever mirrored to Google's `extendedProperties`; the named keys stay in our\n * database.\n */\nexport const bookingMetadataSchema = z\n .object({\n schema_version: z.number().int().default(CALENDAR_METADATA_SCHEMA_VERSION),\n source: z.enum(BOOKING_SOURCES).nullable().optional(),\n service: z.string().max(64).nullable().optional(),\n visitor_id: z.string().max(64).nullable().optional(),\n session_id: z.string().max(64).nullable().optional(),\n gclid: z.string().max(256).nullable().optional(),\n fbclid: z.string().max(256).nullable().optional(),\n utm_source: z.string().max(128).nullable().optional(),\n utm_medium: z.string().max(128).nullable().optional(),\n utm_campaign: z.string().max(128).nullable().optional(),\n utm_term: z.string().max(128).nullable().optional(),\n utm_content: z.string().max(128).nullable().optional(),\n landing_page: z.string().max(2048).nullable().optional(),\n referrer: z.string().max(2048).nullable().optional(),\n notes: z.string().max(2000).nullable().optional(),\n custom: z.record(jsonScalar).nullable().optional(),\n })\n .strict();\n\nfunction refineEndXor(\n value: { start_at: string; end_at?: string | null; duration_minutes?: number | null },\n ctx: z.RefinementCtx,\n): void {\n const hasEnd = value.end_at !== undefined && value.end_at !== null;\n const hasDuration = value.duration_minutes !== undefined && value.duration_minutes !== null;\n if (hasEnd === hasDuration) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"provide exactly one of end_at or duration_minutes\",\n path: [\"end_at\"],\n });\n return;\n }\n if (hasEnd && new Date(value.end_at as string) <= new Date(value.start_at)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"end_at must be after start_at\",\n path: [\"end_at\"],\n });\n }\n}\n\nexport const bookingCreateSchema = z\n .object({\n calendar_key: z.string().min(1).max(64),\n // Free-form: appointment types are the client site's own vocabulary, not\n // configuration the dashboard holds.\n appointment_type: z.string().max(64).nullable().optional(),\n start_at: isoInstant,\n end_at: isoInstant.nullable().optional(),\n duration_minutes: z.number().int().positive().max(MAX_BOOKING_MINUTES).nullable().optional(),\n /** The booker's zone — distinct from the business's and the calendar's. */\n time_zone: ianaTz,\n title: z.string().max(300).nullable().optional(),\n description: z.string().max(8000).nullable().optional(),\n location: bookingLocationNullableSchema.optional(),\n customer: bookingCustomerSchema,\n attendees: z.array(bookingAttendeeSchema).max(MAX_ATTENDEES).default([]),\n send_invites: z.boolean().default(true),\n reminders: bookingRemindersSchema.nullable().optional(),\n metadata: bookingMetadataSchema.nullable().optional(),\n idempotency_key: z.string().max(128).nullable().optional(),\n buffer_before_minutes: z.number().int().min(0).max(MAX_BOOKING_MINUTES).default(0),\n buffer_after_minutes: z.number().int().min(0).max(MAX_BOOKING_MINUTES).default(0),\n })\n .strict()\n .superRefine(refineEndXor);\n\nexport const bookingRescheduleSchema = z\n .object({\n start_at: isoInstant,\n end_at: isoInstant.nullable().optional(),\n duration_minutes: z.number().int().positive().max(MAX_BOOKING_MINUTES).nullable().optional(),\n time_zone: ianaTz,\n notify_attendees: z.boolean().default(true),\n reason: z.string().max(500).nullable().optional(),\n })\n .strict()\n .superRefine(refineEndXor);\n\nexport const bookingCancelSchema = z\n .object({\n reason: z.string().max(500).nullable().optional(),\n notify_attendees: z.boolean().default(true),\n })\n .strict();\n\n// `z.input` so Zod defaults stay optional for callers.\nexport type BookingCreateInput = z.input<typeof bookingCreateSchema>;\nexport type BookingRescheduleInput = z.input<typeof bookingRescheduleSchema>;\nexport type BookingCancelInput = z.input<typeof bookingCancelSchema>;\nexport type BookingAttendee = z.input<typeof bookingAttendeeSchema>;\nexport type BookingReminders = z.input<typeof bookingRemindersSchema>;\nexport type BookingLocation = z.input<typeof bookingLocationSchema>;\nexport type BookingCustomer = z.input<typeof bookingCustomerSchema>;\nexport type BookingMetadata<\n TCustom extends Record<string, JsonScalar> = Record<string, JsonScalar>,\n> = Omit<z.input<typeof bookingMetadataSchema>, \"custom\"> & { custom?: TCustom | null };\n\n// ---------------------------------------------------------------------------\n// Read shapes — server responses, trusted and therefore not re-validated here.\n// ---------------------------------------------------------------------------\n\nexport interface CalendarSummary {\n calendar_key: string;\n label: string;\n time_zone: string;\n status: CalendarSyncStatus;\n /** Secret-key only. A public key gets `null`: whose Google account is behind\n * a calendar is a third party's identity, not the client site's business. */\n google_account_email?: string | null;\n granted_scopes?: string[] | null;\n connected_at?: string | null;\n}\n\nexport interface BusyInterval {\n start_at: string;\n end_at: string;\n source: \"google\" | \"booking\";\n}\n\nexport interface BusyResponse {\n calendar_key: string;\n time_zone: string;\n window: { since: string; until: string };\n busy: BusyInterval[];\n generated_at: string;\n}\n\nexport interface Booking {\n id: string;\n calendar_key: string;\n status: BookingStatus;\n google_sync_state: GoogleSyncState;\n start_at: string;\n end_at: string;\n time_zone: string;\n appointment_type: string | null;\n title: string;\n customer: BookingCustomer;\n google_html_link: string | null;\n meet_url: string | null;\n /** Returned only on create — the capability credential for manage links. */\n manage_token?: string | null;\n}\n","import type { BusyInterval } from \"./schema\";\nimport { instantFromWallClock, offsetMinutesAt } from \"./time\";\n\n/**\n * Slot computation lives in the client site, not in our database.\n *\n * Opening hours, slot length, notice and buffers differ per client and per use\n * case; modelling them as dashboard config would mean every new client needs\n * data entry before their site works. The API answers only \"when is this person\n * busy\" — this pure helper turns that plus the site's own hours into offerable\n * slots.\n */\n\nexport interface OpeningInterval {\n /** Local wall-clock `HH:MM` in the calendar's zone. */\n start: string;\n end: string;\n}\n\nexport interface OpeningHours {\n /** 0 = Sunday … 6 = Saturday. A missing weekday is closed. */\n weekly: Partial<Record<number, OpeningInterval[]>>;\n /** `YYYY-MM-DD` → intervals, replacing that day's weekly rule entirely. */\n overrides?: Record<string, OpeningInterval[]>;\n /** `YYYY-MM-DD` dates that are closed regardless of the weekly rule. */\n closedDates?: string[];\n}\n\nexport interface ComputeSlotsOptions {\n busy: BusyInterval[];\n openingHours: OpeningHours;\n timeZone: string;\n durationMinutes: number;\n granularityMinutes?: number;\n minNoticeMinutes?: number;\n bufferBeforeMinutes?: number;\n bufferAfterMinutes?: number;\n windowDays?: number;\n now?: Date;\n}\n\nexport interface Slot {\n start_at: string;\n end_at: string;\n}\n\nexport interface ComputeSlotsResult {\n slots: Slot[];\n nextAvailableAt: string | null;\n}\n\nfunction parseHhMm(value: string): [number, number] {\n const [hour, minute] = value.split(\":\").map(Number);\n return [hour || 0, minute || 0];\n}\n\nfunction dateKeyOf(date: Date, timeZone: string): string {\n const fmt = new Intl.DateTimeFormat(\"en-CA\", {\n timeZone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n });\n return fmt.format(date);\n}\n\n/** Weekday of a `YYYY-MM-DD` local date, read at noon UTC so no offset can\n * shift it across a day boundary. */\nfunction weekdayFromDateKey(dateKey: string): number {\n const [year, month, day] = dateKey.split(\"-\").map(Number);\n return new Date(Date.UTC(year, month - 1, day, 12)).getUTCDay();\n}\n\n/** Midday of the local date containing `at` — a stable anchor to step from,\n * immune to a midnight DST jump. */\nfunction startOfLocalDay(at: Date, timeZone: string): Date {\n const [year, month, day] = dateKeyOf(at, timeZone).split(\"-\").map(Number);\n return instantFromWallClock(timeZone, year, month, day, 12, 0);\n}\n\nfunction overlaps(aStart: number, aEnd: number, bStart: number, bEnd: number): boolean {\n return aStart < bEnd && aEnd > bStart;\n}\n\nexport function computeSlots(options: ComputeSlotsOptions): ComputeSlotsResult {\n const {\n busy,\n openingHours,\n timeZone,\n durationMinutes,\n granularityMinutes = 15,\n minNoticeMinutes = 0,\n bufferBeforeMinutes = 0,\n bufferAfterMinutes = 0,\n windowDays = 30,\n now = new Date(),\n } = options;\n\n const earliest = now.getTime() + minNoticeMinutes * 60_000;\n const busyRanges = busy.map((interval) => [\n new Date(interval.start_at).getTime(),\n new Date(interval.end_at).getTime(),\n ]);\n\n const slots: Slot[] = [];\n // Advance by CALENDAR days, not by 86_400_000 ms. A DST day is 23 or 25 hours\n // long, so fixed-millisecond stepping skips a local date entirely at spring\n // forward and visits one twice at fall back — in America/Toronto, adding 24h\n // from 2026-03-08T04:30Z jumps straight from the 7th to the 9th.\n let cursor = startOfLocalDay(now, timeZone);\n for (let dayOffset = 0; dayOffset < windowDays; dayOffset += 1) {\n const dateKey = dateKeyOf(cursor, timeZone);\n const [year, month, day] = dateKey.split(\"-\").map(Number);\n // `Date.UTC` normalises day 32 into the next month, so this needs no\n // month-length handling.\n cursor = instantFromWallClock(timeZone, year, month, day + 1, 12, 0);\n\n if (openingHours.closedDates?.includes(dateKey)) continue;\n\n const intervals =\n openingHours.overrides?.[dateKey] ?? openingHours.weekly[weekdayFromDateKey(dateKey)] ?? [];\n for (const interval of intervals) {\n const [openHour, openMinute] = parseHhMm(interval.start);\n const [closeHour, closeMinute] = parseHhMm(interval.end);\n const opensAt = instantFromWallClock(timeZone, year, month, day, openHour, openMinute);\n const closesAt = instantFromWallClock(timeZone, year, month, day, closeHour, closeMinute);\n\n for (\n let start = opensAt.getTime();\n start + durationMinutes * 60_000 <= closesAt.getTime();\n start += granularityMinutes * 60_000\n ) {\n const end = start + durationMinutes * 60_000;\n if (start < earliest) continue;\n\n // A slot is unavailable if its BUFFERED span touches anything busy —\n // the buffers are what keep a gap between appointments.\n const blockedStart = start - bufferBeforeMinutes * 60_000;\n const blockedEnd = end + bufferAfterMinutes * 60_000;\n const taken = busyRanges.some(([busyStart, busyEnd]) =>\n overlaps(blockedStart, blockedEnd, busyStart, busyEnd),\n );\n if (taken) continue;\n\n slots.push({\n start_at: new Date(start).toISOString(),\n end_at: new Date(end).toISOString(),\n });\n }\n }\n }\n\n slots.sort((a, b) => a.start_at.localeCompare(b.start_at));\n return { slots, nextAvailableAt: slots[0]?.start_at ?? null };\n}\n\n/** Group slots by local date, the shape every date-picker UI wants. */\nexport function groupSlotsByDay(\n slots: Slot[],\n timeZone: string,\n): { date: string; slots: Slot[] }[] {\n const byDay = new Map<string, Slot[]>();\n for (const slot of slots) {\n const key = dateKeyOf(new Date(slot.start_at), timeZone);\n const bucket = byDay.get(key);\n if (bucket) bucket.push(slot);\n else byDay.set(key, [slot]);\n }\n return [...byDay.entries()]\n .map(([date, daySlots]) => ({ date, slots: daySlots }))\n .sort((a, b) => a.date.localeCompare(b.date));\n}\n\nexport { offsetMinutesAt };\n","\"use client\";\n\nimport type { Context, ReactNode } from \"react\";\nimport { createContext, useCallback, useContext, useEffect, useMemo, useState } from \"react\";\n\nimport type {\n Booking,\n BookingCreateInput,\n BusyInterval,\n CalendarReadClient,\n CalendarSummary,\n ComputeSlotsOptions,\n OpeningHours,\n Slot,\n} from \"./resources/calendar\";\nimport { computeSlots, groupSlotsByDay, resolveBrowserTimeZone } from \"./resources/calendar\";\n\n/**\n * Headless hooks only — no DOM, no CSS, no widget.\n *\n * A styled booking form would fight every client's design system, and these\n * packages already ship no consent UI for the same reason. The site renders;\n * these hooks own fetching, slot math and submit state.\n *\n * The context is created lazily on first access, never at module scope: a\n * module-scope `createContext()` runs during server module evaluation and throws\n * \"createContext only works in Client Components\" when a Server Component graph\n * merely imports a barrel that re-exports this file.\n */\nlet _calendarClientContext: Context<CalendarReadClient | null> | undefined;\nfunction calendarClientContext(): Context<CalendarReadClient | null> {\n return (_calendarClientContext ??= createContext<CalendarReadClient | null>(null));\n}\n\nexport function CalendarClientProvider({\n value,\n children,\n}: {\n value: CalendarReadClient | null;\n children: ReactNode;\n}): ReactNode {\n const Ctx = calendarClientContext();\n return <Ctx.Provider value={value}>{children}</Ctx.Provider>;\n}\n\nexport function useCalendarClient(): CalendarReadClient {\n const client = useContext(calendarClientContext());\n if (!client) {\n throw new Error(\n \"useCalendarClient requires <CalendarClientProvider>. Wire it via createTracking({ calendar }).\",\n );\n }\n return client;\n}\n\nexport interface UseCalendarBusyResult {\n busy: BusyInterval[];\n timeZone: string;\n isLoading: boolean;\n error: Error | null;\n refetch: () => void;\n}\n\n/** Free/busy for one calendar over a window. Public key, straight from the browser. */\nexport function useCalendarBusy(\n calendarKey: string,\n window: { since: string; until: string },\n): UseCalendarBusyResult {\n const client = useCalendarClient();\n const [busy, setBusy] = useState<BusyInterval[]>([]);\n const [timeZone, setTimeZone] = useState<string>(resolveBrowserTimeZone());\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n const [nonce, setNonce] = useState(0);\n\n useEffect(() => {\n const controller = new AbortController();\n setIsLoading(true);\n client\n .busy(calendarKey, { since: window.since, until: window.until })\n .then((response) => {\n if (controller.signal.aborted) return;\n setBusy(response.busy);\n setTimeZone(response.time_zone);\n setError(null);\n })\n .catch((cause: unknown) => {\n if (controller.signal.aborted) return;\n setError(cause instanceof Error ? cause : new Error(String(cause)));\n })\n .finally(() => {\n if (!controller.signal.aborted) setIsLoading(false);\n });\n return () => controller.abort();\n }, [client, calendarKey, window.since, window.until, nonce]);\n\n const refetch = useCallback(() => setNonce((value) => value + 1), []);\n return { busy, timeZone, isLoading, error, refetch };\n}\n\nexport interface UseSlotsOptions extends Omit<ComputeSlotsOptions, \"busy\" | \"timeZone\"> {\n openingHours: OpeningHours;\n timeZone?: string;\n}\n\n/** Slot math, memoized. Pure — the site owns the opening hours it passes in. */\nexport function useSlots(\n busy: BusyInterval[],\n timeZone: string,\n options: UseSlotsOptions,\n): { slots: Slot[]; days: { date: string; slots: Slot[] }[]; nextAvailableAt: string | null } {\n const zone = options.timeZone ?? timeZone;\n return useMemo(() => {\n const { slots, nextAvailableAt } = computeSlots({ ...options, busy, timeZone: zone });\n return { slots, days: groupSlotsByDay(slots, zone), nextAvailableAt };\n }, [busy, zone, options]);\n}\n\nexport type BookingFormStatus = \"idle\" | \"submitting\" | \"confirmed\" | \"failed\";\n\nexport interface UseBookingFormOptions {\n /** The site's own route handler — writes never leave the server with a key. */\n endpoint?: string;\n onConfirmed?: (booking: Booking) => void;\n}\n\nexport interface UseBookingFormResult {\n status: BookingFormStatus;\n error: Error | null;\n booking: Booking | null;\n submit: (input: BookingCreateInput) => Promise<void>;\n reset: () => void;\n}\n\n/**\n * Submit state for a booking.\n *\n * Posts to the SITE's own route handler, not to us: a booking needs a secret\n * key, which must never reach a browser bundle.\n */\nexport function useBookingForm(options: UseBookingFormOptions = {}): UseBookingFormResult {\n const endpoint = options.endpoint ?? \"/api/aranova/calendar/bookings\";\n const [status, setStatus] = useState<BookingFormStatus>(\"idle\");\n const [error, setError] = useState<Error | null>(null);\n const [booking, setBooking] = useState<Booking | null>(null);\n\n const submit = useCallback(\n async (input: BookingCreateInput) => {\n setStatus(\"submitting\");\n setError(null);\n try {\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(input),\n });\n const body: unknown = await response.json().catch(() => null);\n if (!response.ok) {\n const detail =\n body &&\n typeof body === \"object\" &&\n typeof (body as { detail?: unknown }).detail === \"string\"\n ? (body as { detail: string }).detail\n : \"Booking failed\";\n throw new Error(detail);\n }\n setBooking(body as Booking);\n setStatus(\"confirmed\");\n options.onConfirmed?.(body as Booking);\n } catch (cause) {\n setError(cause instanceof Error ? cause : new Error(String(cause)));\n setStatus(\"failed\");\n }\n },\n [endpoint, options],\n );\n\n const reset = useCallback(() => {\n setStatus(\"idle\");\n setError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9D,QAAM,CAAC,OAAO,QAAQ,IAAIA,UAAuB,IAAI;AACrD,QAAM,CAAC,SAAS,UAAU,IAAIA,UAAyB,IAAI;AAE3D,QAAM,SAASE;AAAA,IACb,OAAO,UAA8B;AACnC,gBAAU,YAAY;AACtB,eAAS,IAAI;AACb,UAAI;AACF,cAAM,WAAW,MAAM,MAAM,UAAU;AAAA,UACrC,QAAQ;AAAA,UACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,UAC9C,MAAM,KAAK,UAAU,KAAK;AAAA,QAC5B,CAAC;AACD,cAAM,OAAgB,MAAM,SAAS,KAAK,EAAE,MAAM,MAAM,IAAI;AAC5D,YAAI,CAAC,SAAS,IAAI;AAChB,gBAAM,SACJ,QACA,OAAO,SAAS,YAChB,OAAQ,KAA8B,WAAW,WAC5C,KAA4B,SAC7B;AACN,gBAAM,IAAI,MAAM,MAAM;AAAA,QACxB;AACA,mBAAW,IAAe;AAC1B,kBAAU,WAAW;AACrB,gBAAQ,cAAc,IAAe;AAAA,MACvC,SAAS,OAAO;AACd,iBAAS,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;AAClE,kBAAU,QAAQ;AAAA,MACpB;AAAA,IACF;AAAA,IACA,CAAC,UAAU,OAAO;AAAA,EACpB;AAEA,QAAM,QAAQA,aAAY,MAAM;AAC9B,cAAU,MAAM;AAChB,aAAS,IAAI;AACb,eAAW,IAAI;AAAA,EACjB,GAAG,CAAC,CAAC;AAEL,SAAO,EAAE,QAAQ,OAAO,SAAS,QAAQ,MAAM;AACjD;","names":["listeners","CACHE_PREFIX","cacheKey","readCache","writeCache","MAX_BUFFERED_EVENTS","identityHeaders","z","z","z","z","z","z","z","z","z","z","z","currentPath","currentPath","currentPath","z","useEffect","useState","DEFAULT_CHOICE","useState","useEffect","useEffect","Fragment","jsx","jsxs","trackingConfigKey","useEffect","Script","Fragment","jsx","jsxs","Script","createContext","useCallback","useContext","useEffect","useMemo","useCallback","useState","jsx","useState","useCallback","PhoneField","jsx","jsxs","useEffect","createContext","useMemo","useCallback","useContext","z","durationMinutes","createContext","useCallback","useContext","useEffect","useMemo","useState","jsx","createContext","useContext","window","useState","useEffect","useCallback","useMemo"]}
1
+ {"version":3,"sources":["../../tracking-core/src/phone.ts","../../tracking-core/src/user-data.ts","../../tracking-core/src/consent.ts","../../tracking-core/src/capabilities.ts","../../tracking-core/src/tracking.ts","../../tracking-core/src/gtag.ts","../../tracking-core/src/fbq.ts","../../tracking-core/src/landing.ts","../../tracking-core/src/payloads.ts","../../tracking-core/src/resources/conversion-firing.ts","../../tracking-core/src/resources/conversion-config.ts","../../tracking-core/src/resources/automatic-transaction.ts","../../tracking-core/src/resources/automatic-trigger.ts","../../tracking-core/src/resources/intl/date.ts","../../tracking-core/src/resources/sales/money.ts","../../tracking-core/src/resources/tracking-config-runtime.ts","../../tracking-core/src/session.ts","../../tracking-core/src/events/page-view.ts","../../tracking-core/src/ingest.ts","../../tracking-core/src/events/cta-click.ts","../../tracking-core/src/events/sdk-heartbeat.ts","../../tracking-core/src/events/form-start.ts","../../tracking-core/src/events/form-submit.ts","../../tracking-core/src/events/multi-page-session.ts","../../tracking-core/src/events/page-exit.ts","../../tracking-core/src/events/phone-click.ts","../../tracking-core/src/events/scroll-depth.ts","../../tracking-core/src/events/specific-page-visit.ts","../../tracking-core/src/events/time-on-site.ts","../../tracking-core/src/events/semantics.ts","../../tracking-core/src/events/registry.ts","../../tracking-core/src/resources/http/errors.ts","../../tracking-core/src/resources/http/request.ts","../../tracking-core/src/resources/sales/transport.ts","../../tracking-core/src/resources/sales/client.ts","../../tracking-core/src/resources/sales/schema.ts","../../tracking-core/src/resources/services.ts","../../tracking-core/src/phone-field.ts","../src/index.ts","../../tracking-core/src/resources/calendar/transport.ts","../../tracking-core/src/resources/calendar/time.ts","../../tracking-core/src/resources/calendar/read-client.ts","../../tracking-core/src/resources/calendar/schema.ts","../../tracking-core/src/resources/calendar/slots.ts","../../tracking-core/src/calendar-react.tsx"],"sourcesContent":["// Framework-agnostic phone-number utilities — isomorphic (browser + Node/RSC),\n// zero React. Bundled `libphonenumber-js` (standard metadata) so clients add no\n// dependency. The transmitted value is ALWAYS E.164; display is the only knob.\n\nimport { AsYouType, parsePhoneNumberFromString, type CountryCode } from \"libphonenumber-js\";\n\nexport type { CountryCode };\n\n/**\n * How a phone number is shown in the UI. The transmitted value is always E.164\n * and is deliberately NOT part of this — only the display format is configurable.\n * A function form covers the long tail (`(parsed) => string`).\n */\nexport type PhoneDisplayFormat =\n | \"national\"\n | \"international\"\n | \"e164\"\n | ((parsed: ParsedPhone) => string);\n\nexport interface ParsedPhone {\n /** E.164 (`\"+14165550199\"`) or `null` when the input isn't a valid number. This is what gets transmitted. */\n e164: string | null;\n /** National display form (`\"(416) 555-0199\"`); empty string when unparseable. */\n national: string;\n /** International display form (`\"+1 416 555 0199\"`); empty string when unparseable. */\n international: string;\n /** ISO-3166 country resolved by libphonenumber, or `null`. */\n country: CountryCode | null;\n isValid: boolean;\n}\n\n/** Region assumed for numbers typed without a country code. */\nexport const DEFAULT_PHONE_COUNTRY: CountryCode = \"CA\";\n\n/** Parse a raw/display string into every representation at once (one parse → display + wire never drift). */\nexport function parsePhone(raw: string, country?: CountryCode): ParsedPhone {\n const region = country ?? DEFAULT_PHONE_COUNTRY;\n const parsed = parsePhoneNumberFromString(raw ?? \"\", region);\n if (!parsed) {\n return { e164: null, national: \"\", international: \"\", country: region, isValid: false };\n }\n const isValid = parsed.isValid();\n return {\n // E.164 is only surfaced for a *valid* number — a possible-but-invalid input\n // (e.g. too few digits) still parses but must not be transmitted.\n e164: isValid ? parsed.number : null,\n national: parsed.formatNational(),\n international: parsed.formatInternational(),\n country: parsed.country ?? region,\n isValid,\n };\n}\n\n/** Normalize any raw/display value to E.164, or `null` if it isn't a valid number. */\nexport function toE164(raw: string, country?: CountryCode): string | null {\n return parsePhone(raw, country).e164;\n}\n\n/** Format a value for display. Defaults to `'national'`. Never affects the wire value. */\nexport function formatPhone(\n value: string,\n format: PhoneDisplayFormat = \"national\",\n country?: CountryCode,\n): string {\n const parsed = parsePhone(value, country);\n if (typeof format === \"function\") return format(parsed);\n switch (format) {\n case \"international\":\n return parsed.international || value;\n case \"e164\":\n return parsed.e164 ?? value;\n case \"national\":\n default:\n return parsed.national || value;\n }\n}\n\n/** Live, incremental formatting for an `<input>` as the user types (`AsYouType`). */\nexport function formatPhoneAsTyped(raw: string, country?: CountryCode): string {\n return new AsYouType(country ?? DEFAULT_PHONE_COUNTRY).input(raw ?? \"\");\n}\n","// Enhanced-conversions user_data bridge (Google Ads \"user-provided data\").\n//\n// Why this exists: Google's automatic user-provided-data capture demonstrably\n// misses phone fields on client sites (verified live: a filled tel input never\n// produced a `pn` hit parameter), and our offline sale uploads are phone-hash\n// keyed — without a phone↔click pairing built at conversion time, none of them\n// can match. This module makes the SDK the deterministic capture path: it\n// extracts the visitor's own email/phone from `form_submit` fields (or an\n// explicit override / a recorded sale's customer fields), normalizes them\n// (E.164 phone, lowercased email), and sets them as PLAINTEXT\n// `gtag('set','user_data', …)` immediately before a conversion fires. gtag.js\n// normalizes further and SHA-256 hashes IN THE BROWSER — plaintext never\n// leaves the page, and we never own Google's hashing contract.\n//\n// Privacy posture: the stash is module-level memory only — never persisted to\n// any storage, never added to our own ingest payloads (the form fields were\n// already part of the site's `form_submit` metadata; we only read them).\n// Consent gating happens at the egress in `fireConversionWithConsent` (the\n// same gate every conversion already passes through); an explicit consent\n// denial additionally clears the stash and nulls gtag's page state (see\n// consent.ts). This module must NOT import consent.ts — consent.ts imports us\n// for that clearing hook, and the reverse edge would be a cycle.\n\nimport { toE164, type CountryCode } from \"./phone\";\n\n/** Raw identifiers a caller may hand us (normalized before use). */\nexport interface ConversionUserData {\n email?: string | null;\n phone?: string | null;\n}\n\n/** Normalized identifiers as gtag's `user_data` expects them. */\nexport interface NormalizedUserData {\n email: string | null;\n /** E.164 (`\"+16477836797\"`) — the format Google's parser reliably accepts. */\n phoneNumber: string | null;\n}\n\nconst EMAIL_SHAPE = /^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/;\nconst EMAIL_NAME_HINT = /e[-_]?mail/i;\n// `\\b` won't do: underscores are word chars, so `customer_phone` would miss.\n// The leading guard keeps bare \"tel\" from matching e.g. \"hotel\".\nconst PHONE_NAME_HINT = /(^|[^a-z])(phone|tel|mobile|cell)/i;\n\n// Page-lifetime, memory-only. Freshest non-null value wins per identifier.\nlet stash: NormalizedUserData = { email: null, phoneNumber: null };\n\n/**\n * Trim + lowercase + shape-check. Deliberately NO gmail dot/plus\n * canonicalization — gtag.js applies Google's own normalization before\n * hashing, and owning that contract here would be drift waiting to happen.\n */\nexport function normalizeEmail(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const cleaned = raw.trim().toLowerCase();\n return EMAIL_SHAPE.test(cleaned) ? cleaned : null;\n}\n\ninterface FieldLike {\n name?: unknown;\n type?: unknown;\n label?: unknown;\n value?: unknown;\n}\n\nfunction fieldText(field: FieldLike, key: \"name\" | \"type\" | \"label\"): string {\n const value = field[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/**\n * Deterministic extraction from `form_submit` `fields[]`: for each identifier,\n * a typed field (`type=\"email\"` / `type=\"tel\"`) wins over a name/label match\n * (`user_email`, `customer_phone`, …), in document order. A field whose value\n * fails normalization does NOT consume the slot — scanning continues, so one\n * malformed phone field can't mask a later valid one. Never throws.\n */\nexport function extractUserDataFromFormFields(\n fields: unknown,\n country?: CountryCode,\n): NormalizedUserData {\n const result: NormalizedUserData = { email: null, phoneNumber: null };\n if (!Array.isArray(fields)) return result;\n const passes: Array<(field: FieldLike, hint: RegExp, type: string) => boolean> = [\n (field, _hint, type) => fieldText(field, \"type\").toLowerCase() === type,\n (field, hint) => hint.test(fieldText(field, \"name\")) || hint.test(fieldText(field, \"label\")),\n ];\n for (const matches of passes) {\n for (const raw of fields) {\n if (raw === null || typeof raw !== \"object\") continue;\n const field = raw as FieldLike;\n if (typeof field.value !== \"string\" || field.value.length === 0) continue;\n if (result.email === null && matches(field, EMAIL_NAME_HINT, \"email\")) {\n result.email = normalizeEmail(field.value);\n }\n if (result.phoneNumber === null && matches(field, PHONE_NAME_HINT, \"tel\")) {\n try {\n result.phoneNumber = toE164(field.value, country);\n } catch {\n // libphonenumber choked on garbage — leave the slot open\n }\n }\n }\n if (result.email !== null && result.phoneNumber !== null) break;\n }\n return result;\n}\n\n/** Normalize + merge into the stash (non-null values win over existing). */\nexport function stashUserData(data: ConversionUserData, country?: CountryCode): void {\n const email = normalizeEmail(data.email);\n let phoneNumber: string | null = null;\n if (typeof data.phone === \"string\" && data.phone.length > 0) {\n try {\n phoneNumber = toE164(data.phone, country);\n } catch {\n phoneNumber = null;\n }\n }\n stash = {\n email: email ?? stash.email,\n phoneNumber: phoneNumber ?? stash.phoneNumber,\n };\n}\n\n/** Extract from `form_submit` fields and merge into the stash. Never throws. */\nexport function stashUserDataFromFormFields(fields: unknown, country?: CountryCode): void {\n try {\n const extracted = extractUserDataFromFormFields(fields, country);\n stash = {\n email: extracted.email ?? stash.email,\n phoneNumber: extracted.phoneNumber ?? stash.phoneNumber,\n };\n } catch {\n // extraction must never break event tracking\n }\n}\n\n/** Snapshot of the current stash (copy — mutations don't leak back). */\nexport function getStashedUserData(): NormalizedUserData {\n return { ...stash };\n}\n\n/** Drop everything (consent denial, tests). */\nexport function clearStashedUserData(): void {\n stash = { email: null, phoneNumber: null };\n}\n\n/**\n * Set gtag's per-page `user_data` right before a conversion fires: explicit\n * values win per-key over the stash; an empty merge sets nothing at all.\n * Browser-gated and throw-proof — the conversion must fire regardless.\n * NOT consent-checked here: the single caller (`fireConversionWithConsent`)\n * has already returned on denial before reaching this.\n *\n * Returns whether a `gtag('set','user_data', …)` call was made.\n */\nexport function applyUserDataForConversion(\n explicit?: ConversionUserData | null,\n country?: CountryCode,\n): boolean {\n if (typeof window === \"undefined\" || typeof window.gtag !== \"function\") return false;\n let email = stash.email;\n let phoneNumber = stash.phoneNumber;\n if (explicit) {\n const normalizedEmail = normalizeEmail(explicit.email);\n if (normalizedEmail) email = normalizedEmail;\n if (typeof explicit.phone === \"string\" && explicit.phone.length > 0) {\n try {\n phoneNumber = toE164(explicit.phone, country) ?? phoneNumber;\n } catch {\n // keep the stashed phone\n }\n }\n }\n if (email === null && phoneNumber === null) return false;\n try {\n window.gtag(\"set\", \"user_data\", {\n ...(email !== null ? { email } : {}),\n ...(phoneNumber !== null ? { phone_number: phoneNumber } : {}),\n });\n return true;\n } catch {\n return false;\n }\n}\n","import type { ConsentState } from \"./types\";\nimport { clearStashedUserData } from \"./user-data\";\n\n/**\n * localStorage key for the visitor's explicit consent choice.\n */\nexport const CONSENT_STATE_KEY = \"consent_state\";\n\n/**\n * localStorage key for the ISO timestamp when consent was last changed.\n */\nexport const CONSENT_TIMESTAMP_KEY = \"consent_timestamp\";\n\n/**\n * localStorage key for the ISO timestamp when an explicit decline expires.\n *\n * Written alongside a `denied` choice; absent for grants (they never expire).\n * Computed at WRITE time so every reader — including the inline\n * `beforeInteractive` scripts that can't import this module — only has to\n * compare a stored ISO string against the clock.\n */\nexport const CONSENT_EXPIRES_AT_KEY = \"consent_expires_at\";\n\n/**\n * How long an explicit decline is honored before the visitor reverts to the\n * default-granted state. Explicit grants never expire.\n */\nexport const DEFAULT_DECLINE_TTL_DAYS = 90;\n\nconst DAY_MS = 86_400_000;\n\n/**\n * Google Consent Mode value sent to `gtag('consent', 'update', ...)`.\n */\nexport type GtagConsentValue = \"granted\" | \"denied\";\n\n/**\n * Consent Mode v2 payload sent to Google Ads when consent changes.\n */\nexport interface ConsentUpdatePayload {\n ad_storage: GtagConsentValue;\n ad_user_data: GtagConsentValue;\n ad_personalization: GtagConsentValue;\n analytics_storage: GtagConsentValue;\n}\n\n/** Effective consent state — the opt-out model has no \"pending\". */\nexport type ConsentChoiceState = \"granted\" | \"denied\";\n\n/**\n * Where the effective state came from: `explicit` when the visitor made a\n * stored, still-valid choice; `default` otherwise (no choice, expired decline,\n * storage blocked, SSR).\n */\nexport type ConsentSource = \"default\" | \"explicit\";\n\n/**\n * The effective consent decision plus its provenance.\n */\nexport interface ConsentChoice {\n state: ConsentChoiceState;\n source: ConsentSource;\n /** ISO timestamp of the explicit choice; null for the default state. */\n updatedAt: string | null;\n /** ISO expiry of an unexpired decline; null for grants and the default state. */\n expiresAt: string | null;\n}\n\n/** Options for explicit consent writes. */\nexport interface SetConsentOptions {\n /** Days an explicit decline is honored. Defaults to {@link DEFAULT_DECLINE_TTL_DAYS}. */\n declineTtlDays?: number;\n}\n\nconst DEFAULT_CHOICE: ConsentChoice = {\n state: \"granted\",\n source: \"default\",\n updatedAt: null,\n expiresAt: null,\n};\n\ntype ConsentChangeListener = (choice: ConsentChoice) => void;\nconst changeListeners = new Set<ConsentChangeListener>();\n\n/**\n * Subscribe to consent changes (opt-in, opt-out, reset) made in THIS tab.\n * Cross-tab changes surface via the browser's `storage` event instead.\n * Returns an unsubscribe function.\n */\nexport function onConsentChange(listener: ConsentChangeListener): () => void {\n changeListeners.add(listener);\n return () => {\n changeListeners.delete(listener);\n };\n}\n\n// Takes the intended choice rather than re-reading storage: when localStorage\n// is blocked, a re-read would report default-granted right after an opt-out\n// click even though the live gtag/fbq revoke DID apply for this page load.\nfunction notifyConsentChanged(choice: ConsentChoice): void {\n for (const listener of changeListeners) {\n try {\n listener(choice);\n } catch {\n // a listener must never break the consent flow\n }\n }\n}\n\n/**\n * Build the Google Consent Mode v2 update payload for a single consent state.\n */\nexport function buildConsentPayload(state: GtagConsentValue): ConsentUpdatePayload {\n return {\n ad_storage: state,\n ad_user_data: state,\n ad_personalization: state,\n analytics_storage: state,\n };\n}\n\n/**\n * Resolve the visitor's effective consent (opt-out model).\n *\n * Default is GRANTED. Only a stored, unexpired explicit decline yields\n * `denied`. SSR, blocked storage, and expired declines all resolve to the\n * default. A legacy decline stored by the opt-in-era SDK (no expiry key) stays\n * denied and gets a fresh 90-day expiry backfilled, keeping this reader\n * consistent with the inline scripts (which treat a missing expiry as denied).\n */\nexport function getConsentChoice(): ConsentChoice {\n if (typeof window === \"undefined\") return DEFAULT_CHOICE;\n\n try {\n const stored = window.localStorage.getItem(CONSENT_STATE_KEY);\n const updatedAt = window.localStorage.getItem(CONSENT_TIMESTAMP_KEY);\n\n if (stored === \"granted\")\n return { state: \"granted\", source: \"explicit\", updatedAt, expiresAt: null };\n\n if (stored === \"denied\") {\n let expiresAt = window.localStorage.getItem(CONSENT_EXPIRES_AT_KEY);\n if (!expiresAt) {\n expiresAt = new Date(Date.now() + DEFAULT_DECLINE_TTL_DAYS * DAY_MS).toISOString();\n try {\n window.localStorage.setItem(CONSENT_EXPIRES_AT_KEY, expiresAt);\n } catch {\n // backfill is best-effort; the decline is still honored this read\n }\n }\n // A garbled expiry parses to NaN, the comparison is false, and the decline\n // stays honored (fail closed on the decliner's side). Only a parseable\n // expiry in the past reverts to the default.\n if (!(Date.parse(expiresAt) <= Date.now()))\n return { state: \"denied\", source: \"explicit\", updatedAt, expiresAt };\n }\n } catch {\n // localStorage blocked (sandboxed iframe / storage disabled) — default\n }\n\n return DEFAULT_CHOICE;\n}\n\n/**\n * Read the visitor's effective consent state.\n *\n * Opt-out model: returns `granted` unless a stored, unexpired explicit decline\n * exists. Never returns `pending` — that value survives in {@link ConsentState}\n * only so pre-v2 call sites keep compiling.\n */\nexport function getConsentState(): ConsentState {\n return getConsentChoice().state;\n}\n\nfunction pushConsentToPlatforms(state: GtagConsentValue): void {\n if (typeof window === \"undefined\") return;\n\n if (typeof window.gtag === \"function\")\n window.gtag(\"consent\", \"update\", buildConsentPayload(state));\n\n // Mirror to the Meta Pixel so one control gates both ad platforms.\n if (typeof window.fbq === \"function\")\n window.fbq(\"consent\", state === \"granted\" ? \"grant\" : \"revoke\");\n}\n\n/**\n * Persist an explicit visitor consent choice and push it live to Google\n * Consent Mode and the Meta Pixel.\n *\n * Declines expire after {@link DEFAULT_DECLINE_TTL_DAYS} days (override via\n * `options.declineTtlDays`); grants never expire.\n */\nexport function setConsentState(state: GtagConsentValue, options?: SetConsentOptions): void {\n if (typeof window === \"undefined\") return;\n\n // Compute the full intended choice BEFORE touching storage so (a) a garbage\n // TTL can't throw mid-write (state written, expiry not), and (b) listeners\n // get the visitor's actual choice even when storage is blocked.\n const requestedTtl = options?.declineTtlDays;\n const ttlDays =\n typeof requestedTtl === \"number\" && Number.isFinite(requestedTtl) && requestedTtl > 0\n ? requestedTtl\n : DEFAULT_DECLINE_TTL_DAYS;\n const updatedAt = new Date().toISOString();\n const expiresAt =\n state === \"denied\" ? new Date(Date.now() + ttlDays * DAY_MS).toISOString() : null;\n\n try {\n window.localStorage.setItem(CONSENT_STATE_KEY, state);\n window.localStorage.setItem(CONSENT_TIMESTAMP_KEY, updatedAt);\n if (expiresAt !== null) {\n window.localStorage.setItem(CONSENT_EXPIRES_AT_KEY, expiresAt);\n } else {\n window.localStorage.removeItem(CONSENT_EXPIRES_AT_KEY);\n }\n } catch {\n // localStorage blocked — still push the live consent update below so the\n // visitor's click takes effect for this page load even if it can't persist\n }\n\n pushConsentToPlatforms(state);\n if (state === \"denied\") {\n // A mid-session revoke also scrubs enhanced-conversions page state: drop\n // the stashed identifiers and best-effort null gtag's user_data.\n clearStashedUserData();\n try {\n if (typeof window.gtag === \"function\") window.gtag(\"set\", \"user_data\", null);\n } catch {\n // scrubbing is best-effort; the consent update above already gates fires\n }\n }\n notifyConsentChanged({ state, source: \"explicit\", updatedAt, expiresAt });\n}\n\n/**\n * Explicitly opt the visitor in to ad tracking (never expires).\n */\nexport function optIn(): void {\n setConsentState(\"granted\");\n}\n\n/**\n * Explicitly opt the visitor out of ad tracking for\n * {@link DEFAULT_DECLINE_TTL_DAYS} days (override via `options.declineTtlDays`).\n *\n * This is the primitive a client site's footer \"cookie preferences\" control\n * should call — the packages ship no consent UI of their own.\n */\nexport function optOut(options?: SetConsentOptions): void {\n setConsentState(\"denied\", options);\n}\n\n/**\n * Clear the stored explicit choice, returning the visitor to the\n * default-granted state, and push that state live to gtag + Meta.\n *\n * Power a \"Cookie preferences\" reset in a footer:\n *\n * ```tsx\n * const { reset } = useCookiePreferences();\n * <button onClick={reset}>Reset cookie preferences</button>\n * ```\n */\nexport function resetConsent(): void {\n if (typeof window === \"undefined\") return;\n\n try {\n window.localStorage.removeItem(CONSENT_STATE_KEY);\n window.localStorage.removeItem(CONSENT_TIMESTAMP_KEY);\n window.localStorage.removeItem(CONSENT_EXPIRES_AT_KEY);\n } catch {\n // localStorage blocked — nothing to clear\n }\n\n pushConsentToPlatforms(\"granted\");\n notifyConsentChanged(DEFAULT_CHOICE);\n}\n\n/**\n * Re-apply a stored explicit consent choice to Google Consent Mode + Meta.\n *\n * @deprecated The v2 consent-default path ({@link applyDefaultConsentState} /\n * `createConsentDefaultScript`) already applies the effective state at\n * bootstrap, making this redundant. Pushes platform updates directly — it must\n * NOT route through {@link setConsentState}, which would renew the decline's\n * 90-day expiry on every page load.\n */\nexport function restoreStoredConsent(): ConsentState {\n const choice = getConsentChoice();\n\n if (choice.source === \"explicit\") pushConsentToPlatforms(choice.state);\n\n return choice.state;\n}\n\n/**\n * Inline-JS fragment that resolves the effective consent value into\n * `var aranovaConsent = 'granted' | 'denied'`.\n *\n * Single source of the expiry logic for every inline `<script>` builder (gtag\n * and Meta), so the runtime reader and the inline readers can't drift. Must\n * stay dependency-free ES5 and never throw (localStorage access throws in\n * sandboxed iframes).\n */\nexport function createEffectiveConsentSnippet(): string {\n // IIFE keeps the temporaries off the page's global scope — only\n // `aranovaConsent` (the value consumed by the rest of the script) leaks.\n return `\nvar aranovaConsent = (function () {\n try {\n if (window.localStorage.getItem('${CONSENT_STATE_KEY}') === 'denied') {\n var exp = window.localStorage.getItem('${CONSENT_EXPIRES_AT_KEY}');\n var expMs = exp ? Date.parse(exp) : NaN;\n if (!(expMs <= Date.now())) return 'denied';\n }\n } catch (e) {}\n return 'granted';\n})();\n`.trim();\n}\n","// Capability self-report registry.\n//\n// Every SDK construct registers itself here at construction time, and the\n// registered set rides out on `TrackingClientContext.capabilities`, which the\n// backend persists on the session row. The dashboard derives what a client site\n// ACTUALLY has installed from those sessions, rather than trusting an operator\n// checkbox — see contracts/tracking-capabilities.json, which pins this id list\n// against the backend enum and the dashboard type union.\n//\n// Browser-only by design: a server-side client (calendar bookings) emits no\n// session, and its artifact is better evidence than a self-report anyway.\n//\n// This module deliberately imports nothing: it is the one thing every other\n// resource can import without adding an edge that could close a cycle.\n\n/**\n * Every capability an install can report. Pinned by\n * `contracts/tracking-capabilities.json` — adding one here without a catalog\n * entry fails the drift test.\n */\nexport const TRACKING_CAPABILITIES = [\n \"ad_tags_google\",\n \"ad_tags_meta\",\n \"base_tracking\",\n \"blog_rendering\",\n \"calendar_read\",\n \"calendar_write\",\n \"consent_controls\",\n \"conversion_goals_auto\",\n \"conversion_goals_manual\",\n \"cta_click_capture\",\n \"form_capture\",\n \"phone_click_capture\",\n \"phone_fields\",\n] as const;\n\nexport type TrackingCapability = (typeof TRACKING_CAPABILITIES)[number];\n\n/**\n * DOM attribute a server-rendered surface stamps to report itself.\n *\n * Blog rendering never calls the Aranova API — it reads the CDN directly — so\n * neither the ingest payload nor the request-header path can see it. The\n * renderer stamps this attribute instead and the browser context collector\n * picks it up on the next batch.\n */\nexport const CAPABILITY_DOM_ATTRIBUTE = \"data-aranova-capability\";\n\nconst registered = new Set<TrackingCapability>();\n\n/**\n * Record that a capability is present in this runtime.\n *\n * Idempotent and side-effect free — safe to call on every construction,\n * including React strict-mode double mounts.\n */\nexport function registerCapability(capability: TrackingCapability): void {\n registered.add(capability);\n}\n\n/**\n * Capabilities registered so far in this runtime, sorted for a stable wire\n * value (so the backend can hash the array to skip redundant writes).\n *\n * Also collects `data-aranova-capability` markers from the DOM, which is how\n * server-rendered surfaces that never call our API report themselves.\n */\nexport function getRegisteredCapabilities(): TrackingCapability[] {\n const all = new Set<TrackingCapability>(registered);\n for (const marker of readDomMarkers()) all.add(marker);\n return Array.from(all).sort();\n}\n\nfunction readDomMarkers(): TrackingCapability[] {\n if (typeof document === \"undefined\") return [];\n const known = new Set<string>(TRACKING_CAPABILITIES);\n const found: TrackingCapability[] = [];\n // Unknown values are dropped rather than forwarded: the backend rejects ids\n // outside its enum, and a stray attribute on a client's page must never be\n // able to fail an otherwise-valid ingest batch.\n for (const node of document.querySelectorAll(`[${CAPABILITY_DOM_ATTRIBUTE}]`)) {\n const value = node.getAttribute(CAPABILITY_DOM_ATTRIBUTE);\n if (value && known.has(value)) found.push(value as TrackingCapability);\n }\n return found;\n}\n\n/** Test-only: drop everything registered so far. */\nexport function resetRegisteredCapabilitiesForTests(): void {\n registered.clear();\n}\n","import type { TrackingParams } from \"./types\";\n\n/**\n * Default attribution cookie lifetime: 90 days.\n */\nexport const TRACKING_COOKIE_MAX_AGE_SECONDS = 7_776_000;\n\n/**\n * Attribution query/cookie keys captured by the SDK.\n */\nexport const TRACKING_PARAM_KEYS = [\n \"gclid\",\n // Google's iOS/Safari replacement click IDs — issued when privacy features\n // withhold gclid (wbraid: web-to-web, gbraid: app-to-web). First-class\n // citizens: captured, persisted, and attributed exactly like gclid.\n \"wbraid\",\n \"gbraid\",\n // Yelp Ads click id (40 hex chars), appended to ad-click URLs.\n \"ylpcid\",\n \"fbclid\",\n \"utm_source\",\n \"utm_medium\",\n \"utm_campaign\",\n \"utm_term\",\n \"utm_content\",\n] as const;\n\nexport type TrackingParamKey = (typeof TRACKING_PARAM_KEYS)[number];\n\n/**\n * Create an all-null attribution parameter object.\n */\nexport function createEmptyTrackingParams(): TrackingParams {\n return {\n gclid: null,\n wbraid: null,\n gbraid: null,\n ylpcid: null,\n fbclid: null,\n utm_source: null,\n utm_medium: null,\n utm_campaign: null,\n utm_term: null,\n utm_content: null,\n };\n}\n\n/**\n * Normalize a raw cookie value into a tracking value.\n *\n * Empty strings and non-string values become `null`.\n */\nexport function normalizeTrackingCookieValue(value: unknown): string | null {\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\n/**\n * Read all tracking params using the provided cookie reader.\n *\n * This is shared by browser, React, and Next server integrations.\n */\nexport function getTrackingParamsFromCookieReader(\n readCookie: (key: TrackingParamKey) => unknown,\n): TrackingParams {\n return TRACKING_PARAM_KEYS.reduce<TrackingParams>((params, key) => {\n params[key] = normalizeTrackingCookieValue(readCookie(key));\n return params;\n }, createEmptyTrackingParams());\n}\n\n/**\n * Extract tracking params from URL search params.\n *\n * Only non-empty values are returned.\n */\nexport function getTrackingQueryValues(\n searchParams: Pick<URLSearchParams, \"get\">,\n): Partial<Record<TrackingParamKey, string>> {\n return TRACKING_PARAM_KEYS.reduce<Partial<Record<TrackingParamKey, string>>>((params, key) => {\n const value = searchParams.get(key);\n\n if (typeof value === \"string\" && value.trim().length > 0) {\n params[key] = value;\n }\n\n return params;\n }, {});\n}\n\n/**\n * localStorage fallback prefix. Meta/Facebook in-app browsers (Instagram / FB\n * webviews) frequently block `document.cookie`; when a cookie write can't be\n * confirmed we mirror the value here so attribution (and `_fbc`) survives the\n * session and subsequent in-webview reloads instead of being silently lost.\n */\nconst FALLBACK_STORAGE_PREFIX = \"_aranova_track_\";\n\nfunction fallbackKey(name: string): string {\n return `${FALLBACK_STORAGE_PREFIX}${name}`;\n}\n\n/**\n * Persist a cookie value AND mirror it to localStorage. Generic over the cookie\n * name so it serves the attribution params AND the Meta `_fbc` cookie. Never\n * throws.\n *\n * The localStorage mirror is written UNCONDITIONALLY — it is NOT gated on a\n * cookie read-back. Meta/Instagram in-app webviews partition cookies: the write\n * is visible to a same-page read (so a verify-after-write would falsely pass)\n * yet is silently dropped on the next navigation/reload. Gating the fallback on\n * that read-back would leave the value unrecoverable in exactly the case it\n * exists for; a stale same-name cookie from a prior visit would also mask a\n * blocked write. So we always write both. {@link readCookieValue} prefers the\n * cookie when present, which keeps the mirror harmless when cookies work and\n * load-bearing when they don't survive navigation.\n */\nexport function persistCookieValue(\n name: string,\n value: string,\n maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS,\n): void {\n const encoded = encodeURIComponent(value);\n if (typeof document !== \"undefined\") {\n try {\n document.cookie = `${name}=${encoded}; Max-Age=${maxAgeSeconds}; Path=/; SameSite=Lax`;\n } catch {\n // cookie blocked — the localStorage mirror below is the fallback\n }\n }\n if (typeof window !== \"undefined\") {\n try {\n window.localStorage.setItem(fallbackKey(name), encoded);\n } catch {\n // both blocked — give up silently, never break the host site\n }\n }\n}\n\n/**\n * Read a cookie value, falling back to the localStorage mirror written by\n * {@link persistCookieValue} when the cookie is absent (blocked webview).\n */\nexport function readCookieValue(name: string): string | null {\n if (typeof document !== \"undefined\") {\n const cookies = document.cookie ? document.cookie.split(\"; \") : [];\n const match = cookies.find((cookie) => cookie.startsWith(`${name}=`));\n if (match) {\n const [, rawValue = \"\"] = match.split(\"=\");\n return normalizeTrackingCookieValue(decodeURIComponent(rawValue));\n }\n }\n if (typeof window !== \"undefined\") {\n try {\n const stored = window.localStorage.getItem(fallbackKey(name));\n if (stored) return normalizeTrackingCookieValue(decodeURIComponent(stored));\n } catch {\n // ignore\n }\n }\n return null;\n}\n\n/**\n * Read a tracking cookie from `document.cookie` (or the localStorage fallback).\n *\n * Returns `null` during SSR or when neither source has the value.\n */\nexport function getCookieValueFromDocument(key: TrackingParamKey): string | null {\n return readCookieValue(key);\n}\n\n/**\n * Persist one attribution value as a first-party cookie (localStorage fallback\n * when cookies are blocked).\n */\nexport function setTrackingCookie(\n key: TrackingParamKey,\n value: string,\n maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS,\n): void {\n persistCookieValue(key, value, maxAgeSeconds);\n}\n\n/**\n * Merge two attribution param sets, preferring `primary`'s non-null values and\n * filling the gaps from `fallback`. Used to combine the cookie-backed read with\n * the synchronous init-time snapshot so a value captured before an SPA router\n * stripped the URL (or before a webview blocked the cookie) still wins.\n */\nexport function mergeTrackingParams(\n primary: TrackingParams,\n fallback: TrackingParams,\n): TrackingParams {\n return TRACKING_PARAM_KEYS.reduce<TrackingParams>((merged, key) => {\n merged[key] = primary[key] ?? fallback[key];\n return merged;\n }, createEmptyTrackingParams());\n}\n\n/**\n * Capture any tracking params present in a URL search parameter source and\n * persist them to first-party cookies.\n *\n * Returns the subset of params that were found and persisted.\n */\nexport function persistTrackingParamsFromSearchParams(\n searchParams: Pick<URLSearchParams, \"get\">,\n maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS,\n): Partial<Record<TrackingParamKey, string>> {\n const trackingValues = getTrackingQueryValues(searchParams);\n\n Object.entries(trackingValues).forEach(([key, value]) => {\n setTrackingCookie(key as TrackingParamKey, value, maxAgeSeconds);\n });\n\n return trackingValues;\n}\n\n/**\n * Capture tracking params from a URL, persist them to first-party cookies, and\n * return the current cookie-backed attribution state.\n *\n * Defaults to `window.location.href` in the browser.\n */\nexport function captureTrackingParamsFromLocation(\n url = typeof window === \"undefined\" ? \"\" : window.location.href,\n maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS,\n): TrackingParams {\n const resolvedUrl =\n typeof window === \"undefined\"\n ? new URL(url || \"https://example.invalid\")\n : new URL(url, window.location.origin);\n persistTrackingParamsFromSearchParams(resolvedUrl.searchParams, maxAgeSeconds);\n return getTrackingParamsFromCookieReader(getCookieValueFromDocument);\n}\n","// This module loads the Google tag (gtag.js), applies Consent Mode, and fires\n// `gtag('config', …)` (remarketing) plus real-time `gtag('event','conversion')`\n// via `fireGtagConversion` (GAP28). Consent v2 is OPT-OUT: the effective state\n// is granted unless the visitor stored an explicit, unexpired decline, so tags\n// run from first paint for the default visitor.\n// See docs/google-ads-deployment/gtags-and-conversion-tracking.md.\n\nimport { buildConsentPayload, createEffectiveConsentSnippet, getConsentState } from \"./consent\";\nimport type { GtagEnvironmentMap } from \"./types\";\n\n/**\n * Google Tag Manager script host used for gtag loading.\n */\nexport const GTAG_SCRIPT_HOST = \"https://www.googletagmanager.com/gtag/js\";\n\n/**\n * Attribute used to mark scripts inserted by the tracking SDK.\n */\nexport const TRACKING_SCRIPT_ATTRIBUTE = \"data-aranova-tracking\";\n\nfunction getScriptMarker(id: string): string {\n return `aranova-${id}`;\n}\n\n/**\n * Pattern matching valid Google Ads / GA4 tag IDs.\n *\n * Accepted formats: `AW-123456789`, `G-XXXXXXXXXX`, `GT-XXXXXXX`, `DC-XXXXXXX`.\n * IDs that don't match are silently dropped to prevent script injection when\n * interpolated into inline `<script>` content.\n */\nconst GTAG_ID_PATTERN = /^[A-Z]{1,3}-[A-Za-z0-9_-]+$/;\n\nexport function isValidGtagId(id: string): boolean {\n return GTAG_ID_PATTERN.test(id);\n}\n\n/**\n * Create an inline script that initializes gtag with the visitor's EFFECTIVE\n * consent as the Consent Mode default (opt-out model).\n *\n * Resolves granted/denied synchronously from localStorage in one shot — a\n * decliner never gets a granted window and the default visitor never gets a\n * denied one, so no `wait_for_update` and no follow-up restore script is\n * needed. Run it `beforeInteractive` so the default lands before gtag.js.\n */\nexport function createConsentDefaultScript(): string {\n return `\nwindow.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\nwindow.gtag = gtag;\n${createEffectiveConsentSnippet()}\ngtag('consent', 'default', {\n ad_storage: aranovaConsent,\n ad_user_data: aranovaConsent,\n ad_personalization: aranovaConsent,\n analytics_storage: aranovaConsent\n});\n`.trim();\n}\n\n/**\n * Create an inline script that initializes gtag for a Google Ads tag id.\n */\nexport function createGtagInitScript(gtagId: string): string {\n if (!isValidGtagId(gtagId)) return \"\";\n return `\nwindow.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\nwindow.gtag = gtag;\ngtag('js', new Date());\ngtag('config', '${gtagId}');\n`.trim();\n}\n\n/**\n * Create an inline script that pushes the effective consent as an update.\n *\n * @deprecated Redundant since consent v2 — `createConsentDefaultScript()`\n * already resolves the effective state (including decline expiry) into the\n * Consent Mode default, so no restore pass is needed. Kept expiry-aware for\n * integrations that still render it.\n */\nexport function createConsentRestoreScript(): string {\n return `\n${createEffectiveConsentSnippet()}\nif (window.gtag) {\n window.gtag('consent', 'update', {\n ad_storage: aranovaConsent,\n ad_user_data: aranovaConsent,\n ad_personalization: aranovaConsent,\n analytics_storage: aranovaConsent\n });\n}\n`.trim();\n}\n\n/**\n * Ensure `window.gtag` and `window.dataLayer` exist and return the gtag shim.\n */\nexport function ensureGtagFunction(): NonNullable<Window[\"gtag\"]> {\n window.dataLayer = window.dataLayer || [];\n\n if (typeof window.gtag === \"function\") return window.gtag;\n\n // CRITICAL: push the `arguments` object, NOT a rest-param array. gtag.js only\n // treats the canonical `dataLayer.push(arguments)` form as a command — a plain\n // array pushed to the dataLayer is ignored. With the array form, every\n // gtag('config' | 'consent' | 'event') call silently no-ops: the account never\n // registers, consent mode never applies, and conversions never fire (verified\n // live — the array form sends zero network hits; the arguments form sends the\n // pagead/conversion ping). Mirror Google's canonical inline snippet exactly.\n function gtag(): void {\n // eslint-disable-next-line prefer-rest-params\n window.dataLayer?.push(arguments);\n }\n window.gtag = gtag;\n\n return window.gtag;\n}\n\nconst SEND_TO_RE = /^AW-[A-Za-z0-9]+\\/[A-Za-z0-9_-]+$/;\n\n/** A gtag `send_to` target, e.g. `AW-123456789/AbC-D_efg`. */\nexport function isValidSendTo(sendTo: string): boolean {\n return SEND_TO_RE.test(sendTo);\n}\n\nexport interface GtagConversionInput {\n /** `AW-<id>/<label>` — the conversion action's firing target. */\n sendTo: string;\n /** Conversion value in MAJOR units; omit to let Google apply the action's default. */\n value?: number | null;\n currency?: string | null;\n transactionId?: string | null;\n}\n\n/**\n * Fire a real-time on-site conversion — `gtag('event','conversion',{ send_to, … })`\n * (GAP28). Browser-gated and never throws: `record()` is isomorphic and runs server-side\n * under a secret key where `window`/`gtag` are absent, so this no-ops there. Consent\n * gating + de-dup are the caller's responsibility (see `fireConversionWithConsent`).\n * Returns whether the event was actually pushed.\n */\nexport function fireGtagConversion(input: GtagConversionInput): boolean {\n if (typeof window === \"undefined\" || typeof window.gtag !== \"function\") return false;\n if (!isValidSendTo(input.sendTo)) return false;\n const params: Record<string, unknown> = { send_to: input.sendTo };\n if (input.value != null) params.value = input.value;\n if (input.currency) params.currency = input.currency;\n if (input.transactionId) params.transaction_id = input.transactionId;\n try {\n window.gtag(\"event\", \"conversion\", params);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Apply the visitor's EFFECTIVE consent as the Consent Mode default\n * (opt-out model): granted unless a stored, unexpired decline exists.\n *\n * Reading via `getConsentState()` also backfills the expiry key for\n * legacy opt-in-era declines, keeping later inline reads consistent.\n */\nexport function applyDefaultConsentState(): void {\n const gtag = ensureGtagFunction();\n gtag(\n \"consent\",\n \"default\",\n buildConsentPayload(getConsentState() === \"denied\" ? \"denied\" : \"granted\"),\n );\n}\n\n/**\n * Load the external gtag script once for the provided Google Ads tag id.\n */\nexport function loadGtagScript(gtagId: string): void {\n if (typeof document === \"undefined\") return;\n\n const marker = getScriptMarker(\"gtag-loader\");\n const existingScript = document.querySelector<HTMLScriptElement>(\n `script[${TRACKING_SCRIPT_ATTRIBUTE}=\"${marker}\"]`,\n );\n if (existingScript) return;\n\n const script = document.createElement(\"script\");\n script.async = true;\n script.src = `${GTAG_SCRIPT_HOST}?id=${encodeURIComponent(gtagId)}`;\n script.setAttribute(TRACKING_SCRIPT_ATTRIBUTE, marker);\n document.head.append(script);\n}\n\n/**\n * Send the initial `gtag('js')` and `gtag('config')` calls.\n */\nexport function initializeGtag(gtagId: string): void {\n const gtag = ensureGtagFunction();\n gtag(\"js\", new Date());\n gtag(\"config\", gtagId);\n}\n\n/**\n * Push the current effective consent to gtag as an update.\n *\n * @deprecated Redundant since consent v2 — `applyDefaultConsentState()`\n * already applies the effective state at bootstrap. Pushes directly (no\n * storage writes), so it never renews a decline's expiry.\n */\nexport function restoreConsentState(): void {\n if (typeof window === \"undefined\") return;\n\n const consentState = getConsentState();\n if (consentState === \"granted\" || consentState === \"denied\")\n window.gtag?.(\"consent\", \"update\", buildConsentPayload(consentState));\n}\n\n/**\n * Load and initialize Google Ads tracking with Consent Mode support.\n *\n * Used by framework components and browser-script initialization.\n */\nexport function bootstrapGoogleAdsTracking(gtagId: string): void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n if (!isValidGtagId(gtagId)) return;\n\n applyDefaultConsentState();\n loadGtagScript(gtagId);\n initializeGtag(gtagId);\n}\n\n/**\n * Load and initialize Google Ads tracking for ALL labelled gtag IDs.\n *\n * Every ID in the map gets a `gtag('config', ...)` call — gtag natively\n * supports multiple configured tags on the same page. The script loader\n * only runs once (for the first ID); subsequent IDs reuse the shared\n * `dataLayer`.\n */\nexport function bootstrapMultipleGtags(gtagIds: GtagEnvironmentMap): void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n\n const ids = Object.values(gtagIds).filter(\n (id): id is string => typeof id === \"string\" && isValidGtagId(id),\n );\n if (ids.length === 0) return;\n\n applyDefaultConsentState();\n loadGtagScript(ids[0]!);\n\n // Call gtag('js') once, then gtag('config') per ID. initializeGtag\n // calls both, but gtag('js') should only fire once per page load.\n const gtag = ensureGtagFunction();\n gtag(\"js\", new Date());\n for (const id of ids) {\n gtag(\"config\", id);\n }\n}\n\n/**\n * Create an inline script that initializes gtag for multiple Google Ads tag ids.\n *\n * Used by the Next.js `GoogleAdsTracking` component when rendering `<Script>`\n * tags for a multi-gtag configuration.\n */\nexport function createGtagInitScriptMulti(gtagIds: string[]): string {\n const safeIds = gtagIds.filter(isValidGtagId);\n const configs = safeIds.map((id) => `gtag('config', '${id}');`).join(\"\\n\");\n return `\nwindow.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\nwindow.gtag = gtag;\ngtag('js', new Date());\n${configs}\n`.trim();\n}\n","// The Meta Pixel (`fbq`) loader — the Facebook analogue of `gtag.ts`. It loads\n// fbevents.js and fires `fbq('init', …)` + `fbq('track','PageView')` to build Meta\n// remarketing / custom audiences (and let Meta optimize delivery + attribute).\n// Consent v2 is OPT-OUT: the pixel runs from first paint unless the visitor\n// stored an explicit, unexpired decline. This is NOT our in-house analytics\n// (that's the event ingest pipeline); it's the ad-platform tag, exactly like the\n// Google tag is for Google Ads.\n//\n// It also forms the Conversions-API-canonical `_fbc` cookie from the landing\n// `fbclid` (and reads the Pixel-set `_fbp`) so a future server-side Meta\n// Conversions API writeback has everything it needs.\n\nimport { createEffectiveConsentSnippet, getConsentState } from \"./consent\";\nimport { persistCookieValue, readCookieValue, TRACKING_COOKIE_MAX_AGE_SECONDS } from \"./tracking\";\nimport { TRACKING_SCRIPT_ATTRIBUTE } from \"./gtag\";\nimport type { MetaPixelEnvironmentMap } from \"./types\";\n\n/** Meta Pixel script host. */\nexport const FB_EVENTS_SCRIPT_HOST = \"https://connect.facebook.net/en_US/fbevents.js\";\n\n/** Cookie names Meta uses for the Conversions API. */\nexport const FBC_COOKIE = \"_fbc\";\nexport const FBP_COOKIE = \"_fbp\";\n\n/**\n * Valid Meta Pixel ID: a 15-16 digit number. IDs that don't match are dropped to\n * prevent script injection when interpolated into inline `<script>` content\n * (mirrors GTAG_ID_PATTERN).\n */\nconst META_PIXEL_ID_PATTERN = /^\\d{15,16}$/;\n\nexport function isValidMetaPixelId(id: string): boolean {\n return META_PIXEL_ID_PATTERN.test(id);\n}\n\n// ---------------------------------------------------------------------------\n// _fbc / _fbp cookie formation\n// ---------------------------------------------------------------------------\n\n/**\n * subdomainIndex for the `_fbc` value: `com` → 0, `example.com` → 1,\n * `www.example.com` → 2 (dot-label count minus one).\n */\nexport function computeFbSubdomainIndex(hostname: string): number {\n const labels = hostname.split(\".\").filter(Boolean);\n return Math.max(0, labels.length - 1);\n}\n\n/**\n * Build the CAPI-canonical `_fbc` value: `fb.<subdomainIndex>.<creationMs>.<fbclid>`.\n * Never hashed.\n */\nexport function buildFbc(fbclid: string, now: number, hostname?: string): string {\n const host = hostname ?? (typeof window === \"undefined\" ? \"\" : window.location.hostname);\n return `fb.${computeFbSubdomainIndex(host)}.${now}.${fbclid}`;\n}\n\n/** Current `_fbc` cookie (or localStorage fallback), if any. */\nexport function getFbcCookie(): string | null {\n return readCookieValue(FBC_COOKIE);\n}\n\n/** Current `_fbp` cookie — set by the Meta Pixel; we only ever read it. */\nexport function getFbpCookie(): string | null {\n return readCookieValue(FBP_COOKIE);\n}\n\nfunction readFbclidFromUrl(): string | null {\n if (typeof window === \"undefined\") return null;\n try {\n const value = new URL(window.location.href).searchParams.get(\"fbclid\");\n return value && value.trim().length > 0 ? value : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Form and persist `_fbc` from the landing `fbclid` when the Pixel hasn't already\n * set it. Reads the fbclid from the URL first, then the captured attribution\n * cookie. No-ops when there's no fbclid or `_fbc` already exists. `_fbp` is\n * Pixel-only — never written here.\n */\nexport function captureFbc(now = typeof Date === \"undefined\" ? 0 : Date.now()): void {\n if (typeof window === \"undefined\") return;\n // A Pixel-set `_fbc` is canonical — don't overwrite it.\n if (getFbcCookie()) return;\n const fbclid = readFbclidFromUrl() ?? readCookieValue(\"fbclid\");\n if (!fbclid) return;\n persistCookieValue(FBC_COOKIE, buildFbc(fbclid, now), TRACKING_COOKIE_MAX_AGE_SECONDS);\n}\n\n// ---------------------------------------------------------------------------\n// fbq loader (mirrors gtag.ts)\n// ---------------------------------------------------------------------------\n\ntype FbqStub = ((...args: unknown[]) => void) & {\n callMethod?: (...args: unknown[]) => void;\n queue: unknown[][];\n push: unknown;\n loaded: boolean;\n version: string;\n};\n\nfunction getScriptMarker(id: string): string {\n return `aranova-${id}`;\n}\n\n/**\n * Ensure `window.fbq` exists (the standard fbevents bootstrap stub) and return\n * it. Safe to call repeatedly — it only initializes once.\n */\nexport function ensureFbqFunction(): NonNullable<Window[\"fbq\"]> {\n const w = window as Window & { fbq?: FbqStub; _fbq?: FbqStub };\n if (typeof w.fbq === \"function\") return w.fbq;\n\n const fbq = function (this: unknown, ...args: unknown[]) {\n if (fbq.callMethod) fbq.callMethod.apply(fbq, args);\n else fbq.queue.push(args);\n } as FbqStub;\n\n fbq.push = fbq;\n fbq.loaded = true;\n fbq.version = \"2.0\";\n fbq.queue = [];\n\n w.fbq = fbq;\n if (!w._fbq) w._fbq = fbq;\n return fbq;\n}\n\n/**\n * Apply the visitor's EFFECTIVE consent to the Meta Pixel (opt-out model):\n * grant unless a stored, unexpired decline exists.\n */\nexport function applyDefaultMetaConsentState(): void {\n ensureFbqFunction()(\"consent\", getConsentState() === \"denied\" ? \"revoke\" : \"grant\");\n}\n\n/** Load fbevents.js once. */\nexport function loadFbeventsScript(): void {\n if (typeof document === \"undefined\") return;\n const marker = getScriptMarker(\"fbq-loader\");\n const existing = document.querySelector<HTMLScriptElement>(\n `script[${TRACKING_SCRIPT_ATTRIBUTE}=\"${marker}\"]`,\n );\n if (existing) return;\n\n const script = document.createElement(\"script\");\n script.async = true;\n script.src = FB_EVENTS_SCRIPT_HOST;\n script.setAttribute(TRACKING_SCRIPT_ATTRIBUTE, marker);\n document.head.append(script);\n}\n\n/** `fbq('init', id)` + the initial PageView. */\nexport function initializeMetaPixel(pixelId: string): void {\n const fbq = ensureFbqFunction();\n fbq(\"init\", pixelId);\n fbq(\"track\", \"PageView\");\n}\n\n/**\n * Push the current effective consent to fbq.\n *\n * @deprecated Redundant since consent v2 — `applyDefaultMetaConsentState()`\n * already applies the effective state at bootstrap. Pushes directly (no\n * storage writes), so it never renews a decline's expiry.\n */\nexport function restoreMetaConsentState(): void {\n if (typeof window === \"undefined\") return;\n const state = getConsentState();\n if (state === \"granted\") window.fbq?.(\"consent\", \"grant\");\n else if (state === \"denied\") window.fbq?.(\"consent\", \"revoke\");\n}\n\n/**\n * Load + initialize one Meta Pixel with Consent Mode support, and form `_fbc`.\n */\nexport function bootstrapMetaPixel(pixelId: string): void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n if (!isValidMetaPixelId(pixelId)) return;\n\n applyDefaultMetaConsentState();\n loadFbeventsScript();\n initializeMetaPixel(pixelId);\n captureFbc();\n}\n\n/**\n * Load + initialize ALL labelled Meta Pixel IDs (script loads once; `fbq('init')`\n * fires per id — the Pixel supports multiple pixels on one page).\n */\nexport function bootstrapMultiplePixels(pixelIds: MetaPixelEnvironmentMap): void {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n const ids = Object.values(pixelIds).filter(\n (id): id is string => typeof id === \"string\" && isValidMetaPixelId(id),\n );\n if (ids.length === 0) return;\n\n applyDefaultMetaConsentState();\n loadFbeventsScript();\n const fbq = ensureFbqFunction();\n for (const id of ids) {\n fbq(\"init\", id);\n }\n fbq(\"track\", \"PageView\");\n captureFbc();\n}\n\n// ---------------------------------------------------------------------------\n// Inline <script> builders for the Next.js <Script> path (mirror gtag.ts)\n// ---------------------------------------------------------------------------\n\n/** The standard fbevents stub as an inline string. */\nfunction fbqStubScript(): string {\n return `\n!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?\nn.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;\nn.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;\nt.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,\ndocument,'script','${FB_EVENTS_SCRIPT_HOST}');`.trim();\n}\n\n/**\n * Inline script that loads the fbevents stub and applies the visitor's\n * EFFECTIVE consent (opt-out model) before any `init`/`PageView` fires.\n */\nexport function createMetaConsentDefaultScript(): string {\n return `${fbqStubScript()}\n${createEffectiveConsentSnippet()}\nfbq('consent', aranovaConsent === 'denied' ? 'revoke' : 'grant');`;\n}\n\n/** Inline script that inits one pixel + PageView. */\nexport function createMetaPixelInitScript(pixelId: string): string {\n if (!isValidMetaPixelId(pixelId)) return \"\";\n return `fbq('init', '${pixelId}');\\nfbq('track', 'PageView');`;\n}\n\n/** Inline script that inits multiple pixels + a single PageView. */\nexport function createMetaPixelInitScriptMulti(pixelIds: string[]): string {\n const inits = pixelIds.filter(isValidMetaPixelId).map((id) => `fbq('init', '${id}');`);\n if (inits.length === 0) return \"\";\n return `${inits.join(\"\\n\")}\\nfbq('track', 'PageView');`;\n}\n\n/**\n * Inline script that pushes the effective consent into fbq.\n *\n * @deprecated Redundant since consent v2 — `createMetaConsentDefaultScript()`\n * already applies the effective state (including decline expiry) before the\n * pixel initializes. Kept expiry-aware for integrations that still render it.\n */\nexport function createMetaConsentRestoreScript(): string {\n return `\n${createEffectiveConsentSnippet()}\nif (window.fbq) {\n window.fbq('consent', aranovaConsent === 'denied' ? 'revoke' : 'grant');\n}`.trim();\n}\n","// Session-scoped LANDING attribution (ADR-016).\n//\n// The carried attribution channel (tracking.ts) persists gclid/fbclid/utm_*\n// for 90 days so journey stitching and conversion writeback keep working\n// across sessions. This module answers a different question — \"what did THIS\n// session's landing URL actually carry?\" — so the dashboard's source label is\n// never poisoned by a click from an earlier session.\n//\n// One localStorage record, keyed to the current session id and overwritten\n// whenever a new session is minted: self-cleaning, O(1) storage, survives\n// in-webview reloads (localStorage, not cookies — Meta/IG webviews silently\n// drop cookie writes, the exact failure mode the carried channel already\n// engineers around). An in-memory mirror covers storage-blocked environments.\n\nimport { getTrackingQueryValues, TRACKING_PARAM_KEYS, type TrackingParamKey } from \"./tracking\";\n\n/**\n * localStorage key for the landing-params record (same `_aranova_track_`\n * family as the carried-channel cookie mirrors).\n */\nexport const LANDING_STORAGE_KEY = \"_aranova_track_landing\";\n\n/**\n * Serialized landing record: the params present in the landing URL of the\n * session identified by `session_id`.\n */\nexport interface StoredLandingRecord {\n session_id: string;\n params: Partial<Record<TrackingParamKey, string>>;\n}\n\nlet memoryRecord: StoredLandingRecord | null = null;\n\nfunction sanitizeParams(value: unknown): Partial<Record<TrackingParamKey, string>> {\n if (typeof value !== \"object\" || value === null) return {};\n const source = value as Record<string, unknown>;\n return TRACKING_PARAM_KEYS.reduce<Partial<Record<TrackingParamKey, string>>>((params, key) => {\n const entry = source[key];\n if (typeof entry === \"string\" && entry.length > 0) params[key] = entry;\n return params;\n }, {});\n}\n\nfunction readStoredRecord(): StoredLandingRecord | null {\n try {\n const raw = window.localStorage.getItem(LANDING_STORAGE_KEY);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as Partial<StoredLandingRecord>;\n if (typeof parsed.session_id !== \"string\" || parsed.session_id.length === 0) return null;\n return { session_id: parsed.session_id, params: sanitizeParams(parsed.params) };\n } catch {\n return null;\n }\n}\n\nfunction writeRecord(record: StoredLandingRecord): void {\n memoryRecord = record;\n try {\n window.localStorage.setItem(LANDING_STORAGE_KEY, JSON.stringify(record));\n } catch {\n // Storage blocked — the in-memory mirror above still serves this page.\n }\n}\n\nfunction captureFromUrl(url?: string): Partial<Record<TrackingParamKey, string>> {\n try {\n const resolved = new URL(url ?? window.location.href, window.location.origin);\n return getTrackingQueryValues(resolved.searchParams);\n } catch {\n return {};\n }\n}\n\n/**\n * Return the landing params for `sessionId`, capturing them from the current\n * URL when no record for that session exists yet.\n *\n * First-wins: a record whose `session_id` matches is returned as-is (a second\n * tab's URL never clobbers the session's true landing). A missing or\n * mismatched record means a new session just started — the current URL IS that\n * session's landing, so it is captured and persisted. Read-only with respect\n * to the carried channel: never touches cookies. Never throws; returns `{}`\n * during SSR.\n */\nexport function getOrCaptureLandingParams(\n sessionId: string,\n url?: string,\n): Partial<Record<TrackingParamKey, string>> {\n if (typeof window === \"undefined\") return {};\n\n const stored = readStoredRecord();\n if (stored && stored.session_id === sessionId) {\n memoryRecord = stored;\n return stored.params;\n }\n if (memoryRecord && memoryRecord.session_id === sessionId) {\n return memoryRecord.params;\n }\n\n const record: StoredLandingRecord = { session_id: sessionId, params: captureFromUrl(url) };\n writeRecord(record);\n return record.params;\n}\n\n/**\n * The 10 landing wire fields, null-filled. Key PRESENCE tells the backend the\n * landing is explicitly known; when it is NOT known the keys must be omitted\n * entirely so the backend falls back to parsing first_page.\n */\nexport interface LandingPayloadFields {\n landing_gclid: string | null;\n landing_wbraid: string | null;\n landing_gbraid: string | null;\n landing_ylpcid: string | null;\n landing_fbclid: string | null;\n landing_utm_source: string | null;\n landing_utm_medium: string | null;\n landing_utm_campaign: string | null;\n landing_utm_term: string | null;\n landing_utm_content: string | null;\n}\n\n/**\n * Build the landing portion of a session payload — the single place the\n * \"present iff known\" wire contract is enforced. Returns `{}` (omit the keys)\n * when there is no landing knowledge: during SSR the session's landing URL is\n * simply not observable, and sending explicit nulls would wrongly tell the\n * backend \"this session landed with no params\", suppressing its fallback.\n */\nexport function buildLandingPayloadFields(\n sessionId: string,\n override?: Partial<Record<TrackingParamKey, string>>,\n): Partial<LandingPayloadFields> {\n const params =\n override ?? (typeof window === \"undefined\" ? null : getOrCaptureLandingParams(sessionId));\n if (params === null) return {};\n return {\n landing_gclid: params.gclid ?? null,\n landing_wbraid: params.wbraid ?? null,\n landing_gbraid: params.gbraid ?? null,\n landing_ylpcid: params.ylpcid ?? null,\n landing_fbclid: params.fbclid ?? null,\n landing_utm_source: params.utm_source ?? null,\n landing_utm_medium: params.utm_medium ?? null,\n landing_utm_campaign: params.utm_campaign ?? null,\n landing_utm_term: params.utm_term ?? null,\n landing_utm_content: params.utm_content ?? null,\n };\n}\n\n/**\n * Drop the landing record (localStorage + memory). Paired with\n * `resetTrackingIdentity()`; also used by tests.\n */\nexport function clearLandingRecord(): void {\n memoryRecord = null;\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.removeItem(LANDING_STORAGE_KEY);\n } catch {\n // ignored\n }\n}\n","import { getRegisteredCapabilities } from \"./capabilities\";\nimport { getFbcCookie, getFbpCookie } from \"./fbq\";\nimport { buildLandingPayloadFields } from \"./landing\";\nimport type { TrackingParamKey } from \"./tracking\";\nimport type {\n TrackingClientContext,\n TrackingEnvironment,\n TrackingEventCreatePayload,\n TrackingInstallSurface,\n TrackingParams,\n TrackingSessionUpsertPayload,\n} from \"./types\";\n\ninterface TrackingContextInput {\n packageName?: string | null;\n pageTitle?: string | null;\n referrer?: string | null;\n sdkVersion?: string | null;\n siteOrigin?: string | null;\n environment?: TrackingEnvironment;\n activeGtagIds?: Record<string, string> | null;\n}\n\ninterface TrackingEventInput {\n eventType: string;\n metadata?: Record<string, unknown> | null;\n pageUrl?: string | null;\n sessionId: string;\n}\n\ninterface TrackingSessionInput {\n consentState?: Record<string, unknown> | null;\n firstPage?: string | null;\n sessionId: string;\n visitorId?: string | null;\n /**\n * Landing attribution override (ADR-016). When omitted, the session's\n * persisted landing record is used (captured from the current URL if the\n * session has none yet).\n */\n landingParams?: Partial<Record<TrackingParamKey, string>>;\n}\n\n/**\n * Build runtime context attached to tracking sessions and events.\n */\nexport function createTrackingClientContext(\n surface: TrackingInstallSurface,\n input: TrackingContextInput = {},\n): TrackingClientContext {\n return {\n surface,\n sdk_version: input.sdkVersion ?? null,\n package_name: input.packageName ?? null,\n site_origin:\n input.siteOrigin ?? (typeof window === \"undefined\" ? null : window.location.origin),\n page_title:\n input.pageTitle ?? (typeof document === \"undefined\" ? null : document.title || null),\n referrer:\n input.referrer ?? (typeof document === \"undefined\" ? null : document.referrer || null),\n environment: input.environment ?? \"production\",\n active_gtag_ids: input.activeGtagIds ?? null,\n capabilities: getRegisteredCapabilities(),\n };\n}\n\n/**\n * Build the session portion of a tracking ingest request.\n */\nexport function createTrackingSessionUpsertPayload(\n trackingParams: TrackingParams,\n input: TrackingSessionInput,\n context: TrackingClientContext,\n): TrackingSessionUpsertPayload {\n return {\n session_id: input.sessionId,\n visitor_id: input.visitorId ?? null,\n gclid: trackingParams.gclid,\n wbraid: trackingParams.wbraid,\n gbraid: trackingParams.gbraid,\n ylpcid: trackingParams.ylpcid,\n fbclid: trackingParams.fbclid,\n fbc: getFbcCookie(),\n fbp: getFbpCookie(),\n utm_source: trackingParams.utm_source,\n utm_medium: trackingParams.utm_medium,\n utm_campaign: trackingParams.utm_campaign,\n utm_term: trackingParams.utm_term,\n utm_content: trackingParams.utm_content,\n // Omitted entirely when the landing isn't observable (SSR, no override) —\n // present-as-null would wrongly tell the backend \"landed with no params\".\n ...buildLandingPayloadFields(input.sessionId, input.landingParams),\n first_page: input.firstPage ?? null,\n consent_state: input.consentState ?? null,\n context,\n };\n}\n\n/**\n * Build one event payload before it is batched into a tracking ingest request.\n */\nexport function createTrackingEventCreatePayload(\n trackingParams: TrackingParams,\n input: TrackingEventInput,\n context: TrackingClientContext,\n): TrackingEventCreatePayload {\n return {\n session_id: input.sessionId,\n event_type: input.eventType,\n gclid: trackingParams.gclid,\n wbraid: trackingParams.wbraid,\n gbraid: trackingParams.gbraid,\n ylpcid: trackingParams.ylpcid,\n fbclid: trackingParams.fbclid,\n fbc: getFbcCookie(),\n fbp: getFbpCookie(),\n page_url: input.pageUrl ?? (typeof window === \"undefined\" ? null : window.location.href),\n metadata: input.metadata ?? null,\n context,\n };\n}\n","// Consent-gated, de-duped orchestration around the raw `fireGtagConversion` (GAP28).\n//\n// Consent v2 (opt-out model): fire unless the visitor's effective consent is an\n// explicit, unexpired decline. There is no \"pending\" state and therefore no\n// queue — the default visitor converts in real time.\n//\n// `fireGtagConversion` is itself browser-gated and never throws, so this is safe to call\n// from the isomorphic sales `record()` — server-side it simply no-ops.\n\nimport { getConsentState } from \"../consent\";\nimport { fireGtagConversion, isValidSendTo, type GtagConversionInput } from \"../gtag\";\nimport { applyUserDataForConversion, type ConversionUserData } from \"../user-data\";\n\nconst DEDUP_PREFIX = \"_aranova_conv_\";\n\nexport type ConversionFireOutcome = \"fired\" | \"denied\" | \"duplicate\" | \"invalid\" | \"retryable\";\n\nfunction dedupKey(input: GtagConversionInput): string {\n return `${DEDUP_PREFIX}${input.transactionId ?? \"\"}:${input.sendTo}`;\n}\n\n// Has this (transaction_id, send_to) already fired? Read-only — the key is written ONLY\n// after a successful fire (see `fireOnce`), so a fire that never happened (e.g. gtag not\n// ready yet) is never suppressed on retry. Best-effort: a blocked sessionStorage reads as\n// \"not fired\" so the conversion still gets a chance.\nfunction alreadyFired(input: GtagConversionInput): boolean {\n if (!input.transactionId || typeof window === \"undefined\") return false;\n try {\n return window.sessionStorage.getItem(dedupKey(input)) !== null;\n } catch {\n return false;\n }\n}\n\nfunction markFired(input: GtagConversionInput): void {\n if (!input.transactionId || typeof window === \"undefined\") return;\n try {\n window.sessionStorage.setItem(dedupKey(input), \"1\");\n } catch {\n // sessionStorage unavailable — Google's counting_type is the authoritative backstop\n }\n}\n\n/**\n * Fire a conversion through the consent gate + de-dup guard.\n *\n * Enhanced conversions: right before the fire (past the consent gate AND the\n * de-dup guard — a duplicate that won't emit an event must not mutate gtag's\n * page-level user_data either), gtag's `user_data` is set from the explicit\n * `options.userData` merged over the form-submit stash — this is the single\n * choke point all firing paths (recordSale, trackConversion, autofire) flow\n * through, so every conversion hit carries the visitor's hashed identifiers\n * when any are known. Re-setting before each fire is idempotent (gtag scopes\n * user_data to the page), so a later autofire on the same page matches too.\n * The de-dup key is written only AFTER a successful fire, so a fire that\n * never happened (gtag not ready) is never suppressed on retry.\n */\nexport function fireConversionWithConsent(\n input: GtagConversionInput,\n options?: { userData?: ConversionUserData | null },\n): ConversionFireOutcome {\n if (getConsentState() === \"denied\") return \"denied\";\n if (alreadyFired(input)) return \"duplicate\";\n if (!isValidSendTo(input.sendTo)) return \"invalid\";\n try {\n applyUserDataForConversion(options?.userData);\n if (!fireGtagConversion(input)) return \"retryable\";\n markFired(input);\n return \"fired\";\n } catch {\n return \"retryable\";\n }\n}\n\n/**\n * Flush conversions queued while consent was pending.\n *\n * @deprecated No-op since consent v2 — there is no \"pending\" state, so nothing\n * is ever queued. Kept exported so pre-v2 integrations keep compiling.\n */\nexport function flushPendingConversions(): void {\n // intentionally empty\n}\n","// The client tracking config the SDK reads at runtime (GAP28 / ENG-46).\n//\n// The browser fetches the per-business object published to R2/CDN. This module is a\n// TOLERANT reader — it ignores unknown fields, defaults every field, and never throws — so\n// the backend can add fields freely (additive-only within the `v1` schema major) without\n// breaking an older SDK, and a newer object never breaks an older reader. See\n// docs/tracking-package/conversion-config-schema.md for the contract.\n\nexport interface ServiceFiring {\n send_to: string;\n /** Action's configured default value (cents); the SDK fires it only when a sale has no amount. */\n value_cents?: number | null;\n currency?: string | null;\n}\n\n/** Serializable on-page trigger (owned by tracking-core/src/events/trigger-spec.ts). The shape\n * varies by `event_type`; only the parameter for that type is set. */\nexport interface ConfigTriggerSpec {\n event_type: string;\n threshold_percent?: number;\n threshold_seconds?: number;\n page_threshold?: number;\n page_name?: string;\n}\n\n/** One unified conversion goal: a revenue `sale` or an on-page `event`. */\nexport interface ConversionGoal {\n key: string;\n label?: string;\n kind: \"sale\" | \"event\";\n /** Structured fire-when for event-goals; null for sales. */\n trigger: ConfigTriggerSpec | null;\n firing: ServiceFiring | null;\n}\n\nexport interface ConversionConfig {\n schema_version: number;\n config_version: number;\n business_id?: string;\n customer_id?: string | null;\n environment?: string;\n google_tracking_state: \"active\" | \"disabled\";\n gtag_ids: Record<string, string>;\n meta_pixel_ids: Record<string, string>;\n /** LEGACY: sale-goals only (for pre-unified-goal readers). */\n services: Array<{\n key: string;\n label?: string;\n firing: ServiceFiring | null;\n }>;\n /** Unified goal list (sales + on-page events). Superset of `services`. */\n goals: ConversionGoal[];\n}\n\nexport interface ConversionConfigStore {\n /** Firing config for a goal/service key, or null when it doesn't fire on-site. */\n getFiring(key: string): ServiceFiring | null;\n /** The full goal for a key, or null when unknown. */\n getGoal(key: string): ConversionGoal | null;\n /** Every adopted goal (sales + events). */\n listGoals(): ConversionGoal[];\n /** The currently adopted config (baked / cached fallback until the fetch lands). */\n current(): ConversionConfig | null;\n /** True once a config is adopted (seeded synchronously from cache/baked, or fetched). */\n isReady(): boolean;\n /**\n * Run `listener` when a config first becomes available — immediately if already\n * ready, otherwise on the first adopt. Lets auto-fire replay automatic events that\n * occurred before the async CDN fetch resolved. Returns an unsubscribe fn.\n */\n onResolve(listener: () => void): () => void;\n /** Force a background revalidate against the CDN object. */\n revalidate(): Promise<void>;\n}\n\nfunction isStringMap(value: unknown): value is Record<string, string> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.values(value).every((v) => typeof v === \"string\")\n );\n}\n\nfunction parseFiring(value: unknown): ServiceFiring | null {\n if (!value || typeof value !== \"object\") return null;\n const f = value as Record<string, unknown>;\n if (typeof f.send_to !== \"string\") return null;\n return {\n send_to: f.send_to,\n value_cents: typeof f.value_cents === \"number\" ? f.value_cents : null,\n currency: typeof f.currency === \"string\" ? f.currency : null,\n };\n}\n\nfunction parseTrigger(value: unknown): ConfigTriggerSpec | null {\n if (!value || typeof value !== \"object\") return null;\n const t = value as Record<string, unknown>;\n if (typeof t.event_type !== \"string\") return null;\n const spec: ConfigTriggerSpec = { event_type: t.event_type };\n if (typeof t.threshold_percent === \"number\") spec.threshold_percent = t.threshold_percent;\n if (typeof t.threshold_seconds === \"number\") spec.threshold_seconds = t.threshold_seconds;\n if (typeof t.page_threshold === \"number\") spec.page_threshold = t.page_threshold;\n if (typeof t.page_name === \"string\") spec.page_name = t.page_name;\n return spec;\n}\n\n/** Tolerant parse of a raw config object — never throws; returns null only when unusable. */\nexport function parseConversionConfig(raw: unknown): ConversionConfig | null {\n if (!raw || typeof raw !== \"object\") return null;\n const obj = raw as Record<string, unknown>;\n const servicesRaw = Array.isArray(obj.services) ? obj.services : [];\n const services = servicesRaw.flatMap((entry) => {\n if (!entry || typeof entry !== \"object\") return [];\n const s = entry as Record<string, unknown>;\n if (typeof s.key !== \"string\") return [];\n return [\n {\n key: s.key,\n label: typeof s.label === \"string\" ? s.label : undefined,\n firing: parseFiring(s.firing),\n },\n ];\n });\n const goalsRaw = Array.isArray(obj.goals) ? obj.goals : null;\n // Back-compat: an object from a pre-unified-goal backend has no `goals` — derive them from\n // the legacy `services` (all sale-goals) so the store always has a unified list.\n const goals: ConversionGoal[] = goalsRaw\n ? goalsRaw.flatMap((entry) => {\n if (!entry || typeof entry !== \"object\") return [];\n const g = entry as Record<string, unknown>;\n if (typeof g.key !== \"string\") return [];\n return [\n {\n key: g.key,\n label: typeof g.label === \"string\" ? g.label : undefined,\n kind: g.kind === \"event\" ? \"event\" : \"sale\",\n trigger: parseTrigger(g.trigger),\n firing: parseFiring(g.firing),\n },\n ];\n })\n : services.map((s) => ({\n key: s.key,\n label: s.label,\n kind: \"sale\" as const,\n trigger: null,\n firing: s.firing,\n }));\n return {\n schema_version: typeof obj.schema_version === \"number\" ? obj.schema_version : 1,\n config_version: typeof obj.config_version === \"number\" ? obj.config_version : 0,\n business_id: typeof obj.business_id === \"string\" ? obj.business_id : undefined,\n customer_id: typeof obj.customer_id === \"string\" ? obj.customer_id : null,\n environment: typeof obj.environment === \"string\" ? obj.environment : undefined,\n google_tracking_state: obj.google_tracking_state === \"active\" ? \"active\" : \"disabled\",\n gtag_ids: isStringMap(obj.gtag_ids) ? obj.gtag_ids : {},\n meta_pixel_ids: isStringMap(obj.meta_pixel_ids) ? obj.meta_pixel_ids : {},\n services,\n goals,\n };\n}\n\n// --- stale-while-revalidate cache (sessionStorage) -----------------------------------------\n\nconst CACHE_PREFIX = \"_aranova_cfg_\";\n\ninterface CachedEntry {\n etag: string | null;\n config: ConversionConfig;\n}\n\nfunction cacheKey(url: string): string {\n return `${CACHE_PREFIX}${url}`;\n}\n\nfunction readCache(url: string): CachedEntry | null {\n if (typeof window === \"undefined\") return null;\n try {\n const raw = window.sessionStorage.getItem(cacheKey(url));\n if (!raw) return null;\n const parsed = JSON.parse(raw) as { etag?: unknown; config?: unknown };\n const config = parseConversionConfig(parsed.config);\n if (!config) return null;\n return {\n etag: typeof parsed.etag === \"string\" ? parsed.etag : null,\n config,\n };\n } catch {\n return null;\n }\n}\n\nfunction writeCache(url: string, entry: CachedEntry): void {\n if (typeof window === \"undefined\") return;\n try {\n window.sessionStorage.setItem(cacheKey(url), JSON.stringify(entry));\n } catch {\n // sessionStorage unavailable — runtime adoption still works, just not across inits\n }\n}\n\nexport interface ResolveConversionConfigOptions {\n /** Full URL of the per-business CDN object. */\n cdnUrl: string;\n /** Offline-correct fallback (e.g. the CLI-baked snapshot). */\n baked?: ConversionConfig | null;\n /** Injectable for tests / non-global-fetch runtimes. */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Resolve the config with stale-while-revalidate: seed synchronously from the\n * sessionStorage cache (or the baked fallback), then conditionally re-fetch the CDN object\n * with `If-None-Match`. A fetched object is adopted only if its `config_version` is strictly\n * greater than what's cached, so a reordered edge copy can't downgrade fresher state.\n * Non-blocking and browser-only; a failed fetch leaves the seed in place.\n */\nexport function resolveConversionConfig(\n options: ResolveConversionConfigOptions,\n): ConversionConfigStore {\n const cached = readCache(options.cdnUrl);\n let current: ConversionConfig | null = cached?.config ?? options.baked ?? null;\n let etag: string | null = cached?.etag ?? null;\n const goalsByKey = new Map<string, ConversionGoal>();\n const resolveListeners = new Set<() => void>();\n\n function rebuildIndex(): void {\n goalsByKey.clear();\n for (const goal of current?.goals ?? []) {\n goalsByKey.set(goal.key, goal);\n }\n }\n\n function notifyResolved(): void {\n // One-shot: only the FIRST adoption matters for replay. Snapshot then clear so a\n // listener that re-subscribes inside its callback isn't double-run.\n const listeners = [...resolveListeners];\n resolveListeners.clear();\n // Isolate each listener: the set is already cleared, so one throwing subscriber\n // must not drop the others' buffered replays. Swallow (best-effort) to match the\n // SDK's policy of never surfacing tracking errors to the host page.\n for (const listener of listeners) {\n try {\n listener();\n } catch {\n // never let one subscriber break conversion replay\n }\n }\n }\n\n function adopt(next: ConversionConfig | null, nextEtag: string | null): void {\n if (!next) return;\n if (current && next.config_version <= current.config_version) return;\n const wasEmpty = current === null;\n current = next;\n etag = nextEtag;\n rebuildIndex();\n writeCache(options.cdnUrl, { etag, config: next });\n if (wasEmpty) notifyResolved();\n }\n\n async function revalidate(): Promise<void> {\n if (typeof window === \"undefined\") return;\n try {\n const doFetch = options.fetchImpl ?? globalThis.fetch;\n if (!doFetch) return;\n const headers: Record<string, string> = {};\n if (etag) headers[\"If-None-Match\"] = etag;\n const response = await doFetch(options.cdnUrl, {\n method: \"GET\",\n headers,\n });\n if (response.status === 304 || !response.ok) return;\n adopt(parseConversionConfig(await response.json()), response.headers.get(\"ETag\"));\n } catch {\n // best-effort; the cached / baked fallback stays in place\n }\n }\n\n rebuildIndex();\n void revalidate();\n\n return {\n getFiring: (key) => goalsByKey.get(key)?.firing ?? null,\n getGoal: (key) => goalsByKey.get(key) ?? null,\n listGoals: () => [...goalsByKey.values()],\n current: () => current,\n isReady: () => current !== null,\n onResolve: (listener) => {\n if (current !== null) {\n listener();\n return () => {};\n }\n resolveListeners.add(listener);\n return () => resolveListeners.delete(listener);\n },\n revalidate,\n };\n}\n","const STORAGE_KEY = \"_aranova_auto_txn_map\";\nconst transactionIds = new Map<string, string>();\nlet legacyCounter = 0;\n\ninterface StoredTransactionMap {\n sessionId: string;\n entries: Record<string, string>;\n}\n\nfunction scopeKey(sessionId: string, goalKey: string, path: string): string {\n return JSON.stringify([sessionId, goalKey, path]);\n}\n\nfunction randomId(): string {\n const cryptoApi = globalThis.crypto;\n if (typeof cryptoApi?.randomUUID === \"function\") return cryptoApi.randomUUID();\n if (typeof cryptoApi?.getRandomValues === \"function\") {\n const bytes = cryptoApi.getRandomValues(new Uint8Array(16));\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n }\n // Ancient-browser fallback. Keep fixed-length opaque shape; modern browsers\n // always use Web Crypto above.\n legacyCounter = (legacyCounter + 1) % 0x1_0000_0000;\n const timestamp = Date.now().toString(16).padStart(12, \"0\");\n const counter = legacyCounter.toString(16).padStart(8, \"0\");\n const random = Math.floor(Math.random() * 0xffffffffffff)\n .toString(16)\n .padStart(12, \"0\");\n return `${timestamp}${counter}${random}`.slice(0, 32);\n}\n\nfunction isValidTransactionId(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n /^auto:(?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/i.test(\n value,\n ) &&\n value.length <= 64\n );\n}\n\nfunction readStoredMap(sessionId: string): StoredTransactionMap {\n if (typeof window === \"undefined\") return { sessionId, entries: {} };\n try {\n const raw = window.localStorage.getItem(STORAGE_KEY);\n if (!raw) return { sessionId, entries: {} };\n const parsed = JSON.parse(raw) as Partial<StoredTransactionMap>;\n if (\n parsed.sessionId !== sessionId ||\n !parsed.entries ||\n typeof parsed.entries !== \"object\" ||\n Array.isArray(parsed.entries)\n ) {\n return { sessionId, entries: {} };\n }\n return { sessionId, entries: parsed.entries };\n } catch {\n return { sessionId, entries: {} };\n }\n}\n\nfunction writeStoredMap(stored: StoredTransactionMap): void {\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.setItem(STORAGE_KEY, JSON.stringify(stored));\n } catch {\n // Storage unavailable; page-lifetime stability is still preserved.\n }\n}\n\n/**\n * Return one opaque, bounded Google transaction ID per session/goal/path.\n *\n * The raw session id and URL path stay in first-party local storage and are\n * never sent to Google. The one-current-session map preserves deduplication\n * across tabs while discarding prior-session mappings.\n */\nexport function getAutomaticTransactionId(\n sessionId: string,\n goalKey: string,\n path: string,\n): string {\n const key = scopeKey(sessionId, goalKey, path);\n const existing = transactionIds.get(key);\n if (existing) return existing;\n\n const stored = readStoredMap(sessionId);\n const storedId = stored.entries[key];\n if (isValidTransactionId(storedId)) {\n transactionIds.set(key, storedId);\n return storedId;\n }\n\n const transactionId = `auto:${randomId()}`;\n transactionIds.set(key, transactionId);\n // Re-read before write so another tab that won the race remains authoritative.\n const latest = readStoredMap(sessionId);\n const concurrentId = latest.entries[key];\n if (isValidTransactionId(concurrentId)) {\n transactionIds.set(key, concurrentId);\n return concurrentId;\n }\n latest.entries[key] = transactionId;\n writeStoredMap(latest);\n return transactionId;\n}\n\nexport function resetAutomaticTransactionIdsForTests(): void {\n transactionIds.clear();\n legacyCounter = 0;\n}\n","import type { ConversionGoal } from \"./conversion-config\";\n\nfunction hasNumberField<K extends string>(\n metadata: Readonly<Record<string, unknown>>,\n key: K,\n): metadata is Readonly<Record<string, unknown> & Record<K, number>> {\n return typeof metadata[key] === \"number\";\n}\n\nfunction hasStringField<K extends string>(\n metadata: Readonly<Record<string, unknown>>,\n key: K,\n): metadata is Readonly<Record<string, unknown> & Record<K, string>> {\n return typeof metadata[key] === \"string\";\n}\n\n/** Shared automatic-goal matcher used by every SDK runtime. */\nexport function automaticThresholdMet(\n goal: ConversionGoal,\n eventType: string,\n metadata: Readonly<Record<string, unknown>>,\n): boolean {\n const trigger = goal.trigger;\n if (!trigger || trigger.event_type !== eventType) return false;\n switch (eventType) {\n case \"scroll_depth\":\n return (\n hasNumberField(metadata, \"depth_percent\") &&\n trigger.threshold_percent != null &&\n metadata.depth_percent >= trigger.threshold_percent\n );\n case \"time_on_site\":\n return (\n hasNumberField(metadata, \"duration_ms\") &&\n trigger.threshold_seconds != null &&\n metadata.duration_ms >= trigger.threshold_seconds * 1000\n );\n case \"multi_page_session\":\n return (\n hasNumberField(metadata, \"page_count\") &&\n trigger.page_threshold != null &&\n metadata.page_count >= trigger.page_threshold\n );\n case \"specific_page_visit\":\n return hasStringField(metadata, \"page_name\") && metadata.page_name === trigger.page_name;\n case \"page_view\":\n case \"form_start\":\n case \"phone_click\":\n return true;\n default:\n return false;\n }\n}\n","/**\n * Format an ISO timestamp in a specific IANA time zone (e.g. `America/Toronto`),\n * so dashboards stop hand-rolling `Intl`. Defaults to a short date-time; pass\n * `opts` to override fields. The `timeZone` is always forced to the argument.\n */\nexport function formatDateInTz(\n iso: string,\n timeZone: string,\n opts?: Intl.DateTimeFormatOptions,\n locale?: string,\n): string {\n const date = new Date(iso);\n // Guard malformed input: Intl.format(Invalid Date) throws a RangeError.\n if (Number.isNaN(date.getTime())) return iso;\n return new Intl.DateTimeFormat(locale, {\n year: \"numeric\",\n month: \"short\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n ...opts,\n timeZone,\n }).format(date);\n}\n","import type { SupportedCurrency } from \"./schema\";\n\n/**\n * Money conversion helpers.\n *\n * The API speaks **integer minor units (cents)** exclusively. These helpers move\n * between a human-facing major amount (dollars) and cents, and format cents for\n * display — so a consumer always has both representations without float math.\n */\n\n// Minor-unit exponent per supported currency (USD/CAD = 2 decimal places).\nconst MINOR_UNIT_EXPONENT: Record<SupportedCurrency, number> = {\n USD: 2,\n CAD: 2,\n};\n\nfunction exponentFor(currency: SupportedCurrency): number {\n return MINOR_UNIT_EXPONENT[currency] ?? 2;\n}\n\n/**\n * Convert a major amount (dollars `250.5`) to integer minor units (`25050`).\n *\n * Convenience only — the wire is always integer cents. Uses float multiply +\n * `Math.round`, so values that aren't exactly representable in binary float\n * (e.g. `1.005`) can round to the neighbouring cent. If you already hold an\n * exact cents integer, pass it straight through and skip this helper.\n */\nexport function toMinor(amount: number, currency: SupportedCurrency): number {\n return Math.round(amount * 10 ** exponentFor(currency));\n}\n\n/** Convert integer minor units (`25050`) to a major amount (`250.5`). */\nexport function fromMinor(cents: number, currency: SupportedCurrency): number {\n return cents / 10 ** exponentFor(currency);\n}\n\n/**\n * Format integer minor units as a localized currency string (e.g. `\"$250.50\"`).\n * Uses the built-in `Intl.NumberFormat` — no extra dependency.\n */\nexport function formatMoney(cents: number, currency: SupportedCurrency, locale?: string): string {\n return new Intl.NumberFormat(locale, { style: \"currency\", currency }).format(\n fromMinor(cents, currency),\n );\n}\n\n// Hoisted to `resources/intl/date` so the calendar resource shares the same\n// binding; still public API via `sales-public.ts`.\nexport { formatDateInTz } from \"../intl/date\";\n","import { applyDefaultConsentState, isValidGtagId, loadGtagScript } from \"../gtag\";\nimport {\n parseConversionConfig,\n type ConversionConfig,\n type ConversionGoal,\n} from \"./conversion-config\";\nimport { fireConversionWithConsent } from \"./conversion-firing\";\nimport { getAutomaticTransactionId } from \"./automatic-transaction\";\nimport { automaticThresholdMet } from \"./automatic-trigger\";\nimport { fromMinor } from \"./sales/money\";\nimport type { SupportedCurrency } from \"./sales/schema\";\n\n/**\n * Where a business's published tracking config lives.\n *\n * `businessId` + `environment` are the stable identity; the ORIGIN it is fetched\n * from is deployment-specific (production CDN vs. a local object store), which is\n * why `cdnBaseUrl` exists. Codegen bakes only the identity, so one committed\n * generated file works in every environment and only an env var changes.\n *\n * `cdnUrl` remains supported and WINS when present — every client repo generated\n * before `cdnBaseUrl` passes one, and those must keep working untouched.\n */\nexport interface TrackingConfigReference {\n /**\n * Fully-resolved object URL. Optional: omit it and pass `cdnBaseUrl` (or rely\n * on the production default) to have it composed from the identity below.\n */\n cdnUrl?: string;\n /**\n * Origin (optionally with a path prefix) the config object is served from, e.g.\n * `https://demos.aranova.io` in production or\n * `http://localhost:9100/aranova-demos` against a local MinIO. Ignored when\n * `cdnUrl` is set; blank or omitted falls back to {@link DEFAULT_CDN_BASE_URL}.\n * `tracking-cli gen` wires this to an env var so retargeting is config, not code.\n */\n cdnBaseUrl?: string;\n businessId: string;\n environment: \"production\" | \"test\";\n}\n\n/** Production object-storage origin — the default when nothing overrides it. */\nexport const DEFAULT_CDN_BASE_URL = \"https://demos.aranova.io\";\n\n/**\n * Object key for a business's config, mirroring the backend's\n * `core/storage.py::tracking_config_key`. The backend stays the authority: it\n * publishes at this key and returns the absolute URL, which is what the CLI bakes\n * as the legacy `cdnUrl`. This is the composition path for references that carry\n * identity instead of a URL — the `v1` prefix is the schema MAJOR and must move in\n * lockstep with the backend if it is ever cut to `v2`.\n */\nfunction trackingConfigKey(businessId: string, environment: \"production\" | \"test\"): string {\n return `tracking-config/v1/${businessId}-${environment}.json`;\n}\n\n/**\n * The URL a reference resolves to. An explicit `cdnUrl` wins (back-compat);\n * otherwise compose from `cdnBaseUrl` (or the production default).\n *\n * A blank/whitespace `cdnBaseUrl` is treated as UNSET rather than composed: the\n * generated module reads it from an env var, and a var that is present-but-empty\n * (a stray `NEXT_PUBLIC_ARANOVA_CDN_BASE_URL=` line) would otherwise produce\n * `/tracking-config/...` — a same-origin request to the client's own site.\n */\nexport function resolveTrackingConfigUrl(ref: TrackingConfigReference): string {\n if (ref.cdnUrl) return ref.cdnUrl;\n const configured = ref.cdnBaseUrl?.trim();\n const base = (configured || DEFAULT_CDN_BASE_URL).replace(/\\/+$/, \"\");\n return `${base}/${trackingConfigKey(ref.businessId, ref.environment)}`;\n}\n\ntype RuntimeState = \"unconfirmed\" | \"active\" | \"tombstone\";\n\ninterface CachedEntry {\n etag: string | null;\n config: ConversionConfig;\n}\n\ninterface QueuedConversion {\n key: string;\n value?: number | null;\n currency?: string | null;\n transactionId?: string | null;\n}\n\nexport type TrackingConfigConversionOptions = Omit<QueuedConversion, \"key\">;\n\ninterface QueuedPageView {\n href: string;\n title: string | null;\n referrer: string | null;\n}\n\ninterface QueuedAutomaticEvent {\n eventType: string;\n metadata: Record<string, unknown>;\n transactionPath: string;\n transactionScope: string;\n}\n\nconst CACHE_PREFIX = \"_aranova_cfg_runtime_\";\nconst AUTHORITY_TTL_MS = 60_000;\n// Queues are bounded rather than cleared while authority is unconfirmed: the\n// config can appear at any time (a first publish, or R2 recovering), and the\n// most recent items are still worth firing when it does. Unbounded, a site whose\n// config 404s accumulates an entry per page view for the life of the tab.\nconst MAX_QUEUE_LENGTH = 50;\n// While unconfirmed, revalidation is spaced by a growing delay instead of riding\n// every queued item. Without it a missing config produces one no-cache request\n// per page view, forever. `focus` / `visibilitychange` still revalidate, so\n// recovery stays prompt once the object exists.\nconst RETRY_BASE_MS = 5_000;\nconst RETRY_MAX_MS = 5 * 60_000;\n\nconst runtimes = new Map<string, TrackingConfigRuntime>();\nconst configuredIds = new Set<string>();\nlet scriptLoad: Promise<void> | null = null;\nlet jsInitialized = false;\n\nfunction cacheKey(url: string): string {\n return `${CACHE_PREFIX}${url}`;\n}\n\n/** Append, dropping the oldest entry once the cap is reached. */\nfunction pushBounded<T>(queue: T[], item: T): void {\n queue.push(item);\n if (queue.length > MAX_QUEUE_LENGTH) queue.splice(0, queue.length - MAX_QUEUE_LENGTH);\n}\n\nfunction readCache(url: string): CachedEntry | null {\n if (typeof window === \"undefined\") return null;\n try {\n const raw = window.sessionStorage.getItem(cacheKey(url));\n if (!raw) return null;\n const parsed = JSON.parse(raw) as { etag?: unknown; config?: unknown };\n const config = parseConversionConfig(parsed.config);\n if (!config) return null;\n return {\n etag: typeof parsed.etag === \"string\" ? parsed.etag : null,\n config,\n };\n } catch {\n return null;\n }\n}\n\nfunction writeCache(url: string, entry: CachedEntry): void {\n if (typeof window === \"undefined\") return;\n try {\n window.sessionStorage.setItem(cacheKey(url), JSON.stringify(entry));\n } catch {\n // sessionStorage unavailable — runtime still works, just without a conditional candidate\n }\n}\n\nfunction isTombstone(config: ConversionConfig): boolean {\n return config.google_tracking_state === \"disabled\" || Object.keys(config.gtag_ids).length === 0;\n}\n\nfunction validateConfig(config: ConversionConfig, ref: TrackingConfigReference): boolean {\n return (\n config.business_id === ref.businessId &&\n config.environment === ref.environment &&\n (config.google_tracking_state === \"active\" || config.google_tracking_state === \"disabled\")\n );\n}\n\nfunction pageViewSnapshot(): QueuedPageView | null {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return null;\n return {\n href: window.location.href,\n title: document.title || null,\n referrer: document.referrer || null,\n };\n}\n\nfunction ensureScript(gtagId: string): Promise<void> {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return Promise.resolve();\n applyDefaultConsentState();\n loadGtagScript(gtagId);\n if (scriptLoad) return scriptLoad;\n scriptLoad = new Promise((resolve) => {\n const script = document.querySelector<HTMLScriptElement>(\n 'script[data-aranova-tracking=\"aranova-gtag-loader\"]',\n );\n if (!script) {\n resolve();\n return;\n }\n if ((script as HTMLScriptElement & { dataset: DOMStringMap }).dataset.loaded === \"true\") {\n resolve();\n return;\n }\n window.setTimeout(resolve, 0);\n script.addEventListener(\n \"load\",\n () => {\n script.dataset.loaded = \"true\";\n resolve();\n },\n { once: true },\n );\n script.addEventListener(\"error\", () => resolve(), { once: true });\n });\n return scriptLoad;\n}\n\nexport class TrackingConfigRuntime {\n private readonly fetchImpl: typeof fetch;\n /** Resolved config URL — see the constructor for why it is computed once. */\n private readonly url: string;\n private current: ConversionConfig | null = null;\n private etag: string | null = null;\n private stateValue: RuntimeState = \"unconfirmed\";\n private confirmedAt = 0;\n private authorityGeneration = 0;\n private inFlight: Promise<void> | null = null;\n private flushInFlight: Promise<void> | null = null;\n private flushRequested = false;\n private retryTimer: number | null = null;\n private started = false;\n /** Consecutive failed authority attempts — drives the revalidate backoff. */\n private authorityFailures = 0;\n /** Epoch ms before which `ensureAuthority` must not issue another request. */\n private nextAuthorityAttemptAt = 0;\n private readonly conversionQueue: QueuedConversion[] = [];\n private readonly automaticQueue: QueuedAutomaticEvent[] = [];\n private readonly pageQueue: QueuedPageView[] = [];\n private readonly listeners = new Set<() => void>();\n\n constructor(\n readonly ref: TrackingConfigReference,\n fetchImpl: typeof fetch = globalThis.fetch,\n ) {\n // Native browser fetch requires Window/WorkerGlobalScope as its receiver.\n // Calling an unbound native fetch stored on `this` throws \"Illegal invocation\".\n this.fetchImpl = fetchImpl.bind(globalThis);\n // Resolved once: the cache key, the fetch target, and the write-back key must\n // all be the same string, or a reference that composes its URL would read a\n // cache entry it never writes.\n this.url = resolveTrackingConfigUrl(ref);\n const cached = readCache(this.url);\n this.current = cached?.config ?? null;\n this.etag = cached?.etag ?? null;\n this.start();\n }\n\n /** The URL this runtime actually fetches (composed or explicit). */\n configUrl(): string {\n return this.url;\n }\n\n /**\n * Explicitly start authority resolution and Google-tag bootstrap.\n *\n * Idempotent so framework effects can call it after hydration without\n * depending on constructor timing.\n */\n start(): void {\n if (this.started) {\n void this.flush();\n return;\n }\n this.started = true;\n void this.revalidate();\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"visibilitychange\", () => {\n if (document.visibilityState === \"visible\") void this.revalidate();\n });\n window.addEventListener(\"focus\", () => void this.revalidate());\n }\n }\n\n state(): RuntimeState {\n return this.stateValue;\n }\n\n config(): ConversionConfig | null {\n return this.stateValue === \"active\" || this.stateValue === \"tombstone\" ? this.current : null;\n }\n\n __unsafeExpireAuthorityForTests(): void {\n this.confirmedAt = Number.NEGATIVE_INFINITY;\n this.nextAuthorityAttemptAt = 0;\n }\n\n /** Queue depths — asserted by tests to pin the bound. */\n __queueDepthsForTests(): { conversions: number; automatic: number; pages: number } {\n return {\n conversions: this.conversionQueue.length,\n automatic: this.automaticQueue.length,\n pages: this.pageQueue.length,\n };\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n async ensureAuthority(): Promise<boolean> {\n if (this.stateValue !== \"unconfirmed\" && Date.now() - this.confirmedAt < AUTHORITY_TTL_MS) {\n return true;\n }\n // Backoff applies only to this implicit path (driven by queued work). An\n // explicit `revalidate()` — the visibility/focus listeners, or a caller —\n // always goes to the network so recovery is never delayed by the timer.\n if (Date.now() < this.nextAuthorityAttemptAt) return false;\n await this.revalidateAuthority();\n return this.stateValue !== \"unconfirmed\" && Date.now() - this.confirmedAt < AUTHORITY_TTL_MS;\n }\n\n async revalidate(): Promise<void> {\n this.nextAuthorityAttemptAt = 0;\n await this.revalidateAuthority();\n await this.flush();\n }\n\n private async revalidateAuthority(): Promise<void> {\n if (typeof window === \"undefined\" || !this.fetchImpl) return;\n if (this.inFlight) return this.inFlight;\n this.inFlight = this.revalidateNow().finally(() => {\n this.inFlight = null;\n });\n return this.inFlight;\n }\n\n queuePageView(snapshot: QueuedPageView | null = pageViewSnapshot()): void {\n if (!snapshot) return;\n pushBounded(this.pageQueue, snapshot);\n void this.flush();\n }\n\n fireConversion(key: string, options?: TrackingConfigConversionOptions): void {\n pushBounded(this.conversionQueue, { key, ...options });\n void this.flush();\n }\n\n queueAutomaticEvent(\n eventType: string,\n metadata: Record<string, unknown>,\n transactionPath: string,\n transactionScope: string,\n ): void {\n pushBounded(this.automaticQueue, {\n eventType,\n metadata,\n transactionPath,\n transactionScope,\n });\n void this.flush();\n }\n\n listGoals(): ConversionGoal[] {\n return this.current?.goals ?? [];\n }\n\n private async revalidateNow(): Promise<void> {\n try {\n const headers: Record<string, string> = {};\n if (this.etag) headers[\"If-None-Match\"] = this.etag;\n const response = await this.fetchImpl(this.url, {\n method: \"GET\",\n headers,\n cache: \"no-cache\",\n });\n if (response.status === 304 && this.current && validateConfig(this.current, this.ref)) {\n this.confirm(this.current, this.etag);\n return;\n }\n if (!response.ok) {\n this.expireAuthority();\n return;\n }\n const next = parseConversionConfig(await response.json());\n if (!next || !validateConfig(next, this.ref)) {\n this.expireAuthority();\n return;\n }\n if (this.current && next.config_version < this.current.config_version) {\n this.expireAuthority();\n return;\n }\n this.confirm(next, response.headers.get(\"ETag\"));\n } catch {\n this.expireAuthority();\n }\n }\n\n private expireAuthority(): void {\n this.authorityGeneration += 1;\n if (this.stateValue !== \"unconfirmed\") this.stateValue = \"unconfirmed\";\n // Exponential, capped. Queued work keeps accumulating (bounded), so the\n // config appearing later still fires the most recent items.\n this.authorityFailures += 1;\n const delay = Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** (this.authorityFailures - 1));\n this.nextAuthorityAttemptAt = Date.now() + delay;\n }\n\n private confirm(config: ConversionConfig, etag: string | null): void {\n this.authorityGeneration += 1;\n this.current = config;\n this.etag = etag;\n this.confirmedAt = Date.now();\n this.authorityFailures = 0;\n this.nextAuthorityAttemptAt = 0;\n this.stateValue = isTombstone(config) ? \"tombstone\" : \"active\";\n writeCache(this.url, { etag, config });\n if (this.stateValue === \"tombstone\") {\n if (this.retryTimer !== null) {\n window.clearTimeout(this.retryTimer);\n this.retryTimer = null;\n }\n this.conversionQueue.length = 0;\n this.automaticQueue.length = 0;\n this.pageQueue.length = 0;\n }\n for (const listener of this.listeners) listener();\n }\n\n private async flush(): Promise<void> {\n if (this.flushInFlight) {\n this.flushRequested = true;\n return this.flushInFlight;\n }\n this.flushRequested = false;\n this.flushInFlight = this.flushNow().finally(() => {\n this.flushInFlight = null;\n if (this.flushRequested && this.stateValue === \"active\") void this.flush();\n });\n return this.flushInFlight;\n }\n\n private scheduleRetry(): void {\n if (this.retryTimer !== null || typeof window === \"undefined\") return;\n this.retryTimer = window.setTimeout(() => {\n this.retryTimer = null;\n void this.flush();\n }, 1000);\n }\n\n private async flushNow(): Promise<void> {\n if (!(await this.ensureAuthority())) return;\n if (this.stateValue !== \"active\" || !this.current) return;\n const config = this.current;\n const generation = this.authorityGeneration;\n const ids = Object.values(config.gtag_ids).filter(\n (id): id is string => typeof id === \"string\" && isValidGtagId(id),\n );\n if (ids.length === 0) return;\n await ensureScript(ids[0]!);\n if (\n this.authorityGeneration !== generation ||\n this.stateValue !== \"active\" ||\n this.current !== config\n ) {\n return;\n }\n const gtag = window.gtag;\n if (typeof gtag !== \"function\") return;\n try {\n if (!jsInitialized) {\n gtag(\"js\", new Date());\n jsInitialized = true;\n }\n for (const id of ids) {\n if (configuredIds.has(id)) continue;\n gtag(\"config\", id, { send_page_view: false });\n configuredIds.add(id);\n }\n } catch {\n this.scheduleRetry();\n return;\n }\n while (this.pageQueue.length > 0) {\n const page = this.pageQueue[0]!;\n try {\n gtag(\"event\", \"page_view\", {\n page_location: page.href,\n page_title: page.title ?? undefined,\n page_referrer: page.referrer ?? undefined,\n });\n this.pageQueue.shift();\n } catch {\n this.scheduleRetry();\n return;\n }\n }\n while (this.automaticQueue.length > 0) {\n const event = this.automaticQueue[0]!;\n for (const goal of config.goals) {\n if (goal.kind !== \"event\" || !goal.firing) continue;\n if (!automaticThresholdMet(goal, event.eventType, event.metadata)) continue;\n pushBounded(this.conversionQueue, {\n key: goal.key,\n transactionId: getAutomaticTransactionId(\n event.transactionScope,\n goal.key,\n event.transactionPath,\n ),\n });\n }\n this.automaticQueue.shift();\n }\n while (this.conversionQueue.length > 0) {\n const item = this.conversionQueue[0]!;\n const goal = config.goals.find((g) => g.key === item.key);\n const firing = goal?.firing;\n if (!firing) {\n this.conversionQueue.shift();\n continue;\n }\n const currency = item.currency ?? firing.currency ?? null;\n const value =\n item.value ??\n (firing.value_cents != null && currency\n ? fromMinor(firing.value_cents, currency as SupportedCurrency)\n : null);\n const outcome = fireConversionWithConsent({\n sendTo: firing.send_to,\n value,\n currency,\n transactionId: item.transactionId ?? null,\n });\n if (outcome === \"retryable\") {\n this.scheduleRetry();\n return;\n }\n this.conversionQueue.shift();\n }\n }\n}\n\nexport function getTrackingConfigRuntime(\n ref: TrackingConfigReference,\n fetchImpl?: typeof fetch,\n): TrackingConfigRuntime {\n // Keyed on the RESOLVED url: `{cdnUrl}` and an equivalent\n // `{cdnBaseUrl,businessId,environment}` name the same object and must share one\n // runtime, or each would keep its own authority state and gtag bootstrap.\n const key = `${resolveTrackingConfigUrl(ref)}|${ref.businessId}|${ref.environment}`;\n const existing = runtimes.get(key);\n if (existing) return existing;\n const runtime = new TrackingConfigRuntime(ref, fetchImpl ?? globalThis.fetch);\n runtimes.set(key, runtime);\n return runtime;\n}\n\nexport function resetTrackingConfigRuntimesForTests(): void {\n runtimes.clear();\n configuredIds.clear();\n scriptLoad = null;\n jsInitialized = false;\n}\n","// Visitor + session identity for the tracking SDK.\n//\n// Visitor: persistent localStorage UUID, never expires until the user clears\n// browser storage. Used for cross-session correlation.\n//\n// Session: rolling 30-minute idle window. Regenerated when more than\n// SESSION_IDLE_MS has passed since the last event. Matches the behavior of\n// GA4, PostHog, Mixpanel, etc., so analytics is comparable.\n\nimport { clearLandingRecord } from \"./landing\";\n\n/**\n * localStorage key for the persistent visitor id.\n */\nexport const VISITOR_STORAGE_KEY = \"aranova_tracking_visitor\";\n\n/**\n * localStorage key for the rolling session id state.\n */\nexport const SESSION_STORAGE_KEY = \"aranova_tracking_session\";\n\n/**\n * Idle window before a new session id is created.\n */\nexport const SESSION_IDLE_MS = 30 * 60 * 1000;\n\n/**\n * Serialized session state stored in localStorage.\n */\nexport interface StoredSession {\n /** Client-generated session UUID. */\n id: string;\n /** Unix timestamp in milliseconds for the most recent event/session touch. */\n last_event_at: number;\n}\n\nfunction safeUuid(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\")\n return crypto.randomUUID();\n // Fallback for ancient browsers — not cryptographically perfect but unique enough.\n return `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}-${Math.random().toString(16).slice(2)}`;\n}\n\nfunction readLocalStorage(key: string): string | null {\n try {\n return window.localStorage.getItem(key);\n } catch {\n return null;\n }\n}\n\nfunction writeLocalStorage(key: string, value: string): void {\n try {\n window.localStorage.setItem(key, value);\n } catch {\n // Storage may be denied (private mode, blocked cookies, quota). Caller is\n // responsible for degrading gracefully.\n }\n}\n\n/**\n * Return the persistent visitor id for this browser profile.\n *\n * Creates and stores a new id when one does not already exist. During SSR,\n * returns an ephemeral id because browser storage is unavailable.\n */\nexport function getVisitorId(): string {\n if (typeof window === \"undefined\") return safeUuid();\n\n const existing = readLocalStorage(VISITOR_STORAGE_KEY);\n if (existing && existing.length > 0) return existing;\n\n const fresh = safeUuid();\n writeLocalStorage(VISITOR_STORAGE_KEY, fresh);\n return fresh;\n}\n\n/**\n * Result from `getOrRotateSessionId()`.\n */\nexport interface SessionIdResult {\n /** Current session id. */\n id: string;\n /** Whether this call created a new session. */\n isNew: boolean;\n}\n\n/**\n * Return the current session id, rotating it after the idle window expires.\n *\n * Also refreshes `last_event_at` for active sessions.\n */\nexport function getOrRotateSessionId(now: number = Date.now()): SessionIdResult {\n if (typeof window === \"undefined\") return { id: safeUuid(), isNew: true };\n\n const raw = readLocalStorage(SESSION_STORAGE_KEY);\n if (raw) {\n try {\n const parsed = JSON.parse(raw) as Partial<StoredSession>;\n if (typeof parsed.id === \"string\" && typeof parsed.last_event_at === \"number\") {\n if (now - parsed.last_event_at <= SESSION_IDLE_MS) {\n const refreshed: StoredSession = { id: parsed.id, last_event_at: now };\n writeLocalStorage(SESSION_STORAGE_KEY, JSON.stringify(refreshed));\n return { id: parsed.id, isNew: false };\n }\n }\n } catch {\n // Fall through to a fresh session.\n }\n }\n\n const fresh: StoredSession = { id: safeUuid(), last_event_at: now };\n writeLocalStorage(SESSION_STORAGE_KEY, JSON.stringify(fresh));\n return { id: fresh.id, isNew: true };\n}\n\n/**\n * Clear visitor and session identity from localStorage, including the\n * session-scoped landing record (a landing must never outlive its session).\n *\n * Intended for tests, debugging, and explicit user reset flows.\n */\nexport function resetTrackingIdentity(): void {\n clearLandingRecord();\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.removeItem(VISITOR_STORAGE_KEY);\n window.localStorage.removeItem(SESSION_STORAGE_KEY);\n } catch {\n // ignored\n }\n}\n","import { z } from \"zod\";\n\n/**\n * Metadata for the automatic `page_view` event.\n *\n * The SDK emits this on initial load, SPA route changes, and bfcache restores.\n * Consumers do not call `trackEvent('page_view', ...)`; registering\n * `automatic: { page_view: {} }` enables the SDK-owned trigger.\n */\nexport const pageViewMetadataSchema = z\n .object({\n page: z\n .object({\n title: z.string().nullable(),\n path: z.string(),\n search: z.string(),\n hash: z.string(),\n })\n .strict(),\n referrer: z.string().nullable(),\n // `.nullable().optional()` — absent (undefined) OR explicit null OR a\n // real viewport object. Mirrors Pydantic's `_Viewport | None = None`\n // on the backend side so the drift test stays clean.\n viewport: z\n .object({\n w: z.number(),\n h: z.number(),\n })\n .strict()\n .nullable()\n .optional(),\n })\n .strict();\n\nexport type PageViewMetadata = z.infer<typeof pageViewMetadataSchema>;\n\n/**\n * Registration config for automatic `page_view`.\n *\n * `page_view` is required in every trigger registry and currently has no\n * options. Use `{ page_view: {} }`.\n */\nexport const pageViewConfigSchema = z.object({}).strict();\nexport type PageViewConfig = z.infer<typeof pageViewConfigSchema>;\n","// Tracking ingest client. Queues events, debounce-flushes them to the\n// /tracking/events endpoint, and degrades silently on errors so a broken\n// network never breaks the host site.\n\nimport { getRegisteredCapabilities } from \"./capabilities\";\nimport { getConsentChoice, getConsentState } from \"./consent\";\nimport { resetPageViewState } from \"./page-view\";\nimport type { PhoneConfig } from \"./phone-field\";\nimport { captureFbc, getFbcCookie, getFbpCookie } from \"./fbq\";\nimport {\n captureTrackingParamsFromLocation,\n createEmptyTrackingParams,\n getCookieValueFromDocument,\n getTrackingParamsFromCookieReader,\n mergeTrackingParams,\n} from \"./tracking\";\nimport type { TriggerRegistryConfig } from \"./events/registry\";\nimport { buildHeartbeatMetadata } from \"./heartbeat\";\nimport { buildLandingPayloadFields, getOrCaptureLandingParams } from \"./landing\";\nimport { getOrRotateSessionId, getVisitorId } from \"./session\";\nimport { stashUserDataFromFormFields } from \"./user-data\";\nimport type {\n TrackingClientContext,\n TrackingEnvironment,\n TrackingInstallSurface,\n TrackingParams,\n TrackingSessionUpsertPayload,\n} from \"./types\";\n\n/**\n * Default debounce window before queued events are flushed.\n */\nexport const DEFAULT_FLUSH_INTERVAL_MS = 2000;\n\n/**\n * Default queue size that triggers an immediate flush.\n */\nexport const DEFAULT_MAX_QUEUE_SIZE = 10;\n\n/**\n * Hard server-side maximum event count per request body.\n */\nexport const HARD_MAX_BATCH = 50;\n\n/**\n * Ceiling on the exponential backoff between failed delivery attempts.\n */\nexport const MAX_RETRY_BACKOFF_MS = 60_000;\n\n/**\n * Cap on events held in the durable retry buffer. Oldest batches are dropped\n * first once this is exceeded — an unbounded buffer would eventually blow the\n * localStorage quota and take the whole SDK down with it.\n */\nexport const MAX_BUFFERED_EVENTS = 200;\n\n/**\n * localStorage key prefix for the durable retry buffer. Versioned so a future\n * shape change can't be misread as the current one.\n */\nexport const RETRY_BUFFER_KEY_PREFIX = \"aranova_tracking_pending_v1\";\n\n/**\n * What to do with a batch after an attempted delivery.\n *\n * `retry` covers the transport failing and the server saying \"later\" (408, 429,\n * 5xx). `drop` covers a permanent rejection — a 422 from a malformed payload\n * will never succeed, and retrying it forever would wedge every batch behind it.\n */\ntype DeliveryOutcome = \"ok\" | \"retry\" | \"drop\";\n\n/**\n * Header used to authenticate public tracking ingest requests.\n */\nexport const API_KEY_HEADER = \"X-Aranova-Api-Key\";\n\n/**\n * Identity headers stamped on every ingest request. Duplicate fields already\n * present in `session.context` but survive body-parse failures so the backend\n * can attribute 422s to the offending SDK install.\n */\nexport const SDK_VERSION_HEADER = \"X-Aranova-Sdk-Version\";\nexport const SDK_PACKAGE_HEADER = \"X-Aranova-Sdk-Package\";\nexport const SDK_SURFACE_HEADER = \"X-Aranova-Sdk-Surface\";\nexport const SDK_ENVIRONMENT_HEADER = \"X-Aranova-Sdk-Environment\";\n\n/**\n * Configuration for the low-level ingest client.\n *\n * Framework packages usually create this for you through `createTracking()`.\n */\nexport interface TrackingClientConfig {\n /** Public tracking API key issued for the business. */\n apiKey: string;\n /** Tracking endpoint base URL, usually ending in `/tracking`. */\n endpoint: string;\n /** SDK surface creating this client. */\n surface: TrackingInstallSurface;\n /** Package version reported in session context and heartbeat metadata. */\n sdkVersion?: string;\n /** Package name reported in session context and heartbeat metadata. */\n packageName?: string;\n /** Trigger registry so the heartbeat can report registered events. */\n triggers?: TriggerRegistryConfig;\n /** Override the default 2s debounce window. */\n flushIntervalMs?: number;\n /** Override the default 10-event batch trigger. */\n maxQueueSize?: number;\n /** Deployment environment label reported in session context. */\n environment?: TrackingEnvironment;\n /** All active gtag IDs, keyed by label. Included in session context. */\n activeGtagIds?: Record<string, string>;\n /** When true, swallow nothing — useful for tests. */\n debug?: boolean;\n /** Phone-field config, carried for parity; the React hook reads it via context. */\n phone?: PhoneConfig;\n}\n\n/**\n * Input accepted by the low-level stringly-typed client.\n *\n * Prefer the typed `trackEvent(eventName, metadata)` facade exposed by\n * `useTracking()` in React/Next integrations.\n */\nexport interface TrackEventInput {\n /** Event name to enqueue. */\n eventType: string;\n /** URL associated with the event. Defaults to the current page URL. */\n pageUrl?: string | null;\n /** Event-specific metadata. */\n metadata?: Record<string, unknown> | null;\n /** Timestamp override. Defaults to queue time. */\n occurredAt?: Date | string | null;\n}\n\ninterface QueuedEvent {\n event_type: string;\n page_url: string | null;\n metadata: Record<string, unknown> | null;\n occurred_at: string | null;\n}\n\n/**\n * Low-level tracking client responsible for queueing and flushing events.\n */\nexport interface TrackingClient {\n /** Enqueue an event for batched delivery. */\n trackEvent: (input: TrackEventInput) => void;\n /** Flush queued events immediately (fetch, non-keepalive). */\n flush: () => Promise<void>;\n /**\n * Flush queued events through the keepalive transport so the request\n * survives document unload. Use from `pagehide`/`visibilitychange:hidden`\n * handlers — a plain `flush()` there is aborted by the browser on unload.\n */\n flushBeacon: () => void;\n /** Return the current rolling session id. */\n getSessionId: () => string;\n /** Return the persistent visitor id. */\n getVisitorId: () => string;\n /** Remove timers/listeners and prevent future flushes. */\n destroy: () => void;\n}\n\ninterface IngestRequestBody {\n session: TrackingSessionUpsertPayload;\n events: Array<{\n event_type: string;\n page_url: string | null;\n metadata: Record<string, unknown> | null;\n occurred_at: string | null;\n }>;\n}\n\nfunction buildContext(\n surface: TrackingInstallSurface,\n sdkVersion: string | null,\n packageName: string | null,\n environment: TrackingEnvironment,\n activeGtagIds: Record<string, string> | null,\n): TrackingClientContext {\n return {\n surface,\n sdk_version: sdkVersion,\n package_name: packageName,\n site_origin: typeof window === \"undefined\" ? null : window.location.origin,\n page_title: typeof document === \"undefined\" ? null : document.title || null,\n referrer: typeof document === \"undefined\" ? null : document.referrer || null,\n environment,\n active_gtag_ids: activeGtagIds,\n // Rebuilt per flush (this runs inside the payload builder), so a client\n // constructed later on a deeper route still gets reported.\n capabilities: getRegisteredCapabilities(),\n };\n}\n\nfunction readTrackingParams(): TrackingParams {\n if (typeof window === \"undefined\") return createEmptyTrackingParams();\n // Capture from URL on every read so the first event in a session reflects the\n // landing-page params even if the cookie helper hasn't run yet.\n try {\n captureTrackingParamsFromLocation();\n } catch {\n // ignore\n }\n return getTrackingParamsFromCookieReader(getCookieValueFromDocument);\n}\n\nfunction consentSnapshot(): Record<string, unknown> | null {\n try {\n // Effective consent + provenance so the dashboard can tell default-granted\n // (opt-out model, no interaction) apart from an explicit choice.\n const choice = getConsentChoice();\n return {\n state: choice.state,\n source: choice.source,\n updated_at: choice.updatedAt,\n expires_at: choice.expiresAt,\n };\n } catch {\n return null;\n }\n}\n\ninterface IdentityHeaders {\n sdkVersion: string;\n packageName: string;\n surface: string;\n environment: string;\n}\n\nasync function postWithFetch(\n url: string,\n body: string,\n apiKey: string,\n identity: IdentityHeaders,\n keepalive: boolean,\n): Promise<DeliveryOutcome> {\n // No fetch at all (a non-browser runtime): there is nothing to retry against,\n // and scheduling one would spin a timer forever. Give up on the batch.\n if (typeof fetch !== \"function\") return \"drop\";\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n [API_KEY_HEADER]: apiKey,\n [SDK_VERSION_HEADER]: identity.sdkVersion,\n [SDK_PACKAGE_HEADER]: identity.packageName,\n [SDK_SURFACE_HEADER]: identity.surface,\n [SDK_ENVIRONMENT_HEADER]: identity.environment,\n },\n body,\n keepalive,\n // CORS is open on the tracking endpoint; never send cookies.\n credentials: \"omit\",\n mode: \"cors\",\n });\n if (response.ok) return \"ok\";\n if (response.status === 408 || response.status === 429 || response.status >= 500) {\n return \"retry\";\n }\n // 401/403/422 and friends: the payload or the key is wrong, and will still\n // be wrong in 30 seconds.\n return \"drop\";\n } catch {\n // Network-level failure (offline, DNS, CORS preflight, aborted). Never\n // throws to the host site; the batch stays buffered for the next attempt.\n return \"retry\";\n }\n}\n\n/**\n * A batch awaiting delivery. Each one carries its OWN session snapshot: a batch\n * can outlive the session that produced it (buffered across a reload), and\n * re-sending it under whatever session is current would silently misattribute\n * those events.\n */\ninterface PendingBatch {\n session: TrackingSessionUpsertPayload;\n events: QueuedEvent[];\n}\n\nfunction retryBufferKey(apiKey: string, endpoint: string): string {\n return `${RETRY_BUFFER_KEY_PREFIX}:${apiKey}:${endpoint}`;\n}\n\nfunction readPendingBatches(key: string): PendingBatch[] {\n if (typeof window === \"undefined\") return [];\n try {\n const raw = window.localStorage.getItem(key);\n if (!raw) return [];\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter(\n (entry): entry is PendingBatch =>\n typeof entry === \"object\" &&\n entry !== null &&\n \"session\" in entry &&\n Array.isArray((entry as PendingBatch).events),\n );\n } catch {\n // Storage blocked, or a corrupt/foreign value — start clean rather than\n // letting a bad read break the host site.\n return [];\n }\n}\n\n/**\n * Mirror the buffer to storage unconditionally.\n *\n * Deliberately no read-back verification: under partitioned storage a write can\n * succeed for this document and still not be visible to a verifying read, so a\n * verify-gate false-negatives exactly where durability matters most.\n */\nfunction writePendingBatches(key: string, batches: PendingBatch[]): void {\n if (typeof window === \"undefined\") return;\n try {\n if (batches.length === 0) window.localStorage.removeItem(key);\n else window.localStorage.setItem(key, JSON.stringify(batches));\n } catch {\n // Quota exceeded or storage blocked — in-memory retry still works.\n }\n}\n\n/** Drop the oldest batches until the buffer is back under the event cap. */\nfunction trimToBufferCap(batches: PendingBatch[]): PendingBatch[] {\n let total = batches.reduce((sum, batch) => sum + batch.events.length, 0);\n const trimmed = batches.slice();\n while (total > MAX_BUFFERED_EVENTS && trimmed.length > 1) {\n const dropped = trimmed.shift();\n total -= dropped ? dropped.events.length : 0;\n }\n return trimmed;\n}\n\nlet globalClient: TrackingClient | null = null;\nlet globalClientKey: string | null = null;\n\nfunction clientConfigKey(config: TrackingClientConfig): string {\n return `${config.apiKey}@${config.endpoint}#${config.surface}`;\n}\n\n/**\n * Return a page-level singleton tracking client. Creating the client anew on\n * every component mount is wrong — React StrictMode double-mounts dev-only,\n * and destroying+recreating the client between the cleanup and re-run strips\n * away the pushState patch that SPA auto page view relies on. A singleton\n * survives all of that: the client lives for the entire page, and providers\n * just attach/detach auto page view against it.\n *\n * If `apiKey` / `endpoint` / `surface` change between calls, the previous\n * singleton is destroyed and a new one replaces it. This covers hot-config\n * changes without leaking state.\n */\nexport function getOrCreateTrackingClient(config: TrackingClientConfig): TrackingClient {\n const key = clientConfigKey(config);\n if (globalClient !== null && globalClientKey === key) {\n return globalClient;\n }\n if (globalClient !== null) {\n globalClient.destroy();\n }\n globalClient = createTrackingClient(config);\n globalClientKey = key;\n return globalClient;\n}\n\n// Global/delegated captures (document/window listeners: page_exit, scroll_depth,\n// time_on_site, form_start, cta_click, phone_click, bfcache restore) must attach ONCE\n// per page-singleton client — NOT once per React provider mount. A page can mount several\n// <TrackingProvider>s (a supported island pattern: a global provider for page-level\n// triggers plus per-component providers so `useSearchParams()` doesn't opt the whole tree\n// out of static rendering). Since the client is a singleton but each provider runs its own\n// attach effect, N mounts would stack N document listeners and every interaction would emit\n// its event N times. We ref-count attaches against the singleton client's identity: the\n// first mount attaches, later mounts are no-ops, and the last unmount detaches.\ninterface ClientCaptureEntry {\n detach: () => void;\n refCount: number;\n}\nconst clientCaptureRegistry = new WeakMap<TrackingClient, ClientCaptureEntry>();\n\n/**\n * Attach a set of global/delegated captures against a singleton `client` exactly once,\n * ref-counted across provider mounts. `build` performs the actual `document`/`window`\n * listener attachment and returns a single detacher for all of them; it runs only on the\n * first mount for a given client. The returned release decrements the ref-count and runs\n * `build`'s detacher when the last holder releases. Release is idempotent — React\n * StrictMode invokes an effect's cleanup twice in dev, and a double release must not\n * double-decrement.\n */\nexport function attachClientCapturesOnce(\n client: TrackingClient,\n build: () => () => void,\n): () => void {\n let entry = clientCaptureRegistry.get(client);\n if (entry === undefined) {\n entry = { detach: build(), refCount: 0 };\n clientCaptureRegistry.set(client, entry);\n }\n entry.refCount += 1;\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const current = clientCaptureRegistry.get(client);\n if (current === undefined) return;\n current.refCount -= 1;\n if (current.refCount <= 0) {\n current.detach();\n clientCaptureRegistry.delete(client);\n }\n };\n}\n\n/**\n * Tear down the singleton if any. Primarily an escape hatch for tests where\n * each test should see a fresh client; production code rarely needs this.\n * Also clears the in-session SPA referrer so the next test starts with a\n * fresh referrer chain.\n */\nexport function resetGlobalTrackingClient(): void {\n if (globalClient !== null) {\n // Force-detach any captures still attached to this client so their document/window\n // listeners can't leak into the next test even if a provider didn't unmount.\n const entry = clientCaptureRegistry.get(globalClient);\n if (entry !== undefined) {\n entry.detach();\n clientCaptureRegistry.delete(globalClient);\n }\n globalClient.destroy();\n }\n globalClient = null;\n globalClientKey = null;\n resetPageViewState();\n}\n\n/**\n * Create a low-level ingest client.\n *\n * The client queues events, debounces network flushes, sends an SDK heartbeat\n * once per new session, and swallows network errors so analytics never break\n * the host site.\n */\nexport function createTrackingClient(config: TrackingClientConfig): TrackingClient {\n const flushIntervalMs = config.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;\n const maxQueueSize = Math.min(config.maxQueueSize ?? DEFAULT_MAX_QUEUE_SIZE, HARD_MAX_BATCH);\n const sdkVersion = config.sdkVersion ?? null;\n const packageName = config.packageName ?? null;\n // Default to 'production' so the wire payload always carries a valid enum\n // value. Sending null would fail the backend's strict enum validation.\n const environment: TrackingEnvironment = config.environment ?? \"production\";\n const activeGtagIds = config.activeGtagIds ?? null;\n const endpointBase = config.endpoint.replace(/\\/$/, \"\");\n const eventsUrl = `${endpointBase}/events`;\n const identityHeaders: IdentityHeaders = {\n sdkVersion: sdkVersion ?? \"\",\n packageName: packageName ?? \"\",\n surface: config.surface,\n environment,\n };\n\n let queue: QueuedEvent[] = [];\n let flushTimer: ReturnType<typeof setTimeout> | null = null;\n // Batches that have been handed to the network at least once and not yet\n // acknowledged. Mirrored to localStorage so a reload — or a deploy window that\n // 5xxs every request — costs latency instead of data.\n const bufferKey = retryBufferKey(config.apiKey, endpointBase);\n let pending: PendingBatch[] = readPendingBatches(bufferKey);\n // Flushes are serialized through one chain. Batches are no longer removed from\n // the buffer before the response arrives, so two overlapping flushes would\n // send the same batch twice. Chaining (rather than a \"busy\" flag that returns\n // early) keeps `await flush()` meaning \"flushed\" for the caller.\n let flushChain: Promise<void> = Promise.resolve();\n let retryAttempt = 0;\n let firstPage: string | null = null;\n // Attribution captured synchronously at client creation (before any SPA router\n // can strip the query string). Merged into every session payload as a fallback\n // so a blocked-cookie webview or a stripped URL still attributes.\n let initialParams = createEmptyTrackingParams();\n let destroyed = false;\n\n // Initialize identity early so the first POST has stable values.\n const visitorId = getVisitorId();\n const initialSession = getOrRotateSessionId();\n let sessionId = initialSession.id;\n\n if (typeof window !== \"undefined\") {\n firstPage = window.location.href;\n try {\n initialParams = captureTrackingParamsFromLocation();\n } catch {\n // ignore — never break the host site\n }\n // Pin this session's LANDING params now, before any SPA router strips the\n // query string (reuses the stored record when the session already has one).\n getOrCaptureLandingParams(sessionId);\n try {\n captureFbc();\n } catch {\n // ignore\n }\n }\n\n // Queue an sdk_heartbeat event at the start of every new session.\n function enqueueHeartbeat(): void {\n const metadata = buildHeartbeatMetadata(\n config.surface,\n sdkVersion,\n packageName,\n config.triggers ?? null,\n activeGtagIds,\n );\n queue.push({\n event_type: \"sdk_heartbeat\",\n page_url: typeof window === \"undefined\" ? null : window.location.href,\n metadata: metadata as unknown as Record<string, unknown>,\n occurred_at: new Date().toISOString(),\n });\n }\n\n if (initialSession.isNew) {\n enqueueHeartbeat();\n }\n\n // Anything left buffered by a previous page load goes out on the normal\n // debounce, ahead of whatever this page produces.\n if (pending.length > 0) {\n scheduleFlush();\n }\n\n function buildSessionPayload(): TrackingSessionUpsertPayload {\n const rotated = getOrRotateSessionId();\n if (rotated.isNew && rotated.id !== sessionId) {\n // Session rotated mid-page (idle > 30min then user returned).\n enqueueHeartbeat();\n }\n sessionId = rotated.id;\n // Prefer the live cookie/localStorage read; fall back to the init-time\n // snapshot (covers a webview that blocked the cookie AND a router that\n // already stripped the landing URL by flush time).\n const params = mergeTrackingParams(readTrackingParams(), initialParams);\n const context = buildContext(\n config.surface,\n sdkVersion,\n packageName,\n environment,\n activeGtagIds,\n );\n return {\n session_id: sessionId,\n visitor_id: visitorId,\n gclid: params.gclid,\n wbraid: params.wbraid,\n gbraid: params.gbraid,\n ylpcid: params.ylpcid,\n fbclid: params.fbclid,\n fbc: getFbcCookie(),\n fbp: getFbpCookie(),\n utm_source: params.utm_source,\n utm_medium: params.utm_medium,\n utm_campaign: params.utm_campaign,\n utm_term: params.utm_term,\n utm_content: params.utm_content,\n // Landing params for the CURRENT session id — captured on the spot when\n // the session just rotated (the current URL is the rotated session's\n // landing), reused from the stored record otherwise. Keys are omitted\n // entirely when the landing isn't observable (SSR).\n ...buildLandingPayloadFields(sessionId),\n first_page: firstPage,\n consent_state: consentSnapshot(),\n context,\n };\n }\n\n function scheduleFlush(delayMs: number = flushIntervalMs): void {\n if (flushTimer !== null || destroyed) return;\n flushTimer = setTimeout(() => {\n flushTimer = null;\n void flush();\n }, delayMs);\n }\n\n function clearScheduledFlush(): void {\n if (flushTimer !== null) {\n clearTimeout(flushTimer);\n flushTimer = null;\n }\n }\n\n /** Move everything currently queued into the durable buffer. */\n function bufferQueued(): void {\n if (queue.length === 0) return;\n const events = queue.slice(0, HARD_MAX_BATCH);\n queue = queue.slice(events.length);\n pending = trimToBufferCap([...pending, { session: buildSessionPayload(), events }]);\n writePendingBatches(bufferKey, pending);\n }\n\n /**\n * Drain the durable buffer, oldest batch first.\n *\n * A batch leaves the buffer only on `ok` (acknowledged) or `drop` (permanently\n * rejected). Anything else keeps it, so a 5xx window costs latency, not data.\n *\n * Delivery is at-least-once: with no event-level idempotency key on the wire,\n * a response lost after the server committed will re-send that batch. That\n * window is far narrower than the \"every 5xx is permanent loss\" it replaces —\n * closing it needs a client-generated event id plus a backend uniqueness\n * constraint, which is a schema change and its own release.\n */\n function flush(): Promise<void> {\n // `.catch` keeps one unexpected throw from poisoning every later flush.\n flushChain = flushChain.then(runFlush).catch(() => {});\n return flushChain;\n }\n\n async function runFlush(): Promise<void> {\n if (destroyed) return;\n clearScheduledFlush();\n bufferQueued();\n if (pending.length === 0) return;\n\n try {\n while (pending.length > 0) {\n const batch = pending[0]!;\n const body: IngestRequestBody = { session: batch.session, events: batch.events };\n // keepalive=false: this runs on a live page, where a plain fetch\n // completes normally and its failure is observable. The unload path\n // (flushOnUnload) passes true instead — pagehide tears the document down\n // and aborts a plain fetch mid-flight, while keepalive hands the request\n // to the browser to finish after teardown.\n const outcome = await postWithFetch(\n eventsUrl,\n JSON.stringify(body),\n config.apiKey,\n identityHeaders,\n false,\n );\n if (outcome === \"retry\") {\n retryAttempt += 1;\n // Exponential from the normal flush interval, capped. Scheduling\n // happens after `flushing` is cleared, below.\n return;\n }\n pending = pending.slice(1);\n writePendingBatches(bufferKey, pending);\n retryAttempt = 0;\n }\n } finally {\n if (pending.length > 0) {\n const backoff = Math.min(flushIntervalMs * 2 ** retryAttempt, MAX_RETRY_BACKOFF_MS);\n scheduleFlush(backoff);\n } else if (queue.length > 0) {\n // `bufferQueued` takes at most HARD_MAX_BATCH per pass, so a burst\n // larger than one batch still has events waiting.\n scheduleFlush();\n }\n }\n }\n\n function trackEvent(input: TrackEventInput): void {\n if (destroyed) return;\n if (!input || typeof input.eventType !== \"string\" || input.eventType.length === 0) return;\n\n // Enhanced conversions: a form submit is the one moment the visitor's own\n // email/phone pass through the SDK — stash them (memory only) so the\n // conversion that fires next carries user_data. NOT done for phone_click:\n // its metadata holds the BUSINESS's number, not the visitor's. An explicit\n // consent decline also skips the stash entirely — egress is already gated,\n // but a decliner's identifiers shouldn't sit in page memory either.\n if (input.eventType === \"form_submit\" && getConsentState() !== \"denied\") {\n try {\n const fields = (input.metadata as { form?: { fields?: unknown } } | null)?.form?.fields;\n if (fields) stashUserDataFromFormFields(fields, config.phone?.defaultCountry);\n } catch {\n // user-data capture must never break ingest\n }\n }\n\n const occurredAt =\n input.occurredAt instanceof Date\n ? input.occurredAt.toISOString()\n : typeof input.occurredAt === \"string\"\n ? input.occurredAt\n : new Date().toISOString();\n\n queue.push({\n event_type: input.eventType,\n page_url: input.pageUrl ?? (typeof window === \"undefined\" ? null : window.location.href),\n metadata: input.metadata ?? null,\n occurred_at: occurredAt,\n });\n\n if (queue.length >= maxQueueSize) {\n void flush();\n } else {\n scheduleFlush();\n }\n }\n\n /**\n * Last-gasp send on pagehide/visibilitychange.\n *\n * The keepalive request outlives the document, so its outcome can never be\n * observed. The batch it carries is therefore removed from the buffer\n * optimistically: keeping it would re-send on the next page load every time\n * the send actually worked, which is almost always. Any batch behind it stays\n * buffered and is retried on the next load.\n */\n function flushOnUnload(): void {\n bufferQueued();\n clearScheduledFlush();\n if (pending.length === 0) return;\n\n const batch = pending[0]!;\n pending = pending.slice(1);\n writePendingBatches(bufferKey, pending);\n\n const body: IngestRequestBody = { session: batch.session, events: batch.events };\n void postWithFetch(eventsUrl, JSON.stringify(body), config.apiKey, identityHeaders, true);\n }\n\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"pagehide\", flushOnUnload);\n window.addEventListener(\"visibilitychange\", () => {\n if (document.visibilityState === \"hidden\") flushOnUnload();\n });\n }\n\n return {\n trackEvent,\n flush,\n flushBeacon: flushOnUnload,\n getSessionId: () => sessionId,\n getVisitorId: () => visitorId,\n destroy: () => {\n destroyed = true;\n // Fire any pending events through the keepalive path before tearing\n // down. Critical for React StrictMode in dev, where the provider's\n // first mount is immediately unmounted and its 2s debounce would\n // otherwise drop the initial page_view on the floor. Uses fetch\n // keepalive so the request survives the component tearing down.\n if (queue.length > 0) {\n flushOnUnload();\n }\n clearScheduledFlush();\n queue = [];\n if (typeof window !== \"undefined\") {\n window.removeEventListener(\"pagehide\", flushOnUnload);\n }\n },\n };\n}\n","import { z } from \"zod\";\n\n/**\n * Metadata for a manually fired `cta_click` event.\n *\n * Use this for non-phone calls to action such as directions, appointment\n * buttons, downloads, or external booking links.\n */\nexport const ctaClickMetadataSchema = z\n .object({\n cta_name: z.string(),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n section: z.string().nullable().optional(),\n destination_url: z.string().nullable().optional(),\n // Set by auto-capture (and available to manual callers): the link target\n // and a short element descriptor (tag#id) for tying clicks to specific UI.\n href: z.string().nullable().optional(),\n element: z.string().nullable().optional(),\n })\n .strict();\n\nexport type CtaClickMetadata = z.infer<typeof ctaClickMetadataSchema>;\n\n/**\n * Registration config for `cta_click`.\n *\n * The event stays manually fireable; `autoCapture` additionally attaches a\n * delegated click listener that fires it for any element matching `selector`\n * (default `[data-aranova-cta]`) — tag your CTAs, get analytics for free.\n */\nexport const ctaClickConfigSchema = z\n .object({\n autoCapture: z\n .object({\n selector: z.string().optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\nexport type CtaClickConfig = z.infer<typeof ctaClickConfigSchema>;\n","import { z } from \"zod\";\n\n/**\n * Registered trigger names reported by the SDK heartbeat.\n */\nexport const sdkHeartbeatTriggersSchema = z\n .object({\n automatic: z.array(z.string()),\n manual: z.array(z.string()),\n })\n .strict();\n\n/**\n * Metadata for the SDK-internal `sdk_heartbeat` event.\n *\n * The SDK fires this once per new session so the dashboard can show which SDK\n * version, install surface, and trigger registry a client site is running.\n * Consumers do not manually register or fire this event.\n */\nexport const sdkHeartbeatMetadataSchema = z\n .object({\n sdk_version: z.string(),\n package_name: z.string().nullable(),\n surface: z.enum([\"next\", \"react\", \"script\"]),\n triggers: sdkHeartbeatTriggersSchema,\n trigger_config: z.record(z.string(), z.record(z.string(), z.unknown())).nullable().optional(),\n configured_gtag_ids: z.record(z.string(), z.string()).nullable().optional(),\n })\n .strict();\n\nexport type SdkHeartbeatMetadata = z.infer<typeof sdkHeartbeatMetadataSchema>;\n\n/**\n * Internal registration config for `sdk_heartbeat`.\n *\n * This event has no consumer-facing options.\n */\nexport const sdkHeartbeatConfigSchema = z.object({}).strict();\nexport type SdkHeartbeatConfig = z.infer<typeof sdkHeartbeatConfigSchema>;\n","import { z } from \"zod\";\n\n/**\n * Metadata for the automatic `form_start` event.\n *\n * The SDK emits this once per form when the visitor first focuses a field.\n */\nexport const formStartMetadataSchema = z\n .object({\n form: z\n .object({\n id: z.string(),\n action: z.string().nullable(),\n })\n .strict(),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n })\n .strict();\n\nexport type FormStartMetadata = z.infer<typeof formStartMetadataSchema>;\n\n/**\n * Registration config for automatic `form_start`.\n *\n * Use `selector` to narrow which forms can trigger the event. When omitted,\n * the SDK observes all `<form>` elements.\n */\nexport const formStartConfigSchema = z\n .object({\n selector: z.string().optional(),\n })\n .strict();\n\nexport type FormStartConfig = z.infer<typeof formStartConfigSchema>;\n","import { z } from \"zod\";\n\n// form_submit is manual — the SDK never auto-fires this. Consumer code calls\n// `tracking.trackEvent('form_submit', { form, page })` from their own submit\n// handler. Registering it enables the type-level permission; omitting it\n// turns manual calls into a compile error.\n//\n// The optional `fields` array captures submitted form field metadata and JSON\n// values. Consumers explicitly build the fields array themselves so they\n// control exactly what is sent.\n\n/**\n * JSON-serializable value accepted by `form_submit.fields[].value`.\n *\n * This intentionally excludes `undefined`, functions, symbols, `Date`\n * instances, and non-finite numbers. Values are stored in PostgreSQL JSONB, so\n * consumers should send only data that has a stable JSON representation.\n */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nexport const jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>\n z.union([\n z.string(),\n z.number().finite(),\n z.boolean(),\n z.null(),\n z.array(jsonValueSchema),\n z.record(jsonValueSchema),\n ]),\n);\n\n/**\n * Metadata for a manually fired `form_submit` event.\n *\n * Register the event with `manual: { form_submit: {} }`, then call\n * `trackEvent('form_submit', metadata)` from the host site's submit handler.\n *\n * `fields` is optional. If present, each value must be JSON-serializable. Client\n * integrations may intentionally capture raw submitted lead data (including name,\n * email, phone, address, selections, and free text) for first-party analytics and\n * lead operations. Submitted file data is supported after conversion to a\n * JSON-serializable representation; upload larger files separately and send a storage\n * reference. Never include credentials, authentication tokens, payment-card or bank\n * secrets, or private keys.\n *\n * No byte limit is enforced on this metadata, here or on the server — `fields` and its\n * values are unbounded. Keep inlined payloads small anyway: a submit fired just before\n * navigation flushes over `keepalive`, which browsers cap near 64 KB and drop silently.\n *\n * @example\n * ```ts\n * tracking.trackEvent('form_submit', {\n * form: {\n * id: 'lead-form',\n * action: '/api/lead',\n * fields: [\n * {\n * name: 'service_interest',\n * type: 'select',\n * label: 'Service interest',\n * value: 'teeth_whitening',\n * },\n * ],\n * },\n * page: { path: window.location.pathname },\n * });\n * ```\n */\nexport const formSubmitMetadataSchema = z\n .object({\n form: z\n .object({\n id: z.string(),\n action: z.string().nullable(),\n fields: z\n .array(\n z\n .object({\n name: z.string(),\n type: z.string(),\n label: z.string().nullable(),\n value: jsonValueSchema,\n })\n .strict(),\n )\n .optional(),\n })\n .strict(),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n })\n .strict();\n\nexport type FormSubmitMetadata = z.infer<typeof formSubmitMetadataSchema>;\n\n/**\n * Registration config for `form_submit`.\n *\n * This event is manual-only and currently has no registration options. The\n * empty object enables typed `trackEvent('form_submit', ...)` calls.\n */\nexport const formSubmitConfigSchema = z.object({}).strict();\nexport type FormSubmitConfig = z.infer<typeof formSubmitConfigSchema>;\n","import { z } from \"zod\";\n\n/**\n * Metadata for the automatic `multi_page_session` event.\n *\n * Fired when the visitor reaches the configured distinct-page threshold in a\n * single tracking session.\n */\nexport const multiPageSessionMetadataSchema = z\n .object({\n page_count: z.number().int().min(2),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n })\n .strict();\n\nexport type MultiPageSessionMetadata = z.infer<typeof multiPageSessionMetadataSchema>;\n\n/**\n * Registration config for automatic `multi_page_session`.\n */\nexport const multiPageSessionConfigSchema = z\n .object({\n pageThreshold: z.number().int().min(2),\n })\n .strict();\n\nexport type MultiPageSessionConfig = z.infer<typeof multiPageSessionConfigSchema>;\n","import { z } from \"zod\";\n\n/**\n * Metadata for the automatic `page_exit` event.\n *\n * Fired when the user leaves a page (SPA navigation away, tab hidden, or\n * pagehide). `dwell_ms` is the ACTIVE (visible) time spent on the page segment\n * being closed — hidden time never counts, matching `time_on_site` semantics.\n * A page revisited after being hidden emits another `page_exit` for the next\n * visible segment, so summing `dwell_ms` per page/session yields total active\n * dwell without double counting.\n */\nexport const pageExitMetadataSchema = z\n .object({\n dwell_ms: z.number().int().min(0),\n // null = left without any scroll signal; floor is 0 so a valid 0% is never\n // rejected (a single bad field 422s the whole keepalive beacon batch).\n max_scroll_percent: z.number().int().min(0).max(100).nullable(),\n // The gating baseline: the fraction of the page visible at load with\n // zero scrolling — or, for pages that grew after the post-paint snapshot\n // (skeleton/streaming renders), the first-scroll position that\n // established it. null = page had no scrollable range, or the segment\n // ended before the snapshot. `.optional()` is load-bearing: SDK builds\n // predating this field keep POSTing page_exit without the key —\n // requiring it would 422 whole keepalive beacon batches.\n scroll_baseline_percent: z.number().int().min(0).max(100).nullable().optional(),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n })\n .strict();\n\nexport type PageExitMetadata = z.infer<typeof pageExitMetadataSchema>;\n\n/**\n * Registration config for automatic `page_exit`.\n *\n * SDK-internal: attached unconditionally (like `sdk_heartbeat`), so there are\n * no registration options.\n */\nexport const pageExitConfigSchema = z.object({}).strict();\nexport type PageExitConfig = z.infer<typeof pageExitConfigSchema>;\n","import { z } from \"zod\";\n\n/**\n * Metadata for a manually fired `phone_click` event.\n *\n * `phone_number` should be the business phone number from the clicked `tel:`\n * link, not a visitor-entered phone number. `section` can distinguish header,\n * footer, hero, or contact-page links.\n */\nexport const phoneClickMetadataSchema = z\n .object({\n phone_number: z.string(),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n section: z.string().nullable().optional(),\n })\n .strict();\n\nexport type PhoneClickMetadata = z.infer<typeof phoneClickMetadataSchema>;\n\n/**\n * Registration config for `phone_click`.\n *\n * The event stays manually fireable; `autoCapture` additionally attaches a\n * delegated click listener that fires it for any `tel:` link matching\n * `selector` (default `a[href^=\"tel:\"]`) — link your phone number, get the\n * analytics event (and, for a linked phone-click goal, the conversion) for free.\n */\nexport const phoneClickConfigSchema = z\n .object({\n autoCapture: z\n .object({\n selector: z.string().optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\nexport type PhoneClickConfig = z.infer<typeof phoneClickConfigSchema>;\n","import { z } from \"zod\";\n\n/**\n * Metadata for the automatic `scroll_depth` event.\n *\n * Fired once per configured threshold per page.\n */\nexport const scrollDepthMetadataSchema = z\n .object({\n depth_percent: z.number().int().min(1).max(100),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n })\n .strict();\n\nexport type ScrollDepthMetadata = z.infer<typeof scrollDepthMetadataSchema>;\n\n/**\n * Registration config for automatic `scroll_depth`.\n *\n * `thresholds` are integer percentages from 1 to 100.\n */\nexport const scrollDepthConfigSchema = z\n .object({\n thresholds: z.array(z.number().int().min(1).max(100)).min(1),\n })\n .strict();\n\nexport type ScrollDepthConfig = z.infer<typeof scrollDepthConfigSchema>;\n","import { z } from \"zod\";\n\nexport const PAGE_IDENTITY_MAX_LENGTH = 64;\nexport const PAGE_IDENTITY_PATTERN = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;\n\n/** Common page identities offered as presets by operator tooling. */\nexport const SPECIFIC_PAGE_NAMES = [\n \"contact_page\",\n \"about_page\",\n \"services_page\",\n \"booking_page\",\n \"location_page\",\n \"pricing_page\",\n \"faq_page\",\n \"testimonials_page\",\n] as const;\n\nexport const pageIdentitySchema = z\n .string()\n .max(PAGE_IDENTITY_MAX_LENGTH)\n .regex(PAGE_IDENTITY_PATTERN, {\n message:\n \"page identity must be lowercase snake_case, start with a letter, and contain at most 64 characters\",\n });\n\nexport type PageIdentity = z.infer<typeof pageIdentitySchema>;\n\n/** @deprecated Use PageIdentity. Kept as a compatibility alias for existing consumers. */\nexport type SpecificPageName = PageIdentity;\n\n/** @deprecated Use pageIdentitySchema. Kept for source compatibility. */\nexport const specificPageNameSchema = pageIdentitySchema;\n\n/**\n * Metadata for the automatic `specific_page_visit` event.\n *\n * The SDK emits this when the current pathname matches one of the configured\n * named page patterns.\n */\nexport const specificPageVisitMetadataSchema = z\n .object({\n page_name: specificPageNameSchema,\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n })\n .strict();\n\nexport type SpecificPageVisitMetadata = z.infer<typeof specificPageVisitMetadataSchema>;\n\n/**\n * Registration config for automatic `specific_page_visit`.\n *\n * Each page entry pairs a stable, validated identity with a `RegExp` that\n * matches the pathname. The identity can use a preset above or a client-specific\n * lowercase snake-case slug.\n */\nexport const specificPageVisitConfigSchema = z\n .object({\n pages: z\n .array(\n z\n .object({\n name: specificPageNameSchema,\n pathPattern: z.custom<RegExp>((value) => value instanceof RegExp, {\n message: \"pathPattern must be a RegExp\",\n }),\n })\n .strict(),\n )\n .min(1),\n })\n .strict();\n\nexport type SpecificPageVisitConfig = z.infer<typeof specificPageVisitConfigSchema>;\n","import { z } from \"zod\";\n\n/**\n * Metadata for the automatic `time_on_site` event.\n *\n * The SDK starts a visibility-aware timer and fires once when visible\n * engagement crosses the configured threshold.\n */\nexport const timeOnSiteMetadataSchema = z\n .object({\n duration_ms: z.number().int().nonnegative(),\n page: z\n .object({\n path: z.string(),\n })\n .strict(),\n })\n .strict();\n\nexport type TimeOnSiteMetadata = z.infer<typeof timeOnSiteMetadataSchema>;\n\n/**\n * Registration config for automatic `time_on_site`.\n */\nexport const timeOnSiteConfigSchema = z\n .object({\n thresholdSeconds: z.number().int().positive(),\n })\n .strict();\nexport type TimeOnSiteConfig = z.infer<typeof timeOnSiteConfigSchema>;\n","export type EventOutcomeRole = \"lead\" | \"engagement\" | \"navigation\" | \"diagnostic\";\nexport type EventCategory = \"page\" | \"engagement\" | \"lead\" | \"commerce\" | \"system\";\nexport type EventClientVisibility = \"simple\" | \"detailed\" | \"hidden\";\n\nexport interface EventSemantics {\n label: string;\n category: EventCategory;\n outcomeRole: EventOutcomeRole;\n clientVisibility: EventClientVisibility;\n}\n\n/**\n * Lightweight runtime event metadata. This module intentionally imports no\n * Zod schemas so dashboards and framework adapters can consume it without\n * pulling the validation registry into their bundles.\n */\nexport const EVENT_SEMANTICS = {\n page_view: {\n label: \"Page view\",\n category: \"page\",\n outcomeRole: \"navigation\",\n clientVisibility: \"simple\",\n },\n time_on_site: {\n label: \"Time on site\",\n category: \"engagement\",\n outcomeRole: \"engagement\",\n clientVisibility: \"detailed\",\n },\n specific_page_visit: {\n label: \"Key page visit\",\n category: \"engagement\",\n outcomeRole: \"engagement\",\n clientVisibility: \"detailed\",\n },\n scroll_depth: {\n label: \"Scroll depth\",\n category: \"engagement\",\n outcomeRole: \"engagement\",\n clientVisibility: \"detailed\",\n },\n multi_page_session: {\n label: \"Multi-page session\",\n category: \"engagement\",\n outcomeRole: \"engagement\",\n clientVisibility: \"detailed\",\n },\n form_start: {\n label: \"Form started\",\n category: \"engagement\",\n outcomeRole: \"engagement\",\n clientVisibility: \"simple\",\n },\n sdk_heartbeat: {\n label: \"SDK heartbeat\",\n category: \"system\",\n outcomeRole: \"diagnostic\",\n clientVisibility: \"hidden\",\n },\n page_exit: {\n label: \"Page exit\",\n category: \"engagement\",\n outcomeRole: \"diagnostic\",\n clientVisibility: \"detailed\",\n },\n form_submit: {\n label: \"Form submitted\",\n category: \"lead\",\n outcomeRole: \"lead\",\n clientVisibility: \"simple\",\n },\n phone_click: {\n label: \"Phone click\",\n category: \"lead\",\n outcomeRole: \"lead\",\n clientVisibility: \"simple\",\n },\n cta_click: {\n label: \"CTA click\",\n category: \"engagement\",\n outcomeRole: \"engagement\",\n clientVisibility: \"simple\",\n },\n} as const satisfies Record<string, EventSemantics>;\n\nexport type EventName = keyof typeof EVENT_SEMANTICS;\n\nexport function getEventSemantics(eventName: string): EventSemantics | null {\n return eventName in EVENT_SEMANTICS ? EVENT_SEMANTICS[eventName as EventName] : null;\n}\n","import type { z } from \"zod\";\n\nimport {\n ctaClickConfigSchema,\n ctaClickMetadataSchema,\n type CtaClickConfig,\n type CtaClickMetadata,\n} from \"./cta-click\";\nimport {\n sdkHeartbeatConfigSchema,\n sdkHeartbeatMetadataSchema,\n type SdkHeartbeatConfig,\n type SdkHeartbeatMetadata,\n} from \"./sdk-heartbeat\";\nimport {\n formStartConfigSchema,\n formStartMetadataSchema,\n type FormStartConfig,\n type FormStartMetadata,\n} from \"./form-start\";\nimport {\n formSubmitConfigSchema,\n formSubmitMetadataSchema,\n type FormSubmitConfig,\n type FormSubmitMetadata,\n} from \"./form-submit\";\nimport {\n multiPageSessionConfigSchema,\n multiPageSessionMetadataSchema,\n type MultiPageSessionConfig,\n type MultiPageSessionMetadata,\n} from \"./multi-page-session\";\nimport {\n pageExitConfigSchema,\n pageExitMetadataSchema,\n type PageExitConfig,\n type PageExitMetadata,\n} from \"./page-exit\";\nimport {\n pageViewConfigSchema,\n pageViewMetadataSchema,\n type PageViewConfig,\n type PageViewMetadata,\n} from \"./page-view\";\nimport {\n phoneClickConfigSchema,\n phoneClickMetadataSchema,\n type PhoneClickConfig,\n type PhoneClickMetadata,\n} from \"./phone-click\";\nimport {\n scrollDepthConfigSchema,\n scrollDepthMetadataSchema,\n type ScrollDepthConfig,\n type ScrollDepthMetadata,\n} from \"./scroll-depth\";\nimport {\n specificPageVisitConfigSchema,\n specificPageVisitMetadataSchema,\n type SpecificPageVisitConfig,\n type SpecificPageVisitMetadata,\n} from \"./specific-page-visit\";\nimport {\n timeOnSiteConfigSchema,\n timeOnSiteMetadataSchema,\n type TimeOnSiteConfig,\n type TimeOnSiteMetadata,\n} from \"./time-on-site\";\nimport { EVENT_SEMANTICS, type EventName, type EventSemantics } from \"./semantics\";\n\nexport { EVENT_SEMANTICS, getEventSemantics } from \"./semantics\";\nexport type {\n EventCategory,\n EventClientVisibility,\n EventName,\n EventOutcomeRole,\n EventSemantics,\n} from \"./semantics\";\n\n// Event kind — automatic events are fired by the SDK itself when their\n// client-side signal fires (page_view on navigation, time_on_site on timer,\n// etc). Manual events are only fireable via explicit consumer code.\nexport type EventKind = \"automatic\" | \"manual\";\n\n// The registry is the single client-side source of truth for \"what events\n// exist, what shape does their metadata take, and what kind are they\". The\n// backend mirror lives in apps/api/src/schemas/tracking_events.py and is\n// kept in sync via the drift test in apps/api/tests/test_event_schema_drift.py.\nexport const EVENT_REGISTRY = {\n // --- automatic triggers ---\n page_view: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.page_view,\n metadataSchema: pageViewMetadataSchema,\n configSchema: pageViewConfigSchema,\n },\n time_on_site: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.time_on_site,\n metadataSchema: timeOnSiteMetadataSchema,\n configSchema: timeOnSiteConfigSchema,\n },\n specific_page_visit: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.specific_page_visit,\n metadataSchema: specificPageVisitMetadataSchema,\n configSchema: specificPageVisitConfigSchema,\n },\n scroll_depth: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.scroll_depth,\n metadataSchema: scrollDepthMetadataSchema,\n configSchema: scrollDepthConfigSchema,\n },\n multi_page_session: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.multi_page_session,\n metadataSchema: multiPageSessionMetadataSchema,\n configSchema: multiPageSessionConfigSchema,\n },\n form_start: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.form_start,\n metadataSchema: formStartMetadataSchema,\n configSchema: formStartConfigSchema,\n },\n // --- SDK-internal automatic (not consumer-configurable) ---\n sdk_heartbeat: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.sdk_heartbeat,\n metadataSchema: sdkHeartbeatMetadataSchema,\n configSchema: sdkHeartbeatConfigSchema,\n },\n page_exit: {\n kind: \"automatic\",\n semantics: EVENT_SEMANTICS.page_exit,\n metadataSchema: pageExitMetadataSchema,\n configSchema: pageExitConfigSchema,\n },\n // --- manual triggers ---\n form_submit: {\n kind: \"manual\",\n semantics: EVENT_SEMANTICS.form_submit,\n metadataSchema: formSubmitMetadataSchema,\n configSchema: formSubmitConfigSchema,\n },\n phone_click: {\n kind: \"manual\",\n semantics: EVENT_SEMANTICS.phone_click,\n metadataSchema: phoneClickMetadataSchema,\n configSchema: phoneClickConfigSchema,\n },\n cta_click: {\n kind: \"manual\",\n semantics: EVENT_SEMANTICS.cta_click,\n metadataSchema: ctaClickMetadataSchema,\n configSchema: ctaClickConfigSchema,\n },\n} as const satisfies Record<\n EventName,\n {\n kind: EventKind;\n semantics: EventSemantics;\n metadataSchema: z.ZodTypeAny;\n configSchema: z.ZodTypeAny;\n }\n>;\n\n/**\n * Event names that are fired by the SDK when their configured signal occurs.\n *\n * Automatic events are not accepted by the typed `trackEvent()` API.\n */\nexport type AutomaticEventName = {\n [K in EventName]: (typeof EVENT_REGISTRY)[K][\"kind\"] extends \"automatic\" ? K : never;\n}[EventName];\n\n/**\n * Event names that consumer code can fire manually after registering them.\n */\nexport type ManualEventName = {\n [K in EventName]: (typeof EVENT_REGISTRY)[K][\"kind\"] extends \"manual\" ? K : never;\n}[EventName];\n\n// Map an event name to its explicit metadata / config TS type. We pull the\n// inferred types directly from the per-event files rather than deriving\n// via `z.infer<typeof EVENT_REGISTRY[K]['metadataSchema']>` so that error\n// messages name the event-specific type (PageViewMetadata, not an\n// anonymous zod inference).\ntype MetadataByName = {\n page_view: PageViewMetadata;\n time_on_site: TimeOnSiteMetadata;\n specific_page_visit: SpecificPageVisitMetadata;\n scroll_depth: ScrollDepthMetadata;\n multi_page_session: MultiPageSessionMetadata;\n form_start: FormStartMetadata;\n sdk_heartbeat: SdkHeartbeatMetadata;\n page_exit: PageExitMetadata;\n form_submit: FormSubmitMetadata;\n phone_click: PhoneClickMetadata;\n cta_click: CtaClickMetadata;\n};\n\ntype ConfigByName = {\n page_view: PageViewConfig;\n time_on_site: TimeOnSiteConfig;\n specific_page_visit: SpecificPageVisitConfig;\n scroll_depth: ScrollDepthConfig;\n multi_page_session: MultiPageSessionConfig;\n form_start: FormStartConfig;\n sdk_heartbeat: SdkHeartbeatConfig;\n page_exit: PageExitConfig;\n form_submit: FormSubmitConfig;\n phone_click: PhoneClickConfig;\n cta_click: CtaClickConfig;\n};\n\n/**\n * Metadata payload type for a specific tracking event.\n *\n * @example\n * ```ts\n * type SubmitMetadata = EventMetadata<'form_submit'>;\n * ```\n */\nexport type EventMetadata<K extends EventName> = MetadataByName[K];\n\n/**\n * Trigger registration config type for a specific tracking event.\n */\nexport type EventConfig<K extends EventName> = ConfigByName[K];\n\n// Runtime constant arrays for iteration at consumer / factory time.\n/**\n * Runtime list of automatic event names.\n */\nexport const ALL_AUTOMATIC_EVENT_NAMES: readonly AutomaticEventName[] = (\n Object.entries(EVENT_REGISTRY) as Array<[EventName, (typeof EVENT_REGISTRY)[EventName]]>\n)\n .filter(([, def]) => def.kind === \"automatic\")\n .map(([name]) => name) as AutomaticEventName[];\n\n/**\n * Runtime list of manual event names.\n */\nexport const ALL_MANUAL_EVENT_NAMES: readonly ManualEventName[] = (\n Object.entries(EVENT_REGISTRY) as Array<[EventName, (typeof EVENT_REGISTRY)[EventName]]>\n)\n .filter(([, def]) => def.kind === \"manual\")\n .map(([name]) => name) as ManualEventName[];\n\n/**\n * Events that represent a lead/outcome in first-party tracking projections.\n */\nexport const ALL_LEAD_EVENT_NAMES: readonly EventName[] = (\n Object.entries(EVENT_REGISTRY) as Array<[EventName, (typeof EVENT_REGISTRY)[EventName]]>\n)\n .filter(([, def]) => def.semantics.outcomeRole === \"lead\")\n .map(([name]) => name);\n\n/**\n * Trigger registry passed to `createTracking({ triggers })`.\n *\n * `automatic.page_view` is required because every install should capture page\n * views. Other automatic events are opt-in. Manual events must be registered\n * here before the typed client accepts `trackEvent()` calls for them.\n *\n * @example\n * ```ts\n * createTracking({\n * apiKey,\n * endpoint,\n * triggers: {\n * automatic: {\n * page_view: {},\n * time_on_site: { thresholdSeconds: 60 },\n * },\n * manual: {\n * form_submit: {},\n * phone_click: {},\n * },\n * },\n * });\n * ```\n */\nexport type TriggerRegistryConfig = {\n automatic: {\n page_view: EventConfig<\"page_view\">;\n } & Partial<{\n time_on_site: EventConfig<\"time_on_site\">;\n specific_page_visit: EventConfig<\"specific_page_visit\">;\n scroll_depth: EventConfig<\"scroll_depth\">;\n multi_page_session: EventConfig<\"multi_page_session\">;\n form_start: EventConfig<\"form_start\">;\n }>;\n manual?: Partial<{\n form_submit: EventConfig<\"form_submit\">;\n phone_click: EventConfig<\"phone_click\">;\n cta_click: EventConfig<\"cta_click\">;\n }>;\n};\n\n/**\n * Manual event names registered in a concrete trigger registry.\n *\n * Used by `TypedTrackingClient` so `trackEvent()` only accepts events the\n * consumer explicitly enabled.\n */\nexport type RegisteredManualEvents<TRegistry extends TriggerRegistryConfig> = Extract<\n keyof NonNullable<TRegistry[\"manual\"]>,\n ManualEventName\n>;\n\n/**\n * Automatic event names registered in a concrete trigger registry.\n */\nexport type RegisteredAutomaticEvents<TRegistry extends TriggerRegistryConfig> = Extract<\n keyof TRegistry[\"automatic\"],\n AutomaticEventName\n>;\n\n/**\n * Discriminated union of valid manual tracking calls for a registry.\n */\nexport type TrackableEvent<TRegistry extends TriggerRegistryConfig> = {\n [K in RegisteredManualEvents<TRegistry>]: {\n eventType: K;\n metadata: EventMetadata<K>;\n };\n}[RegisteredManualEvents<TRegistry>];\n\n// Runtime helper: look up a schema pair by name. Cast through `unknown`\n// because the registry is `as const` and TS loses the specific schema type\n// when indexing via a dynamic key.\nexport function getEventDefinition(name: EventName): {\n kind: EventKind;\n semantics: EventSemantics;\n metadataSchema: z.ZodTypeAny;\n configSchema: z.ZodTypeAny;\n} {\n return EVENT_REGISTRY[name] as unknown as {\n kind: EventKind;\n semantics: EventSemantics;\n metadataSchema: z.ZodTypeAny;\n configSchema: z.ZodTypeAny;\n };\n}\n","/**\n * Thrown on a non-2xx from any awaited Aranova API call.\n *\n * Lives here rather than inside one resource because more than one resource\n * needs it, and a duplicate class would be a genuine hazard: a name star-exported\n * from two modules is silently dropped unless both resolve to the same binding.\n */\nexport class AranovaApiError extends Error {\n readonly status: number;\n readonly code: string | undefined;\n readonly requestId: string | undefined;\n\n constructor(message: string, options: { status: number; code?: string; requestId?: string }) {\n super(message);\n this.name = \"AranovaApiError\";\n this.status = options.status;\n this.code = options.code;\n this.requestId = options.requestId;\n }\n}\n","import {\n API_KEY_HEADER,\n SDK_ENVIRONMENT_HEADER,\n SDK_PACKAGE_HEADER,\n SDK_SURFACE_HEADER,\n SDK_VERSION_HEADER,\n} from \"../../ingest\";\nimport { AranovaApiError } from \"./errors\";\n\n/** Shared config for every awaited (non fire-and-forget) API helper. */\nexport interface ApiTransportConfig {\n /** Public (`aranv_pk_…`) or secret (`aranv_sk_…`) API key. */\n apiKey: string;\n /** Base tracking endpoint, e.g. `https://aranovainternal-production.up.railway.app/tracking`. */\n endpoint: string;\n /** Optional SDK identity headers (mirrors the event ingest client). */\n sdkVersion?: string;\n packageName?: string;\n surface?: string;\n environment?: string;\n}\n\nfunction identityHeaders(config: ApiTransportConfig): Record<string, string> {\n const headers: Record<string, string> = { [API_KEY_HEADER]: config.apiKey };\n if (config.sdkVersion) headers[SDK_VERSION_HEADER] = config.sdkVersion;\n if (config.packageName) headers[SDK_PACKAGE_HEADER] = config.packageName;\n if (config.surface) headers[SDK_SURFACE_HEADER] = config.surface;\n if (config.environment) headers[SDK_ENVIRONMENT_HEADER] = config.environment;\n return headers;\n}\n\nfunction joinUrl(endpoint: string, path: string): string {\n return `${endpoint.replace(/\\/$/, \"\")}${path}`;\n}\n\n/**\n * Single awaited request. Unlike the event queue, this surfaces failures: any\n * non-2xx rejects with an {@link AranovaApiError}. Returns `undefined` for 204.\n */\nexport async function apiRequest<T>(\n config: ApiTransportConfig,\n method: string,\n path: string,\n body?: unknown,\n extraHeaders?: Record<string, string>,\n): Promise<T> {\n const headers = { ...identityHeaders(config), ...extraHeaders };\n if (body !== undefined) headers[\"Content-Type\"] = \"application/json\";\n\n const response = await fetch(joinUrl(config.endpoint, path), {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n\n if (!response.ok) {\n let detail: string | undefined;\n let code: string | undefined;\n try {\n const parsed: unknown = await response.json();\n if (parsed && typeof parsed === \"object\") {\n const record = parsed as Record<string, unknown>;\n if (typeof record.detail === \"string\") detail = record.detail;\n if (typeof record.code === \"string\") code = record.code;\n }\n } catch {\n // non-JSON error body — fall back to status text\n }\n throw new AranovaApiError(detail ?? response.statusText ?? \"Request failed\", {\n status: response.status,\n code,\n requestId: response.headers.get(\"x-request-id\") ?? undefined,\n });\n }\n\n if (response.status === 204) return undefined as T;\n return (await response.json()) as T;\n}\n","// Hoisted to `resources/http/request`. Both names below are public API via\n// `sales-public.ts`, so they keep their original spellings.\nimport type { ApiTransportConfig } from \"../http/request\";\nimport { apiRequest } from \"../http/request\";\n\nexport type SalesTransportConfig = ApiTransportConfig;\nexport const salesRequest = apiRequest;\n","import type {\n BusinessConfig,\n CustomerGetOptions,\n CustomerGetResult,\n CustomerKpis,\n CustomerListPage,\n CustomerListQuery,\n CustomerSummaryQuery,\n Sale,\n SaleCursorPage,\n SaleInput,\n SaleListQueryV2,\n SaleSummaryQueryV2,\n SaleSummaryV2,\n SaleUpdateInput,\n SupportedCurrency,\n} from \"./schema\";\nimport { registerCapability } from \"../../capabilities\";\nimport type { ConversionConfigStore } from \"../conversion-config\";\nimport { fireConversionWithConsent } from \"../conversion-firing\";\nimport type { TrackingConfigRuntime } from \"../tracking-config-runtime\";\nimport { getConsentState } from \"../../consent\";\nimport { stashUserData, type ConversionUserData } from \"../../user-data\";\nimport { salesRequest, type SalesTransportConfig } from \"./transport\";\nimport { fromMinor } from \"./money\";\n\n/** Config for {@link createSalesClient}. */\nexport interface SalesClientConfig extends SalesTransportConfig {\n /** Applied when an individual `record()` call omits `currency`. */\n defaultCurrency?: SupportedCurrency;\n /**\n * GAP28: when present, `record()` ALSO fires a real-time on-site conversion\n * (`gtag('event','conversion')`) for any recorded service that has a `firing` send_to in\n * the resolved config. Consent-gated + de-duped; no-ops server-side. Wire it from\n * `resolveConversionConfig(...)`.\n */\n firing?: Pick<ConversionConfigStore, \"getFiring\"> | TrackingConfigRuntime;\n}\n\n// Fire the on-site conversion(s) for a just-recorded sale. Per-service value = the sale's\n// amount when present, else the action's configured default from config (Google applies\n// its own default when neither is sent). transaction_id ties the gtag fire to the sale so\n// retries/reloads de-dup within the WEBPAGE action.\nfunction fireRecordedConversions(\n firing: Pick<ConversionConfigStore, \"getFiring\"> | TrackingConfigRuntime | undefined,\n input: {\n external_id?: string | null;\n amount_total_cents?: number | null;\n customer_email?: string | null;\n customer_phone?: string | null;\n },\n recorded: { service?: string | null; amount_cents: number | null }[],\n sale: Sale,\n currency: SupportedCurrency,\n): void {\n if (!firing) return;\n // Enhanced conversions: the sale's own customer identifiers are the\n // strongest possible user_data signal — pass them into every per-service\n // fire, and refresh the stash so later same-page event-goal fires match too.\n const userData: ConversionUserData | null =\n input.customer_email || input.customer_phone\n ? { email: input.customer_email ?? null, phone: input.customer_phone ?? null }\n : null;\n // Denied consent: the fires below no-op anyway, so don't retain the\n // identifiers in page memory either.\n if (userData && getConsentState() !== \"denied\") stashUserData(userData);\n const txnBase = input.external_id ?? sale.id;\n for (const item of recorded) {\n if (!item.service) continue;\n if (\"fireConversion\" in firing) {\n firing.fireConversion(item.service, {\n value: item.amount_cents != null ? fromMinor(item.amount_cents, currency) : undefined,\n currency,\n transactionId: `${txnBase}:${item.service}`,\n });\n continue;\n }\n const config = firing.getFiring(item.service);\n if (!config) continue;\n const cents = item.amount_cents ?? config.value_cents ?? null;\n fireConversionWithConsent(\n {\n sendTo: config.send_to,\n value: cents != null ? fromMinor(cents, currency) : null,\n currency: config.currency ?? currency,\n transactionId: `${txnBase}:${item.service}`,\n },\n { userData },\n );\n }\n}\n\n/** Phone-keyed customer rollups (sk-only; a public key gets a `403`). */\nexport interface SalesCustomersClient {\n list(query?: CustomerListQuery): Promise<CustomerListPage>;\n /** `id` is the customer's E.164 phone. */\n get(id: string, options?: CustomerGetOptions): Promise<CustomerGetResult>;\n summary(query?: CustomerSummaryQuery): Promise<CustomerKpis>;\n}\n\n/** Business config (low-sensitivity — accepts a public or secret key). */\nexport interface SalesBusinessClient {\n config(): Promise<BusinessConfig>;\n}\n\n/**\n * One isomorphic sales client — what a key may *do* is enforced by the backend,\n * not by hiding methods. A **public** key (`aranv_pk_…`) may `record` (the\n * backend rejects reads/CRUD from it with a `403`); a **secret** key\n * (`aranv_sk_…`), used **server-side only**, gets full read/list/update/delete.\n * Never ship a secret key in a browser bundle.\n *\n * Generic over the service-key union `TService` and the manual-conversion key union\n * `TConversion`: bind the types emitted by `@aranova/tracking-cli gen` (`AranovaService`\n * and `AranovaConversion`) for compile-time-checked `service` / `trackConversion` keys.\n */\nexport interface SalesClient<\n TService extends string = string,\n TConversion extends string = string,\n> {\n record(\n input: Omit<SaleInput, \"currency\" | \"occurred_at\" | \"service\" | \"services\"> & {\n service?: TService | null;\n // XOR with `service`: record multiple services in one sale, each priced\n // individually. `amount_total_cents` is then optional (the backend derives\n // it as the sum). Keys are checked against the codegen `TService` union.\n services?: Array<{ service: TService; amount_cents: number }>;\n currency?: SupportedCurrency;\n occurred_at?: string;\n },\n ): Promise<Sale>;\n /**\n * Record a revenue sale — the intent-revealing alias of {@link record}. Identical\n * behavior (same function reference): POSTs `/sales` and fires the on-site conversion\n * when the sale-goal is WEBPAGE-mapped. Use either for real revenue; use\n * {@link trackConversion} for a non-revenue on-page event.\n */\n recordSale(\n input: Omit<SaleInput, \"currency\" | \"occurred_at\" | \"service\" | \"services\"> & {\n service?: TService | null;\n services?: Array<{ service: TService; amount_cents: number }>;\n currency?: SupportedCurrency;\n occurred_at?: string;\n },\n ): Promise<Sale>;\n /**\n * Fire ONLY the on-site conversion for an event-goal `key` — for MANUAL event-goals\n * (`form_submit`, `phone_click`, `cta_click`) the consumer triggers explicitly. No `/sales`\n * write. No-ops when the goal isn't WEBPAGE-mapped (no resolved `send_to`) or the config\n * isn't wired. Consent-gated + de-duped. (Automatic event-goals fire themselves — no call.)\n */\n trackConversion(\n key: TConversion,\n options?: {\n transactionId?: string | null;\n value?: number | null;\n currency?: SupportedCurrency;\n /**\n * Enhanced conversions override: the visitor's own email/phone for this\n * conversion. Wins per-key over the automatic form-submit stash — the\n * escape hatch when a form's fields defeat the extraction heuristics.\n */\n userData?: ConversionUserData | null;\n },\n ): void;\n /** Keyset list with optional server sort + opt-in `total_count`. */\n list(query?: SaleListQueryV2): Promise<SaleCursorPage>;\n /**\n * Currency-grouped aggregations for the key's business. Additive v2 options:\n * calendar/custom ranges, IANA `timezone`, `granularity`, and `compare_to`.\n * Legacy `24h/7d/30d` keep their exact prior numbers. Secret key only.\n */\n summary(query: SaleSummaryQueryV2): Promise<SaleSummaryV2>;\n get(id: string): Promise<Sale>;\n update(\n id: string,\n patch: Omit<SaleUpdateInput, \"service\" | \"services\"> & {\n service?: TService | null;\n // Present ⇒ replaces the whole service set (XOR with `service`); the\n // backend recomputes `amount_total_cents` from the sum.\n services?: Array<{ service: TService; amount_cents: number }>;\n },\n ): Promise<Sale>;\n delete(id: string): Promise<void>;\n /** Phone-keyed customer rollups (sk-only). */\n customers: SalesCustomersClient;\n /** Business config (pk or sk). */\n business: SalesBusinessClient;\n}\n\nexport function createSalesClient<\n TService extends string = string,\n TConversion extends string = string,\n>(config: SalesClientConfig): SalesClient<TService, TConversion> {\n // `firing` is what makes trackConversion do anything at all — without it the\n // method returns immediately, so its presence IS the manual-goal capability.\n // The sales LEDGER verbs are not reported: they are moving to the internal\n // app and are not a client-site capability.\n if (config.firing) registerCapability(\"conversion_goals_manual\");\n\n type RecordInput = Parameters<SalesClient<TService, TConversion>[\"record\"]>[0];\n\n async function record(input: RecordInput): Promise<Sale> {\n const currency = input.currency ?? config.defaultCurrency;\n if (!currency) {\n throw new Error(\n \"record: `currency` is required (pass it on the sale or set config.defaultCurrency)\",\n );\n }\n const body: SaleInput = {\n ...input,\n currency,\n occurred_at: input.occurred_at ?? new Date().toISOString(),\n };\n const sale = await salesRequest<Sale>(config, \"POST\", \"/sales\", body);\n // GAP28: fire the real-time on-site conversion(s) AFTER the sale is recorded, so the\n // gtag transaction_id and the offline path agree. Never throws (best-effort fire).\n const recorded = input.services?.length\n ? input.services.map((s) => ({\n service: s.service,\n amount_cents: s.amount_cents,\n }))\n : [\n {\n service: input.service,\n amount_cents: input.amount_total_cents ?? null,\n },\n ];\n fireRecordedConversions(config.firing, input, recorded, sale, currency);\n return sale;\n }\n\n return {\n record,\n // recordSale is the intent-revealing alias — same behavior, clearer call site.\n recordSale: record,\n\n trackConversion(key, options) {\n // Manual event-goal: fire the WEBPAGE conversion only (no /sales). No-op when the goal\n // isn't WEBPAGE-mapped or the config isn't wired.\n if (config.firing && \"fireConversion\" in config.firing) {\n // Enhanced conversions on the runtime path: the drain fires gtag\n // itself, reading user_data from the stash — persist the explicit\n // override there so it isn't lost to the queue.\n if (options?.userData && getConsentState() !== \"denied\") stashUserData(options.userData);\n config.firing.fireConversion(key, {\n value: options?.value ?? undefined,\n currency: options?.currency ?? config.defaultCurrency ?? undefined,\n transactionId: options?.transactionId ?? null,\n });\n return;\n }\n const firing = config.firing?.getFiring(key);\n if (!firing) return;\n const currency = firing.currency ?? options?.currency ?? config.defaultCurrency ?? null;\n const cents = firing.value_cents ?? null;\n const value =\n options?.value ??\n (cents != null && currency ? fromMinor(cents, currency as SupportedCurrency) : null);\n fireConversionWithConsent(\n {\n sendTo: firing.send_to,\n value,\n currency,\n transactionId: options?.transactionId ?? null,\n },\n { userData: options?.userData },\n );\n },\n\n async list(query) {\n // Pagination + sort travel at the top level; everything else is a filter.\n const { cursor, limit, sort, order, want_total, ...filters } = query ?? {};\n return salesRequest<SaleCursorPage>(config, \"POST\", \"/sales/query\", {\n filters,\n ...(limit !== undefined ? { limit } : {}),\n ...(cursor !== undefined ? { cursor } : {}),\n ...(sort !== undefined ? { sort } : {}),\n ...(order !== undefined ? { order } : {}),\n ...(want_total !== undefined ? { want_total } : {}),\n });\n },\n\n async summary(query) {\n const {\n range,\n include_categories,\n include_deleted_services,\n top_n,\n since,\n until,\n timezone,\n granularity,\n compare_to,\n ...filters\n } = query;\n return salesRequest<SaleSummaryV2>(config, \"POST\", \"/sales/summary\", {\n filters,\n ...(range !== undefined ? { range } : {}),\n ...(include_categories !== undefined ? { include_categories } : {}),\n ...(include_deleted_services !== undefined ? { include_deleted_services } : {}),\n ...(top_n !== undefined ? { top_n } : {}),\n ...(since !== undefined ? { since } : {}),\n ...(until !== undefined ? { until } : {}),\n ...(timezone !== undefined ? { timezone } : {}),\n ...(granularity !== undefined ? { granularity } : {}),\n ...(compare_to !== undefined ? { compare_to } : {}),\n });\n },\n\n async get(id) {\n return salesRequest<Sale>(config, \"GET\", `/sales/${id}`);\n },\n\n async update(id, patch) {\n return salesRequest<Sale>(config, \"PATCH\", `/sales/${id}`, patch);\n },\n\n async delete(id) {\n await salesRequest<void>(config, \"DELETE\", `/sales/${id}`);\n },\n\n customers: {\n async list(query) {\n const { segment, sort, order, cursor, limit, want_total, ...filters } = query ?? {};\n return salesRequest<CustomerListPage>(config, \"POST\", \"/customers/query\", {\n filters,\n ...(segment !== undefined ? { segment } : {}),\n ...(sort !== undefined ? { sort } : {}),\n ...(order !== undefined ? { order } : {}),\n ...(cursor !== undefined ? { cursor } : {}),\n ...(limit !== undefined ? { limit } : {}),\n ...(want_total !== undefined ? { want_total } : {}),\n });\n },\n async get(id, options) {\n const params = new URLSearchParams();\n if (options?.include_sales !== undefined)\n params.set(\"include_sales\", String(options.include_sales));\n if (options?.limit !== undefined) params.set(\"limit\", String(options.limit));\n if (options?.cursor != null) params.set(\"cursor\", options.cursor);\n const qs = params.toString();\n // `id` is the E.164 phone (`+1…`) — must be URL-encoded.\n return salesRequest<CustomerGetResult>(\n config,\n \"GET\",\n `/customers/${encodeURIComponent(id)}${qs ? `?${qs}` : \"\"}`,\n );\n },\n async summary(query) {\n const { range, since, until, timezone, compare_to, ...filters } = query ?? {};\n return salesRequest<CustomerKpis>(config, \"POST\", \"/customers/summary\", {\n filters,\n ...(range !== undefined ? { range } : {}),\n ...(since !== undefined ? { since } : {}),\n ...(until !== undefined ? { until } : {}),\n ...(timezone !== undefined ? { timezone } : {}),\n ...(compare_to !== undefined ? { compare_to } : {}),\n });\n },\n },\n\n business: {\n async config() {\n return salesRequest<BusinessConfig>(config, \"GET\", \"/business/config\");\n },\n },\n };\n}\n","import { z } from \"zod\";\n\n/**\n * Sales / Conversions wire schemas — the client-side source of truth.\n *\n * `saleCreateSchema` is mirrored by `SaleCreateSchema` in\n * `apps/api/src/schemas/tracking_sales.py` and enforced by the backend drift\n * test (the `resources` section of `events.schema.json`). Keep them in lockstep.\n *\n * Money is **integer minor units (cents)**; `quantity` is a decimal string;\n * `currency` is the required `SupportedCurrency` enum.\n */\n\nexport const SUPPORTED_CURRENCIES = [\"USD\", \"CAD\"] as const;\nexport type SupportedCurrency = (typeof SUPPORTED_CURRENCIES)[number];\n\nconst TRACKING_ENVIRONMENTS = [\"production\", \"development\"] as const;\n\nconst currencySchema = z.enum(SUPPORTED_CURRENCIES);\nconst centsSchema = z.number().int().nonnegative();\nconst quantitySchema = z.string().regex(/^\\d+(\\.\\d{1,3})?$/);\n// Free-form JSON object — the sale's extensibility escape hatch. Mirrors the\n// Pydantic `dict[str, Any]` (`additionalProperties: true`) on the wire.\nconst metadataSchema = z.record(z.unknown());\n\nexport const saleItemSchema = z\n .object({\n external_item_id: z.string().nullable().optional(),\n name: z.string().nullable().optional(),\n category: z.string().nullable().optional(),\n quantity: quantitySchema,\n unit_price_cents: centsSchema,\n // Non-negativity validated on the wire — same contract as the other cents\n // fields — and backstopped by the DB CHECK.\n unit_cost_cents: centsSchema.nullable().optional(),\n })\n .strict();\n\n// One service covered by a sale, at its own price. `service` is the per-business\n// service key, validated against the taxonomy by the backend at write time.\nexport const saleServiceSchema = z\n .object({\n service: z.string(),\n amount_cents: centsSchema,\n })\n .strict();\n\n// Raw customer identity. Stored as-is on the backend for human display in\n// dashboards; hashing happens at writeback-upload time in the future Google\n// Ads reconciliation worker (see docs/tracking-package/conversion-writeback.md).\n// The SDK never hashes — pass values straight through.\nconst customerNameSchema = z.string().max(200);\nconst customerPhoneSchema = z.string().max(64);\nconst customerEmailSchema = z.string().max(320).email();\n\n// The singular `service` (priced by `amount_total_cents`) and the plural\n// `services` (each priced individually) are mutually exclusive. When `services`\n// is present, `amount_total_cents` is optional and the backend derives it as the\n// sum; otherwise it is required. Shared by create + update.\nfunction refineServiceXor(\n val: {\n service?: string | null;\n services?: ReadonlyArray<{ service: string; amount_cents: number }> | null;\n amount_total_cents?: number | null;\n },\n ctx: z.RefinementCtx,\n { requireAmount }: { requireAmount: boolean },\n): void {\n if (val.services != null) {\n if (val.service != null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"pass either `service` or `services`, not both\",\n path: [\"services\"],\n });\n }\n if (val.services.length === 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"`services` must not be empty\",\n path: [\"services\"],\n });\n }\n const keys = val.services.map((s) => s.service);\n if (new Set(keys).size !== keys.length) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"`services` must not list the same service more than once\",\n path: [\"services\"],\n });\n }\n if (val.amount_total_cents != null) {\n const sum = val.services.reduce((acc, s) => acc + s.amount_cents, 0);\n if (val.amount_total_cents !== sum) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message:\n \"amount_total_cents must equal the sum of the services amounts \" +\n \"(omit it to derive it automatically)\",\n path: [\"amount_total_cents\"],\n });\n }\n }\n } else if (requireAmount && val.amount_total_cents == null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"amount_total_cents is required unless `services` is provided\",\n path: [\"amount_total_cents\"],\n });\n }\n}\n\nexport const saleCreateSchema = z\n .object({\n external_id: z.string().nullable().optional(),\n description: z.string().nullable().optional(),\n service: z.string().nullable().optional(),\n services: z.array(saleServiceSchema).nullable().optional(),\n currency: currencySchema,\n // Optional only because the plural `services` form derives it from the sum\n // (see refineServiceXor); the singular/serviceless path still requires it.\n amount_total_cents: centsSchema.nullable().optional(),\n occurred_at: z.string().datetime(),\n environment: z.enum(TRACKING_ENVIRONMENTS).default(\"production\"),\n items: z.array(saleItemSchema).default([]),\n metadata: metadataSchema.nullable().optional(),\n customer_name: customerNameSchema.nullable().optional(),\n customer_phone: customerPhoneSchema.nullable().optional(),\n customer_email: customerEmailSchema.nullable().optional(),\n // CASL consent attestation: the customer agreed to receive SMS. Recorded\n // with a timestamp server-side; every SMS send path gates on it.\n //\n // Tri-state: omit it (or send null) to let the server apply the business's\n // configured default-opt-in policy, honouring a returning customer's\n // remembered preference. Send an explicit boolean to assert consent state\n // yourself — `false` records a deliberate opt-out.\n sms_consent: z.boolean().nullable().optional(),\n })\n .strict()\n .superRefine((val, ctx) => refineServiceXor(val, ctx, { requireAmount: true }));\n\nexport const saleUpdateSchema = z\n .object({\n description: z.string().nullable().optional(),\n service: z.string().nullable().optional(),\n services: z.array(saleServiceSchema).nullable().optional(),\n currency: currencySchema.optional(),\n amount_total_cents: centsSchema.optional(),\n occurred_at: z.string().datetime().optional(),\n items: z.array(saleItemSchema).optional(),\n metadata: metadataSchema.nullable().optional(),\n customer_name: customerNameSchema.nullable().optional(),\n // Re-attest when changing a filler-looking name; the server clears the\n // prior attestation whenever `customer_name` changes.\n customer_name_placeholder_confirmed: z.boolean().optional(),\n customer_phone: customerPhoneSchema.nullable().optional(),\n customer_email: customerEmailSchema.nullable().optional(),\n // NOT NULL server-side: omit to leave unchanged (explicit null is rejected).\n sms_consent: z.boolean().optional(),\n })\n .strict()\n .superRefine((val, ctx) => refineServiceXor(val, ctx, { requireAmount: false }));\n\nexport type SaleItemInput = z.input<typeof saleItemSchema>;\nexport type SaleServiceInput = z.input<typeof saleServiceSchema>;\n// Use the INPUT type so fields with Zod defaults (environment, items) and\n// occurred_at are optional for callers — the sales client fills them in.\nexport type SaleInput = z.input<typeof saleCreateSchema>;\nexport type SaleUpdateInput = z.input<typeof saleUpdateSchema>;\n\n// ---------------------------------------------------------------------------\n// Read shapes (server responses; not validated on the client)\n// ---------------------------------------------------------------------------\n\nexport interface SaleItem {\n id: string;\n external_item_id: string | null;\n name: string | null;\n category: string | null;\n quantity: string;\n unit_price_cents: number;\n unit_cost_cents: number | null;\n}\n\nexport interface SaleService {\n id: string;\n service_id: string;\n service_key: string;\n service_label: string;\n amount_cents: number;\n}\n\nexport interface Sale {\n id: string;\n business_id: string;\n business_name?: string | null;\n external_id: string | null;\n currency: SupportedCurrency;\n amount_total_cents: number;\n description: string | null;\n // Singular service fields are populated only for single-service sales (kept\n // for backwards compatibility); `services` is always the full set.\n service_id: string | null;\n service_key?: string | null;\n service_label?: string | null;\n services: SaleService[];\n occurred_at: string;\n environment: (typeof TRACKING_ENVIRONMENTS)[number];\n metadata: Record<string, unknown> | null;\n customer_name: string | null;\n /** Operator attestation that a filler-looking `customer_name` is genuine. */\n customer_name_placeholder_confirmed: boolean;\n /** Server timestamp for when the name attestation was recorded. */\n customer_name_placeholder_confirmed_at: string | null;\n customer_phone: string | null;\n customer_email: string | null;\n /** CASL consent attestation stored on the sale; SMS send paths gate on it server-side. */\n sms_consent: boolean;\n /** Server timestamp for when the consent attestation was recorded. */\n sms_consent_granted_at: string | null;\n created_at: string;\n updated_at: string;\n items: SaleItem[];\n}\n\n/**\n * The offset page shape returned by the internal admin list, which this client\n * never calls (`list()` is keyset and returns {@link SaleCursorPage}).\n *\n * @deprecated Unused by this client — no verb returns or accepts it. Kept for one release; removed in the next major.\n */\nexport interface SaleListPage {\n items: Sale[];\n total: number;\n}\n\nexport interface SaleCursorPage {\n items: Sale[];\n next_cursor: string | null;\n /** Populated only when `want_total` was requested (a single indexed COUNT). */\n total_count?: number;\n has_more?: boolean;\n}\n\n/**\n * Sortable columns on the internal admin (offset) list. `list()` is typed to\n * {@link SaleKeysetSortField}, which omits `customer_name` and `business_name`.\n *\n * @deprecated Unused by this client — no verb returns or accepts it. Kept for one release; removed in the next major.\n */\nexport type SaleSortField =\n | \"occurred_at\"\n | \"created_at\"\n | \"amount_total_cents\"\n | \"customer_name\"\n | \"business_name\";\n\nexport type SaleSortOrder = \"asc\" | \"desc\";\n\n/**\n * Comprehensive filter shape mirrored from the backend's `SaleQueryFilters`.\n *\n * `search` runs case-insensitively across `customer_name`, `customer_phone`,\n * `customer_email`, `description`, and `external_id` — the human-facing\n * columns. `service_id` is the resolved per-business service UUID (different\n * from the create-time `service` *key*).\n */\nexport interface SaleFilters {\n business_id?: string;\n external_id?: string;\n service_id?: string;\n /** E.164 phone — the canonical customer key; filters sales for one customer. */\n customer_phone?: string;\n currency?: SupportedCurrency;\n environment?: (typeof TRACKING_ENVIRONMENTS)[number];\n since?: string;\n until?: string;\n min_amount_cents?: number;\n max_amount_cents?: number;\n search?: string;\n}\n\n/**\n * Full query input for `SalesClient.list()` — filters + pagination.\n *\n * Pagination is **keyset (cursor)**: `next_cursor` returned by one page is\n * passed back as `cursor` on the next. `null` / undefined cursor = first page.\n *\n * Ordering is selectable via `sort`/`order` on {@link SaleListQueryV2}. A cursor\n * encodes a position under the sort it was minted with, so replaying it under a\n * different sort is rejected (422) — page with the sort you started with.\n */\n/**\n * @deprecated Superseded by {@link SaleListQueryV2}, which is what `list()` accepts.\n * Its ordering note was also stale — `sort`/`order` are supported. Removed in the next major.\n */\nexport interface SaleListQuery extends SaleFilters {\n limit?: number;\n cursor?: string | null;\n}\n\n/** Keyset-safe sort columns (NOT-NULL, indexed). */\nexport type SaleKeysetSortField = \"occurred_at\" | \"created_at\" | \"amount_total_cents\";\n\n/** v2 list query — adds server sort + opt-in total. */\nexport interface SaleListQueryV2 extends SaleListQuery {\n sort?: SaleKeysetSortField;\n order?: SaleSortOrder;\n /** Opt-in: a single indexed COUNT over the filtered set. */\n want_total?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Sales summary (aggregations). Read by `SalesClient.summary()`. Every monetary\n// figure is grouped **by currency** — USD and CAD cents are never summed into a\n// single total. Money stays integer cents; only `quantity` is a decimal string.\n// ---------------------------------------------------------------------------\n\nexport const TRACKING_RANGES = [\"24h\", \"7d\", \"30d\"] as const;\nexport type TrackingOverviewRange = (typeof TRACKING_RANGES)[number];\n\n/** Query input for `SalesClient.summary()` — filters + range + options. */\n/**\n * @deprecated The v1 summary query. `summary()` accepts {@link SaleSummaryQueryV2};\n * the v1 endpoint no longer exists. Removed in the next major.\n */\nexport interface SaleSummaryQuery extends SaleFilters {\n range: TrackingOverviewRange;\n /** Include the per-category line-item breakdown (extra join; default false). */\n include_categories?: boolean;\n /** Surface soft-deleted services individually (flagged \"(deleted)\") instead of\n * rolling them into a single \"Deleted services\" bucket. Default false. */\n include_deleted_services?: boolean;\n /** Cap on the by-service / by-category rows (1–50, default 10). */\n top_n?: number;\n}\n\nexport interface CurrencyRevenue {\n currency: SupportedCurrency;\n sale_count: number;\n revenue_cents: number;\n average_order_value_cents: number;\n}\n\nexport interface SalesServiceBreakdown {\n service_id: string | null;\n service_key: string | null;\n /** \"Unassigned\" when the sale has no service. */\n service_label: string | null;\n currency: SupportedCurrency;\n sale_count: number;\n revenue_cents: number;\n}\n\nexport interface SalesCategoryBreakdown {\n category: string | null;\n currency: SupportedCurrency;\n /** sum(unit_price_cents * quantity) — advisory, not authoritative. */\n revenue_cents: number;\n /** Decimal string. */\n quantity: string;\n}\n\nexport interface SalesTrendPoint {\n bucket_start: string;\n currency: SupportedCurrency;\n sale_count: number;\n revenue_cents: number;\n}\n\n/**\n * @deprecated The v1 summary response. `summary()` returns {@link SaleSummaryV2};\n * the v1 endpoint no longer exists. Removed in the next major.\n */\nexport interface SaleSummary {\n range: TrackingOverviewRange;\n business_id: string | null;\n metrics: {\n sale_count: number;\n distinct_customers: number;\n by_currency: CurrencyRevenue[];\n };\n by_service: SalesServiceBreakdown[];\n by_currency: CurrencyRevenue[];\n by_category: SalesCategoryBreakdown[];\n series: SalesTrendPoint[];\n}\n\n// ---------------------------------------------------------------------------\n// v2 dashboard surface (additive, back-compat). Reads only → plain interfaces,\n// not drift-checked. Legacy `24h/7d/30d` callers get the same numbers; new\n// ranges/options layer on tz-correct calendar windows + comparisons.\n// ---------------------------------------------------------------------------\n\nexport const NAMED_RANGES = [\n \"today\",\n \"yesterday\",\n \"wtd\",\n \"mtd\",\n \"qtd\",\n \"ytd\",\n \"24h\",\n \"7d\",\n \"30d\",\n \"90d\",\n \"custom\",\n] as const;\n/** Superset of `TrackingOverviewRange` (`24h`/`7d`/`30d` stay valid). */\nexport type NamedRange = (typeof NAMED_RANGES)[number];\nexport type Granularity = \"hour\" | \"day\" | \"week\" | \"month\" | \"auto\";\nexport type CompareTo = \"previous_period\" | \"previous_year\" | \"none\";\n\nexport interface DistinctCustomersByCurrency {\n currency: SupportedCurrency;\n distinct_customers: number;\n}\n\nexport interface SummaryWindow {\n since: string;\n until: string;\n}\n\nexport interface SummaryCurrencyDelta {\n currency: SupportedCurrency;\n revenue_cents_delta: number;\n /** Ratio (0.12 = +12%); null when previous revenue was 0. */\n revenue_pct_delta: number | null;\n sale_count_delta: number;\n}\n\nexport interface SummaryDeltas {\n by_currency: SummaryCurrencyDelta[];\n sale_count_delta: number;\n distinct_customers_delta: number;\n}\n\nexport interface SaleSummaryPrevious {\n window: SummaryWindow;\n metrics: SaleSummaryV2[\"metrics\"];\n by_currency: CurrencyRevenue[];\n series: SalesTrendPoint[];\n}\n\n/** Query input for `SalesClient.summary()` v2 — widened range + tz/compare options. */\nexport interface SaleSummaryQueryV2 extends SaleFilters {\n range?: NamedRange;\n /** Required when `range === 'custom'`. */\n since?: string;\n until?: string;\n /** IANA tz, e.g. `America/Toronto`. Default = business tz. */\n timezone?: string;\n granularity?: Granularity;\n compare_to?: CompareTo;\n include_categories?: boolean;\n include_deleted_services?: boolean;\n top_n?: number;\n}\n\n/** Superset of `SaleSummary` (assignable to it). */\nexport interface SaleSummaryV2 extends Omit<SaleSummary, \"range\" | \"metrics\"> {\n range: NamedRange;\n metrics: SaleSummary[\"metrics\"] & {\n distinct_customers_by_currency: DistinctCustomersByCurrency[];\n };\n timezone: string | null;\n window: SummaryWindow | null;\n granularity: string | null;\n previous: SaleSummaryPrevious | null;\n deltas: SummaryDeltas | null;\n}\n\n// ---------------------------------------------------------------------------\n// Customers — phone-keyed (a customer IS their E.164 phone). `customer_id` is\n// the E.164 string. Money is per-currency, never summed.\n// ---------------------------------------------------------------------------\n\nexport type CustomerSegment = \"new\" | \"returning\" | \"repeat\" | \"lapsed\";\nexport type CustomerSortField = \"total_spent\" | \"last_purchase\" | \"purchases\" | \"first_purchase\";\n\nexport interface CustomerCurrencyTotal {\n currency: SupportedCurrency;\n revenue_cents: number;\n sale_count: number;\n average_order_value_cents: number;\n}\n\nexport interface CustomerSummary {\n /** The E.164 phone — the canonical customer id. */\n customer_id: string;\n display_name: string | null;\n email: string | null;\n phone: string;\n first_purchase_at: string;\n last_purchase_at: string;\n purchase_count: number;\n segment: CustomerSegment;\n totals: CustomerCurrencyTotal[];\n}\n\nexport type CustomerProfile = CustomerSummary;\n\nexport interface CustomerListQuery extends Omit<SaleFilters, \"external_id\"> {\n segment?: CustomerSegment;\n sort?: CustomerSortField;\n order?: SaleSortOrder;\n cursor?: string | null;\n limit?: number;\n want_total?: boolean;\n}\n\nexport interface CustomerListPage {\n items: CustomerSummary[];\n next_cursor: string | null;\n total_count: number | null;\n}\n\nexport interface CustomerGetOptions {\n include_sales?: boolean;\n limit?: number;\n cursor?: string | null;\n}\n\nexport interface CustomerGetResult {\n customer: CustomerProfile;\n /** Present only when `include_sales: true` (and a business-scoped key). */\n sales?: SaleCursorPage | null;\n}\n\nexport interface CustomerSummaryQuery extends SaleFilters {\n range?: NamedRange;\n since?: string;\n until?: string;\n timezone?: string;\n compare_to?: CompareTo;\n}\n\nexport interface CustomerSegmentCount {\n segment: CustomerSegment;\n count: number;\n}\n\nexport interface CustomerCurrencyDelta {\n currency: SupportedCurrency;\n revenue_cents_delta: number;\n /** Ratio (0.12 = +12%); null when previous revenue was 0. */\n revenue_pct_delta: number | null;\n}\n\nexport interface CustomerKpisDeltas {\n total_customers_delta: number;\n new_customers_delta: number;\n returning_customers_delta: number;\n repeat_rate_delta: number;\n ltv_by_currency: CustomerCurrencyDelta[];\n}\n\nexport interface CustomerKpisPrevious {\n window_since: string;\n window_until: string;\n total_customers: number;\n new_customers: number;\n returning_customers: number;\n repeat_rate: number;\n ltv_by_currency: CustomerCurrencyTotal[];\n}\n\nexport interface CustomerKpis {\n range: NamedRange;\n timezone: string;\n window_since: string;\n window_until: string;\n total_customers: number;\n new_customers: number;\n returning_customers: number;\n repeat_rate: number;\n by_segment: CustomerSegmentCount[];\n ltv_by_currency: CustomerCurrencyTotal[];\n /** Present only when `compare_to` is set. */\n previous?: CustomerKpisPrevious | null;\n deltas?: CustomerKpisDeltas | null;\n}\n\n// ---------------------------------------------------------------------------\n// Business config — supersets `fetchServices()`.\n// ---------------------------------------------------------------------------\n\nexport interface BusinessConfigService {\n key: string;\n label: string;\n archived: boolean;\n}\n\nexport interface BusinessConfigFeatures {\n customers: boolean;\n comparisons: boolean;\n retention: boolean;\n}\n\n/** A built-in customer field a business can require on every sale. */\nexport type SaleBuiltinRequirableField =\n | \"customer_name\"\n | \"customer_phone\"\n | \"customer_email\"\n | \"description\";\n\n/** v1 value types. `enum` is single-select over the property's `options`. */\nexport type SalePropertyType = \"string\" | \"number\" | \"boolean\" | \"enum\" | \"date\";\n\nexport interface SalePropertyOption {\n key: string;\n label: string;\n}\n\n/** One custom sale property as the sale form sees it: overrides applied, options\n * already filtered to the business's enabled subset. */\nexport interface EffectiveSaleProperty {\n key: string;\n label: string;\n type: SalePropertyType;\n required: boolean;\n options?: SalePropertyOption[] | null;\n}\n\nexport interface BusinessConfig {\n business_id: string;\n display_name: string;\n timezone: string;\n primary_currency: SupportedCurrency;\n currencies: SupportedCurrency[];\n default_phone_country: string | null;\n services: BusinessConfigService[];\n features: BusinessConfigFeatures;\n // The sale-form contract. Read these BEFORE building a sale form: they say\n // what THIS business requires, so a missing field is a render decision rather\n // than a 422 discovered on write.\n builtin_required: SaleBuiltinRequirableField[];\n properties: EffectiveSaleProperty[];\n /** Whether the form should pre-tick the SMS consent box. A form default only —\n * the per-sale `sms_consent` attestation is what every send path gates on. */\n sms_consent_default_opt_in: boolean;\n}\n","import { salesRequest, type SalesTransportConfig } from \"./sales/transport\";\n\n/** A business's active service, as returned by `GET /tracking/services`. */\nexport interface PublicServiceItem {\n key: string;\n label: string;\n}\n\n/**\n * Fetch the caller's business's active service taxonomy. Accepts a public or\n * secret key (the taxonomy is low-sensitivity category names). Powers the\n * `@aranova/tracking-cli gen` codegen.\n */\nexport async function fetchServices(config: SalesTransportConfig): Promise<PublicServiceItem[]> {\n return salesRequest<PublicServiceItem[]>(config, \"GET\", \"/services\");\n}\n","// Layer 0 (init config) + Layer 3 (tracking integration) for phone fields.\n// Kept in core so both the React and Next packages share identical types, and\n// the `phoneField` helper stays isomorphic.\n\nimport type { JsonValue } from \"./events/form-submit\";\nimport { toE164, type CountryCode, type PhoneDisplayFormat } from \"./phone\";\n\n/**\n * Init-time phone config (`createTracking({ phone })`). The transmitted value is\n * ALWAYS E.164 and is deliberately not configurable here — only display is.\n */\nexport interface PhoneConfig {\n /** Region assumed for numbers typed without a country code. Default `'CA'`. */\n defaultCountry?: CountryCode;\n /** How the input DISPLAYS to the user. Default `'national'`. Does not affect the wire. */\n display?: PhoneDisplayFormat;\n}\n\n/** A single tracked form field destined for `form_submit.fields[]`. */\nexport interface TrackedField {\n name: string;\n type: string;\n value: JsonValue;\n label?: string | null;\n}\n\n/**\n * Build a tracked field whose wire value is ALWAYS E.164. The client keeps its\n * own display value for UI/email; this puts `+E.164` on the wire (or `null` when\n * the input isn't a valid number).\n */\nexport function phoneField(name: string, raw: string, country?: CountryCode): TrackedField {\n return { name, type: \"phone\", value: toE164(raw, country) };\n}\n","// Public entry for @aranova/tracking-next — see docs/tracking-package/installing.md\nexport {\n DEFAULT_DECLINE_TTL_DAYS,\n getConsentChoice,\n getConsentState,\n onConsentChange,\n optIn,\n optOut,\n resetConsent,\n setConsentState,\n type ConsentChoice,\n type ConsentChoiceState,\n type ConsentSource,\n type SetConsentOptions,\n} from \"../../tracking-core/src/index\";\nexport {\n captureTrackingParamsFromLocation,\n createTrackingClientContext,\n createTrackingEventCreatePayload,\n createTrackingSessionUpsertPayload,\n EVENT_SEMANTICS,\n getEventSemantics,\n getTrackingConfigRuntime,\n resolveConversionConfig,\n resolveTrackingConfigUrl,\n TRACKING_PARAM_KEYS,\n} from \"../../tracking-core/src/index\";\n// Enhanced-conversions user_data bridge — automatic via form_submit capture;\n// these are the explicit-control escape hatches (see docs/tracking-package).\nexport {\n clearStashedUserData,\n stashUserData,\n type ConversionUserData,\n} from \"../../tracking-core/src/index\";\n// Event registry type surface — auto-scales as events are added (the runtime\n// registry + zod schemas are intentionally NOT re-exported; tracking-core keeps\n// them off the type-only surface so bundles aren't tainted).\nexport type * from \"../../tracking-core/src/events\";\n// Non-event core types — not in the events barrel, so listed explicitly.\nexport type {\n ConsentState,\n ConversionConfig,\n ConversionConfigStore,\n GtagEnvironmentMap,\n MetaPixelEnvironmentMap,\n TrackingClient,\n TrackingClientContext,\n TrackingEventCreatePayload,\n TrackingInitConfig,\n TrackingInstallSurface,\n TrackingConfigReference,\n TrackingParams,\n TrackingSessionUpsertPayload,\n TypedTrackEventOptions,\n TypedTrackingClient,\n} from \"../../tracking-core/src/index\";\n// The React surface is re-exported from the `./client` entry, NOT from the\n// component files directly. Importing them relatively would let tsup inline\n// them here and strip their `\"use client\"` directive — the bug that made\n// <AdPlatformTracking> unusable in a root layout. See src/client.ts.\n// This keeps the root entry itself server-safe: server code value-imports\n// `toE164` and other React-free helpers from it.\nexport {\n AdPlatformTracking,\n ConsentBanner,\n createTracking,\n GoogleAdsTracking,\n useConsent,\n useConsentState,\n useCookiePreferences,\n useGclid,\n useTrackingParams,\n type AdPlatformTrackingProps,\n type ConsentBannerProps,\n type CreateTrackingOptions,\n type CreateTrackingResult,\n type GoogleAdsTrackingProps,\n type TrackingProviderProps,\n type UseConsentResult,\n type UseCookiePreferencesOptions,\n type UseCookiePreferencesResult,\n} from \"@aranova/tracking-next/client\";\n// Server-only helpers (`createTrackingMiddleware`, `getTrackingParamsServer`)\n// are exposed via the dedicated `@aranova/tracking-next/middleware` and\n// `@aranova/tracking-next/server` subpaths so client bundles never pull in\n// `next/headers` or other server-only modules.\n// Sales — one client for every environment. Construct with a PUBLIC key to write\n// sales from a client component (reads are rejected by the backend with a helpful\n// 403), or a SECRET key in a route handler / server action for full read/CRUD.\n// Browser-safe to import: bundle safety is \"never ship a secret key\", so the\n// client lives on the root entry (not behind `/server`).\n// Sales surface — the SAME composition the `@aranova/tracking-next/sales` entry\n// ships, kept on the root for back-compat. Single source of truth (core's\n// sales-public = sales barrel + services), so a new sales symbol flows to both\n// entries with no allowlist to edit.\nexport * from \"../../tracking-core/src/sales-public\";\n// Calendar: read surface + headless React hooks. Booking WRITES are not here —\n// they need a secret key and live behind `./calendar-server`.\nexport * from \"../../tracking-core/src/calendar-public\";\nexport {\n CalendarClientProvider,\n useBookingForm,\n useCalendarBusy,\n useCalendarClient,\n useSlots,\n} from \"../../tracking-core/src/calendar-react\";\n\n// Phone — isomorphic utils + the React field (hook + component). The pure utils\n// are also available tree-shakeably from `@aranova/tracking-next/phone`.\nexport {\n DEFAULT_PHONE_COUNTRY,\n formatPhone,\n formatPhoneAsTyped,\n parsePhone,\n phoneField,\n toE164,\n} from \"../../tracking-core/src/index\";\nexport type {\n CountryCode,\n ParsedPhone,\n PhoneConfig,\n PhoneDisplayFormat,\n TrackedField,\n} from \"../../tracking-core/src/index\";\nexport {\n PhoneField,\n usePhoneConfig,\n usePhoneField,\n type PhoneFieldApi,\n type PhoneFieldProps,\n type PhoneInputProps,\n type UsePhoneFieldOptions,\n} from \"@aranova/tracking-next/client\";\n","import type { ApiTransportConfig } from \"../http/request\";\nimport { apiRequest } from \"../http/request\";\n\nexport type CalendarTransportConfig = ApiTransportConfig;\n\n/** Prefixes `/calendar` so callers pass resource-relative paths. */\nexport async function calendarRequest<T>(\n config: CalendarTransportConfig,\n method: string,\n path: string,\n body?: unknown,\n): Promise<T> {\n return apiRequest<T>(config, method, `/calendar${path}`, body);\n}\n","import { formatDateInTz } from \"../intl/date\";\n\nexport { formatDateInTz };\n\n/** The visitor's own zone, so a booking page defaults to their local times. */\nexport function resolveBrowserTimeZone(): string {\n try {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n } catch {\n return \"UTC\";\n }\n}\n\n/** Parts of an instant as seen in a specific zone. */\nfunction partsInTz(date: Date, timeZone: string): Record<string, number> {\n const formatter = new Intl.DateTimeFormat(\"en-US\", {\n timeZone,\n hour12: false,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n });\n const out: Record<string, number> = {};\n for (const part of formatter.formatToParts(date)) {\n if (part.type !== \"literal\") out[part.type] = Number(part.value);\n }\n // `hour` comes back as 24 at midnight under hour12:false in some engines.\n if (out.hour === 24) out.hour = 0;\n return out;\n}\n\n/** Offset in minutes between UTC and `timeZone` at a given instant. */\nexport function offsetMinutesAt(date: Date, timeZone: string): number {\n const p = partsInTz(date, timeZone);\n const asUtc = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second);\n return (asUtc - Math.floor(date.getTime() / 1000) * 1000) / 60_000;\n}\n\n/**\n * The instant matching a wall-clock time in `timeZone`.\n *\n * Two passes because the offset itself depends on the instant: guess with the\n * offset at the naive time, then re-solve with the offset that guess landed in.\n * That second pass is what makes DST-transition days come out right.\n */\nexport function instantFromWallClock(\n timeZone: string,\n year: number,\n month: number,\n day: number,\n hour = 0,\n minute = 0,\n): Date {\n const naive = Date.UTC(year, month - 1, day, hour, minute);\n const firstGuess = new Date(naive - offsetMinutesAt(new Date(naive), timeZone) * 60_000);\n const corrected = naive - offsetMinutesAt(firstGuess, timeZone) * 60_000;\n return new Date(corrected);\n}\n\n/** `YYYY-MM-DD` for an instant as seen in `timeZone`. */\nexport function localDateKey(iso: string, timeZone: string): string {\n const p = partsInTz(new Date(iso), timeZone);\n const pad = (n: number) => String(n).padStart(2, \"0\");\n return `${p.year}-${pad(p.month)}-${pad(p.day)}`;\n}\n\nexport function startOfDayInTz(dateKey: string, timeZone: string): Date {\n const [year, month, day] = dateKey.split(\"-\").map(Number);\n return instantFromWallClock(timeZone, year, month, day, 0, 0);\n}\n\nexport function endOfDayInTz(dateKey: string, timeZone: string): Date {\n const start = startOfDayInTz(dateKey, timeZone);\n // Add a calendar day rather than 24h: DST days are 23 or 25 hours long.\n const p = partsInTz(start, timeZone);\n return instantFromWallClock(timeZone, p.year, p.month, p.day + 1, 0, 0);\n}\n\nexport function durationMinutes(startIso: string, endIso: string): number {\n return Math.round((new Date(endIso).getTime() - new Date(startIso).getTime()) / 60_000);\n}\n\n/** `10:00 – 10:30` in the given zone. */\nexport function formatSlotRange(\n startIso: string,\n endIso: string,\n timeZone: string,\n locale?: string,\n): string {\n const opts: Intl.DateTimeFormatOptions = { hour: \"2-digit\", minute: \"2-digit\", timeZone };\n const fmt = new Intl.DateTimeFormat(locale, opts);\n return `${fmt.format(new Date(startIso))} – ${fmt.format(new Date(endIso))}`;\n}\n","import { registerCapability } from \"../../capabilities\";\nimport { AranovaApiError } from \"../http/errors\";\nimport type { BusyResponse, CalendarErrorCode, CalendarSummary } from \"./schema\";\nimport type { CalendarTransportConfig } from \"./transport\";\nimport { calendarRequest } from \"./transport\";\nimport { resolveBrowserTimeZone } from \"./time\";\n\n/**\n * The browser-side calendar client — reads only.\n *\n * There is deliberately no write verb on this type. A public key ships in a JS\n * bundle and its Origin allowlist is a browser-enforced header a script forges\n * trivially; a booking is not a database row but an event on a real person's\n * calendar that mails their contacts. Writes live in\n * `@aranova/tracking-next/calendar-server`, which is `server-only`.\n */\nexport interface CalendarReadClientConfig extends CalendarTransportConfig {\n /** Falls back to the visitor's own zone. */\n defaultTimeZone?: string;\n /** Required when the key is not already scoped to one business. */\n businessId?: string;\n}\n\nexport interface BusyQuery {\n /**\n * ISO 8601 instants WITH an offset — the API rejects a naive or date-only\n * value with a 400. `startOfDayInTz`/`endOfDayInTz` turn a picked date into\n * the right pair for a given zone.\n */\n since: string;\n until: string;\n timeZone?: string;\n}\n\nexport interface CalendarReadClient<TCalendarKey extends string = string> {\n /** Labels, timezones and status — everything a widget needs before booking. */\n listCalendars(): Promise<CalendarSummary[]>;\n /** Busy intervals only. Never the contents of the grantee's events. */\n busy(calendarKey: TCalendarKey, query: BusyQuery): Promise<BusyResponse>;\n}\n\nfunction withBusiness(config: CalendarReadClientConfig, path: string): string {\n if (!config.businessId) return path;\n const separator = path.includes(\"?\") ? \"&\" : \"?\";\n return `${path}${separator}business_id=${encodeURIComponent(config.businessId)}`;\n}\n\nexport function createCalendarReadClient<TCalendarKey extends string = string>(\n config: CalendarReadClientConfig,\n): CalendarReadClient<TCalendarKey> {\n registerCapability(\"calendar_read\");\n return {\n async listCalendars() {\n return calendarRequest<CalendarSummary[]>(config, \"GET\", withBusiness(config, \"/calendars\"));\n },\n async busy(calendarKey, query) {\n const params = new URLSearchParams({\n since: query.since,\n until: query.until,\n });\n const timeZone = query.timeZone ?? config.defaultTimeZone ?? resolveBrowserTimeZone();\n params.set(\"time_zone\", timeZone);\n return calendarRequest<BusyResponse>(\n config,\n \"GET\",\n withBusiness(config, `/${encodeURIComponent(calendarKey)}/busy?${params.toString()}`),\n );\n },\n };\n}\n\n/** Narrow an unknown error to a specific calendar failure code. */\nexport function isCalendarError(\n error: unknown,\n code?: CalendarErrorCode,\n): error is AranovaApiError {\n if (!(error instanceof AranovaApiError)) return false;\n return code === undefined || error.code === code;\n}\n","import { z } from \"zod\";\n\n// Mirrored by `apps/api/src/schemas/tracking_calendar.py` and pinned by the\n// event-schema drift test. Keep both sides in step.\n//\n// The location union is a plain `z.union`, deliberately: a discriminated union\n// emits `oneOf` + discriminator metadata on the Python side and `anyOf` here,\n// which would fail the drift snapshot. Both sides stay plain.\n\n/** Bumped when the durable `metadata` payload changes shape. */\nexport const CALENDAR_METADATA_SCHEMA_VERSION = 1;\n\nexport const MAX_ATTENDEES = 20;\nexport const MAX_REMINDER_OVERRIDES = 5;\n/** Google's ceiling for `reminders.overrides[].minutes`: four weeks. */\nexport const MAX_REMINDER_MINUTES = 40_320;\nexport const MAX_BOOKING_MINUTES = 1_440;\n\nexport const BOOKING_SOURCES = [\"website\", \"phone\", \"walk_in\", \"import\", \"operator\"] as const;\nexport const BOOKING_STATUSES = [\"pending\", \"confirmed\", \"cancelled\", \"no_show\"] as const;\nexport const GOOGLE_SYNC_STATES = [\"queued\", \"synced\", \"uncertain\", \"failed\", \"drifted\"] as const;\nexport const CALENDAR_SYNC_STATUSES = [\n \"pending_invite\",\n \"awaiting_calendar_selection\",\n \"connected\",\n \"needs_reconnect\",\n \"revoked\",\n \"disabled\",\n] as const;\n\n/** Every failure the calendar API can hand back, so a site can branch on it. */\nexport const CALENDAR_ERROR_CODES = [\n \"slot_unavailable\",\n \"calendar_not_connected\",\n \"calendar_disconnected\",\n \"booking_not_found\",\n \"outside_booking_window\",\n \"rate_limited\",\n \"google_error\",\n] as const;\nexport type CalendarErrorCode = (typeof CALENDAR_ERROR_CODES)[number];\n\nexport type BookingStatus = (typeof BOOKING_STATUSES)[number];\nexport type GoogleSyncState = (typeof GOOGLE_SYNC_STATES)[number];\nexport type CalendarSyncStatus = (typeof CALENDAR_SYNC_STATUSES)[number];\nexport type JsonScalar = string | number | boolean | null;\n\nconst isoInstant = z.string().datetime({ offset: true });\n\n/**\n * Does the runtime actually know this zone?\n *\n * `Intl.DateTimeFormat` rather than `Intl.supportedValuesOf(\"timeZone\")`: the\n * latter returns canonical zones only and omits live aliases (`Asia/Calcutta`,\n * `US/Pacific`, `Europe/Kiev`) that the API's `ZoneInfo` accepts. Validating\n * against it would reject values the server stores happily.\n */\nfunction isKnownTimeZone(timeZone: string): boolean {\n try {\n new Intl.DateTimeFormat(undefined, { timeZone });\n return true;\n } catch {\n return false;\n }\n}\n\n// The refinement is invisible to `zod-to-json-schema` — unrepresentable\n// constraints are dropped — so `events.schema.json` and the drift test against\n// the Pydantic mirror are unaffected while both sides gain the real check.\nconst ianaTz = z\n .string()\n .min(1)\n .max(64)\n .regex(/^[A-Za-z0-9_+\\-/]+$/)\n .refine(isKnownTimeZone, { message: \"unknown IANA time zone\" });\n\nexport const bookingAttendeeSchema = z\n .object({\n email: z.string().max(320).email(),\n display_name: z.string().max(200).nullable().optional(),\n optional: z.boolean().default(false),\n })\n .strict();\n\nexport const bookingReminderSchema = z\n .object({\n method: z.enum([\"email\", \"popup\"]),\n minutes_before: z.number().int().min(0).max(MAX_REMINDER_MINUTES),\n })\n .strict();\n\nexport const bookingRemindersSchema = z\n .object({\n use_calendar_defaults: z.boolean().default(true),\n overrides: z.array(bookingReminderSchema).max(MAX_REMINDER_OVERRIDES).default([]),\n })\n .strict();\n\nexport const bookingLocationSchema = z.union([\n z.object({ kind: z.literal(\"google_meet\") }).strict(),\n z.object({ kind: z.literal(\"physical\"), address: z.string().max(1024) }).strict(),\n z.object({ kind: z.literal(\"phone\"), phone: z.string().max(64) }).strict(),\n z.object({ kind: z.literal(\"custom\"), text: z.string().max(1024) }).strict(),\n]);\n\n/**\n * The nullable form, flattened.\n *\n * `bookingLocationSchema.nullable()` would nest one `anyOf` inside another,\n * while Pydantic's `BookingLocation | None` flattens to a single list — the\n * drift snapshot compares structure, so both sides emit the flat shape.\n */\nexport const bookingLocationNullableSchema = z.union([...bookingLocationSchema.options, z.null()]);\n\nexport const bookingCustomerSchema = z\n .object({\n // Required: Google needs an address to send the invite that confirms the\n // booking, and that invite is the whole confirmation mechanism.\n email: z.string().max(320).email(),\n name: z.string().max(200).nullable().optional(),\n phone: z.string().max(64).nullable().optional(),\n sms_consent: z.boolean().default(false),\n })\n .strict();\n\nconst jsonScalar = z.union([z.string(), z.number(), z.boolean(), z.null()]);\n\n/**\n * Named attribution keys plus a flat escape hatch.\n *\n * `custom` is flat and scalar-only on purpose: it mirrors trivially in Pydantic,\n * stays JSONB-queryable, and bounds what a caller can push. Only `custom` is\n * ever mirrored to Google's `extendedProperties`; the named keys stay in our\n * database.\n */\nexport const bookingMetadataSchema = z\n .object({\n schema_version: z.number().int().default(CALENDAR_METADATA_SCHEMA_VERSION),\n source: z.enum(BOOKING_SOURCES).nullable().optional(),\n service: z.string().max(64).nullable().optional(),\n visitor_id: z.string().max(64).nullable().optional(),\n session_id: z.string().max(64).nullable().optional(),\n gclid: z.string().max(256).nullable().optional(),\n fbclid: z.string().max(256).nullable().optional(),\n utm_source: z.string().max(128).nullable().optional(),\n utm_medium: z.string().max(128).nullable().optional(),\n utm_campaign: z.string().max(128).nullable().optional(),\n utm_term: z.string().max(128).nullable().optional(),\n utm_content: z.string().max(128).nullable().optional(),\n landing_page: z.string().max(2048).nullable().optional(),\n referrer: z.string().max(2048).nullable().optional(),\n notes: z.string().max(2000).nullable().optional(),\n custom: z.record(jsonScalar).nullable().optional(),\n })\n .strict();\n\nfunction refineEndXor(\n value: { start_at: string; end_at?: string | null; duration_minutes?: number | null },\n ctx: z.RefinementCtx,\n): void {\n const hasEnd = value.end_at !== undefined && value.end_at !== null;\n const hasDuration = value.duration_minutes !== undefined && value.duration_minutes !== null;\n if (hasEnd === hasDuration) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"provide exactly one of end_at or duration_minutes\",\n path: [\"end_at\"],\n });\n return;\n }\n if (hasEnd && new Date(value.end_at as string) <= new Date(value.start_at)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"end_at must be after start_at\",\n path: [\"end_at\"],\n });\n }\n}\n\nexport const bookingCreateSchema = z\n .object({\n calendar_key: z.string().min(1).max(64),\n // Free-form: appointment types are the client site's own vocabulary, not\n // configuration the dashboard holds.\n appointment_type: z.string().max(64).nullable().optional(),\n start_at: isoInstant,\n end_at: isoInstant.nullable().optional(),\n duration_minutes: z.number().int().positive().max(MAX_BOOKING_MINUTES).nullable().optional(),\n /** The booker's zone — distinct from the business's and the calendar's. */\n time_zone: ianaTz,\n title: z.string().max(300).nullable().optional(),\n description: z.string().max(8000).nullable().optional(),\n location: bookingLocationNullableSchema.optional(),\n customer: bookingCustomerSchema,\n attendees: z.array(bookingAttendeeSchema).max(MAX_ATTENDEES).default([]),\n send_invites: z.boolean().default(true),\n reminders: bookingRemindersSchema.nullable().optional(),\n metadata: bookingMetadataSchema.nullable().optional(),\n idempotency_key: z.string().max(128).nullable().optional(),\n buffer_before_minutes: z.number().int().min(0).max(MAX_BOOKING_MINUTES).default(0),\n buffer_after_minutes: z.number().int().min(0).max(MAX_BOOKING_MINUTES).default(0),\n })\n .strict()\n .superRefine(refineEndXor);\n\nexport const bookingRescheduleSchema = z\n .object({\n start_at: isoInstant,\n end_at: isoInstant.nullable().optional(),\n duration_minutes: z.number().int().positive().max(MAX_BOOKING_MINUTES).nullable().optional(),\n time_zone: ianaTz,\n notify_attendees: z.boolean().default(true),\n reason: z.string().max(500).nullable().optional(),\n })\n .strict()\n .superRefine(refineEndXor);\n\nexport const bookingCancelSchema = z\n .object({\n reason: z.string().max(500).nullable().optional(),\n notify_attendees: z.boolean().default(true),\n })\n .strict();\n\n// `z.input` so Zod defaults stay optional for callers.\nexport type BookingCreateInput = z.input<typeof bookingCreateSchema>;\nexport type BookingRescheduleInput = z.input<typeof bookingRescheduleSchema>;\nexport type BookingCancelInput = z.input<typeof bookingCancelSchema>;\nexport type BookingAttendee = z.input<typeof bookingAttendeeSchema>;\nexport type BookingReminders = z.input<typeof bookingRemindersSchema>;\nexport type BookingLocation = z.input<typeof bookingLocationSchema>;\nexport type BookingCustomer = z.input<typeof bookingCustomerSchema>;\nexport type BookingMetadata<\n TCustom extends Record<string, JsonScalar> = Record<string, JsonScalar>,\n> = Omit<z.input<typeof bookingMetadataSchema>, \"custom\"> & { custom?: TCustom | null };\n\n// ---------------------------------------------------------------------------\n// Read shapes — server responses, trusted and therefore not re-validated here.\n// ---------------------------------------------------------------------------\n\nexport interface CalendarSummary {\n calendar_key: string;\n label: string;\n time_zone: string;\n status: CalendarSyncStatus;\n /** Secret-key only. A public key gets `null`: whose Google account is behind\n * a calendar is a third party's identity, not the client site's business. */\n google_account_email?: string | null;\n granted_scopes?: string[] | null;\n connected_at?: string | null;\n}\n\nexport interface BusyInterval {\n start_at: string;\n end_at: string;\n source: \"google\" | \"booking\";\n}\n\nexport interface BusyResponse {\n calendar_key: string;\n time_zone: string;\n window: { since: string; until: string };\n busy: BusyInterval[];\n generated_at: string;\n}\n\nexport interface Booking {\n id: string;\n calendar_key: string;\n status: BookingStatus;\n google_sync_state: GoogleSyncState;\n start_at: string;\n end_at: string;\n time_zone: string;\n appointment_type: string | null;\n title: string;\n customer: BookingCustomer;\n google_html_link: string | null;\n meet_url: string | null;\n /** Returned only on create — the capability credential for manage links. */\n manage_token?: string | null;\n}\n","import type { BusyInterval } from \"./schema\";\nimport { instantFromWallClock, offsetMinutesAt } from \"./time\";\n\n/**\n * Slot computation lives in the client site, not in our database.\n *\n * Opening hours, slot length, notice and buffers differ per client and per use\n * case; modelling them as dashboard config would mean every new client needs\n * data entry before their site works. The API answers only \"when is this person\n * busy\" — this pure helper turns that plus the site's own hours into offerable\n * slots.\n */\n\nexport interface OpeningInterval {\n /** Local wall-clock `HH:MM` in the calendar's zone. */\n start: string;\n end: string;\n}\n\nexport interface OpeningHours {\n /** 0 = Sunday … 6 = Saturday. A missing weekday is closed. */\n weekly: Partial<Record<number, OpeningInterval[]>>;\n /** `YYYY-MM-DD` → intervals, replacing that day's weekly rule entirely. */\n overrides?: Record<string, OpeningInterval[]>;\n /** `YYYY-MM-DD` dates that are closed regardless of the weekly rule. */\n closedDates?: string[];\n}\n\nexport interface ComputeSlotsOptions {\n busy: BusyInterval[];\n openingHours: OpeningHours;\n timeZone: string;\n durationMinutes: number;\n granularityMinutes?: number;\n minNoticeMinutes?: number;\n bufferBeforeMinutes?: number;\n bufferAfterMinutes?: number;\n windowDays?: number;\n now?: Date;\n}\n\nexport interface Slot {\n start_at: string;\n end_at: string;\n}\n\nexport interface ComputeSlotsResult {\n slots: Slot[];\n nextAvailableAt: string | null;\n}\n\nfunction parseHhMm(value: string): [number, number] {\n const [hour, minute] = value.split(\":\").map(Number);\n return [hour || 0, minute || 0];\n}\n\nfunction dateKeyOf(date: Date, timeZone: string): string {\n const fmt = new Intl.DateTimeFormat(\"en-CA\", {\n timeZone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n });\n return fmt.format(date);\n}\n\n/** Weekday of a `YYYY-MM-DD` local date, read at noon UTC so no offset can\n * shift it across a day boundary. */\nfunction weekdayFromDateKey(dateKey: string): number {\n const [year, month, day] = dateKey.split(\"-\").map(Number);\n return new Date(Date.UTC(year, month - 1, day, 12)).getUTCDay();\n}\n\n/** Midday of the local date containing `at` — a stable anchor to step from,\n * immune to a midnight DST jump. */\nfunction startOfLocalDay(at: Date, timeZone: string): Date {\n const [year, month, day] = dateKeyOf(at, timeZone).split(\"-\").map(Number);\n return instantFromWallClock(timeZone, year, month, day, 12, 0);\n}\n\nfunction overlaps(aStart: number, aEnd: number, bStart: number, bEnd: number): boolean {\n return aStart < bEnd && aEnd > bStart;\n}\n\nexport function computeSlots(options: ComputeSlotsOptions): ComputeSlotsResult {\n const {\n busy,\n openingHours,\n timeZone,\n durationMinutes,\n granularityMinutes = 15,\n minNoticeMinutes = 0,\n bufferBeforeMinutes = 0,\n bufferAfterMinutes = 0,\n windowDays = 30,\n now = new Date(),\n } = options;\n\n const earliest = now.getTime() + minNoticeMinutes * 60_000;\n const busyRanges = busy.map((interval) => [\n new Date(interval.start_at).getTime(),\n new Date(interval.end_at).getTime(),\n ]);\n\n const slots: Slot[] = [];\n // Advance by CALENDAR days, not by 86_400_000 ms. A DST day is 23 or 25 hours\n // long, so fixed-millisecond stepping skips a local date entirely at spring\n // forward and visits one twice at fall back — in America/Toronto, adding 24h\n // from 2026-03-08T04:30Z jumps straight from the 7th to the 9th.\n let cursor = startOfLocalDay(now, timeZone);\n for (let dayOffset = 0; dayOffset < windowDays; dayOffset += 1) {\n const dateKey = dateKeyOf(cursor, timeZone);\n const [year, month, day] = dateKey.split(\"-\").map(Number);\n // `Date.UTC` normalises day 32 into the next month, so this needs no\n // month-length handling.\n cursor = instantFromWallClock(timeZone, year, month, day + 1, 12, 0);\n\n if (openingHours.closedDates?.includes(dateKey)) continue;\n\n const intervals =\n openingHours.overrides?.[dateKey] ?? openingHours.weekly[weekdayFromDateKey(dateKey)] ?? [];\n for (const interval of intervals) {\n const [openHour, openMinute] = parseHhMm(interval.start);\n const [closeHour, closeMinute] = parseHhMm(interval.end);\n const opensAt = instantFromWallClock(timeZone, year, month, day, openHour, openMinute);\n const closesAt = instantFromWallClock(timeZone, year, month, day, closeHour, closeMinute);\n\n for (\n let start = opensAt.getTime();\n start + durationMinutes * 60_000 <= closesAt.getTime();\n start += granularityMinutes * 60_000\n ) {\n const end = start + durationMinutes * 60_000;\n if (start < earliest) continue;\n\n // A slot is unavailable if its BUFFERED span touches anything busy —\n // the buffers are what keep a gap between appointments.\n const blockedStart = start - bufferBeforeMinutes * 60_000;\n const blockedEnd = end + bufferAfterMinutes * 60_000;\n const taken = busyRanges.some(([busyStart, busyEnd]) =>\n overlaps(blockedStart, blockedEnd, busyStart, busyEnd),\n );\n if (taken) continue;\n\n slots.push({\n start_at: new Date(start).toISOString(),\n end_at: new Date(end).toISOString(),\n });\n }\n }\n }\n\n slots.sort((a, b) => a.start_at.localeCompare(b.start_at));\n return { slots, nextAvailableAt: slots[0]?.start_at ?? null };\n}\n\n/** Group slots by local date, the shape every date-picker UI wants. */\nexport function groupSlotsByDay(\n slots: Slot[],\n timeZone: string,\n): { date: string; slots: Slot[] }[] {\n const byDay = new Map<string, Slot[]>();\n for (const slot of slots) {\n const key = dateKeyOf(new Date(slot.start_at), timeZone);\n const bucket = byDay.get(key);\n if (bucket) bucket.push(slot);\n else byDay.set(key, [slot]);\n }\n return [...byDay.entries()]\n .map(([date, daySlots]) => ({ date, slots: daySlots }))\n .sort((a, b) => a.date.localeCompare(b.date));\n}\n\nexport { offsetMinutesAt };\n","\"use client\";\n\nimport type { Context, ReactNode } from \"react\";\nimport { createContext, useCallback, useContext, useEffect, useMemo, useState } from \"react\";\n\nimport type {\n Booking,\n BookingCreateInput,\n BusyInterval,\n CalendarReadClient,\n CalendarSummary,\n ComputeSlotsOptions,\n OpeningHours,\n Slot,\n} from \"./resources/calendar\";\nimport { computeSlots, groupSlotsByDay, resolveBrowserTimeZone } from \"./resources/calendar\";\n\n/**\n * Headless hooks only — no DOM, no CSS, no widget.\n *\n * A styled booking form would fight every client's design system, and these\n * packages already ship no consent UI for the same reason. The site renders;\n * these hooks own fetching, slot math and submit state.\n *\n * The context is created lazily on first access, never at module scope: a\n * module-scope `createContext()` runs during server module evaluation and throws\n * \"createContext only works in Client Components\" when a Server Component graph\n * merely imports a barrel that re-exports this file.\n */\nlet _calendarClientContext: Context<CalendarReadClient | null> | undefined;\nfunction calendarClientContext(): Context<CalendarReadClient | null> {\n return (_calendarClientContext ??= createContext<CalendarReadClient | null>(null));\n}\n\nexport function CalendarClientProvider({\n value,\n children,\n}: {\n value: CalendarReadClient | null;\n children: ReactNode;\n}): ReactNode {\n const Ctx = calendarClientContext();\n return <Ctx.Provider value={value}>{children}</Ctx.Provider>;\n}\n\nexport function useCalendarClient(): CalendarReadClient {\n const client = useContext(calendarClientContext());\n if (!client) {\n throw new Error(\n \"useCalendarClient requires <CalendarClientProvider>. Wire it via createTracking({ calendar }).\",\n );\n }\n return client;\n}\n\nexport interface UseCalendarBusyResult {\n busy: BusyInterval[];\n timeZone: string;\n isLoading: boolean;\n error: Error | null;\n refetch: () => void;\n}\n\n/** Free/busy for one calendar over a window. Public key, straight from the browser. */\nexport function useCalendarBusy(\n calendarKey: string,\n window: { since: string; until: string },\n): UseCalendarBusyResult {\n const client = useCalendarClient();\n const [busy, setBusy] = useState<BusyInterval[]>([]);\n const [timeZone, setTimeZone] = useState<string>(resolveBrowserTimeZone());\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n const [nonce, setNonce] = useState(0);\n\n useEffect(() => {\n const controller = new AbortController();\n setIsLoading(true);\n client\n .busy(calendarKey, { since: window.since, until: window.until })\n .then((response) => {\n if (controller.signal.aborted) return;\n setBusy(response.busy);\n setTimeZone(response.time_zone);\n setError(null);\n })\n .catch((cause: unknown) => {\n if (controller.signal.aborted) return;\n setError(cause instanceof Error ? cause : new Error(String(cause)));\n })\n .finally(() => {\n if (!controller.signal.aborted) setIsLoading(false);\n });\n return () => controller.abort();\n }, [client, calendarKey, window.since, window.until, nonce]);\n\n const refetch = useCallback(() => setNonce((value) => value + 1), []);\n return { busy, timeZone, isLoading, error, refetch };\n}\n\nexport interface UseSlotsOptions extends Omit<ComputeSlotsOptions, \"busy\" | \"timeZone\"> {\n openingHours: OpeningHours;\n timeZone?: string;\n}\n\n/** Slot math, memoized. Pure — the site owns the opening hours it passes in. */\nexport function useSlots(\n busy: BusyInterval[],\n timeZone: string,\n options: UseSlotsOptions,\n): { slots: Slot[]; days: { date: string; slots: Slot[] }[]; nextAvailableAt: string | null } {\n const zone = options.timeZone ?? timeZone;\n return useMemo(() => {\n const { slots, nextAvailableAt } = computeSlots({ ...options, busy, timeZone: zone });\n return { slots, days: groupSlotsByDay(slots, zone), nextAvailableAt };\n }, [busy, zone, options]);\n}\n\nexport type BookingFormStatus = \"idle\" | \"submitting\" | \"confirmed\" | \"failed\";\n\nexport interface UseBookingFormOptions {\n /** The site's own route handler — writes never leave the server with a key. */\n endpoint?: string;\n onConfirmed?: (booking: Booking) => void;\n}\n\nexport interface UseBookingFormResult {\n status: BookingFormStatus;\n error: Error | null;\n booking: Booking | null;\n submit: (input: BookingCreateInput) => Promise<void>;\n reset: () => void;\n}\n\n/**\n * Submit state for a booking.\n *\n * Posts to the SITE's own route handler, not to us: a booking needs a secret\n * key, which must never reach a browser bundle.\n */\nexport function useBookingForm(options: UseBookingFormOptions = {}): UseBookingFormResult {\n const endpoint = options.endpoint ?? \"/api/aranova/calendar/bookings\";\n const [status, setStatus] = useState<BookingFormStatus>(\"idle\");\n const [error, setError] = useState<Error | null>(null);\n const [booking, setBooking] = useState<Booking | null>(null);\n\n const submit = useCallback(\n async (input: BookingCreateInput) => {\n setStatus(\"submitting\");\n setError(null);\n try {\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(input),\n });\n const body: unknown = await response.json().catch(() => null);\n if (!response.ok) {\n const detail =\n body &&\n typeof body === \"object\" &&\n typeof (body as { detail?: unknown }).detail === \"string\"\n ? (body as { detail: string }).detail\n : \"Booking failed\";\n throw new Error(detail);\n }\n setBooking(body as Booking);\n setStatus(\"confirmed\");\n options.onConfirmed?.(body as Booking);\n } catch (cause) {\n setError(cause instanceof Error ? cause : new Error(String(cause)));\n setStatus(\"failed\");\n }\n },\n [endpoint, options],\n );\n\n const reset = useCallback(() => {\n setStatus(\"idle\");\n setError(null);\n setBooking(null);\n }, []);\n\n return { status, error, booking, submit, reset };\n}\n\nexport type { CalendarSummary };\n"],"mappings":";AAIA,SAAS,WAAW,kCAAoD;AA4BjE,IAAM,wBAAqC;AAG3C,SAAS,WAAW,KAAa,SAAoC;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