@sentientui/core 0.37.0 → 0.39.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.
Files changed (45) hide show
  1. package/README.md +43 -1
  2. package/dist/{chunk-NCLBL5V3.mjs → chunk-EVF5PQ4U.mjs} +1 -1
  3. package/dist/{chunk-NCLBL5V3.mjs.map → chunk-EVF5PQ4U.mjs.map} +1 -1
  4. package/dist/chunk-VE2K45X4.mjs +2 -0
  5. package/dist/chunk-VE2K45X4.mjs.map +1 -0
  6. package/dist/chunk-XZRKD2GS.mjs +2 -0
  7. package/dist/chunk-XZRKD2GS.mjs.map +1 -0
  8. package/dist/{index-C-meVCmm.d.cts → index-BAfi7_FG.d.cts} +90 -5
  9. package/dist/{index-DbpGK3Dj.d.ts → index-DyKtujwf.d.ts} +90 -5
  10. package/dist/index-consent.js.map +1 -1
  11. package/dist/index-consent.mjs +1 -1
  12. package/dist/index-engagement.js +1 -1
  13. package/dist/index-engagement.js.map +1 -1
  14. package/dist/index-engagement.mjs +1 -1
  15. package/dist/index-graph.d.cts +5 -5
  16. package/dist/index-graph.d.ts +5 -5
  17. package/dist/index-graph.js +1 -1
  18. package/dist/index-graph.js.map +1 -1
  19. package/dist/index-graph.mjs +1 -1
  20. package/dist/index-graph.mjs.map +1 -1
  21. package/dist/index-local.d.cts +3 -3
  22. package/dist/index-local.d.ts +3 -3
  23. package/dist/index-region.d.cts +1 -1
  24. package/dist/index-region.d.ts +1 -1
  25. package/dist/index-region.mjs +1 -1
  26. package/dist/index-server.d.cts +78 -5
  27. package/dist/index-server.d.ts +78 -5
  28. package/dist/index-server.js +1 -1
  29. package/dist/index-server.js.map +1 -1
  30. package/dist/index-server.mjs +1 -1
  31. package/dist/index-server.mjs.map +1 -1
  32. package/dist/index.d.cts +3 -3
  33. package/dist/index.d.ts +3 -3
  34. package/dist/index.js +1 -1
  35. package/dist/index.js.map +1 -1
  36. package/dist/index.mjs +1 -1
  37. package/dist/{region-skeleton-D2ahkcbe.d.cts → region-skeleton-BRIVB-qf.d.cts} +1 -0
  38. package/dist/{region-skeleton-D2ahkcbe.d.ts → region-skeleton-BRIVB-qf.d.ts} +1 -0
  39. package/dist/{session-meta-DlCp0tyi.d.ts → session-meta-BtRtwsHI.d.ts} +7 -2
  40. package/dist/{session-meta-CJ-QAskZ.d.cts → session-meta-qx4kIL5y.d.cts} +7 -2
  41. package/package.json +1 -1
  42. package/dist/chunk-5CCBWT6H.mjs +0 -2
  43. package/dist/chunk-5CCBWT6H.mjs.map +0 -1
  44. package/dist/chunk-DU3AXQHR.mjs +0 -2
  45. package/dist/chunk-DU3AXQHR.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/snapshot.ts","../src/timeout.ts","../src/durable.ts","../src/queue.ts","../src/goal-queue.ts","../src/forget.ts"],"sourcesContent":["/**\n * Decision snapshot: the SPA / return-visit pre-paint source. Written after\n * every successful decide; read by the inline pre-paint script (before any\n * framework code runs) and by init() to seed slot/persona state.\n */\nimport type { ServedEdits } from './region-skeleton.js';\nimport type { SlotResult } from './slots.js';\nimport type { BlockNode, SitePalette } from './blocks.js';\n\nexport const SNAPSHOT_STORAGE_KEY_PREFIX = '_snt_snap:';\n/** A snapshot older than this is ignored (the inline pre-paint's 2592e6). */\nexport const SNAPSHOT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** Versioned compound locator: resolve id → dataAttr → selector, then verify\n * against fingerprint. Lets a slot survive DOM/markup drift. */\nexport type CompoundLocator = {\n v?: number;\n id?: string;\n dataAttr?: { name: string; value: string };\n selector?: string;\n urlMatch?: string;\n /** Where the element is expected to exist — see page-scope.ts. Health only, never serving. */\n page?: string;\n fingerprint?: { tag?: string; text?: string };\n semanticId?: string;\n};\n\n/** Bounded, declarative operations a registry arm may apply to its element.\n * The style set is a fixed whitelist (validated server-side); no arbitrary CSS,\n * HTML, or JS ever. `text` is applied via textContent; https-only URLs.\n * moveBefore/moveAfter (exactly one) reposition the element relative to a\n * uniquely-resolving sibling anchor — post-decide only, never pre-paint. */\nexport type SlotOps = {\n text?: string;\n style?: Record<string, string>;\n hidden?: boolean;\n href?: string;\n imageSrc?: string;\n imageAlt?: string;\n moveBefore?: CompoundLocator;\n moveAfter?: CompoundLocator;\n};\n\n/** Registry-mode apply info per slot: where to apply and what to set. Stored so\n * a returning visitor's pre-paint can reapply it. `target` is the Phase-2 bare\n * selector; `locator` (Phase 3) is the compound locator, preferred when present. */\nexport type SlotConfigEntry = {\n kind: 'tokens' | 'arms';\n target?: string;\n locator?: CompoundLocator;\n content?: string;\n ops?: SlotOps;\n /** Composition Blocks per arm — ALL arms, not just the served one, because\n * Option-B rendering pre-paints every arm hidden and reveals the served one\n * (spec §6). Holdout sessions receive the baseline arm's tree only, so the\n * control group's DOM stays meaningful. Absent for non-composition slots. */\n blocks?: Record<string, BlockNode>;\n /** The served Rewrite arm (spec 2026-09-23 §4.3): per-node edits plus the\n * skeleton fingerprint and leaf map they were written against. */\n edits?: ServedEdits;\n /** The server has no skeleton for this region — capture and report one. */\n needsSkeleton?: true;\n /** Redesign arms per arm id — ALL arms, same Option-B reason as `blocks`.\n * Served only to pages that declared RenderCaps.compose. */\n compose?: Record<string, import('./style-vocabulary.js').ComposeArm>;\n /** A hybrid <Adaptive> held back: its id still has un-migrated variant\n * history, so the page renders its original until the operator migrates. */\n blocked?: 'variant_history';\n};\n\nexport type DecisionSnapshot = {\n v: 1;\n persona: string;\n band: 'low' | 'medium' | 'high';\n slots: Record<string, SlotResult>;\n layoutOrder: string[] | null;\n savedAt: number;\n // Additive (kept at v:1 so existing snapshots stay valid — bumping the version\n // would flush every returning visitor's snapshot and flash the baseline once).\n // Present only for registry-mode (no-code) installs.\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Derived site palette for Composition Block rendering — cached so the\n * pre-paint render already looks native (a palette that pops in post-decide\n * would be its own flash). */\n palette?: SitePalette;\n /** The site-style entries the served compose arms reference — cached so the\n * pre-paint render already borrows the site's classes. Additive (v stays 1). */\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n /** The `data-sentient-stage` value last decided — already coarsened, and\n * present only for a `stageAttributes` install (additive, v stays 1). */\n stage?: string;\n};\n\nconst BANDS = ['low', 'medium', 'high'];\n\n/** Returns null on missing, corrupt, or wrong-version data — never throws. */\nexport function readSnapshot(apiKey: string): DecisionSnapshot | null {\n try {\n const raw = localStorage.getItem(SNAPSHOT_STORAGE_KEY_PREFIX + apiKey);\n if (!raw) return null;\n const p = JSON.parse(raw) as Partial<DecisionSnapshot> | null;\n if (\n !p ||\n typeof p !== 'object' ||\n p.v !== 1 ||\n typeof p.persona !== 'string' ||\n typeof p.band !== 'string' ||\n !BANDS.includes(p.band) ||\n typeof p.slots !== 'object' ||\n p.slots === null ||\n Array.isArray(p.slots) ||\n !(p.layoutOrder === null || Array.isArray(p.layoutOrder)) ||\n typeof p.savedAt !== 'number' ||\n // The documented 30-day life, the same bound the inline pre-paint script\n // applies: an older decision is ignored everywhere (grader NEW-5).\n !(Date.now() - p.savedAt < SNAPSHOT_MAX_AGE_MS) ||\n // slotConfig is optional; when present it must be a plain object.\n !(p.slotConfig === undefined || (typeof p.slotConfig === 'object' && p.slotConfig !== null && !Array.isArray(p.slotConfig)))\n ) {\n return null;\n }\n // A malformed cached vocabulary degrades to palette styling, never throws.\n const v = p.vocabulary as { entries?: unknown; images?: unknown } | undefined;\n if (v !== undefined && (typeof v !== 'object' || v === null || !Array.isArray(v.entries) || !Array.isArray(v.images))) {\n delete p.vocabulary;\n }\n // Same for the stage: a non-string never reaches setAttribute.\n if (p.stage !== undefined && typeof p.stage !== 'string') delete p.stage;\n return p as DecisionSnapshot;\n } catch {\n return null;\n }\n}\n\n/** Best-effort persist — storage failures are swallowed. */\nexport function writeSnapshot(apiKey: string, snap: DecisionSnapshot): void {\n try {\n localStorage.setItem(SNAPSHOT_STORAGE_KEY_PREFIX + apiKey, JSON.stringify(snap));\n } catch {\n /* private mode / quota — the snapshot is an optimization, never a requirement */\n }\n}\n\n/**\n * Inline pre-paint script (Rung 1a): reads the snapshot and sets\n * `data-sentient-persona` / `data-sentient-confidence` on <html> before\n * first paint. Single-writer: it never overwrites attributes already set.\n *\n * Safety properties (pinned by tests):\n * - apiKey goes through JSON.stringify, then '<' is escaped to <, so a\n * hostile key can neither break the JS string nor terminate the <script>.\n * - Built by string concatenation and contains no backticks, so the output\n * survives being embedded in template-literal-based renderers.\n */\nexport function renderPrePaintScript(apiKey: string, opts?: { stage?: boolean }): string {\n const key = JSON.stringify(SNAPSHOT_STORAGE_KEY_PREFIX + apiKey).replace(/</g, '\\\\u003c');\n return (\n '(function(){try{' +\n // DNT/GPC: the SDK never reads what it stored for an opted-out browser\n // (grader F3 — this fallback had no gate at all).\n // Every signal isDoNotTrackEnabled reads, not just the standard one.\n 'var N=navigator,W=window;if(N.doNotTrack==\"1\"||N.doNotTrack==\"yes\"||W.doNotTrack==\"1\"||N.msDoNotTrack==\"1\"||N.globalPrivacyControl)return;' +\n 'var r=localStorage.getItem(' + key + ');if(!r)return;' +\n 'var s=JSON.parse(r);' +\n 'if(!s||s.v!==1||typeof s.persona!==\"string\"||typeof s.band!==\"string\")return;' +\n // The same 30-day life readSnapshot enforces.\n 'if(!(' + SNAPSHOT_MAX_AGE_MS + '>Date.now()-s.savedAt))return;' +\n 'var d=document.documentElement;' +\n // Opt-in stage attribute (`stageAttributes`): the snapshot holds only the\n // already-coarsened value, so this copies it as-is. Before the persona\n // single-writer return below — an SSR persona must not stop it — but with\n // its own single-writer check, so an SSR-written stage wins. Absent from\n // the output entirely without the option (the default bytes are pinned).\n (opts?.stage\n ? 'if(typeof s.stage==\"string\"&&!d.hasAttribute(\"data-sentient-stage\"))d.setAttribute(\"data-sentient-stage\",s.stage);'\n : '') +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",s.persona);' +\n 'd.setAttribute(\"data-sentient-confidence\",s.band);' +\n '}catch(e){}})();'\n );\n}\n","// Browser request ceilings (audit S8). No browser fetch had a timeout, so a\n// stalled connection — captive portal, dropped mobile radio, an overloaded\n// edge — held a decide or an assign open indefinitely while the page sat on\n// its baseline, and a hung ingest POST wedged a queue's in-flight slot.\n\n/** Read-only calls (winner, weights) and each session upsert. */\nexport const REQUEST_TIMEOUT_MS = 5000;\n/** A SENT decide or assign. The server records them whether or not we read\n * the answer (decide's slot_decisions rows are trials; assign logs the\n * exposure at draw time) — so neither is ever cut short on latency (a slow answer is still applied late, which is\n * what makes the trial real). This ceiling only frees a dead connection. */\nexport const DECIDE_TIMEOUT_MS = 30000;\n/** Durable queue POSTs. Retried on abort, and deduplicated server-side by\n * event id / goal id, so a timeout never double-counts. */\nexport const QUEUE_TIMEOUT_MS = 15000;\n/** How long decide/assign wait for the session upsert before giving up\n * WITHOUT sending: the session retry chain can run ~14 s under 429s, and a\n * decision that is never requested writes no trial (a late decide would —\n * close-out books every slot_decisions row, CONTRACTS §2 \"Which decisions\n * exist\"). The page keeps its baseline; the next page view decides. */\nexport const SESSION_WAIT_MS = 2500;\n\n/** An AbortSignal that fires after `ms`, and a `clear` for when the request\n * settles. No-op where AbortController is missing (the signal is optional). */\nexport function timeoutSignal(ms: number): { signal?: AbortSignal; clear: () => void } {\n if (typeof AbortController !== 'function') return { clear: () => undefined };\n const ctl = new AbortController();\n const t = setTimeout(() => ctl.abort(), ms);\n return { signal: ctl.signal, clear: () => clearTimeout(t) };\n}\n\n/** Resolves true when `p` settles within `ms`, false otherwise. */\nexport function settlesWithin(p: Promise<unknown>, ms: number): Promise<boolean> {\n return new Promise((resolve) => {\n const t = setTimeout(() => resolve(false), ms);\n const done = (): void => {\n clearTimeout(t);\n resolve(true);\n };\n p.then(done, done);\n });\n}\n","/**\n * Reliability primitives shared by every outbound SDK transport.\n *\n * Extracted from queue.ts so the goal sender cannot drift from the event\n * queue on the three decisions that decide whether data survives: which\n * responses are worth retrying, how long to wait, and how the cross-reload\n * bucket is read and written. Behaviour is byte-identical to the versions\n * these replace.\n */\n\nconst MAX_BACKOFF_MS = 60_000;\n/** 2^6 s = 64 s, already past MAX_BACKOFF_MS — the cap that stops the shift overflowing. */\nconst BACKOFF_EXPONENT_CAP = 6;\n\n/** Delay before the next attempt after `consecutiveFailures` failed ones (1-based). */\nexport function backoffDelayMs(consecutiveFailures: number): number {\n return Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.min(consecutiveFailures, BACKOFF_EXPONENT_CAP));\n}\n\n/** What one delivery attempt achieved. `dropped` is terminal but unsuccessful. */\nexport type DeliveryOutcome = 'delivered' | 'dropped' | 'retry';\n\n/**\n * Classifies a response into the three outcomes that matter to a transport.\n *\n * 2xx delivered. A 4xx other than 429 will never succeed however many times we\n * try it (bad key, rejected body, unknown session), so retrying it loops\n * forever and starves real data out of the bucket — drop it, but distinctly,\n * so callers can tell the developer. 429 and 5xx are transient.\n *\n * `ok` is consulted before `status` deliberately: it is the semantic check, and\n * it keeps stubs that set only `ok` (used throughout the SDK test suite)\n * behaving as they did before this was extracted. An unrecognizable response\n * with neither is treated as retryable, matching the original queue.\n */\nexport function classifyResponse(res: { ok?: boolean; status?: number }): DeliveryOutcome {\n if (res.ok === true) return 'delivered';\n const { status } = res;\n if (typeof status !== 'number') return 'retry';\n if (status >= 200 && status < 300) return 'delivered';\n if (status >= 400 && status < 500 && status !== 429) return 'dropped';\n return 'retry';\n}\n\n/** Anything a persisted bucket can hold: it needs a stable server-side dedupe id. */\nexport type Identified = { id: string };\n\n/**\n * Reads a persisted bucket AND clears it — the caller takes ownership of the\n * items and is responsible for re-persisting any that fail again. Returns the\n * newest `max` entries; a corrupt or absent bucket reads as empty.\n */\nexport function drainBucket<T extends Identified>(storageKey: string, max: number): T[] {\n try {\n const raw = localStorage.getItem(storageKey);\n if (!raw) return [];\n const parsed = JSON.parse(raw) as T[];\n if (!Array.isArray(parsed)) return [];\n localStorage.removeItem(storageKey);\n return parsed.slice(-max);\n } catch {\n return [];\n }\n}\n\n/**\n * Merges `items` into the persisted bucket, de-duped by id (last write wins)\n * before the size cap. The dedupe matters: a batch that 5xx's repeatedly\n * in-session hands the same ids back on every retry, and without it each retry\n * appends another copy and `slice(-max)` evicts other distinct failed items to\n * make room for the duplicates.\n */\nexport function writeBucket<T extends Identified>(items: T[], max: number, storageKey: string): void {\n try {\n const existing = (() => {\n try {\n const raw = localStorage.getItem(storageKey);\n if (!raw) return [] as T[];\n const parsed = JSON.parse(raw) as T[];\n return Array.isArray(parsed) ? parsed : ([] as T[]);\n } catch {\n return [] as T[];\n }\n })();\n const byId = new Map<string, T>();\n for (const e of existing) byId.set(e.id, e);\n for (const e of items) byId.set(e.id, e);\n localStorage.setItem(storageKey, JSON.stringify([...byId.values()].slice(-max)));\n } catch {\n /* storage unavailable — the in-memory retry path still applies */\n }\n}\n\n/**\n * Removes the given ids from the persisted bucket. Called once an item is\n * acknowledged so a transient failure that was written to localStorage isn't\n * replayed on the next page load after the in-session retry succeeded.\n */\nexport function purgeBucket(ids: string[], storageKey: string): void {\n try {\n const raw = localStorage.getItem(storageKey);\n if (!raw) return;\n const parsed = JSON.parse(raw) as Identified[];\n if (!Array.isArray(parsed)) return;\n const drop = new Set(ids);\n const remaining = parsed.filter((e) => !drop.has(e.id));\n if (remaining.length === parsed.length) return; // nothing to remove\n if (remaining.length === 0) localStorage.removeItem(storageKey);\n else localStorage.setItem(storageKey, JSON.stringify(remaining));\n } catch {\n /* ignore */\n }\n}\n","/** Batched event queue with reliable transport (fetch + keepalive, localStorage retry). */\n\nimport { forgetGeneration } from './storage-key.js';\nimport { QUEUE_TIMEOUT_MS, timeoutSignal } from './timeout.js';\nimport { backoffDelayMs, classifyResponse, drainBucket, purgeBucket, writeBucket } from './durable.js';\n\nexport type EventType =\n | 'variant_assigned'\n | 'goal_achieved'\n | 'scroll_depth'\n | 'dwell'\n | 'cursor_signal'\n | 'component_visible'\n | 'component_exited'\n | 'micro_signal'\n // A funnel DECLARATION, not telemetry: the server upserts the funnel entity\n // and never stores it in raw_events. Listed here so callers can express it\n // without casting through the track() signature.\n | 'funnel_declared'\n // One per page load and per SPA route change, so a visit's journey through the\n // site is reconstructable. Carries `path` and nothing else.\n | 'pageview'\n // Session-level interaction aggregates for the browser-agent axis (one\n // cumulative snapshot per bank point on the `__session__` sentinel). Read by\n // the bot scorer only; never attributed to a component, never a reward.\n | 'interaction_stats';\n\nexport type SentientEvent = {\n id: string;\n sessionId: string;\n projectId: string;\n componentId: string;\n variantId?: string;\n eventType: EventType;\n goalType?: string;\n /**\n * Page path the event happened on, e.g. `/pricing`. Set automatically from\n * `location.pathname` — deliberately NOT `location.href`, so query strings\n * (which routinely carry emails, reset tokens and order ids) never leave the\n * browser. The server re-strips them anyway; this is the first of two gates.\n * Undefined outside a browser (SSR), where there is no page to name.\n */\n path?: string;\n payload: Record<string, unknown>;\n timestamp: number;\n timeInSession: number;\n};\n\nexport type QueueConfig = {\n ingestUrl: string;\n apiKey: string;\n flushIntervalMs?: number;\n maxBatchSize?: number;\n maxRetrySize?: number;\n};\n\nexport type EventQueue = {\n push(event: SentientEvent): void;\n flush(): void;\n /** Stop the queue with a final flush. `forget`: the visitor asked to be\n * forgotten — a failed final delivery must NOT be persisted for retry\n * (it re-created the retry bucket after forget-me removed it). */\n destroy(opts?: { forget?: boolean }): void;\n};\n\nconst MAX_SENT_IDS = 500;\n// 64 KB is the per-origin keepalive budget on every modern browser. We split unload\n// flushes into chunks below this to avoid the whole batch being dropped.\nconst KEEPALIVE_BUDGET_BYTES = 56 * 1024;\n\n/**\n * Persisted retry-bucket key, namespaced by apiKey prefix so multiple projects\n * on the same origin each get their own bucket. Exported so the client's\n * forget-me teardown can remove it.\n */\nexport function retryStorageKey(apiKey: string): string {\n return `_snt_retry_${apiKey.slice(0, 12)}`;\n}\n\nconst SSR_QUEUE: EventQueue = {\n push: () => undefined,\n flush: () => undefined,\n destroy: () => undefined,\n};\n\n/**\n * Creates a batched event queue with periodic and lifecycle-triggered flushes.\n */\nexport function createEventQueue(config: QueueConfig): EventQueue {\n if (typeof window === 'undefined') {\n return SSR_QUEUE;\n }\n\n const flushIntervalMs = config.flushIntervalMs ?? 5000;\n const maxBatchSize = config.maxBatchSize ?? 20;\n const maxRetrySize = config.maxRetrySize ?? 100;\n const ingestUrl = config.ingestUrl;\n const apiKey = config.apiKey;\n const RETRY_KEY = retryStorageKey(apiKey);\n // Set by destroy({ forget: true }); see the type's doc.\n let forgotten = false;\n const createdGen = forgetGeneration(apiKey);\n const persistBucket: typeof writeBucket = (...a) => {\n if (!forgotten && forgetGeneration(apiKey) === createdGen) writeBucket(...a);\n };\n\n const queue: SentientEvent[] = [];\n const sentIds = new Set<string>();\n const sentIdOrder: string[] = [];\n\n const markSent = (ids: string[]): void => {\n for (const id of ids) {\n queuedIds.delete(id); // free the in-flight slot\n if (sentIds.has(id)) continue;\n sentIds.add(id);\n sentIdOrder.push(id);\n }\n while (sentIdOrder.length > MAX_SENT_IDS) {\n const oldest = sentIdOrder.shift();\n if (oldest) sentIds.delete(oldest);\n }\n // A batch that previously 5xx'd was persisted to the cross-reload retry\n // backstop. Now that it's acknowledged (delivered, or 4xx-dropped as\n // unretryable), drop those ids from localStorage too — otherwise the next\n // page load would replay an already-handled event. `sentIds` is in-memory\n // only, so it can't suppress that cross-reload duplicate on its own.\n purgeBucket(ids, RETRY_KEY);\n };\n\n // Tracks IDs currently in `queue` or in flight (handed to transportBatch\n // but not yet confirmed). Entries are removed on markSent or when an event\n // is dropped, so the set stays bounded by in-flight + queued size.\n const queuedIds = new Set<string>();\n\n // Bound the in-memory queue at the same cap as the persisted retry bucket\n // (maxRetrySize). During a sustained outage flush() keeps re-enqueueing every\n // failed batch while the page keeps producing events, and only the\n // localStorage bucket was capped — so a multi-hour outage on a long-lived\n // SPA tab grew this array without limit. Drop-oldest, matching writeBucket's\n // slice(-max) shed policy: the newest events are the ones a recovering\n // server can still use.\n const capQueue = (): void => {\n while (queue.length > maxRetrySize) {\n const dropped = queue.shift();\n if (dropped) queuedIds.delete(dropped.id);\n }\n };\n\n const enqueue = (event: SentientEvent): void => {\n if (sentIds.has(event.id) || queuedIds.has(event.id)) return;\n queuedIds.add(event.id);\n queue.push(event);\n capQueue();\n };\n\n // A retryable failure hands the batch back to the in-memory queue so the\n // backoff-gated interval flush retries it in-session (localStorage is only the\n // cross-reload backstop). The ids are still tracked in queuedIds — they were\n // pulled from `queue` on flush but never markSent — so we re-add them WITHOUT\n // going through enqueue (which would skip them as already-queued) and without\n // deleting/re-adding queuedIds. Already-sent events are never re-queued, and a\n // single event stays a single copy: `queue` is fully drained each flush.\n const requeueFailed = (batch: SentientEvent[]): void => {\n for (const event of batch) {\n if (sentIds.has(event.id)) continue;\n queuedIds.add(event.id); // idempotent — keeps id-tracking consistent\n queue.push(event);\n }\n // Failed batches count against the same bound as fresh pushes — this path\n // is exactly the one that grew unbounded during an outage (see capQueue).\n capQueue();\n };\n\n const retryEvents = drainBucket<SentientEvent>(RETRY_KEY, maxRetrySize);\n for (const event of retryEvents) {\n enqueue(event);\n }\n\n // Pause flushing until backoff expires.\n let backoffUntil = 0;\n let consecutiveFailures = 0;\n\n // Authenticated transport. keepalive: true gives unload-survival; we still await\n // the response so 5xx/429 actually surface and we can retry.\n const transportBatch = (batch: SentientEvent[], salvage = true): void => {\n if (batch.length === 0) return;\n const body = JSON.stringify(batch);\n const ids = batch.map((e) => e.id);\n\n let pending: Promise<Response> | Response;\n const queueTimer = timeoutSignal(QUEUE_TIMEOUT_MS);\n try {\n // Bounded (QUEUE_TIMEOUT_MS): a hung POST never settles, which held this\n // batch in flight forever. An abort is a retry; ids dedupe server-side.\n pending = fetch(ingestUrl, {\n method: 'POST',\n keepalive: true,\n signal: queueTimer.signal,\n body,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n });\n } catch {\n // Synchronous throw (typically jsdom in tests, or extreme browser failure).\n persistBucket(batch, maxRetrySize, RETRY_KEY);\n requeueFailed(batch);\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n return;\n }\n\n Promise.resolve(pending).then(queueTimer.clear, queueTimer.clear);\n // fetch can sometimes return a value directly (tests using stubGlobal). Handle both.\n const handleResponse = (res: Response): void => {\n if (classifyResponse(res) !== 'retry') {\n // An API older than migration 108 400s the whole batch over the unknown\n // 'pageview' type, and a 4xx is terminal — which silently dropped the\n // co-batched exposures and goals too. Re-send once without the\n // pageviews (valid on the old API); the pageviews themselves are\n // unsendable there and are dropped as delivered.\n if (!res.ok && salvage) {\n const rest = batch.filter((e) => e.eventType !== 'pageview');\n if (rest.length > 0 && rest.length < batch.length) {\n markSent(batch.filter((e) => e.eventType === 'pageview').map((e) => e.id));\n transportBatch(rest, false);\n return;\n }\n }\n // 2xx = success. 4xx (except 429) will never succeed — drop them rather than loop.\n markSent(ids);\n consecutiveFailures = 0;\n backoffUntil = 0;\n return;\n }\n // 5xx / 429 → retry with backoff.\n persistBucket(batch, maxRetrySize, RETRY_KEY);\n requeueFailed(batch);\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n };\n\n // Thenable, not instanceof: another realm's Promise failed it (N11-4).\n if (pending && typeof (pending as PromiseLike<unknown>).then === 'function') {\n pending.then(handleResponse).catch(() => {\n persistBucket(batch, maxRetrySize, RETRY_KEY);\n requeueFailed(batch);\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n });\n } else {\n handleResponse(pending as unknown as Response); // test stubs return a plain value\n }\n };\n\n // Pack events into a batch that stays under the keepalive byte budget AND the\n // configured event-count cap. Returns the prefix of `pool` that fits.\n // Uses UTF-8 byte length (not char count) — emoji/CJK payloads can be 3–4×\n // larger as bytes and would otherwise blow the keepalive budget.\n const encoder = typeof TextEncoder !== 'undefined' ? new TextEncoder() : null;\n const byteLength = (s: string): number =>\n encoder ? encoder.encode(s).length : s.length;\n const packBatch = (pool: SentientEvent[]): SentientEvent[] => {\n const out: SentientEvent[] = [];\n let bytes = 2; // for the surrounding []\n for (const e of pool) {\n const size = byteLength(JSON.stringify(e)) + 1; // +1 for comma\n if (out.length > 0 && bytes + size > KEEPALIVE_BUDGET_BYTES) break;\n if (out.length >= maxBatchSize) break;\n out.push(e);\n bytes += size;\n }\n return out;\n };\n\n const flush = (): void => {\n try {\n if (Date.now() < backoffUntil) return;\n while (queue.length > 0) {\n // Re-check inside the loop: transportBatch can set backoffUntil\n // synchronously (a sync throw or a same-tick Response) and re-enqueue the\n // failed batch, so a mid-drain backoff must stop further chunks this tick\n // (otherwise the just-re-enqueued batch would immediately retry-loop).\n if (Date.now() < backoffUntil) break;\n const pending = queue.filter((e) => !sentIds.has(e.id));\n queue.length = 0;\n if (pending.length === 0) break;\n const batch = packBatch(pending);\n if (batch.length === 0) break;\n // Put anything we didn't pack back on the queue for the next tick.\n if (batch.length < pending.length) {\n queue.push(...pending.slice(batch.length));\n }\n transportBatch(batch);\n }\n } catch {\n /* never throw */\n }\n };\n\n let flushTimerActive = true;\n let intervalId: ReturnType<typeof setInterval> | null = null;\n\n intervalId = setInterval(() => {\n if (!flushTimerActive) return;\n flush();\n }, flushIntervalMs);\n\n const onVisibilityChange = (): void => {\n if (document.visibilityState === 'hidden') {\n flush();\n }\n };\n\n // `pagehide` (not `beforeunload`): a `beforeunload` listener can disqualify a\n // page from the back/forward cache. `pagehide` fires on real unloads AND on\n // bfcache eviction, and `visibilitychange:hidden` already covers most leaves,\n // so flush-on-leave stays covered without inhibiting bfcache.\n const onPageHide = (): void => {\n flush();\n };\n\n document.addEventListener('visibilitychange', onVisibilityChange);\n window.addEventListener('pagehide', onPageHide);\n\n return {\n push(event: SentientEvent): void {\n enqueue(event);\n if (queue.length >= maxBatchSize) {\n flush();\n }\n },\n flush,\n destroy(opts?: { forget?: boolean }): void {\n if (opts?.forget) forgotten = true;\n flushTimerActive = false;\n if (intervalId !== null) {\n clearInterval(intervalId);\n intervalId = null;\n }\n document.removeEventListener('visibilitychange', onVisibilityChange);\n window.removeEventListener('pagehide', onPageHide);\n flush();\n },\n };\n}\n","/**\n * Durable transport for `POST /v1/goals`.\n *\n * A conversion is the single most valuable event the SDK emits, and it used to\n * be the least reliable one: `goal()` fired a bare `fetch(...).catch(() => {})`,\n * which only observes network-layer failures. A 429 (the per-IP limit is 100\n * req/min, and shared egress — corporate NAT, carriers, storefront proxies —\n * hits it routinely), a 5xx, or a 400 all RESOLVE, so the catch never ran and\n * the response was discarded unread. The conversion was gone with no retry and\n * nothing surfaced to the developer.\n *\n * This gives goals the same guarantees the event queue has always had: retry\n * with backoff in-session, a localStorage bucket that survives reload, and\n * dedupe by id. Retry is safe because `goalId` is a client-generated UUID that\n * the server dedupes on (`ON CONFLICT DO NOTHING`) — the safety was already\n * there, it just wasn't used.\n *\n * Unlike events, `/v1/goals` takes ONE goal per request, so this is a serial\n * sender rather than a batcher, and a flush sends at most `maxPerFlush` so a\n * backlog drains at a pace the rate limiter tolerates instead of re-triggering\n * the 429 that created it.\n */\n\nimport { forgetGeneration } from './storage-key.js';\nimport { QUEUE_TIMEOUT_MS, timeoutSignal } from './timeout.js';\nimport { backoffDelayMs, classifyResponse, drainBucket, purgeBucket, writeBucket } from './durable.js';\n\n/** One queued conversion. `id` is the goalId — the server's dedupe key. */\nexport type PendingGoal = {\n id: string;\n /** Pre-serialized request body, so a persisted goal replays byte-identically. */\n body: string;\n};\n\nexport type GoalQueueConfig = {\n /** Absolute URL of the goals endpoint. */\n url: string;\n apiKey: string;\n headers: Record<string, string>;\n flushIntervalMs?: number;\n maxRetrySize?: number;\n maxPerFlush?: number;\n /** Called when a goal is permanently dropped (non-retryable status), so the\n * client can warn in debug mode. Never called for retryable failures. */\n onDrop?: (goal: PendingGoal, status: number) => void;\n};\n\nexport type GoalQueue = {\n /** Sends immediately; on a retryable failure the goal is queued and retried. */\n send(goal: PendingGoal): void;\n flush(): void;\n /** Stop the queue with a final flush. `forget`: the visitor asked to be\n * forgotten — a failed final delivery must NOT be persisted for retry\n * (it re-created the retry bucket after forget-me removed it). */\n destroy(opts?: { forget?: boolean }): void;\n};\n\nconst MAX_SENT_IDS = 200;\n\n/**\n * Persisted goal-retry bucket key, namespaced by apiKey prefix so multiple\n * projects on one origin keep separate buckets. Exported so the client's\n * forget-me teardown can remove it.\n */\nexport function goalRetryStorageKey(apiKey: string): string {\n return `_snt_goal_retry_${apiKey.slice(0, 12)}`;\n}\n\nconst SSR_GOAL_QUEUE: GoalQueue = {\n send: () => undefined,\n flush: () => undefined,\n destroy: () => undefined,\n};\n\nexport function createGoalQueue(config: GoalQueueConfig): GoalQueue {\n if (typeof window === 'undefined') return SSR_GOAL_QUEUE;\n\n const flushIntervalMs = config.flushIntervalMs ?? 5000;\n const maxRetrySize = config.maxRetrySize ?? 100;\n const maxPerFlush = config.maxPerFlush ?? 5;\n const RETRY_KEY = goalRetryStorageKey(config.apiKey);\n // Set by destroy({ forget: true }); see the type's doc.\n let forgotten = false;\n const createdGen = forgetGeneration(config.apiKey);\n const persistBucket: typeof writeBucket = (...a) => {\n if (!forgotten && forgetGeneration(config.apiKey) === createdGen) writeBucket(...a);\n };\n\n const pending: PendingGoal[] = [];\n const pendingIds = new Set<string>();\n const sentIds = new Set<string>();\n const sentIdOrder: string[] = [];\n\n let backoffUntil = 0;\n let consecutiveFailures = 0;\n let disposed = false;\n\n const markSent = (goal: PendingGoal): void => {\n pendingIds.delete(goal.id);\n if (!sentIds.has(goal.id)) {\n sentIds.add(goal.id);\n sentIdOrder.push(goal.id);\n }\n while (sentIdOrder.length > MAX_SENT_IDS) {\n const oldest = sentIdOrder.shift();\n if (oldest) sentIds.delete(oldest);\n }\n // Acknowledged (delivered, or dropped as unretryable) — clear it from the\n // cross-reload bucket so the next page load doesn't replay it.\n purgeBucket([goal.id], RETRY_KEY);\n };\n\n const markFailed = (goal: PendingGoal): void => {\n persistBucket([goal], maxRetrySize, RETRY_KEY);\n if (!sentIds.has(goal.id) && !pendingIds.has(goal.id)) {\n pendingIds.add(goal.id);\n pending.push(goal);\n }\n // One failed ROUND counts once, however many goals were in flight. flush()\n // launches up to maxPerFlush transports synchronously, so counting per goal\n // turned a single bad tick into consecutiveFailures=5 and a 32s backoff\n // where the first failure warrants 2s. queue.ts counts per batch; match it.\n if (Date.now() >= backoffUntil) {\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n }\n };\n\n const transport = (goal: PendingGoal): void => {\n let res: Promise<Response> | Response;\n const queueTimer = timeoutSignal(QUEUE_TIMEOUT_MS);\n try {\n // Bounded like the event queue: an abort retries, the goalId dedupes.\n res = fetch(config.url, {\n method: 'POST',\n keepalive: true,\n signal: queueTimer.signal,\n body: goal.body,\n headers: config.headers,\n });\n } catch {\n // Synchronous throw (jsdom in tests, or extreme browser failure).\n markFailed(goal);\n return;\n }\n\n const handle = (r: Response): void => {\n const outcome = classifyResponse(r);\n if (outcome === 'retry') {\n markFailed(goal);\n return;\n }\n // Terminal either way, but a drop is a wiring bug the developer can fix —\n // a 400 \"session not found\", a 401 from a misconfigured origin allowlist —\n // and used to be swallowed entirely. Say so instead of failing silently.\n if (outcome === 'dropped') config.onDrop?.(goal, r.status);\n markSent(goal);\n consecutiveFailures = 0;\n backoffUntil = 0;\n };\n\n Promise.resolve(res).then(queueTimer.clear, queueTimer.clear);\n // fetch can return a plain value under test stubs. Handle both.\n // A thenable check, not instanceof: a fetch wrapper returning another\n // realm's Promise was handled as a Response and retried (grader N11-4).\n if (res && typeof (res as PromiseLike<unknown>).then === 'function') (res as Promise<Response>).then(handle).catch(() => markFailed(goal));\n else handle(res as unknown as Response); // test stubs return a plain value\n };\n\n const flush = (): void => {\n try {\n if (disposed) return;\n if (Date.now() < backoffUntil) return;\n let sentThisTick = 0;\n while (pending.length > 0 && sentThisTick < maxPerFlush) {\n if (Date.now() < backoffUntil) break; // a same-tick failure re-armed backoff\n const goal = pending.shift()!;\n pendingIds.delete(goal.id);\n if (sentIds.has(goal.id)) continue;\n sentThisTick++;\n transport(goal);\n }\n } catch {\n /* never throw from a lifecycle handler */\n }\n };\n\n // Replay anything a previous page load failed to deliver. Left for the first\n // interval tick rather than sent now, so a page that reloads under an ongoing\n // outage doesn't stampede the endpoint during init.\n const restored = drainBucket<PendingGoal>(RETRY_KEY, maxRetrySize);\n for (const goal of restored) {\n if (!pendingIds.has(goal.id)) {\n pendingIds.add(goal.id);\n pending.push(goal);\n }\n }\n // drainBucket CLEARS storage as it reads, but only maxPerFlush goals leave per\n // tick — so a 40-goal backlog moved to memory and the visitor navigating two\n // seconds later lost the 35 that hadn't been sent yet. Put them straight back;\n // markSent purges each id individually once it is actually acknowledged.\n if (restored.length > 0) writeBucket(restored, maxRetrySize, RETRY_KEY);\n\n const intervalId = setInterval(flush, flushIntervalMs);\n const onVisibilityChange = (): void => {\n if (document.visibilityState === 'hidden') flush();\n };\n const onPageHide = (): void => flush();\n document.addEventListener('visibilitychange', onVisibilityChange);\n window.addEventListener('pagehide', onPageHide);\n\n return {\n send(goal: PendingGoal): void {\n if (disposed) {\n // A goal fired before a pause, still waiting on the first session\n // upsert, arrives after dispose(): banked for the next page's queue\n // instead of dropped unreported (grader R9-3, CONTRACTS §7). Never\n // after a forget — persistBucket checks that.\n if (!sentIds.has(goal.id)) persistBucket([goal], maxRetrySize, RETRY_KEY);\n return;\n }\n if (sentIds.has(goal.id) || pendingIds.has(goal.id)) return;\n // A conversion goes out now — it is often the last thing that happens\n // before a redirect to a thank-you page. Only a failure makes it queued.\n if (Date.now() < backoffUntil) {\n // Persist BEFORE parking it in memory. A goal only ever reached the\n // cross-reload bucket via markFailed — i.e. only after a failed attempt\n // — so a conversion queued during someone else's backoff lived in memory\n // alone, and flush() early-returns while backoff is armed, so pagehide\n // could not rescue it either. A purchase firing 300ms after a rate-limited\n // add_to_cart was lost on the checkout redirect: exactly the outage this\n // queue exists to survive.\n persistBucket([goal], maxRetrySize, RETRY_KEY);\n pendingIds.add(goal.id);\n pending.push(goal);\n return;\n }\n transport(goal);\n },\n flush,\n destroy(opts?: { forget?: boolean }): void {\n if (opts?.forget) forgotten = true;\n clearInterval(intervalId);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n window.removeEventListener('pagehide', onPageHide);\n flush();\n disposed = true;\n },\n };\n}\n","import { sessionCookieName, storageSuffix, LEGACY_SESSION_COOKIE_NAME, markForgotten } from './storage-key.js';\nimport { SNAPSHOT_STORAGE_KEY_PREFIX } from './snapshot.js';\nimport { retryStorageKey } from './queue.js';\nimport { goalRetryStorageKey } from './goal-queue.js';\n\n/**\n * Forget-me WITHOUT a client: delete everything the SDK stores for `apiKey`'s\n * visitor. `client.destroy()` does this for a live tracking client, which only\n * exists when consent was granted in this page view — so a visitor who said\n * \"no\" somewhere the SDK wasn't watching (a CMP settings page, checkout)\n * kept the 365-day id, the decision snapshot and the retry buckets for good,\n * and the pre-paint script kept personalizing from that snapshot (audit N2).\n * Callers run this when the consent source reports a refusal at boot.\n *\n * Writes nothing unless something was stored: the legacy tombstone (which\n * stops this project re-adopting the shared bare `_snt_uid`) is only written\n * when there is a bare id to block. Returns whether anything was removed.\n */\nexport function forgetVisitor(apiKey: string): boolean {\n if (typeof window === 'undefined' || !apiKey) return false;\n markForgotten(apiKey);\n let removed = false;\n const name = sessionCookieName(apiKey);\n try {\n if (new RegExp(`(?:^|; )${name}=`).test(document.cookie)) {\n const secure = location.protocol === 'https:' ? '; Secure' : '';\n document.cookie = `${name}=; max-age=0; SameSite=lax; path=/${secure}`;\n removed = true;\n }\n } catch {\n /* cookies unavailable */\n }\n const suffix = storageSuffix(apiKey);\n const exact = [\n name,\n // Written by builds before 2026; current SDKs only ever delete it.\n '_snt_graph_edges',\n SNAPSHOT_STORAGE_KEY_PREFIX + apiKey,\n retryStorageKey(apiKey),\n goalRetryStorageKey(apiKey),\n `_snt_graph_nodes${suffix}`,\n ];\n const prefixes = [`_snt_asgn${suffix}_`];\n for (const store of ['localStorage', 'sessionStorage'] as const) {\n try {\n const s = window[store];\n for (const k of exact) {\n if (s.getItem(k) !== null) {\n s.removeItem(k);\n removed = true;\n }\n }\n for (let i = s.length - 1; i >= 0; i--) {\n const k = s.key(i);\n if (k && prefixes.some((p) => k.startsWith(p))) {\n s.removeItem(k);\n removed = true;\n }\n }\n } catch {\n /* storage unavailable */\n }\n }\n try {\n // Every layer session.ts's legacy read adopts from, sessionStorage too.\n const bare =\n new RegExp(`(?:^|; )${LEGACY_SESSION_COOKIE_NAME}=[^;]`).test(document.cookie) ||\n localStorage.getItem(LEGACY_SESSION_COOKIE_NAME) !== null ||\n sessionStorage.getItem(LEGACY_SESSION_COOKIE_NAME) !== null;\n if (bare) localStorage.setItem(`${LEGACY_SESSION_COOKIE_NAME}_tomb${suffix}`, '1');\n } catch {\n /* storage unavailable */\n }\n return removed;\n}\n"],"mappings":"wEASO,IAAMA,EAA8B,aAoF3C,IAAMC,GAAQ,CAAC,MAAO,SAAU,MAAM,EAG/B,SAASC,GAAaC,EAAyC,CACpE,GAAI,CACF,IAAMC,EAAM,aAAa,QAAQC,EAA8BF,CAAM,EACrE,GAAI,CAACC,EAAK,OAAO,KACjB,IAAME,EAAI,KAAK,MAAMF,CAAG,EACxB,GACE,CAACE,GACD,OAAOA,GAAM,UACbA,EAAE,IAAM,GACR,OAAOA,EAAE,SAAY,UACrB,OAAOA,EAAE,MAAS,UAClB,CAACL,GAAM,SAASK,EAAE,IAAI,GACtB,OAAOA,EAAE,OAAU,UACnBA,EAAE,QAAU,MACZ,MAAM,QAAQA,EAAE,KAAK,GACrB,EAAEA,EAAE,cAAgB,MAAQ,MAAM,QAAQA,EAAE,WAAW,IACvD,OAAOA,EAAE,SAAY,UAGrB,EAAE,KAAK,IAAI,EAAIA,EAAE,QAAU,SAE3B,EAAEA,EAAE,aAAe,QAAc,OAAOA,EAAE,YAAe,UAAYA,EAAE,aAAe,MAAQ,CAAC,MAAM,QAAQA,EAAE,UAAU,GAEzH,OAAO,KAGT,IAAMC,EAAID,EAAE,WACZ,OAAIC,IAAM,SAAc,OAAOA,GAAM,UAAYA,IAAM,MAAQ,CAAC,MAAM,QAAQA,E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,YAAYN,CAAM,GAAG,EACvC,QAAWO,IAAS,CAAC,eAAgB,gBAAgB,EACnD,GAAI,CACF,IAAMC,EAAI,OAAOD,CAAK,EACtB,QAAWE,KAAKP,EACVM,EAAE,QAAQC,CAAC,IAAM,OACnBD,EAAE,WAAWC,CAAC,EACdd,EAAU,IAGd,QAASe,EAAIF,EAAE,OAAS,EAAGE,GAAK,EAAGA,IAAK,CACtC,IAAMD,EAAID,EAAE,IAAIE,CAAC,EACbD,GAAKH,EAAS,KAAMK,GAAMF,EAAE,WAAWE,CAAC,CAAC,IAC3CH,EAAE,WAAWC,CAAC,EACdd,EAAU,GAEd,CACF,OAAQI,EAAA,CAER,CAEF,GAAI,EAGA,IAAI,OAAO,WAAWa,CAA0B,OAAO,EAAE,KAAK,SAAS,MAAM,GAC7E,aAAa,QAAQA,CAA0B,IAAM,MACrD,eAAe,QAAQA,CAA0B,IAAM,OAC/C,aAAa,QAAQ,GAAGA,CAA0B,QAAQZ,CAAM,GAAI,GAAG,CACnF,OAAQD,EAAA,CAER,CACA,OAAOJ,CACT","names":["SNAPSHOT_STORAGE_KEY_PREFIX","BANDS","readSnapshot","apiKey","raw","SNAPSHOT_STORAGE_KEY_PREFIX","p","v","e","writeSnapshot","snap","renderPrePaintScript","opts","timeoutSignal","ms","ctl","t","settlesWithin","p","resolve","done","backoffDelayMs","consecutiveFailures","classifyResponse","res","status","drainBucket","storageKey","max","raw","parsed","writeBucket","items","existing","e","byId","purgeBucket","ids","drop","remaining","MAX_SENT_IDS","KEEPALIVE_BUDGET_BYTES","retryStorageKey","apiKey","SSR_QUEUE","createEventQueue","config","_a","_b","_c","flushIntervalMs","maxBatchSize","maxRetrySize","ingestUrl","RETRY_KEY","forgotten","createdGen","forgetGeneration","persistBucket","a","writeBucket","queue","sentIds","sentIdOrder","markSent","ids","id","queuedIds","oldest","purgeBucket","capQueue","dropped","enqueue","event","requeueFailed","batch","retryEvents","drainBucket","backoffUntil","consecutiveFailures","transportBatch","salvage","body","e","pending","queueTimer","timeoutSignal","backoffDelayMs","handleResponse","res","classifyResponse","rest","encoder","byteLength","s","packBatch","pool","out","bytes","size","flush","flushTimerActive","intervalId","onVisibilityChange","onPageHide","opts","MAX_SENT_IDS","goalRetryStorageKey","apiKey","SSR_GOAL_QUEUE","createGoalQueue","config","_a","_b","_c","flushIntervalMs","maxRetrySize","maxPerFlush","RETRY_KEY","forgotten","createdGen","forgetGeneration","persistBucket","a","writeBucket","pending","pendingIds","sentIds","sentIdOrder","backoffUntil","consecutiveFailures","disposed","markSent","goal","oldest","purgeBucket","markFailed","backoffDelayMs","transport","res","queueTimer","timeoutSignal","e","handle","r","outcome","classifyResponse","flush","sentThisTick","restored","drainBucket","intervalId","onVisibilityChange","onPageHide","opts","forgetVisitor","apiKey","markForgotten","removed","name","sessionCookieName","secure","e","suffix","storageSuffix","exact","SNAPSHOT_STORAGE_KEY_PREFIX","retryStorageKey","goalRetryStorageKey","prefixes","store","s","k","i","p","LEGACY_SESSION_COOKIE_NAME"]}
@@ -1,6 +1,6 @@
1
1
  import { $ as SitePalette, a4 as StyleVocabulary } from './style-vocabulary-Ba_g6_DD.cjs';
2
- import { d as SlotConfigEntry, e as SlotDeclInput, b as CompoundLocator } from './session-meta-CJ-QAskZ.cjs';
3
- import { c as RenderCaps, R as RegionSkeleton } from './region-skeleton-D2ahkcbe.cjs';
2
+ import { d as SlotConfigEntry, e as SlotDeclInput, b as CompoundLocator } from './session-meta-qx4kIL5y.cjs';
3
+ import { c as RenderCaps, R as RegionSkeleton } from './region-skeleton-BRIVB-qf.cjs';
4
4
  import './index-consent.cjs';
5
5
  import { SlotResult } from '@sentientui/policy';
6
6
 
@@ -129,6 +129,20 @@ type GraphClient = {
129
129
  */
130
130
  declare function sanitizePageUrl(href: string): string;
131
131
 
132
+ /** `true` = coarse (`customer`/`lapsed` → `returning`); `'detailed'` = the stage as computed. */
133
+ type StageAttributes = boolean | 'detailed';
134
+ declare const STAGE_ATTRIBUTE = "data-sentient-stage";
135
+ /** The value the page may see for `stage`, or null for "set nothing". */
136
+ declare function exposedStage(stage: unknown, mode: StageAttributes | undefined): string | null;
137
+ /**
138
+ * Write (or, with null, remove) the attribute. Unlike the persona attributes
139
+ * this OVERWRITES: the pre-paint value comes from the previous visit's
140
+ * snapshot, and a visitor who bought since must not keep reading as `carted`
141
+ * for the rest of this visit. The stage is frozen per visit server-side, so a
142
+ * decide answer never changes it twice in one visit.
143
+ */
144
+ declare function setStageAttribute(value: string | null, doc?: Document): void;
145
+
132
146
  declare const PROD_KEYLESS_ERROR = "[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.";
133
147
  declare const LOCAL_MODE_BANNER = "[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.";
134
148
 
@@ -171,6 +185,27 @@ declare function forgetGeneration(apiKey: string): number;
171
185
  declare const PAGE_SCOPE_RE: RegExp;
172
186
  declare function pageScopeMatches(page: string | undefined, pathname: string): boolean;
173
187
 
188
+ /**
189
+ * url_reached matching, shared by the snippet (client-side wiring) and the API
190
+ * (server-side matching on pageview ingest) so the two can never disagree about
191
+ * whether a path satisfies a goal.
192
+ *
193
+ * A pattern matches the current path on an exact hit or a path-segment
194
+ * boundary — never a bare substring. Substring matching made the degenerate '/'
195
+ * pattern (what the editor's "Track page visits" button saves on a homepage)
196
+ * contain every path, firing the homepage goal on every route; it also let
197
+ * '/pricing' over-match '/pricing-details'. The root '/' matches only '/', and
198
+ * '/pricing' matches '/pricing' and '/pricing/monthly' but not '/pricing-x'.
199
+ */
200
+ declare function urlMatches(pattern: string, path: string): boolean;
201
+ /**
202
+ * Reduce a pasted full URL to its path. An operator who copies
203
+ * `https://host/pricing` into a url_reached goal saved a pattern that no
204
+ * pathname ever starts with, so the goal silently never fired. A path (or
205
+ * anything unparseable) passes through unchanged.
206
+ */
207
+ declare function normalizeUrlPattern(p: string): string;
208
+
174
209
  /**
175
210
  * The adaptation reveal — the 0.X-second moment a visitor notices the page is
176
211
  * for them (`what-sentient-is-becoming.md` §"Fast generation and the wow",
@@ -278,6 +313,12 @@ type SentientConfig = {
278
313
  * variantIds) still fetch once when the seed carries no content.
279
314
  */
280
315
  initialAssignments?: Record<string, string>;
316
+ /**
317
+ * Component ids an SSR preload found moved onto the shared track
318
+ * (`preloadAssignmentsDetailed` / `preloadDecisions` with the unified cap).
319
+ * Their cached assignments are ignored and `isUnified` reports them.
320
+ */
321
+ initialUnified?: string[];
281
322
  /**
282
323
  * Segment used for SSR preload (`device:source`). When set with `initialAssignments`,
283
324
  * seeds the assignment cache under this key so hydration matches the server bandit row.
@@ -381,11 +422,30 @@ type SentientConfig = {
381
422
  * Defaults to the nonce of a script already on the page.
382
423
  */
383
424
  nonce?: string;
425
+ /**
426
+ * Opt-in: write the visitor's funnel stage to `<html data-sentient-stage>`
427
+ * after each decide (and remember it for the next visit's pre-paint script),
428
+ * so a theme can make deterministic CSS changes per stage. Only projects
429
+ * with stages turned on send one. `true` exposes `new`, `browsing`, `carted`
430
+ * and `returning` (has bought here — `customer`/`lapsed` collapsed, since any
431
+ * script on the page can read it); `'detailed'` exposes `customer` and
432
+ * `lapsed` as they are. How the visitor arrived is never written.
433
+ */
434
+ stageAttributes?: StageAttributes;
384
435
  };
385
436
  type AssignResult = {
386
437
  variantId: string;
387
438
  assignmentTtlMs: number;
388
439
  content?: string;
440
+ /** The operator migrated this component onto the shared track (one
441
+ * component model). Only answered to a request that sent `{ unified: true }`;
442
+ * nothing was assigned — `variantId` is only the declared baseline. */
443
+ unified?: true;
444
+ };
445
+ /** What the caller of `assign` can do with the answer. */
446
+ type AssignOptions = {
447
+ /** Can render this component on the shared track (decide it as a slot). */
448
+ unified?: boolean;
389
449
  };
390
450
 
391
451
  /** An editor-defined goal delivered with a registry-mode decision, for the
@@ -418,6 +478,12 @@ type DecideOutcome = {
418
478
  sectionMap?: SectionMapEntry[];
419
479
  palette?: SitePalette;
420
480
  vocabulary?: StyleVocabulary;
481
+ /** The visit's funnel stage — only for projects with stages on, never for
482
+ * the control group. Raw: see `stageAttributes` for what reaches the page. */
483
+ stage?: string;
484
+ /** The visit's serving context (an arrival class or the stage). Never
485
+ * written to the page or the snapshot. */
486
+ context?: string;
421
487
  };
422
488
  type DecideInput = {
423
489
  sections?: string[];
@@ -498,9 +564,23 @@ type SentientClient = {
498
564
  */
499
565
  componentGoal(componentId: string, goalType: string, opts?: ComponentGoalOptions): void;
500
566
  identify(userId: string): void;
567
+ /**
568
+ * The visitor id (session id) for carrying a conversion to your server
569
+ * later: store it with the order/sign-up, then pass it to `trackServerGoal`.
570
+ * Null until the client is tracking with consent, and after forget-me.
571
+ * Optional only so hand-rolled clients (test doubles) keep type-checking;
572
+ * every client the SDK creates implements it.
573
+ */
574
+ getVisitorId?(): string | null;
501
575
  getAssignment(componentId: string, segment: string): Assignment | null;
502
- /** Server-side variant assignment. Caches the result locally per (component, segment). */
503
- assign(componentId: string, variantIds?: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>): Promise<AssignResult | null>;
576
+ /** True once this page knows the component was moved onto the shared track
577
+ * (SSR preload or a `unified` assign answer). */
578
+ isUnified?(componentId: string): boolean;
579
+ /** Server-side variant assignment. Caches the result locally per (component, segment).
580
+ * `opts.unified`: the caller can render a migrated component on the shared
581
+ * track; the server may then answer `{ unified: true }` (nothing assigned,
582
+ * nothing cached) and the caller decides it as a slot instead. */
583
+ assign(componentId: string, variantIds?: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>, opts?: AssignOptions): Promise<AssignResult | null>;
504
584
  /**
505
585
  * Single-roundtrip decision for layout sections, component variants, and
506
586
  * adaptive slots. Awaits the session upsert (like `assign`) so the server
@@ -530,6 +610,11 @@ type SentientClient = {
530
610
  * (registered before skeletons existed). Once per id per client; the server
531
611
  * stores it only while the slot has none. Optional for hand-rolled clients. */
532
612
  reportSkeleton?(slotId: string, skeleton: SkeletonReport): void;
613
+ /** Agent-readable data for the arm a slot served (`agentData` /
614
+ * `agentDataByVariant` on a slot-path <Adaptive>). Once per (slot, arm) per
615
+ * client, fire-and-forget; the server stores it against that arm so
616
+ * /sentient.json shows what visitors are shown. Optional for hand-rolled clients. */
617
+ reportAgentData?(slotId: string, armId: string, data: unknown): void;
533
618
  /** A served Rewrite arm could not be applied because the region's markup no
534
619
  * longer matches the skeleton it was written for. Batched, deduped per
535
620
  * (slot, fingerprint), never throws. Enough distinct visitors reporting the
@@ -656,4 +741,4 @@ declare function routeKey(): string;
656
741
  */
657
742
  declare function init(config: SentientConfig): SentientClient;
658
743
 
659
- export { type AssignResult as A, init as B, type ComponentGoalOptions as C, type DecideInput as D, type EventQueue as E, isDoNotTrackEnabled as F, type GoalDefinition as G, pageScopeMatches as H, resetRevealStyles as I, reveal as J, routeKey as K, LEGACY_SESSION_COOKIE_NAME as L, type MicroSignalEmitter as M, sanitizePageUrl as N, sessionCookieName as O, PAGE_SCOPE_RE as P, type QueueConfig as Q, REVEAL_MS as R, type SectionMapEntry as S, setCspNonce as T, type WeightEntry as W, _registerConsentUpgradeInit as _, type Assignment as a, type AssignmentCache as b, type AuthoredArmReport as c, type ComponentWeightEntry as d, type DecideOutcome as e, type EventType as f, type GoalOptions as g, type GraphClient as h, type GraphConfig as i, type GraphSnapshot as j, LOCAL_MODE_BANNER as k, type MicroSignalType as l, PROD_KEYLESS_ERROR as m, type PageNode as n, type RevealOptions as o, type SentientClient as p, type SentientConfig as q, type SentientEvent as r, type SessionConfig as s, type SessionManager as t, type SkeletonReport as u, applyNonce as v, attachMicroSignalDetectors as w, cspNonce as x, forgetGeneration as y, grantConsent as z };
744
+ export { setStageAttribute as $, type AssignOptions as A, cspNonce as B, type ComponentGoalOptions as C, type DecideInput as D, type EventQueue as E, exposedStage as F, type GoalDefinition as G, forgetGeneration as H, grantConsent as I, init as J, isDoNotTrackEnabled as K, LEGACY_SESSION_COOKIE_NAME as L, type MicroSignalEmitter as M, normalizeUrlPattern as N, pageScopeMatches as O, PAGE_SCOPE_RE as P, type QueueConfig as Q, REVEAL_MS as R, STAGE_ATTRIBUTE as S, resetRevealStyles as T, reveal as U, routeKey as V, type WeightEntry as W, sanitizePageUrl as X, sessionCookieName as Y, setCspNonce as Z, _registerConsentUpgradeInit as _, type AssignResult as a, urlMatches as a0, type Assignment as b, type AssignmentCache as c, type AuthoredArmReport as d, type ComponentWeightEntry as e, type DecideOutcome as f, type EventType as g, type GoalOptions as h, type GraphClient as i, type GraphConfig as j, type GraphSnapshot as k, LOCAL_MODE_BANNER as l, type MicroSignalType as m, PROD_KEYLESS_ERROR as n, type PageNode as o, type RevealOptions as p, type SectionMapEntry as q, type SentientClient as r, type SentientConfig as s, type SentientEvent as t, type SessionConfig as u, type SessionManager as v, type SkeletonReport as w, type StageAttributes as x, applyNonce as y, attachMicroSignalDetectors as z };
@@ -1,6 +1,6 @@
1
1
  import { $ as SitePalette, a4 as StyleVocabulary } from './style-vocabulary-Ba_g6_DD.js';
2
- import { d as SlotConfigEntry, e as SlotDeclInput, b as CompoundLocator } from './session-meta-DlCp0tyi.js';
3
- import { c as RenderCaps, R as RegionSkeleton } from './region-skeleton-D2ahkcbe.js';
2
+ import { d as SlotConfigEntry, e as SlotDeclInput, b as CompoundLocator } from './session-meta-BtRtwsHI.js';
3
+ import { c as RenderCaps, R as RegionSkeleton } from './region-skeleton-BRIVB-qf.js';
4
4
  import './index-consent.js';
5
5
  import { SlotResult } from '@sentientui/policy';
6
6
 
@@ -129,6 +129,20 @@ type GraphClient = {
129
129
  */
130
130
  declare function sanitizePageUrl(href: string): string;
131
131
 
132
+ /** `true` = coarse (`customer`/`lapsed` → `returning`); `'detailed'` = the stage as computed. */
133
+ type StageAttributes = boolean | 'detailed';
134
+ declare const STAGE_ATTRIBUTE = "data-sentient-stage";
135
+ /** The value the page may see for `stage`, or null for "set nothing". */
136
+ declare function exposedStage(stage: unknown, mode: StageAttributes | undefined): string | null;
137
+ /**
138
+ * Write (or, with null, remove) the attribute. Unlike the persona attributes
139
+ * this OVERWRITES: the pre-paint value comes from the previous visit's
140
+ * snapshot, and a visitor who bought since must not keep reading as `carted`
141
+ * for the rest of this visit. The stage is frozen per visit server-side, so a
142
+ * decide answer never changes it twice in one visit.
143
+ */
144
+ declare function setStageAttribute(value: string | null, doc?: Document): void;
145
+
132
146
  declare const PROD_KEYLESS_ERROR = "[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.";
133
147
  declare const LOCAL_MODE_BANNER = "[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.";
134
148
 
@@ -171,6 +185,27 @@ declare function forgetGeneration(apiKey: string): number;
171
185
  declare const PAGE_SCOPE_RE: RegExp;
172
186
  declare function pageScopeMatches(page: string | undefined, pathname: string): boolean;
173
187
 
188
+ /**
189
+ * url_reached matching, shared by the snippet (client-side wiring) and the API
190
+ * (server-side matching on pageview ingest) so the two can never disagree about
191
+ * whether a path satisfies a goal.
192
+ *
193
+ * A pattern matches the current path on an exact hit or a path-segment
194
+ * boundary — never a bare substring. Substring matching made the degenerate '/'
195
+ * pattern (what the editor's "Track page visits" button saves on a homepage)
196
+ * contain every path, firing the homepage goal on every route; it also let
197
+ * '/pricing' over-match '/pricing-details'. The root '/' matches only '/', and
198
+ * '/pricing' matches '/pricing' and '/pricing/monthly' but not '/pricing-x'.
199
+ */
200
+ declare function urlMatches(pattern: string, path: string): boolean;
201
+ /**
202
+ * Reduce a pasted full URL to its path. An operator who copies
203
+ * `https://host/pricing` into a url_reached goal saved a pattern that no
204
+ * pathname ever starts with, so the goal silently never fired. A path (or
205
+ * anything unparseable) passes through unchanged.
206
+ */
207
+ declare function normalizeUrlPattern(p: string): string;
208
+
174
209
  /**
175
210
  * The adaptation reveal — the 0.X-second moment a visitor notices the page is
176
211
  * for them (`what-sentient-is-becoming.md` §"Fast generation and the wow",
@@ -278,6 +313,12 @@ type SentientConfig = {
278
313
  * variantIds) still fetch once when the seed carries no content.
279
314
  */
280
315
  initialAssignments?: Record<string, string>;
316
+ /**
317
+ * Component ids an SSR preload found moved onto the shared track
318
+ * (`preloadAssignmentsDetailed` / `preloadDecisions` with the unified cap).
319
+ * Their cached assignments are ignored and `isUnified` reports them.
320
+ */
321
+ initialUnified?: string[];
281
322
  /**
282
323
  * Segment used for SSR preload (`device:source`). When set with `initialAssignments`,
283
324
  * seeds the assignment cache under this key so hydration matches the server bandit row.
@@ -381,11 +422,30 @@ type SentientConfig = {
381
422
  * Defaults to the nonce of a script already on the page.
382
423
  */
383
424
  nonce?: string;
425
+ /**
426
+ * Opt-in: write the visitor's funnel stage to `<html data-sentient-stage>`
427
+ * after each decide (and remember it for the next visit's pre-paint script),
428
+ * so a theme can make deterministic CSS changes per stage. Only projects
429
+ * with stages turned on send one. `true` exposes `new`, `browsing`, `carted`
430
+ * and `returning` (has bought here — `customer`/`lapsed` collapsed, since any
431
+ * script on the page can read it); `'detailed'` exposes `customer` and
432
+ * `lapsed` as they are. How the visitor arrived is never written.
433
+ */
434
+ stageAttributes?: StageAttributes;
384
435
  };
385
436
  type AssignResult = {
386
437
  variantId: string;
387
438
  assignmentTtlMs: number;
388
439
  content?: string;
440
+ /** The operator migrated this component onto the shared track (one
441
+ * component model). Only answered to a request that sent `{ unified: true }`;
442
+ * nothing was assigned — `variantId` is only the declared baseline. */
443
+ unified?: true;
444
+ };
445
+ /** What the caller of `assign` can do with the answer. */
446
+ type AssignOptions = {
447
+ /** Can render this component on the shared track (decide it as a slot). */
448
+ unified?: boolean;
389
449
  };
390
450
 
391
451
  /** An editor-defined goal delivered with a registry-mode decision, for the
@@ -418,6 +478,12 @@ type DecideOutcome = {
418
478
  sectionMap?: SectionMapEntry[];
419
479
  palette?: SitePalette;
420
480
  vocabulary?: StyleVocabulary;
481
+ /** The visit's funnel stage — only for projects with stages on, never for
482
+ * the control group. Raw: see `stageAttributes` for what reaches the page. */
483
+ stage?: string;
484
+ /** The visit's serving context (an arrival class or the stage). Never
485
+ * written to the page or the snapshot. */
486
+ context?: string;
421
487
  };
422
488
  type DecideInput = {
423
489
  sections?: string[];
@@ -498,9 +564,23 @@ type SentientClient = {
498
564
  */
499
565
  componentGoal(componentId: string, goalType: string, opts?: ComponentGoalOptions): void;
500
566
  identify(userId: string): void;
567
+ /**
568
+ * The visitor id (session id) for carrying a conversion to your server
569
+ * later: store it with the order/sign-up, then pass it to `trackServerGoal`.
570
+ * Null until the client is tracking with consent, and after forget-me.
571
+ * Optional only so hand-rolled clients (test doubles) keep type-checking;
572
+ * every client the SDK creates implements it.
573
+ */
574
+ getVisitorId?(): string | null;
501
575
  getAssignment(componentId: string, segment: string): Assignment | null;
502
- /** Server-side variant assignment. Caches the result locally per (component, segment). */
503
- assign(componentId: string, variantIds?: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>): Promise<AssignResult | null>;
576
+ /** True once this page knows the component was moved onto the shared track
577
+ * (SSR preload or a `unified` assign answer). */
578
+ isUnified?(componentId: string): boolean;
579
+ /** Server-side variant assignment. Caches the result locally per (component, segment).
580
+ * `opts.unified`: the caller can render a migrated component on the shared
581
+ * track; the server may then answer `{ unified: true }` (nothing assigned,
582
+ * nothing cached) and the caller decides it as a slot instead. */
583
+ assign(componentId: string, variantIds?: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>, opts?: AssignOptions): Promise<AssignResult | null>;
504
584
  /**
505
585
  * Single-roundtrip decision for layout sections, component variants, and
506
586
  * adaptive slots. Awaits the session upsert (like `assign`) so the server
@@ -530,6 +610,11 @@ type SentientClient = {
530
610
  * (registered before skeletons existed). Once per id per client; the server
531
611
  * stores it only while the slot has none. Optional for hand-rolled clients. */
532
612
  reportSkeleton?(slotId: string, skeleton: SkeletonReport): void;
613
+ /** Agent-readable data for the arm a slot served (`agentData` /
614
+ * `agentDataByVariant` on a slot-path <Adaptive>). Once per (slot, arm) per
615
+ * client, fire-and-forget; the server stores it against that arm so
616
+ * /sentient.json shows what visitors are shown. Optional for hand-rolled clients. */
617
+ reportAgentData?(slotId: string, armId: string, data: unknown): void;
533
618
  /** A served Rewrite arm could not be applied because the region's markup no
534
619
  * longer matches the skeleton it was written for. Batched, deduped per
535
620
  * (slot, fingerprint), never throws. Enough distinct visitors reporting the
@@ -656,4 +741,4 @@ declare function routeKey(): string;
656
741
  */
657
742
  declare function init(config: SentientConfig): SentientClient;
658
743
 
659
- export { type AssignResult as A, init as B, type ComponentGoalOptions as C, type DecideInput as D, type EventQueue as E, isDoNotTrackEnabled as F, type GoalDefinition as G, pageScopeMatches as H, resetRevealStyles as I, reveal as J, routeKey as K, LEGACY_SESSION_COOKIE_NAME as L, type MicroSignalEmitter as M, sanitizePageUrl as N, sessionCookieName as O, PAGE_SCOPE_RE as P, type QueueConfig as Q, REVEAL_MS as R, type SectionMapEntry as S, setCspNonce as T, type WeightEntry as W, _registerConsentUpgradeInit as _, type Assignment as a, type AssignmentCache as b, type AuthoredArmReport as c, type ComponentWeightEntry as d, type DecideOutcome as e, type EventType as f, type GoalOptions as g, type GraphClient as h, type GraphConfig as i, type GraphSnapshot as j, LOCAL_MODE_BANNER as k, type MicroSignalType as l, PROD_KEYLESS_ERROR as m, type PageNode as n, type RevealOptions as o, type SentientClient as p, type SentientConfig as q, type SentientEvent as r, type SessionConfig as s, type SessionManager as t, type SkeletonReport as u, applyNonce as v, attachMicroSignalDetectors as w, cspNonce as x, forgetGeneration as y, grantConsent as z };
744
+ export { setStageAttribute as $, type AssignOptions as A, cspNonce as B, type ComponentGoalOptions as C, type DecideInput as D, type EventQueue as E, exposedStage as F, type GoalDefinition as G, forgetGeneration as H, grantConsent as I, init as J, isDoNotTrackEnabled as K, LEGACY_SESSION_COOKIE_NAME as L, type MicroSignalEmitter as M, normalizeUrlPattern as N, pageScopeMatches as O, PAGE_SCOPE_RE as P, type QueueConfig as Q, REVEAL_MS as R, STAGE_ATTRIBUTE as S, resetRevealStyles as T, reveal as U, routeKey as V, type WeightEntry as W, sanitizePageUrl as X, sessionCookieName as Y, setCspNonce as Z, _registerConsentUpgradeInit as _, type AssignResult as a, urlMatches as a0, type Assignment as b, type AssignmentCache as c, type AuthoredArmReport as d, type ComponentWeightEntry as e, type DecideOutcome as f, type EventType as g, type GoalOptions as h, type GraphClient as i, type GraphConfig as j, type GraphSnapshot as k, LOCAL_MODE_BANNER as l, type MicroSignalType as m, PROD_KEYLESS_ERROR as n, type PageNode as o, type RevealOptions as p, type SectionMapEntry as q, type SentientClient as r, type SentientConfig as s, type SentientEvent as t, type SessionConfig as u, type SessionManager as v, type SkeletonReport as w, type StageAttributes as x, applyNonce as y, attachMicroSignalDetectors as z };