@trycurious/js 0.1.0 → 0.2.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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/identity.ts","../src/cache.ts","../src/events.ts","../src/tags.ts","../src/version.ts","../src/transport.ts","../src/client.ts"],"sourcesContent":["// The SDK error model (docs/sdk.md §24), shared in shape with the server\n// package: a stable code and a bounded, redacted message. Browser diagnostics\n// reach the customer only through hooks (onFallback, onEventDrop); nothing is\n// logged unless debug is on, and nothing ever carries a key, a user field,\n// content or a raw body.\n\nexport type CuriousErrorCode =\n | \"invalid_configuration\"\n | \"invalid_key_type\"\n | \"invalid_input\"\n | \"timeout\"\n | \"network_error\"\n | \"authentication_error\"\n | \"origin_not_allowed\"\n | \"rate_limited\"\n | \"undeclared_element\"\n | \"server_error\"\n | \"protocol_error\"\n | \"content_shape_mismatch\"\n | \"queue_full\"\n | \"event_rejected\"\n | \"identity_conflict\"\n | \"capability_unavailable\"\n | \"mutation_drift\"\n | \"lock_timeout\";\n\nexport type CuriousErrorSummary = {\n code: CuriousErrorCode;\n status?: number;\n retryable: boolean;\n requestId?: string;\n serverCode?: string;\n message: string;\n};\n\nexport class CuriousError extends Error {\n readonly summary: CuriousErrorSummary;\n constructor(summary: CuriousErrorSummary) {\n super(summary.message);\n this.name = \"CuriousError\";\n this.summary = summary;\n }\n get code(): CuriousErrorCode {\n return this.summary.code;\n }\n}\n\nconst LIMIT = 300;\n\nexport function summary(\n code: CuriousErrorCode,\n message: string,\n extra: Partial<Omit<CuriousErrorSummary, \"code\" | \"message\">> = {},\n): CuriousErrorSummary {\n const retryable = extra.retryable ??\n (code === \"timeout\" || code === \"network_error\" || code === \"rate_limited\" || code === \"server_error\");\n const out: CuriousErrorSummary = {\n code,\n retryable,\n message: message.length > LIMIT ? `${message.slice(0, LIMIT)}…` : message,\n };\n if (extra.status !== undefined) out.status = extra.status;\n if (extra.requestId !== undefined) out.requestId = extra.requestId;\n if (extra.serverCode !== undefined) out.serverCode = extra.serverCode;\n return out;\n}\n\ntype Envelope = { error: string; message: string };\n\nfunction envelope(body: unknown): Envelope | null {\n if (\n typeof body === \"object\" && body !== null &&\n typeof (body as Envelope).error === \"string\" && typeof (body as Envelope).message === \"string\"\n ) return body as Envelope;\n return null;\n}\n\n// Map an API error (the data plane's `{error, message}` envelope at a status)\n// onto the code a hook receives. Item-level errors inside a batch 200 pass\n// their own code with a synthetic status.\nexport function summarizeHttpError(status: number, body: unknown, requestId: string | null): CuriousErrorSummary {\n const env = envelope(body);\n const message = env?.message ?? `HTTP ${status}`;\n const extra: Partial<CuriousErrorSummary> = { status };\n if (requestId !== null) extra.requestId = requestId;\n if (env !== null) extra.serverCode = env.error;\n if (status === 401) return summary(\"authentication_error\", message, extra);\n if (status === 403) return summary(/origin/i.test(message) ? \"origin_not_allowed\" : \"authentication_error\", message, extra);\n if (status === 408) return summary(\"timeout\", message, extra);\n if (status === 429) return summary(\"rate_limited\", message, extra);\n if (status === 409) {\n if (env?.error === \"idempotency_error\") return summary(\"mutation_drift\", message, extra);\n // The user's identity changed while the decision was selecting; the same\n // request succeeds on a retry. The server package maps it the same way.\n if (env?.error === \"lock_timeout\") return summary(\"lock_timeout\", message, { ...extra, retryable: true });\n if (/no live experiment/i.test(message)) return summary(\"undeclared_element\", message, extra);\n return summary(\"invalid_input\", message, { ...extra, retryable: /retry/i.test(message) });\n }\n if (status >= 500) return summary(\"server_error\", message, extra);\n if (status === 400 || status === 413 || status === 422) return summary(\"invalid_input\", message, extra);\n return summary(\"protocol_error\", message, { ...extra, retryable: false });\n}\n","// Anonymous and known identity in the browser (docs/sdk.md §15, §21).\n//\n// The anonymous id is `anon_<uuid>` from a cryptographic source, kept in a\n// first-party host-only cookie (SameSite=Lax, Secure on https, bounded\n// lifetime) with localStorage as a recovery mirror and memory as the last\n// resort. The SDK never infers identity from a device, IP or fingerprint; the\n// known id arrives only through identify(), after the customer's backend has\n// declared the link with a secret key. Under consent mode `required`, nothing\n// is read or written until grantConsent().\n\nimport { CuriousError, summary } from \"./errors.ts\";\n\nexport const COOKIE_NAME = \"curious_anon\";\nexport const STORAGE_KEY = \"curious:anon\";\nexport const KNOWN_KEY = \"curious:user\";\n// One year: the stickiness a static assignment needs, bounded as the spec\n// asks and disclosed in the docs; the owner's retention review may shorten it.\nexport const DEFAULT_COOKIE_MAX_AGE_SECONDS = 365 * 24 * 60 * 60;\n\nexport type StorageMode = \"cookie\" | \"memory\";\n\nexport type IdentityOptions = {\n cookieMaxAgeSeconds?: number;\n /** Tests inject a document/storage pair; browsers use the globals. */\n document?: Document | undefined;\n storage?: Storage | null | undefined;\n};\n\nexport class Identity {\n private readonly maxAge: number;\n private readonly doc: Document | null;\n private readonly local: Storage | null;\n private readonly session: Storage | null;\n private anonymous: string | null = null;\n private known: string | null = null;\n private enabled = false;\n\n constructor(options: IdentityOptions = {}) {\n this.maxAge = options.cookieMaxAgeSeconds ?? DEFAULT_COOKIE_MAX_AGE_SECONDS;\n this.doc = options.document ?? (typeof document === \"undefined\" ? null : document);\n this.local = options.storage === undefined ? safeStorage(\"localStorage\") : options.storage;\n this.session = safeStorage(\"sessionStorage\");\n }\n\n /** Called when consent allows identity: reads or mints the anonymous id. */\n enable(): void {\n this.enabled = true;\n this.known = this.session === null ? null : safeGet(this.session, KNOWN_KEY);\n this.anonymous = this.readCookie() ?? (this.local === null ? null : safeGet(this.local, STORAGE_KEY));\n if (this.anonymous === null) this.anonymous = newAnonymousId();\n this.persistAnonymous();\n }\n\n /** The id decisions and events are made for: the known user when set, else the anonymous one. */\n get activeUserId(): string {\n if (!this.enabled) {\n throw new CuriousError(summary(\"capability_unavailable\", \"Identity is unavailable before consent\", { retryable: false }));\n }\n return this.known ?? (this.anonymous as string);\n }\n\n get anonymousId(): string | null {\n return this.anonymous;\n }\n\n get knownUserId(): string | null {\n return this.known;\n }\n\n /** After the customer's backend linked the anonymous id, switch the active user. The anonymous id is retained as link evidence. */\n setKnown(userId: string): void {\n this.known = userId;\n if (this.session !== null) safeSet(this.session, KNOWN_KEY, userId);\n }\n\n /** Logout: drop the known id and start a fresh anonymous history. Never unlinks server-side. */\n reset(): void {\n this.known = null;\n if (this.session !== null) safeRemove(this.session, KNOWN_KEY);\n this.anonymous = newAnonymousId();\n this.persistAnonymous();\n }\n\n /** denyConsent(): remove everything the SDK stored about this browser. */\n clear(): void {\n this.enabled = false;\n this.known = null;\n this.anonymous = null;\n if (this.session !== null) safeRemove(this.session, KNOWN_KEY);\n if (this.local !== null) safeRemove(this.local, STORAGE_KEY);\n this.writeCookie(\"\", 0);\n }\n\n private persistAnonymous(): void {\n if (this.anonymous === null) return;\n this.writeCookie(this.anonymous, this.maxAge);\n if (this.local !== null) safeSet(this.local, STORAGE_KEY, this.anonymous);\n }\n\n private readCookie(): string | null {\n if (this.doc === null) return null;\n const match = this.doc.cookie.split(\"; \").find((part) => part.startsWith(`${COOKIE_NAME}=`));\n if (match === undefined) return null;\n const value = decodeURIComponent(match.slice(COOKIE_NAME.length + 1));\n return /^anon_[0-9a-f-]{36}$/.test(value) ? value : null;\n }\n\n private writeCookie(value: string, maxAge: number): void {\n if (this.doc === null) return;\n const secure = this.doc.location?.protocol === \"https:\" ? \"; Secure\" : \"\";\n try {\n // Host-only (no Domain attribute): no widening to parent domains by default.\n this.doc.cookie = `${COOKIE_NAME}=${encodeURIComponent(value)}; Max-Age=${maxAge}; Path=/; SameSite=Lax${secure}`;\n } catch {\n // Cookies blocked: memory and localStorage carry the id for this page.\n }\n }\n}\n\nexport function newAnonymousId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `anon_${crypto.randomUUID()}`;\n }\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return `anon_${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nexport function safeStorage(kind: \"localStorage\" | \"sessionStorage\"): Storage | null {\n try {\n const store = globalThis[kind];\n const probe = \"__curious_probe__\";\n store.setItem(probe, \"1\");\n store.removeItem(probe);\n return store;\n } catch {\n return null;\n }\n}\n\nexport function safeGet(store: Storage, key: string): string | null {\n try {\n return store.getItem(key);\n } catch {\n return null;\n }\n}\n\nexport function safeSet(store: Storage, key: string, value: string): void {\n try {\n store.setItem(key, value);\n } catch {\n // Quota or privacy mode: degrade to memory.\n }\n}\n\nexport function safeRemove(store: Storage, key: string): void {\n try {\n store.removeItem(key);\n } catch {\n // Nothing to do.\n }\n}\n","// The assignment cache (docs/sdk.md §17): returned content kept in\n// sessionStorage (memory fallback) for fast remounts and short repeat\n// navigation, 60 seconds by default. A hit renders without a call, so no new\n// decision row is written; a miss decides before anything is applied. Keyed\n// by key fingerprint, origin, active user and element, so a user or key\n// change never serves another's content.\n\nimport { safeGet, safeRemove, safeSet, safeStorage } from \"./identity.ts\";\n\nexport const CACHE_SCHEMA = 1;\nexport const DEFAULT_CACHE_TTL_MS = 60_000;\nconst PREFIX = \"curious:assign:\";\n\nexport type CachedAssignment = {\n content: unknown;\n armId: string;\n armType: \"control\" | \"variant\" | null;\n experimentId: string;\n experimentStatus: string;\n storedAt: number;\n expiresAt: number;\n schema: number;\n};\n\nexport class AssignmentCache {\n private readonly store: Storage | null;\n private readonly memory = new Map<string, string>();\n private readonly ttlMs: number;\n private readonly fingerprint: string;\n\n constructor(options: { publishableKey: string; ttlMs?: number; storage?: Storage | null }) {\n this.store = options.storage === undefined ? safeStorage(\"sessionStorage\") : options.storage;\n this.ttlMs = options.ttlMs ?? DEFAULT_CACHE_TTL_MS;\n // The last characters of the key, never the key: enough to separate two\n // keys on one origin without storing anything secret-shaped.\n this.fingerprint = options.publishableKey.slice(-8);\n }\n\n private key(userId: string, element: string): string {\n const origin = typeof location === \"undefined\" ? \"\" : location.origin;\n return `${PREFIX}${this.fingerprint}:${origin}:${userId}:${element}`;\n }\n\n get(userId: string, element: string, now = Date.now()): CachedAssignment | null {\n const key = this.key(userId, element);\n const raw = this.store === null ? this.memory.get(key) ?? null : safeGet(this.store, key);\n if (raw === null) return null;\n try {\n const parsed = JSON.parse(raw) as CachedAssignment;\n if (parsed.schema !== CACHE_SCHEMA || parsed.expiresAt <= now) {\n this.remove(userId, element);\n return null;\n }\n return parsed;\n } catch {\n this.remove(userId, element);\n return null;\n }\n }\n\n set(userId: string, element: string, value: Omit<CachedAssignment, \"storedAt\" | \"expiresAt\" | \"schema\">, now = Date.now()): void {\n const entry: CachedAssignment = { ...value, storedAt: now, expiresAt: now + this.ttlMs, schema: CACHE_SCHEMA };\n const key = this.key(userId, element);\n const raw = JSON.stringify(entry);\n if (this.store === null) this.memory.set(key, raw);\n else safeSet(this.store, key, raw);\n }\n\n remove(userId: string, element: string): void {\n const key = this.key(userId, element);\n this.memory.delete(key);\n if (this.store !== null) safeRemove(this.store, key);\n }\n\n /** identify(), reset(), denyConsent(): everything this SDK cached. */\n clear(): void {\n this.memory.clear();\n if (this.store === null) return;\n try {\n const doomed: string[] = [];\n for (let i = 0; i < this.store.length; i += 1) {\n const k = this.store.key(i);\n if (k !== null && k.startsWith(PREFIX)) doomed.push(k);\n }\n for (const k of doomed) this.store.removeItem(k);\n } catch {\n // Privacy mode: nothing persisted to clear.\n }\n }\n}\n","// The browser event queue (docs/sdk.md §19): bounded, mirrored to\n// sessionStorage so a same-tab navigation can retry with the original ids,\n// flushed on interval, count, visibilitychange-to-hidden, pagehide, and\n// explicit calls, with keepalive on lifecycle flushes and the body split under\n// the keepalive budget. Partial results follow the server SDK: successes and\n// duplicates leave, terminal rejections are dropped with a diagnostic,\n// retryable items keep their ids for a later attempt while the page lives.\n\nimport { CuriousError, summarizeHttpError, summary, type CuriousErrorSummary } from \"./errors.ts\";\nimport { safeGet, safeSet, safeStorage } from \"./identity.ts\";\nimport type { Transport } from \"./transport.ts\";\n\nexport type BrowserEventInput = {\n name: string;\n value?: number | null;\n properties?: Record<string, unknown>;\n context?: Record<string, unknown>;\n timestamp?: Date | string;\n id?: string;\n};\n\nexport type QueuedEvent = {\n id: string;\n user_id: string;\n name: string;\n value?: number | null;\n properties?: Record<string, unknown>;\n context?: Record<string, unknown>;\n timestamp?: string;\n};\n\nexport type FlushSummary = { sent: number; duplicates: number; failed: number; pending: number };\n\nexport type EventQueueOptions = {\n transport: Transport;\n userId: () => string;\n flushIntervalMs?: number;\n flushCount?: number;\n queueLimit?: number;\n keepaliveBodyBytes?: number;\n requestTimeoutMs?: number;\n maxAttempts?: number;\n onEventDrop: (error: CuriousErrorSummary) => void;\n storage?: Storage | null | undefined;\n now?: () => number;\n};\n\nconst DEFAULTS = {\n flushIntervalMs: 5_000,\n flushCount: 20,\n queueLimit: 100,\n keepaliveBodyBytes: 48 * 1024,\n requestTimeoutMs: 10_000,\n maxAttempts: 5,\n itemCap: 200,\n} as const;\n\nconst QUEUE_KEY = \"curious:events\";\nexport const RESERVED_PREFIX = \"$\";\n\ntype Entry = { event: QueuedEvent; attempts: number };\n\nexport class EventQueue {\n private readonly o: Required<Omit<EventQueueOptions, \"storage\" | \"now\">>;\n private readonly store: Storage | null;\n private readonly now: () => number;\n private readonly sessionId: string;\n private sequence = 0;\n private entries: Entry[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private inFlight: Promise<FlushSummary> | null = null;\n\n constructor(options: EventQueueOptions) {\n this.o = {\n transport: options.transport,\n userId: options.userId,\n flushIntervalMs: options.flushIntervalMs ?? DEFAULTS.flushIntervalMs,\n flushCount: options.flushCount ?? DEFAULTS.flushCount,\n queueLimit: options.queueLimit ?? DEFAULTS.queueLimit,\n keepaliveBodyBytes: options.keepaliveBodyBytes ?? DEFAULTS.keepaliveBodyBytes,\n requestTimeoutMs: options.requestTimeoutMs ?? DEFAULTS.requestTimeoutMs,\n maxAttempts: options.maxAttempts ?? DEFAULTS.maxAttempts,\n onEventDrop: options.onEventDrop,\n };\n this.store = options.storage === undefined ? safeStorage(\"sessionStorage\") : options.storage;\n this.now = options.now ?? Date.now;\n this.sessionId = Math.random().toString(36).slice(2, 10) + this.now().toString(36);\n this.restore();\n }\n\n get size(): number {\n return this.entries.length;\n }\n\n /** Customer events; `$` names are reserved for the SDK's own capture path. */\n track(input: BrowserEventInput): { id: string; queued: boolean } {\n if (typeof input.name === \"string\" && input.name.startsWith(RESERVED_PREFIX)) {\n throw new CuriousError(summary(\"invalid_input\", \"Event names starting with $ are reserved\", { retryable: false }));\n }\n return this.enqueue(input);\n }\n\n /** The SDK's own autocapture events (`$pageview`, `$click`, `$form_submit`). */\n system(input: BrowserEventInput): { id: string; queued: boolean } {\n return this.enqueue(input);\n }\n\n private enqueue(input: BrowserEventInput): { id: string; queued: boolean } {\n if (typeof input.name !== \"string\" || input.name.trim().length === 0) {\n throw new CuriousError(summary(\"invalid_input\", \"track: name is required\", { retryable: false }));\n }\n const event: QueuedEvent = {\n id: input.id ?? `browser:${this.sessionId}:${++this.sequence}:${Math.random().toString(36).slice(2, 8)}`,\n user_id: this.o.userId(),\n name: input.name,\n };\n if (input.value !== undefined) event.value = input.value;\n if (input.properties !== undefined) event.properties = input.properties;\n if (input.context !== undefined) event.context = input.context;\n if (input.timestamp !== undefined) {\n event.timestamp = input.timestamp instanceof Date ? input.timestamp.toISOString() : input.timestamp;\n }\n if (this.entries.length >= this.o.queueLimit) {\n this.o.onEventDrop(summary(\"queue_full\", `Event queue is full (${this.o.queueLimit}); event not queued`, { retryable: true }));\n return { id: event.id, queued: false };\n }\n this.entries.push({ event, attempts: 0 });\n this.persist();\n if (this.entries.length >= this.o.flushCount) {\n void this.flush();\n } else if (this.timer === null) {\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.flush();\n }, this.o.flushIntervalMs);\n }\n return { id: event.id, queued: true };\n }\n\n /** Deliver what is queued. `keepalive` is for lifecycle flushes (hidden, pagehide, before identify/reset). */\n flush(options: { keepalive?: boolean } = {}): Promise<FlushSummary> {\n if (this.inFlight === null) {\n this.inFlight = this.run(options.keepalive === true).finally(() => {\n this.inFlight = null;\n });\n }\n return this.inFlight;\n }\n\n /** reset()/denyConsent(): forget everything queued. */\n clear(): void {\n this.entries = [];\n this.persist();\n }\n\n private async run(keepalive: boolean): Promise<FlushSummary> {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n const totals: FlushSummary = { sent: 0, duplicates: 0, failed: 0, pending: 0 };\n while (this.entries.length > 0) {\n const batch = this.takeBatch(keepalive);\n if (batch.length === 0) break;\n const retry = await this.deliver(batch, keepalive, totals);\n // Retryable items go back to the front, in order, for a later flush;\n // this pass does not spin on them (the page must never block).\n if (retry.length > 0) {\n this.entries.unshift(...retry);\n this.persist();\n break;\n }\n }\n totals.pending = this.entries.length;\n this.persist();\n return totals;\n }\n\n // Up to the API's item cap, and under the keepalive body budget when the\n // flush rides keepalive.\n private takeBatch(keepalive: boolean): Entry[] {\n const batch: Entry[] = [];\n let bytes = 2;\n while (this.entries.length > 0 && batch.length < DEFAULTS.itemCap) {\n const next = this.entries[0]!;\n const size = JSON.stringify(next.event).length + 1;\n if (keepalive && batch.length > 0 && bytes + size > this.o.keepaliveBodyBytes) break;\n batch.push(this.entries.shift()!);\n bytes += size;\n }\n return batch;\n }\n\n private async deliver(batch: Entry[], keepalive: boolean, totals: FlushSummary): Promise<Entry[]> {\n for (const item of batch) item.attempts += 1;\n let response;\n try {\n response = await this.o.transport.post(\"/events\", { events: batch.map((e) => e.event) }, {\n timeoutMs: this.o.requestTimeoutMs,\n keepalive,\n });\n } catch (error) {\n return this.retryOrDrop(batch, (error as CuriousError).summary, totals);\n }\n if (response.status !== 200) {\n const failure = summarizeHttpError(response.status, response.body, response.requestId);\n if (!failure.retryable) {\n for (const item of batch) {\n totals.failed += 1;\n this.o.onEventDrop(summary(\"event_rejected\", failure.message, { ...failure, retryable: false }));\n }\n return [];\n }\n return this.retryOrDrop(batch, failure, totals);\n }\n const results = (response.body as { results?: unknown })?.results;\n if (!Array.isArray(results)) {\n return this.retryOrDrop(batch, summary(\"protocol_error\", \"Batch response carried no results\", { retryable: true }), totals);\n }\n const retry: Entry[] = [];\n batch.forEach((item, index) => {\n const result = results[index] as { index?: number; status?: string; error?: string; message?: string; duplicate?: true } | null | undefined;\n // An acknowledgement that cannot be matched to its event is not one:\n // retried within the same attempt limit as a malformed whole response.\n if (result === undefined || result === null || typeof result !== \"object\" || result.index !== index) {\n retry.push(...this.retryOrDrop([item], summary(\"protocol_error\", \"Batch response had no result for this event\", { retryable: true }), totals));\n return;\n }\n if (result.status === \"ok\") {\n totals.sent += 1;\n if (result.duplicate === true) totals.duplicates += 1;\n return;\n }\n const itemError = summarizeHttpError(result.error === \"internal_error\" ? 500 : 400, result, response.requestId);\n if (itemError.retryable && item.attempts < this.o.maxAttempts) {\n retry.push(item);\n return;\n }\n totals.failed += 1;\n this.o.onEventDrop(summary(\"event_rejected\", itemError.message, { ...itemError, retryable: false }));\n });\n return retry;\n }\n\n private retryOrDrop(batch: Entry[], failure: CuriousErrorSummary, totals: FlushSummary): Entry[] {\n const retry: Entry[] = [];\n for (const item of batch) {\n if (item.attempts < this.o.maxAttempts) {\n retry.push(item);\n } else {\n totals.failed += 1;\n this.o.onEventDrop(summary(\"event_rejected\", `Gave up after ${item.attempts} attempts: ${failure.message}`, {\n ...failure,\n retryable: false,\n }));\n }\n }\n return retry;\n }\n\n private persist(): void {\n if (this.store === null) return;\n safeSet(this.store, QUEUE_KEY, JSON.stringify(this.entries));\n }\n\n private restore(): void {\n if (this.store === null) return;\n const raw = safeGet(this.store, QUEUE_KEY);\n if (raw === null) return;\n try {\n const parsed = JSON.parse(raw) as Entry[];\n if (Array.isArray(parsed)) this.entries = parsed.filter((e) => e && typeof e.event?.id === \"string\").slice(0, this.o.queueLimit);\n } catch {\n this.entries = [];\n }\n }\n}\n","// Tagged content (docs/sdk.md §14, §16, §18): nodes with `data-curious` keep\n// their own text as the fallback, are decided when they approach the viewport\n// (one IntersectionObserver, 200% root margin), batched into one publishable\n// decide per frame, and never fought over with the page's framework: if\n// something else rewrites an applied node, the SDK records mutation_drift\n// once and leaves it alone. One MutationObserver picks up nodes added later;\n// `data-curious-ignore` excludes a subtree.\n//\n// The SDK replaces one run of plain text and nothing else. A tagged element\n// qualifies when it holds no child elements and at most one text node; the\n// SDK then writes into that text node itself, so a framework that owns the\n// node (React, after hydration) keeps owning it: its later updates reach the\n// page and are seen as drift. An element with child elements, or with text\n// made of several text nodes (a template with expressions), is never decided\n// and never written: assigning `textContent` there would delete the children,\n// and a decision for content that cannot be shown would record an exposure\n// that did not happen.\n\nexport const TAG_ATTRIBUTE = \"data-curious\";\nexport const IGNORE_ATTRIBUTE = \"data-curious-ignore\";\nexport const CRITICAL_ATTRIBUTE = \"data-curious-critical\";\nexport const LOADING_CLASS = \"curious-loading\";\nexport const DEFAULT_ROOT_MARGIN = \"200% 0px\";\n\nexport type TaggedNode = {\n element: string;\n node: Element;\n control: string;\n applied: string | null;\n state: \"idle\" | \"pending\" | \"decided\" | \"fallback\" | \"unsupported\";\n drifted: boolean;\n};\n\n/** Why a tagged element cannot take replaced text. */\nexport type UnsupportedReason = \"child_elements\" | \"several_text_nodes\" | \"void_element\";\n\n/**\n * What became of decided content: written to at least one node, refused\n * because it is not text, or left unwritten because no node could take it\n * (each such node was already reported as unsupported, or the page has since\n * taken its text back).\n */\nexport type ApplyOutcome = \"applied\" | \"not_text\" | \"no_node\";\n\nconst ELEMENT_NODE = 1;\nconst TEXT_NODE = 3;\n// HTML's void elements: a browser never renders text placed inside one.\nconst VOID_ELEMENTS = new Set([\"AREA\", \"BASE\", \"BR\", \"COL\", \"EMBED\", \"HR\", \"IMG\", \"INPUT\", \"LINK\", \"META\", \"SOURCE\", \"TRACK\", \"WBR\"]);\n\n// The one text node the SDK may write into, `null` for an element with no\n// text yet, or the reason the element's content is not one run of plain text.\n// Comment nodes are ignored: they hold no text and are left where they are.\nexport function textSlot(node: Element): { text: Text | null } | { unsupported: UnsupportedReason } {\n if (VOID_ELEMENTS.has(node.tagName.toUpperCase())) return { unsupported: \"void_element\" };\n let text: Text | null = null;\n for (const child of Array.from(node.childNodes)) {\n if (child.nodeType === ELEMENT_NODE) return { unsupported: \"child_elements\" };\n if (child.nodeType !== TEXT_NODE) continue;\n if (text !== null) return { unsupported: \"several_text_nodes\" };\n text = child as Text;\n }\n return { text };\n}\n\nexport type TagRuntimeOptions = {\n /** Called with the set of element names that became pending in one window. */\n onPending: (elements: string[]) => void;\n /** A node the page's framework rewrote after the SDK applied content. */\n onDrift: (element: string) => void;\n /** A tagged node whose content is not one run of plain text; reported once per node, never decided. */\n onUnsupported: (element: string, reason: UnsupportedReason) => void;\n rootMargin?: string;\n root?: ParentNode;\n};\n\nexport class TagRuntime {\n private readonly nodes = new Map<Element, TaggedNode>();\n private readonly byElement = new Map<string, Set<TaggedNode>>();\n private readonly pending = new Set<string>();\n // Nodes whose text the page took back after a decision. Kept apart from\n // `nodes` so the promise survives the node being removed and attached\n // again, and weakly so a discarded node can be collected.\n private released = new WeakSet<Element>();\n private readonly o: TagRuntimeOptions;\n private intersection: IntersectionObserver | null = null;\n private mutation: MutationObserver | null = null;\n private frame: ReturnType<typeof setTimeout> | null = null;\n\n constructor(options: TagRuntimeOptions) {\n this.o = options;\n }\n\n start(): void {\n if (typeof IntersectionObserver === \"function\") {\n this.intersection = new IntersectionObserver((entries) => {\n for (const entry of entries) {\n if (!entry.isIntersecting) continue;\n const tagged = this.nodes.get(entry.target);\n if (tagged === undefined || tagged.state !== \"idle\") continue;\n tagged.state = \"pending\";\n this.pending.add(tagged.element);\n this.intersection?.unobserve(entry.target);\n }\n this.schedule();\n }, { rootMargin: this.o.rootMargin ?? DEFAULT_ROOT_MARGIN, threshold: 0 });\n }\n if (typeof MutationObserver === \"function\") {\n this.mutation = new MutationObserver((records) => {\n for (const record of records) {\n if (record.type === \"childList\") {\n // Nodes the page removed are let go of, so a page that mounts\n // and unmounts sections does not accumulate them here.\n for (const removed of record.removedNodes) {\n if (removed instanceof Element) this.forgetRemoved(removed);\n }\n for (const added of record.addedNodes) {\n if (added instanceof Element) this.scan(added);\n }\n }\n // Text rewritten under an applied node by something else.\n const target = record.target instanceof Element ? record.target : record.target.parentElement;\n if (target !== null) this.detectDrift(target);\n }\n });\n const root = this.o.root ?? document;\n this.mutation.observe(root instanceof Document ? root.documentElement : (root as Node), {\n childList: true,\n subtree: true,\n characterData: true,\n });\n }\n this.scan(this.o.root ?? document);\n }\n\n stop(): void {\n this.intersection?.disconnect();\n this.mutation?.disconnect();\n this.intersection = null;\n this.mutation = null;\n if (this.frame !== null) clearTimeout(this.frame);\n this.frame = null;\n // Nothing is remembered across a stop: a later start() scans the page as\n // it then is. Remembered nodes would be skipped by that scan and never\n // watched by the new observers.\n this.nodes.clear();\n this.byElement.clear();\n this.pending.clear();\n this.released = new WeakSet();\n }\n\n /** Register every tagged node under `root` (the whole document by default). Safe to call repeatedly. */\n scan(root: ParentNode = this.o.root ?? document): void {\n const candidates: Element[] = [];\n if (root instanceof Element && root.hasAttribute(TAG_ATTRIBUTE)) candidates.push(root);\n candidates.push(...Array.from(root.querySelectorAll(`[${TAG_ATTRIBUTE}]`)));\n for (const node of candidates) {\n if (this.nodes.has(node) || this.released.has(node) || node.closest(`[${IGNORE_ATTRIBUTE}]`) !== null) continue;\n const element = (node.getAttribute(TAG_ATTRIBUTE) ?? \"\").trim();\n if (element.length === 0) continue;\n const tagged: TaggedNode = { element, node, control: node.textContent ?? \"\", applied: null, state: \"idle\", drifted: false };\n this.nodes.set(node, tagged);\n const slot = textSlot(node);\n if (\"unsupported\" in slot) {\n // Remembered, so a rescan does not report it again; never observed,\n // never pending, so no decision is requested on its account.\n this.refuse(tagged, slot.unsupported);\n continue;\n }\n let set = this.byElement.get(element);\n if (set === undefined) {\n set = new Set();\n this.byElement.set(element, set);\n }\n set.add(tagged);\n if (this.intersection !== null) this.intersection.observe(node);\n else {\n // No IntersectionObserver (an old or headless environment): decide on scan.\n tagged.state = \"pending\";\n this.pending.add(element);\n }\n }\n if (this.pending.size > 0) this.schedule();\n }\n\n /** Apply decided content to every node of an element that can take it. Non-string content leaves the control in place. */\n apply(element: string, content: unknown): ApplyOutcome {\n const set = this.byElement.get(element);\n if (set === undefined) return \"no_node\";\n if (typeof content !== \"string\") {\n for (const tagged of set) {\n if (!tagged.drifted) tagged.state = \"fallback\";\n }\n return \"not_text\";\n }\n let applied = false;\n for (const tagged of Array.from(set)) {\n // A node the page has removed shows nothing: writing to it is not\n // serving the content.\n if (!tagged.node.isConnected) {\n this.forget(tagged);\n continue;\n }\n // The page rewrote this node after an earlier decision: it owns the\n // text now, and a later decision for the same name (another node\n // mounting, a new user) does not take it back.\n if (tagged.drifted) continue;\n // The page may have changed the node since it was scanned.\n const slot = textSlot(tagged.node);\n if (\"unsupported\" in slot) {\n this.refuse(tagged, slot.unsupported);\n continue;\n }\n // Write into the existing text node, so whatever owns that node keeps\n // owning it. An element with no text yet gets a text node of its own.\n if (slot.text === null) tagged.node.appendChild(tagged.node.ownerDocument.createTextNode(content));\n else if (slot.text.data !== content) slot.text.data = content;\n tagged.applied = content;\n tagged.state = \"decided\";\n this.revealCritical(tagged.node);\n applied = true;\n }\n return applied ? \"applied\" : \"no_node\";\n }\n\n /** Leave the control visible and mark the element as decided against. */\n fallback(element: string): void {\n const set = this.byElement.get(element);\n if (set === undefined) return;\n for (const tagged of set) {\n tagged.state = \"fallback\";\n this.revealCritical(tagged.node);\n }\n }\n\n /** Forget decisions (identify/reset) so the nodes can be decided again for the new user. */\n resetDecisions(): void {\n for (const tagged of Array.from(this.nodes.values())) {\n if (!tagged.node.isConnected) {\n this.forget(tagged);\n continue;\n }\n // A node still waiting for the previous user's answer is decided again\n // too; that answer is discarded when it arrives.\n if ((tagged.state === \"decided\" || tagged.state === \"fallback\" || tagged.state === \"pending\") && !tagged.drifted) {\n tagged.state = \"idle\";\n tagged.applied = null;\n this.intersection?.observe(tagged.node);\n if (this.intersection === null) {\n tagged.state = \"pending\";\n this.pending.add(tagged.element);\n }\n }\n }\n if (this.pending.size > 0) this.schedule();\n }\n\n elements(): string[] {\n return Array.from(this.byElement.keys());\n }\n\n private schedule(): void {\n if (this.frame !== null || this.pending.size === 0) return;\n // A short window collects the tags that became pending together into one\n // batch request.\n this.frame = setTimeout(() => {\n this.frame = null;\n // A node may have changed since it was scanned (a framework rendering\n // children into it, or removing it, before it neared the viewport). Ask\n // only for names that a node near the viewport can still show.\n const batch = Array.from(this.pending).filter((element) => this.hasWritablePendingNode(element));\n this.pending.clear();\n if (batch.length > 0) this.o.onPending(batch);\n }, 0);\n }\n\n // True when a node that neared the viewport (state `pending`) is still on\n // the page and can still take text. A plain sibling that is still off\n // screen does not count: it asks for the decision when it gets near. Nodes\n // that can no longer take text are refused here, and removed ones\n // forgotten, before a decision is requested on their account.\n private hasWritablePendingNode(element: string): boolean {\n const set = this.byElement.get(element);\n if (set === undefined) return false;\n let writable = false;\n for (const tagged of Array.from(set)) {\n if (tagged.state !== \"pending\") continue;\n if (!tagged.node.isConnected) {\n this.forget(tagged);\n continue;\n }\n const slot = textSlot(tagged.node);\n if (\"unsupported\" in slot) this.refuse(tagged, slot.unsupported);\n else writable = true;\n }\n return writable;\n }\n\n private forgetRemoved(removed: Element): void {\n const candidates: Element[] = [removed, ...Array.from(removed.querySelectorAll(`[${TAG_ATTRIBUTE}]`))];\n for (const node of candidates) {\n const tagged = this.nodes.get(node);\n // Still connected means the page moved it; it stays known.\n if (tagged !== undefined && !node.isConnected) this.forget(tagged);\n }\n }\n\n // Drop a node the page has removed. If the same node is attached again, the\n // MutationObserver scans it afresh.\n private forget(tagged: TaggedNode): void {\n this.nodes.delete(tagged.node);\n this.byElement.get(tagged.element)?.delete(tagged);\n this.intersection?.unobserve(tagged.node);\n }\n\n // Take a node out of play for good: never observed, never decided, never\n // written, reported once.\n private refuse(tagged: TaggedNode, reason: UnsupportedReason): void {\n tagged.state = \"unsupported\";\n this.byElement.get(tagged.element)?.delete(tagged);\n this.intersection?.unobserve(tagged.node);\n this.revealCritical(tagged.node);\n this.o.onUnsupported(tagged.element, reason);\n }\n\n private detectDrift(target: Element): void {\n const node = target.closest(`[${TAG_ATTRIBUTE}]`);\n if (node === null) return;\n const tagged = this.nodes.get(node);\n if (tagged === undefined || tagged.state !== \"decided\" || tagged.drifted) return;\n if ((node.textContent ?? \"\") !== tagged.applied) {\n tagged.drifted = true;\n this.released.add(node);\n this.o.onDrift(tagged.element);\n }\n }\n\n private revealCritical(node: Element): void {\n if (node.hasAttribute(CRITICAL_ATTRIBUTE)) {\n document.documentElement.classList.remove(LOADING_CLASS);\n }\n }\n}\n","// Kept in step with package.json by the release checklist; sent as\n// `X-Curious-Client: browser-js/<version>` (docs/sdk.md §6).\nexport const SDK_VERSION = \"0.1.0\";\n","// The browser transport (docs/sdk.md §6, §16, §19): authenticated fetch with\n// the publishable key, a hard deadline, optional keepalive for lifecycle\n// flushes, and the region chosen through the query parameter Supabase\n// documents for callers that cannot add headers to a preflight.\n\nimport { CuriousError, summary } from \"./errors.ts\";\nimport { SDK_VERSION } from \"./version.ts\";\n\nexport type FetchLike = (input: string, init: RequestInit) => Promise<Response>;\n\nexport type TransportResponse = {\n status: number;\n requestId: string | null;\n retryAfterMs: number | null;\n body: unknown;\n};\n\nconst MAX_RESPONSE_BYTES = 1_048_576;\n\nexport class Transport {\n private readonly fetchImpl: FetchLike;\n private readonly baseUrl: string;\n private readonly headers: Record<string, string>;\n\n constructor(options: { publishableKey: string; baseUrl: string; fetch?: FetchLike | undefined }) {\n const fetchImpl = options.fetch ?? (typeof fetch === \"function\" ? fetch.bind(globalThis) : undefined);\n if (fetchImpl === undefined) {\n throw new CuriousError(summary(\"capability_unavailable\", \"fetch is not available\", { retryable: false }));\n }\n this.fetchImpl = fetchImpl;\n this.baseUrl = options.baseUrl.replace(/\\/+$/, \"\");\n this.headers = {\n authorization: `Bearer ${options.publishableKey}`,\n \"content-type\": \"application/json\",\n \"x-curious-client\": `browser-js/${SDK_VERSION}`,\n };\n }\n\n // POST one JSON body within the deadline. Throws for a timeout, a network\n // failure or an unreadable response; returns every HTTP status.\n async post(\n path: string,\n body: unknown,\n options: { timeoutMs: number; keepalive?: boolean },\n ): Promise<TransportResponse> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), options.timeoutMs);\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.baseUrl}${path}`, {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(body),\n signal: controller.signal,\n keepalive: options.keepalive === true,\n credentials: \"omit\",\n mode: \"cors\",\n });\n } catch (error) {\n if (controller.signal.aborted) {\n throw new CuriousError(summary(\"timeout\", `No response within ${options.timeoutMs}ms`));\n }\n throw new CuriousError(summary(\"network_error\", describe(error)));\n } finally {\n clearTimeout(timer);\n }\n const requestId = response.headers.get(\"x-request-id\");\n const retryAfterMs = parseRetryAfter(response.headers.get(\"retry-after\"));\n let text: string;\n try {\n text = await response.text();\n } catch (error) {\n throw new CuriousError(summary(\"network_error\", describe(error), { status: response.status }));\n }\n if (text.length > MAX_RESPONSE_BYTES) {\n throw new CuriousError(summary(\"protocol_error\", \"Response exceeds the size bound\", { status: response.status, retryable: false }));\n }\n let parsed: unknown = null;\n if (text.length > 0) {\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new CuriousError(summary(\"protocol_error\", `Response ${response.status} was not JSON`, {\n status: response.status,\n retryable: false,\n }));\n }\n }\n return { status: response.status, requestId, retryAfterMs, body: parsed };\n }\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error && error.message ? `Request failed: ${error.message}` : \"Request failed\";\n}\n\nexport function parseRetryAfter(value: string | null): number | null {\n if (value === null) return null;\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1000);\n const at = Date.parse(value);\n return Number.isNaN(at) ? null : Math.max(0, at - Date.now());\n}\n","// @trycurious/js — Curious in the browser (docs/sdk.md §13–§23). Publishable\n// keys only. Tagged text is decided when it approaches the viewport, in one\n// batch per frame, through the page's own text as the fallback; events batch\n// through a bounded queue that survives same-tab navigation; identity is an\n// anonymous first-party cookie until the customer's backend links it.\n\nimport { AssignmentCache } from \"./cache.ts\";\nimport { CuriousError, summarizeHttpError, summary, type CuriousErrorSummary } from \"./errors.ts\";\nimport { EventQueue, type BrowserEventInput, type FlushSummary } from \"./events.ts\";\nimport { Identity } from \"./identity.ts\";\nimport { TagRuntime } from \"./tags.ts\";\nimport { Transport, type FetchLike } from \"./transport.ts\";\n\nexport type ConsentMode = \"implicit\" | \"required\" | \"denied\";\n\nexport type BrowserOptions = {\n /** A publishable key (`curious_pk_...`). A secret key is refused: it must never reach a browser. */\n publishableKey: string;\n /** Default `https://api.trycurious.ai/v1`. */\n baseUrl?: string;\n /** The decide deadline; the page's text stays when it passes. Default 1000, may be lowered, never removed. */\n decideTimeoutMs?: number;\n /** `implicit` starts at once; `required` does nothing until grantConsent(); `denied` serves controls and collects nothing. */\n consent?: ConsentMode;\n /**\n * The SDK's own events, on by default (docs/sdk.md §19, Autocapture V1): `$pageview` with the\n * normalized path on start, `$click` and `$form_submit` on tagged nodes with the element name.\n * `false` turns them all off; an object turns individual ones off. The API admits them only under\n * a publishable key with the SDK's client header, which the transport always sends.\n */\n autocapture?: { pageviews?: boolean; taggedClicks?: boolean; taggedFormSubmits?: boolean } | false;\n /** Context sent with every tagged decision; `path` and `locale` are added unless you set them. */\n context?: Record<string, unknown>;\n rootMargin?: string;\n /** Queue tuning; the defaults are the spec's (5 s, 20 events, 100 queued). */\n events?: { flushIntervalMs?: number; flushCount?: number; queueLimit?: number };\n cacheTtlMs?: number;\n cookieMaxAgeSeconds?: number;\n onDecision?: (element: string, result: DecisionResult<unknown>) => void;\n onFallback?: (element: string, error: CuriousErrorSummary) => void;\n onEventDrop?: (error: CuriousErrorSummary) => void;\n onIdentityChange?: (userId: string | null) => void;\n /** For tests. */\n fetch?: FetchLike;\n document?: Document;\n storage?: Storage | null;\n debug?: boolean;\n};\n\nexport type DecisionResult<T> = {\n content: T;\n served: \"curious\" | \"fallback\" | \"cache\";\n armId: string | null;\n armType: \"control\" | \"variant\" | null;\n experimentId: string | null;\n experimentStatus: string | null;\n error?: CuriousErrorSummary;\n requestId: string | null;\n};\n\nexport type BrowserDecisionInput<T> = {\n element: string;\n fallback: T;\n identifiers?: Record<string, unknown>;\n attributes?: Record<string, unknown>;\n context?: Record<string, unknown>;\n};\n\nexport type CuriousBrowser = {\n start(): void;\n stop(): void;\n scan(root?: ParentNode): void;\n decide<T>(input: BrowserDecisionInput<T>): Promise<DecisionResult<T>>;\n track(input: BrowserEventInput): { id: string; queued: boolean };\n flush(options?: { keepalive?: boolean }): Promise<FlushSummary>;\n /**\n * Record a page view for the current location. Call it after a client-side route change: the SDK\n * records one page view on start and does not watch the History API. It records nothing when page\n * views are turned off through `autocapture`.\n */\n page(): { id: string; queued: boolean };\n identify(userId: string): Promise<{ userId: string }>;\n reset(): Promise<void>;\n grantConsent(): void;\n denyConsent(): void;\n readonly anonymousId: string | null;\n readonly userId: string | null;\n};\n\nconst DEFAULTS = { baseUrl: \"https://api.trycurious.ai/v1\", decideTimeoutMs: 1_000 } as const;\nconst PUBLISHABLE_PREFIX = \"curious_pk_\";\nconst DECIDE_BATCH_LIMIT = 50;\n\n// A batch item reports its error code without a status; these are the\n// statuses the same codes carry on a single decide, so both map alike. Kept\n// equal to the server package's table, plus `conflict` (an undeclared\n// element), which only a publishable key meets.\nconst BATCH_ITEM_STATUS: ReadonlyMap<string, number> = new Map([\n [\"internal_error\", 500],\n [\"decision_unavailable\", 503],\n [\"idempotency_error\", 409],\n [\"lock_timeout\", 409],\n [\"conflict\", 409],\n]);\n\nconst UNSUPPORTED_MESSAGE = {\n child_elements: \"The tagged element contains other elements; the SDK replaces plain text only. Tag the innermost element that holds only text\",\n several_text_nodes: \"The tagged element's text is made of several pieces (a template with expressions); the SDK replaces one run of plain text only\",\n void_element: \"The tagged element cannot hold text (an input, an image or another empty element); tag an element whose content is text\",\n} as const;\n\ntype ItemOk = { index: number; element: string; status: \"ok\"; content: unknown; arm_id: string; arm_type: \"control\" | \"variant\" | null; experiment_id: string; experiment_status: string };\ntype ItemError = { index: number; element?: string | null; status: \"error\"; error: string; message: string };\n\nexport function createCurious(options: BrowserOptions): CuriousBrowser {\n if (typeof options.publishableKey !== \"string\" || options.publishableKey.length === 0) {\n throw new CuriousError(summary(\"invalid_configuration\", \"publishableKey is required\", { retryable: false }));\n }\n if (!options.publishableKey.startsWith(PUBLISHABLE_PREFIX)) {\n // A secret key in a page is a leak; refuse without echoing it.\n throw new CuriousError(summary(\"invalid_key_type\", \"The browser SDK takes a publishable key (curious_pk_...). Never ship a secret key to a browser\", { retryable: false }));\n }\n const timeoutMs = Math.min(options.decideTimeoutMs ?? DEFAULTS.decideTimeoutMs, DEFAULTS.decideTimeoutMs * 10);\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new CuriousError(summary(\"invalid_configuration\", \"decideTimeoutMs must be a positive number\", { retryable: false }));\n }\n const onFallback = guarded(options.onFallback);\n const onDecision = guarded(options.onDecision);\n const onEventDrop = guarded(options.onEventDrop);\n const onIdentityChange = guarded(options.onIdentityChange);\n\n const transport = new Transport({ publishableKey: options.publishableKey, baseUrl: options.baseUrl ?? DEFAULTS.baseUrl, fetch: options.fetch });\n const identity = new Identity({\n ...(options.cookieMaxAgeSeconds === undefined ? {} : { cookieMaxAgeSeconds: options.cookieMaxAgeSeconds }),\n document: options.document,\n storage: options.storage,\n });\n const cache = new AssignmentCache({ publishableKey: options.publishableKey, ...(options.cacheTtlMs === undefined ? {} : { ttlMs: options.cacheTtlMs }), ...(options.storage === undefined ? {} : { storage: options.storage }) });\n let consent: ConsentMode = options.consent ?? \"implicit\";\n let started = false;\n let active = false;\n const inFlight = new Map<string, Promise<void>>();\n let events: EventQueue | null = null;\n const listeners: Array<() => void> = [];\n\n const tags = new TagRuntime({\n ...(options.rootMargin === undefined ? {} : { rootMargin: options.rootMargin }),\n onPending: (elements) => void decideTagged(elements),\n onDrift: (element) => onFallback(element, summary(\"mutation_drift\", \"Applied content was rewritten by the page; the SDK will not reapply it\", { retryable: false })),\n onUnsupported: (element, reason) => onFallback(element, summary(\"content_shape_mismatch\", UNSUPPORTED_MESSAGE[reason], { retryable: false })),\n });\n\n function pageContext(): Record<string, unknown> {\n const base: Record<string, unknown> = {};\n if (typeof location !== \"undefined\") base.path = location.pathname;\n if (typeof navigator !== \"undefined\" && navigator.language) base.locale = navigator.language;\n return { ...base, ...(options.context ?? {}) };\n }\n\n function queue(): EventQueue {\n if (events === null) {\n const tuning = options.events ?? {};\n events = new EventQueue({\n transport,\n userId: () => identity.activeUserId,\n onEventDrop,\n storage: options.storage,\n ...(tuning.flushIntervalMs === undefined ? {} : { flushIntervalMs: tuning.flushIntervalMs }),\n ...(tuning.flushCount === undefined ? {} : { flushCount: tuning.flushCount }),\n ...(tuning.queueLimit === undefined ? {} : { queueLimit: tuning.queueLimit }),\n });\n }\n return events;\n }\n\n // One batch decide for the tags that became pending together; one in-flight\n // request per (user, element), cache hits applied without a call.\n async function decideTagged(elements: string[]): Promise<void> {\n if (!active) return;\n const userId = identity.activeUserId;\n const toRequest: string[] = [];\n for (const element of elements) {\n const hit = cache.get(userId, element);\n if (hit !== null) {\n // Reported as served only when a node took the text.\n if (tags.apply(element, hit.content) === \"applied\") {\n onDecision(element, { content: hit.content, served: \"cache\", armId: hit.armId, armType: hit.armType, experimentId: hit.experimentId, experimentStatus: hit.experimentStatus, requestId: null });\n }\n continue;\n }\n if (!inFlight.has(`${userId}:${element}`)) toRequest.push(element);\n }\n if (toRequest.length === 0) return;\n const run = (async () => {\n for (let i = 0; i < toRequest.length; i += DECIDE_BATCH_LIMIT) {\n const slice = toRequest.slice(i, i + DECIDE_BATCH_LIMIT);\n await decideBatch(userId, slice);\n }\n })();\n for (const element of toRequest) inFlight.set(`${userId}:${element}`, run);\n try {\n await run;\n } finally {\n for (const element of toRequest) inFlight.delete(`${userId}:${element}`);\n }\n }\n\n async function decideBatch(userId: string, elements: string[]): Promise<void> {\n // While the request was out the SDK may have been stopped (stop(),\n // denyConsent()) or the visitor may have become someone else (identify(),\n // reset()). An answer for the earlier state is discarded: it is not\n // written to the page, cached or reported. After an identity change the\n // tags have already been queued again for the new user.\n const stale = () => !active || identity.activeUserId !== userId;\n // A later slice of a large batch: nothing more is sent for a state that\n // has already ended.\n if (stale()) return;\n let response;\n try {\n response = await transport.post(\"/decide\", {\n user_id: userId,\n context: pageContext(),\n elements: elements.map((element) => ({ element })),\n }, { timeoutMs });\n } catch (error) {\n if (stale()) return;\n for (const element of elements) fallbackTag(element, (error as CuriousError).summary);\n return;\n }\n if (stale()) return;\n if (response.status !== 200) {\n const failure = summarizeHttpError(response.status, response.body, response.requestId);\n for (const element of elements) fallbackTag(element, failure);\n return;\n }\n const results = (response.body as { results?: unknown })?.results;\n elements.forEach((element, index) => {\n if (stale()) return;\n const item = Array.isArray(results) ? (results[index] as ItemOk | ItemError | null | undefined) : undefined;\n if (item === undefined || item === null || typeof item !== \"object\" || item.index !== index) {\n fallbackTag(element, summary(\"protocol_error\", \"Batch response had no result for this element\", { retryable: false, status: 200 }));\n return;\n }\n if (item.status === \"error\") {\n fallbackTag(element, summarizeHttpError(BATCH_ITEM_STATUS.get(item.error) ?? 400, item, response.requestId));\n return;\n }\n const outcome = tags.apply(element, item.content);\n // apply() can call the customer's onFallback hook, and a hook may stop\n // the SDK or withdraw consent; nothing is cached or reported after that.\n if (stale()) return;\n if (outcome === \"not_text\") {\n fallbackTag(element, summary(\"content_shape_mismatch\", \"Served content is not text\", { retryable: false, status: 200 }));\n return;\n }\n // The decision exists on the server whatever the page did meanwhile, so\n // it is kept for a node that mounts later. It is reported as served\n // only when a node took the text; a node that could not was already\n // reported through onFallback.\n cache.set(userId, element, { content: item.content, armId: item.arm_id, armType: item.arm_type ?? null, experimentId: item.experiment_id, experimentStatus: item.experiment_status });\n if (outcome === \"applied\") {\n onDecision(element, { content: item.content, served: \"curious\", armId: item.arm_id, armType: item.arm_type ?? null, experimentId: item.experiment_id, experimentStatus: item.experiment_status, requestId: response.requestId });\n }\n });\n }\n\n function fallbackTag(element: string, error: CuriousErrorSummary): void {\n tags.fallback(element);\n onFallback(element, error);\n }\n\n function attachLifecycle(): void {\n if (typeof document === \"undefined\") return;\n const onVisibility = () => {\n if (document.visibilityState === \"hidden\" && events !== null) void events.flush({ keepalive: true });\n };\n const onPageHide = () => {\n if (events !== null) void events.flush({ keepalive: true });\n };\n document.addEventListener(\"visibilitychange\", onVisibility);\n addEventListener(\"pagehide\", onPageHide);\n listeners.push(() => document.removeEventListener(\"visibilitychange\", onVisibility));\n listeners.push(() => removeEventListener(\"pagehide\", onPageHide));\n\n if (options.autocapture === false) return;\n const capture = { pageviews: true, taggedClicks: true, taggedFormSubmits: true, ...options.autocapture };\n if (capture.pageviews) {\n queue().system({ name: \"$pageview\", properties: { path: location.pathname } });\n }\n if (capture.taggedClicks) {\n const onClick = (event: Event) => {\n const target = event.target instanceof Element ? event.target.closest(\"[data-curious]\") : null;\n if (target === null || target.closest(\"[data-curious-ignore]\") !== null) return;\n const element = target.getAttribute(\"data-curious\");\n if (element) queue().system({ name: \"$click\", properties: { element_name: element } });\n };\n document.addEventListener(\"click\", onClick, { capture: true, passive: true });\n listeners.push(() => document.removeEventListener(\"click\", onClick, { capture: true }));\n }\n if (capture.taggedFormSubmits) {\n const onSubmit = (event: Event) => {\n const target = event.target instanceof Element ? event.target.closest(\"[data-curious]\") : null;\n if (target === null || target.closest(\"[data-curious-ignore]\") !== null) return;\n const element = target.getAttribute(\"data-curious\");\n if (element) queue().system({ name: \"$form_submit\", properties: { element_name: element } });\n };\n document.addEventListener(\"submit\", onSubmit, { capture: true, passive: true });\n listeners.push(() => document.removeEventListener(\"submit\", onSubmit, { capture: true }));\n }\n }\n\n function activate(): void {\n if (active) return;\n identity.enable();\n active = true;\n attachLifecycle();\n tags.start();\n }\n\n const client: CuriousBrowser = {\n start() {\n started = true;\n if (consent === \"implicit\") activate();\n else if (consent === \"denied\" && typeof document !== \"undefined\") {\n document.documentElement.classList.remove(\"curious-loading\");\n }\n },\n stop() {\n started = false;\n active = false;\n tags.stop();\n for (const off of listeners.splice(0)) off();\n },\n scan(root) {\n if (active) tags.scan(root);\n },\n async decide<T>(input: BrowserDecisionInput<T>): Promise<DecisionResult<T>> {\n const fallback = (error: CuriousErrorSummary, requestId: string | null): DecisionResult<T> => {\n onFallback(input.element, error);\n return { content: input.fallback, served: \"fallback\", armId: null, armType: null, experimentId: null, experimentStatus: null, error, requestId };\n };\n if (!active) return fallback(summary(\"capability_unavailable\", \"The SDK is not active (consent or start)\", { retryable: false }), null);\n const body: Record<string, unknown> = { element: input.element, user_id: identity.activeUserId, context: { ...pageContext(), ...(input.context ?? {}) } };\n if (input.identifiers !== undefined) body.identifiers = input.identifiers;\n if (input.attributes !== undefined) body.attributes = input.attributes;\n let response;\n try {\n response = await transport.post(\"/decide\", body, { timeoutMs });\n } catch (error) {\n return fallback((error as CuriousError).summary, null);\n }\n if (response.status !== 200) return fallback(summarizeHttpError(response.status, response.body, response.requestId), response.requestId);\n const decision = response.body as Partial<ItemOk> | null;\n if (decision === null || typeof decision !== \"object\" || typeof decision.arm_id !== \"string\" || !(\"content\" in decision)) {\n return fallback(summary(\"protocol_error\", \"Decision response was missing required fields\", { retryable: false, status: 200 }), response.requestId);\n }\n if (typeof decision.content !== typeof input.fallback) {\n return fallback(summary(\"content_shape_mismatch\", \"Served content does not match the fallback's shape\", { retryable: false, status: 200 }), response.requestId);\n }\n const result: DecisionResult<T> = { content: decision.content as T, served: \"curious\", armId: decision.arm_id, armType: decision.arm_type ?? null, experimentId: decision.experiment_id ?? null, experimentStatus: decision.experiment_status ?? null, requestId: response.requestId };\n onDecision(input.element, result);\n return result;\n },\n track(input) {\n if (!active) {\n onEventDrop(summary(\"capability_unavailable\", \"Events are not collected before consent\", { retryable: false }));\n return { id: \"\", queued: false };\n }\n return queue().track(input);\n },\n flush(flushOptions) {\n if (events === null) return Promise.resolve({ sent: 0, duplicates: 0, failed: 0, pending: 0 });\n return events.flush(flushOptions);\n },\n page() {\n // The same switch as the page view on start: `autocapture: false` and\n // `autocapture: { pageviews: false }` turn this event off wherever it\n // would come from.\n if (options.autocapture === false || options.autocapture?.pageviews === false) return { id: \"\", queued: false };\n if (!active) {\n onEventDrop(summary(\"capability_unavailable\", \"Events are not collected before consent\", { retryable: false }));\n return { id: \"\", queued: false };\n }\n if (typeof location === \"undefined\") return { id: \"\", queued: false };\n // The path only, as on start: no query string, no hash (docs/sdk.md §19).\n return queue().system({ name: \"$pageview\", properties: { path: location.pathname } });\n },\n // After the customer's backend has linked the anonymous id with a secret\n // key: flush anonymous events, switch the active user, forget cached\n // assignments, decide tags again for the known user.\n async identify(userId) {\n if (typeof userId !== \"string\" || userId.trim().length === 0) {\n throw new CuriousError(summary(\"invalid_input\", \"identify: userId is required\", { retryable: false }));\n }\n if (!active) throw new CuriousError(summary(\"capability_unavailable\", \"The SDK is not active (consent or start)\", { retryable: false }));\n if (events !== null) await events.flush({ keepalive: true });\n identity.setKnown(userId);\n cache.clear();\n tags.resetDecisions();\n onIdentityChange(userId);\n return { userId };\n },\n // Logout: a bounded flush, then a fresh anonymous history. Never unlinks\n // anything server-side, and a failed flush never prevents the isolation.\n async reset() {\n if (events !== null) {\n try {\n await events.flush({ keepalive: true });\n } catch {\n // Best effort.\n }\n events.clear();\n }\n if (active) identity.reset();\n cache.clear();\n tags.resetDecisions();\n onIdentityChange(null);\n },\n grantConsent() {\n consent = \"implicit\";\n if (started) activate();\n },\n denyConsent() {\n consent = \"denied\";\n active = false;\n tags.stop();\n for (const off of listeners.splice(0)) off();\n events?.clear();\n cache.clear();\n identity.clear();\n onIdentityChange(null);\n },\n get anonymousId() {\n return identity.anonymousId;\n },\n get userId() {\n return identity.knownUserId;\n },\n };\n return client;\n}\n\nfunction guarded<A extends unknown[]>(hook: ((...args: A) => void) | undefined): (...args: A) => void {\n return (...args) => {\n if (hook === undefined) return;\n try {\n hook(...args);\n } catch {\n // A customer hook never breaks serving or the queue.\n }\n };\n}\n"],"mappings":";AAmCO,IAAM,eAAN,cAA2B,MAAM;AAAA,EAEtC,YAAYA,UAA8B;AACxC,UAAMA,SAAQ,OAAO;AACrB,SAAK,OAAO;AACZ,SAAK,UAAUA;AAAA,EACjB;AAAA,EACA,IAAI,OAAyB;AAC3B,WAAO,KAAK,QAAQ;AAAA,EACtB;AACF;AAEA,IAAM,QAAQ;AAEP,SAAS,QACd,MACA,SACA,QAAgE,CAAC,GAC5C;AACrB,QAAM,YAAY,MAAM,cACrB,SAAS,aAAa,SAAS,mBAAmB,SAAS,kBAAkB,SAAS;AACzF,QAAM,MAA2B;AAAA,IAC/B;AAAA,IACA;AAAA,IACA,SAAS,QAAQ,SAAS,QAAQ,GAAG,QAAQ,MAAM,GAAG,KAAK,CAAC,WAAM;AAAA,EACpE;AACA,MAAI,MAAM,WAAW,OAAW,KAAI,SAAS,MAAM;AACnD,MAAI,MAAM,cAAc,OAAW,KAAI,YAAY,MAAM;AACzD,MAAI,MAAM,eAAe,OAAW,KAAI,aAAa,MAAM;AAC3D,SAAO;AACT;AAIA,SAAS,SAAS,MAAgC;AAChD,MACE,OAAO,SAAS,YAAY,SAAS,QACrC,OAAQ,KAAkB,UAAU,YAAY,OAAQ,KAAkB,YAAY,SACtF,QAAO;AACT,SAAO;AACT;AAKO,SAAS,mBAAmB,QAAgB,MAAe,WAA+C;AAC/G,QAAM,MAAM,SAAS,IAAI;AACzB,QAAM,UAAU,KAAK,WAAW,QAAQ,MAAM;AAC9C,QAAM,QAAsC,EAAE,OAAO;AACrD,MAAI,cAAc,KAAM,OAAM,YAAY;AAC1C,MAAI,QAAQ,KAAM,OAAM,aAAa,IAAI;AACzC,MAAI,WAAW,IAAK,QAAO,QAAQ,wBAAwB,SAAS,KAAK;AACzE,MAAI,WAAW,IAAK,QAAO,Q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,eAAS,SAAS,MAAM;AACxB,YAAM,MAAM;AACZ,WAAK,eAAe;AACpB,uBAAiB,MAAM;AACvB,aAAO,EAAE,OAAO;AAAA,IAClB;AAAA;AAAA;AAAA,IAGA,MAAM,QAAQ;AACZ,UAAI,WAAW,MAAM;AACnB,YAAI;AACF,gBAAM,OAAO,MAAM,EAAE,WAAW,KAAK,CAAC;AAAA,QACxC,QAAQ;AAAA,QAER;AACA,eAAO,MAAM;AAAA,MACf;AACA,UAAI,OAAQ,UAAS,MAAM;AAC3B,YAAM,MAAM;AACZ,WAAK,eAAe;AACpB,uBAAiB,IAAI;AAAA,IACvB;AAAA,IACA,eAAe;AACb,gBAAU;AACV,UAAI,QAAS,UAAS;AAAA,IACxB;AAAA,IACA,cAAc;AACZ,gBAAU;AACV,eAAS;AACT,WAAK,KAAK;AACV,iBAAW,OAAO,UAAU,OAAO,CAAC,EAAG,KAAI;AAC3C,cAAQ,MAAM;AACd,YAAM,MAAM;AACZ,eAAS,MAAM;AACf,uBAAiB,IAAI;AAAA,IACvB;AAAA,IACA,IAAI,cAAc;AAChB,aAAO,SAAS;AAAA,IAClB;AAAA,IACA,IAAI,SAAS;AACX,aAAO,SAAS;AAAA,IAClB;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,QAA6B,MAAgE;AACpG,SAAO,IAAI,SAAS;AAClB,QAAI,SAAS,OAAW;AACxB,QAAI;AACF,WAAK,GAAG,IAAI;AAAA,IACd,QAAQ;AAAA,IAER;AAAA,EACF;AACF;","names":["summary","DEFAULTS"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/identity.ts","../src/cache.ts","../src/history.ts","../src/events.ts","../src/tags.ts","../src/version.ts","../src/transport.ts","../src/client.ts"],"sourcesContent":["// The SDK error model (docs/sdk.md §24), shared in shape with the server\n// package: a stable code and a bounded, redacted message. Browser diagnostics\n// reach the customer only through hooks (onFallback, onEventDrop); nothing is\n// logged unless debug is on, and nothing ever carries a key, a user field,\n// content or a raw body.\n\nexport type CuriousErrorCode =\n | \"invalid_configuration\"\n | \"invalid_key_type\"\n | \"invalid_input\"\n | \"timeout\"\n | \"network_error\"\n | \"authentication_error\"\n | \"origin_not_allowed\"\n | \"rate_limited\"\n | \"undeclared_element\"\n | \"server_error\"\n | \"protocol_error\"\n | \"content_shape_mismatch\"\n | \"queue_full\"\n | \"event_rejected\"\n | \"identity_conflict\"\n | \"capability_unavailable\"\n | \"mutation_drift\"\n | \"lock_timeout\";\n\nexport type CuriousErrorSummary = {\n code: CuriousErrorCode;\n status?: number;\n retryable: boolean;\n requestId?: string;\n serverCode?: string;\n message: string;\n};\n\nexport class CuriousError extends Error {\n readonly summary: CuriousErrorSummary;\n constructor(summary: CuriousErrorSummary) {\n super(summary.message);\n this.name = \"CuriousError\";\n this.summary = summary;\n }\n get code(): CuriousErrorCode {\n return this.summary.code;\n }\n}\n\nconst LIMIT = 300;\n\nexport function summary(\n code: CuriousErrorCode,\n message: string,\n extra: Partial<Omit<CuriousErrorSummary, \"code\" | \"message\">> = {},\n): CuriousErrorSummary {\n const retryable = extra.retryable ??\n (code === \"timeout\" || code === \"network_error\" || code === \"rate_limited\" || code === \"server_error\");\n const out: CuriousErrorSummary = {\n code,\n retryable,\n message: message.length > LIMIT ? `${message.slice(0, LIMIT)}…` : message,\n };\n if (extra.status !== undefined) out.status = extra.status;\n if (extra.requestId !== undefined) out.requestId = extra.requestId;\n if (extra.serverCode !== undefined) out.serverCode = extra.serverCode;\n return out;\n}\n\ntype Envelope = { error: string; message: string };\n\nfunction envelope(body: unknown): Envelope | null {\n if (\n typeof body === \"object\" && body !== null &&\n typeof (body as Envelope).error === \"string\" && typeof (body as Envelope).message === \"string\"\n ) return body as Envelope;\n return null;\n}\n\n// Map an API error (the data plane's `{error, message}` envelope at a status)\n// onto the code a hook receives. Item-level errors inside a batch 200 pass\n// their own code with a synthetic status.\nexport function summarizeHttpError(status: number, body: unknown, requestId: string | null): CuriousErrorSummary {\n const env = envelope(body);\n const message = env?.message ?? `HTTP ${status}`;\n const extra: Partial<CuriousErrorSummary> = { status };\n if (requestId !== null) extra.requestId = requestId;\n if (env !== null) extra.serverCode = env.error;\n if (status === 401) return summary(\"authentication_error\", message, extra);\n if (status === 403) return summary(/origin/i.test(message) ? \"origin_not_allowed\" : \"authentication_error\", message, extra);\n if (status === 408) return summary(\"timeout\", message, extra);\n if (status === 429) return summary(\"rate_limited\", message, extra);\n if (status === 409) {\n if (env?.error === \"idempotency_error\") return summary(\"mutation_drift\", message, extra);\n // The user's identity changed while the decision was selecting; the same\n // request succeeds on a retry. The server package maps it the same way.\n if (env?.error === \"lock_timeout\") return summary(\"lock_timeout\", message, { ...extra, retryable: true });\n if (/no live experiment/i.test(message)) return summary(\"undeclared_element\", message, extra);\n return summary(\"invalid_input\", message, { ...extra, retryable: /retry/i.test(message) });\n }\n if (status >= 500) return summary(\"server_error\", message, extra);\n if (status === 400 || status === 413 || status === 422) return summary(\"invalid_input\", message, extra);\n return summary(\"protocol_error\", message, { ...extra, retryable: false });\n}\n","// Anonymous and known identity in the browser (docs/sdk.md §15, §21).\n//\n// The anonymous id is `anon_<uuid>` from a cryptographic source, kept in a\n// first-party host-only cookie (SameSite=Lax, Secure on https, bounded\n// lifetime) with localStorage as a recovery mirror and memory as the last\n// resort. The SDK never infers identity from a device, IP or fingerprint; the\n// known id arrives only through identify(), after the customer's backend has\n// declared the link with a secret key. Under consent mode `required`, nothing\n// is read or written until grantConsent().\n\nimport { CuriousError, summary } from \"./errors.ts\";\n\nexport const COOKIE_NAME = \"curious_anon\";\nexport const STORAGE_KEY = \"curious:anon\";\nexport const KNOWN_KEY = \"curious:user\";\n// One year: the stickiness a static assignment needs, bounded as the spec\n// asks and disclosed in the docs; the owner's retention review may shorten it.\nexport const DEFAULT_COOKIE_MAX_AGE_SECONDS = 365 * 24 * 60 * 60;\n\nexport type StorageMode = \"cookie\" | \"memory\";\n\nexport type IdentityOptions = {\n cookieMaxAgeSeconds?: number;\n /** Tests inject a document/storage pair; browsers use the globals. */\n document?: Document | undefined;\n storage?: Storage | null | undefined;\n};\n\nexport class Identity {\n private readonly maxAge: number;\n private readonly doc: Document | null;\n private readonly local: Storage | null;\n private readonly session: Storage | null;\n private anonymous: string | null = null;\n private known: string | null = null;\n private enabled = false;\n\n constructor(options: IdentityOptions = {}) {\n this.maxAge = options.cookieMaxAgeSeconds ?? DEFAULT_COOKIE_MAX_AGE_SECONDS;\n this.doc = options.document ?? (typeof document === \"undefined\" ? null : document);\n this.local = options.storage === undefined ? safeStorage(\"localStorage\") : options.storage;\n this.session = safeStorage(\"sessionStorage\");\n }\n\n /** Called when consent allows identity: reads or mints the anonymous id. */\n enable(): void {\n this.enabled = true;\n this.known = this.session === null ? null : safeGet(this.session, KNOWN_KEY);\n this.anonymous = this.readCookie() ?? (this.local === null ? null : safeGet(this.local, STORAGE_KEY));\n if (this.anonymous === null) this.anonymous = newAnonymousId();\n this.persistAnonymous();\n }\n\n /** The id decisions and events are made for: the known user when set, else the anonymous one. */\n get activeUserId(): string {\n if (!this.enabled) {\n throw new CuriousError(summary(\"capability_unavailable\", \"Identity is unavailable before consent\", { retryable: false }));\n }\n return this.known ?? (this.anonymous as string);\n }\n\n get anonymousId(): string | null {\n return this.anonymous;\n }\n\n get knownUserId(): string | null {\n return this.known;\n }\n\n /** After the customer's backend linked the anonymous id, switch the active user. The anonymous id is retained as link evidence. */\n setKnown(userId: string): void {\n this.known = userId;\n if (this.session !== null) safeSet(this.session, KNOWN_KEY, userId);\n }\n\n /** Logout: drop the known id and start a fresh anonymous history. Never unlinks server-side. */\n reset(): void {\n this.known = null;\n if (this.session !== null) safeRemove(this.session, KNOWN_KEY);\n this.anonymous = newAnonymousId();\n this.persistAnonymous();\n }\n\n /** denyConsent(): remove everything the SDK stored about this browser. */\n clear(): void {\n this.enabled = false;\n this.known = null;\n this.anonymous = null;\n if (this.session !== null) safeRemove(this.session, KNOWN_KEY);\n if (this.local !== null) safeRemove(this.local, STORAGE_KEY);\n this.writeCookie(\"\", 0);\n }\n\n private persistAnonymous(): void {\n if (this.anonymous === null) return;\n this.writeCookie(this.anonymous, this.maxAge);\n if (this.local !== null) safeSet(this.local, STORAGE_KEY, this.anonymous);\n }\n\n private readCookie(): string | null {\n if (this.doc === null) return null;\n const match = this.doc.cookie.split(\"; \").find((part) => part.startsWith(`${COOKIE_NAME}=`));\n if (match === undefined) return null;\n const value = decodeURIComponent(match.slice(COOKIE_NAME.length + 1));\n return /^anon_[0-9a-f-]{36}$/.test(value) ? value : null;\n }\n\n private writeCookie(value: string, maxAge: number): void {\n if (this.doc === null) return;\n const secure = this.doc.location?.protocol === \"https:\" ? \"; Secure\" : \"\";\n try {\n // Host-only (no Domain attribute): no widening to parent domains by default.\n this.doc.cookie = `${COOKIE_NAME}=${encodeURIComponent(value)}; Max-Age=${maxAge}; Path=/; SameSite=Lax${secure}`;\n } catch {\n // Cookies blocked: memory and localStorage carry the id for this page.\n }\n }\n}\n\nexport function newAnonymousId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `anon_${crypto.randomUUID()}`;\n }\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return `anon_${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nexport function safeStorage(kind: \"localStorage\" | \"sessionStorage\"): Storage | null {\n try {\n const store = globalThis[kind];\n const probe = \"__curious_probe__\";\n store.setItem(probe, \"1\");\n store.removeItem(probe);\n return store;\n } catch {\n return null;\n }\n}\n\nexport function safeGet(store: Storage, key: string): string | null {\n try {\n return store.getItem(key);\n } catch {\n return null;\n }\n}\n\nexport function safeSet(store: Storage, key: string, value: string): void {\n try {\n store.setItem(key, value);\n } catch {\n // Quota or privacy mode: degrade to memory.\n }\n}\n\nexport function safeRemove(store: Storage, key: string): void {\n try {\n store.removeItem(key);\n } catch {\n // Nothing to do.\n }\n}\n","// The assignment cache (docs/sdk.md §17): returned content kept in\n// sessionStorage (memory fallback) for fast remounts and short repeat\n// navigation, 60 seconds by default. A hit renders without a call, so no new\n// decision row is written; a miss decides before anything is applied. Keyed\n// by key fingerprint, origin, active user and element, so a user or key\n// change never serves another's content.\n\nimport { safeGet, safeRemove, safeSet, safeStorage } from \"./identity.ts\";\n\nexport const CACHE_SCHEMA = 1;\nexport const DEFAULT_CACHE_TTL_MS = 60_000;\nconst PREFIX = \"curious:assign:\";\n\nexport type CachedAssignment = {\n content: unknown;\n armId: string;\n armType: \"control\" | \"variant\" | null;\n experimentId: string;\n experimentStatus: string;\n storedAt: number;\n expiresAt: number;\n schema: number;\n};\n\nexport class AssignmentCache {\n private readonly store: Storage | null;\n private readonly memory = new Map<string, string>();\n private readonly ttlMs: number;\n private readonly fingerprint: string;\n\n constructor(options: { publishableKey: string; ttlMs?: number; storage?: Storage | null }) {\n this.store = options.storage === undefined ? safeStorage(\"sessionStorage\") : options.storage;\n this.ttlMs = options.ttlMs ?? DEFAULT_CACHE_TTL_MS;\n // The last characters of the key, never the key: enough to separate two\n // keys on one origin without storing anything secret-shaped.\n this.fingerprint = options.publishableKey.slice(-8);\n }\n\n private key(userId: string, element: string): string {\n const origin = typeof location === \"undefined\" ? \"\" : location.origin;\n return `${PREFIX}${this.fingerprint}:${origin}:${userId}:${element}`;\n }\n\n get(userId: string, element: string, now = Date.now()): CachedAssignment | null {\n const key = this.key(userId, element);\n const raw = this.store === null ? this.memory.get(key) ?? null : safeGet(this.store, key);\n if (raw === null) return null;\n try {\n const parsed = JSON.parse(raw) as CachedAssignment;\n if (parsed.schema !== CACHE_SCHEMA || parsed.expiresAt <= now) {\n this.remove(userId, element);\n return null;\n }\n return parsed;\n } catch {\n this.remove(userId, element);\n return null;\n }\n }\n\n set(userId: string, element: string, value: Omit<CachedAssignment, \"storedAt\" | \"expiresAt\" | \"schema\">, now = Date.now()): void {\n const entry: CachedAssignment = { ...value, storedAt: now, expiresAt: now + this.ttlMs, schema: CACHE_SCHEMA };\n const key = this.key(userId, element);\n const raw = JSON.stringify(entry);\n if (this.store === null) this.memory.set(key, raw);\n else safeSet(this.store, key, raw);\n }\n\n remove(userId: string, element: string): void {\n const key = this.key(userId, element);\n this.memory.delete(key);\n if (this.store !== null) safeRemove(this.store, key);\n }\n\n /** identify(), reset(), denyConsent(): everything this SDK cached. */\n clear(): void {\n this.memory.clear();\n if (this.store === null) return;\n try {\n const doomed: string[] = [];\n for (let i = 0; i < this.store.length; i += 1) {\n const k = this.store.key(i);\n if (k !== null && k.startsWith(PREFIX)) doomed.push(k);\n }\n for (const k of doomed) this.store.removeItem(k);\n } catch {\n // Privacy mode: nothing persisted to clear.\n }\n }\n}\n","// Client-side navigation (docs/sdk.md §19). A single-page app changes the\n// address through the History API without loading a page, so the browser\n// tells nobody. The convention among analytics libraries is to wrap\n// `history.pushState` and `history.replaceState` and listen for `popstate`\n// (back and forward); this module does the same, once per page.\n//\n// The wrappers are installed on first use and never removed: another library\n// may have wrapped the same methods after this one, and putting the originals\n// back would cut that library out. A client that stops only unsubscribes, and\n// a wrapper with no subscribers does nothing but call through.\n\ntype Listener = () => void;\n\nconst subscribers = new WeakMap<History, Set<Listener>>();\n\nfunction notify(listeners: Set<Listener>): void {\n for (const listener of Array.from(listeners)) {\n try {\n listener();\n } catch {\n // The page's navigation never fails because of this SDK.\n }\n }\n}\n\nfunction install(target: History): Set<Listener> {\n const existing = subscribers.get(target);\n if (existing !== undefined) return existing;\n const listeners = new Set<Listener>();\n subscribers.set(target, listeners);\n for (const method of [\"pushState\", \"replaceState\"] as const) {\n const original = target[method];\n if (typeof original !== \"function\") continue;\n try {\n target[method] = function (this: History, ...args: Parameters<History[\"pushState\"]>): void {\n // The page's own call first, with its own result or error; the\n // address has changed by the time anyone is told. The native methods\n // return nothing, but a wrapper installed before this one may.\n const result: unknown = original.apply(this, args);\n notify(listeners);\n return result as void;\n };\n } catch {\n // A page that has frozen `history` or made the method read-only: this\n // kind of navigation goes unseen, and nothing else is affected.\n }\n }\n addEventListener(\"popstate\", () => notify(listeners));\n return listeners;\n}\n\n/** Calls `listener` after each History API navigation on this page. Returns the unsubscribe. */\nexport function onHistoryChange(listener: Listener): () => void {\n if (typeof history === \"undefined\" || typeof addEventListener === \"undefined\") return () => {};\n const listeners = install(history);\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n}\n","// The browser event queue (docs/sdk.md §19): bounded, mirrored to\n// sessionStorage so a same-tab navigation can retry with the original ids,\n// flushed on interval, count, visibilitychange-to-hidden, pagehide, and\n// explicit calls, with keepalive on lifecycle flushes and the body split under\n// the keepalive budget. Partial results follow the server SDK: successes and\n// duplicates leave, terminal rejections are dropped with a diagnostic,\n// retryable items keep their ids for a later attempt while the page lives.\n\nimport { CuriousError, summarizeHttpError, summary, type CuriousErrorSummary } from \"./errors.ts\";\nimport { safeGet, safeSet, safeStorage } from \"./identity.ts\";\nimport type { Transport } from \"./transport.ts\";\n\nexport type BrowserEventInput = {\n name: string;\n value?: number | null;\n properties?: Record<string, unknown>;\n context?: Record<string, unknown>;\n timestamp?: Date | string;\n id?: string;\n};\n\nexport type QueuedEvent = {\n id: string;\n user_id: string;\n name: string;\n value?: number | null;\n properties?: Record<string, unknown>;\n context?: Record<string, unknown>;\n timestamp?: string;\n};\n\nexport type FlushSummary = { sent: number; duplicates: number; failed: number; pending: number };\n\nexport type EventQueueOptions = {\n transport: Transport;\n userId: () => string;\n flushIntervalMs?: number;\n flushCount?: number;\n queueLimit?: number;\n keepaliveBodyBytes?: number;\n requestTimeoutMs?: number;\n maxAttempts?: number;\n onEventDrop: (error: CuriousErrorSummary) => void;\n storage?: Storage | null | undefined;\n now?: () => number;\n};\n\nconst DEFAULTS = {\n flushIntervalMs: 5_000,\n flushCount: 20,\n queueLimit: 100,\n keepaliveBodyBytes: 48 * 1024,\n requestTimeoutMs: 10_000,\n maxAttempts: 5,\n itemCap: 200,\n} as const;\n\nconst QUEUE_KEY = \"curious:events\";\nexport const RESERVED_PREFIX = \"$\";\n\ntype Entry = { event: QueuedEvent; attempts: number };\n\nexport class EventQueue {\n private readonly o: Required<Omit<EventQueueOptions, \"storage\" | \"now\">>;\n private readonly store: Storage | null;\n private readonly now: () => number;\n private readonly sessionId: string;\n private sequence = 0;\n private entries: Entry[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private inFlight: Promise<FlushSummary> | null = null;\n\n constructor(options: EventQueueOptions) {\n this.o = {\n transport: options.transport,\n userId: options.userId,\n flushIntervalMs: options.flushIntervalMs ?? DEFAULTS.flushIntervalMs,\n flushCount: options.flushCount ?? DEFAULTS.flushCount,\n queueLimit: options.queueLimit ?? DEFAULTS.queueLimit,\n keepaliveBodyBytes: options.keepaliveBodyBytes ?? DEFAULTS.keepaliveBodyBytes,\n requestTimeoutMs: options.requestTimeoutMs ?? DEFAULTS.requestTimeoutMs,\n maxAttempts: options.maxAttempts ?? DEFAULTS.maxAttempts,\n onEventDrop: options.onEventDrop,\n };\n this.store = options.storage === undefined ? safeStorage(\"sessionStorage\") : options.storage;\n this.now = options.now ?? Date.now;\n this.sessionId = Math.random().toString(36).slice(2, 10) + this.now().toString(36);\n this.restore();\n }\n\n get size(): number {\n return this.entries.length;\n }\n\n /** Customer events; `$` names are reserved for the SDK's own capture path. */\n track(input: BrowserEventInput): { id: string; queued: boolean } {\n if (typeof input.name === \"string\" && input.name.startsWith(RESERVED_PREFIX)) {\n throw new CuriousError(summary(\"invalid_input\", \"Event names starting with $ are reserved\", { retryable: false }));\n }\n return this.enqueue(input);\n }\n\n /** The SDK's own autocapture events (`$pageview`, `$click`, `$form_submit`). */\n system(input: BrowserEventInput): { id: string; queued: boolean } {\n return this.enqueue(input);\n }\n\n private enqueue(input: BrowserEventInput): { id: string; queued: boolean } {\n if (typeof input.name !== \"string\" || input.name.trim().length === 0) {\n throw new CuriousError(summary(\"invalid_input\", \"track: name is required\", { retryable: false }));\n }\n const event: QueuedEvent = {\n id: input.id ?? `browser:${this.sessionId}:${++this.sequence}:${Math.random().toString(36).slice(2, 8)}`,\n user_id: this.o.userId(),\n name: input.name,\n };\n if (input.value !== undefined) event.value = input.value;\n if (input.properties !== undefined) event.properties = input.properties;\n if (input.context !== undefined) event.context = input.context;\n if (input.timestamp !== undefined) {\n event.timestamp = input.timestamp instanceof Date ? input.timestamp.toISOString() : input.timestamp;\n }\n if (this.entries.length >= this.o.queueLimit) {\n this.o.onEventDrop(summary(\"queue_full\", `Event queue is full (${this.o.queueLimit}); event not queued`, { retryable: true }));\n return { id: event.id, queued: false };\n }\n this.entries.push({ event, attempts: 0 });\n this.persist();\n if (this.entries.length >= this.o.flushCount) {\n void this.flush();\n } else if (this.timer === null) {\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.flush();\n }, this.o.flushIntervalMs);\n }\n return { id: event.id, queued: true };\n }\n\n /** Deliver what is queued. `keepalive` is for lifecycle flushes (hidden, pagehide, before identify/reset). */\n flush(options: { keepalive?: boolean } = {}): Promise<FlushSummary> {\n if (this.inFlight === null) {\n this.inFlight = this.run(options.keepalive === true).finally(() => {\n this.inFlight = null;\n });\n }\n return this.inFlight;\n }\n\n /** reset()/denyConsent(): forget everything queued. */\n clear(): void {\n this.entries = [];\n this.persist();\n }\n\n private async run(keepalive: boolean): Promise<FlushSummary> {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n const totals: FlushSummary = { sent: 0, duplicates: 0, failed: 0, pending: 0 };\n while (this.entries.length > 0) {\n const batch = this.takeBatch(keepalive);\n if (batch.length === 0) break;\n const retry = await this.deliver(batch, keepalive, totals);\n // Retryable items go back to the front, in order, for a later flush;\n // this pass does not spin on them (the page must never block).\n if (retry.length > 0) {\n this.entries.unshift(...retry);\n this.persist();\n break;\n }\n }\n totals.pending = this.entries.length;\n this.persist();\n return totals;\n }\n\n // Up to the API's item cap, and under the keepalive body budget when the\n // flush rides keepalive.\n private takeBatch(keepalive: boolean): Entry[] {\n const batch: Entry[] = [];\n let bytes = 2;\n while (this.entries.length > 0 && batch.length < DEFAULTS.itemCap) {\n const next = this.entries[0]!;\n const size = JSON.stringify(next.event).length + 1;\n if (keepalive && batch.length > 0 && bytes + size > this.o.keepaliveBodyBytes) break;\n batch.push(this.entries.shift()!);\n bytes += size;\n }\n return batch;\n }\n\n private async deliver(batch: Entry[], keepalive: boolean, totals: FlushSummary): Promise<Entry[]> {\n for (const item of batch) item.attempts += 1;\n let response;\n try {\n response = await this.o.transport.post(\"/events\", { events: batch.map((e) => e.event) }, {\n timeoutMs: this.o.requestTimeoutMs,\n keepalive,\n });\n } catch (error) {\n return this.retryOrDrop(batch, (error as CuriousError).summary, totals);\n }\n if (response.status !== 200) {\n const failure = summarizeHttpError(response.status, response.body, response.requestId);\n if (!failure.retryable) {\n for (const item of batch) {\n totals.failed += 1;\n this.o.onEventDrop(summary(\"event_rejected\", failure.message, { ...failure, retryable: false }));\n }\n return [];\n }\n return this.retryOrDrop(batch, failure, totals);\n }\n const results = (response.body as { results?: unknown })?.results;\n if (!Array.isArray(results)) {\n return this.retryOrDrop(batch, summary(\"protocol_error\", \"Batch response carried no results\", { retryable: true }), totals);\n }\n const retry: Entry[] = [];\n batch.forEach((item, index) => {\n const result = results[index] as { index?: number; status?: string; error?: string; message?: string; duplicate?: true } | null | undefined;\n // An acknowledgement that cannot be matched to its event is not one:\n // retried within the same attempt limit as a malformed whole response.\n if (result === undefined || result === null || typeof result !== \"object\" || result.index !== index) {\n retry.push(...this.retryOrDrop([item], summary(\"protocol_error\", \"Batch response had no result for this event\", { retryable: true }), totals));\n return;\n }\n if (result.status === \"ok\") {\n totals.sent += 1;\n if (result.duplicate === true) totals.duplicates += 1;\n return;\n }\n const itemError = summarizeHttpError(result.error === \"internal_error\" ? 500 : 400, result, response.requestId);\n if (itemError.retryable && item.attempts < this.o.maxAttempts) {\n retry.push(item);\n return;\n }\n totals.failed += 1;\n this.o.onEventDrop(summary(\"event_rejected\", itemError.message, { ...itemError, retryable: false }));\n });\n return retry;\n }\n\n private retryOrDrop(batch: Entry[], failure: CuriousErrorSummary, totals: FlushSummary): Entry[] {\n const retry: Entry[] = [];\n for (const item of batch) {\n if (item.attempts < this.o.maxAttempts) {\n retry.push(item);\n } else {\n totals.failed += 1;\n this.o.onEventDrop(summary(\"event_rejected\", `Gave up after ${item.attempts} attempts: ${failure.message}`, {\n ...failure,\n retryable: false,\n }));\n }\n }\n return retry;\n }\n\n private persist(): void {\n if (this.store === null) return;\n safeSet(this.store, QUEUE_KEY, JSON.stringify(this.entries));\n }\n\n private restore(): void {\n if (this.store === null) return;\n const raw = safeGet(this.store, QUEUE_KEY);\n if (raw === null) return;\n try {\n const parsed = JSON.parse(raw) as Entry[];\n if (Array.isArray(parsed)) this.entries = parsed.filter((e) => e && typeof e.event?.id === \"string\").slice(0, this.o.queueLimit);\n } catch {\n this.entries = [];\n }\n }\n}\n","// Tagged content (docs/sdk.md §14, §16, §18): nodes with `data-curious` keep\n// their own text as the fallback, are decided when they approach the viewport\n// (one IntersectionObserver, 200% root margin), batched into one publishable\n// decide per frame, and never fought over with the page's framework: if\n// something else rewrites an applied node, the SDK records mutation_drift\n// once and leaves it alone. One MutationObserver picks up nodes added later;\n// `data-curious-ignore` excludes a subtree.\n//\n// The SDK replaces one run of plain text and nothing else. A tagged element\n// qualifies when it holds no child elements and at most one text node; the\n// SDK then writes into that text node itself, so a framework that owns the\n// node (React, after hydration) keeps owning it: its later updates reach the\n// page and are seen as drift. An element with child elements, or with text\n// made of several text nodes (a template with expressions), is never decided\n// and never written: assigning `textContent` there would delete the children,\n// and a decision for content that cannot be shown would record an exposure\n// that did not happen.\n\nexport const TAG_ATTRIBUTE = \"data-curious\";\nexport const IGNORE_ATTRIBUTE = \"data-curious-ignore\";\nexport const CRITICAL_ATTRIBUTE = \"data-curious-critical\";\nexport const LOADING_CLASS = \"curious-loading\";\nexport const DEFAULT_ROOT_MARGIN = \"200% 0px\";\n\nexport type TaggedNode = {\n element: string;\n node: Element;\n control: string;\n applied: string | null;\n state: \"idle\" | \"pending\" | \"decided\" | \"fallback\" | \"unsupported\";\n drifted: boolean;\n};\n\n/** Why a tagged element cannot take replaced text. */\nexport type UnsupportedReason = \"child_elements\" | \"several_text_nodes\" | \"void_element\";\n\n/**\n * What became of decided content: written to at least one node, refused\n * because it is not text, or left unwritten because no node could take it\n * (each such node was already reported as unsupported, or the page has since\n * taken its text back).\n */\nexport type ApplyOutcome = \"applied\" | \"not_text\" | \"no_node\";\n\nconst ELEMENT_NODE = 1;\nconst TEXT_NODE = 3;\n// HTML's void elements: a browser never renders text placed inside one.\nconst VOID_ELEMENTS = new Set([\"AREA\", \"BASE\", \"BR\", \"COL\", \"EMBED\", \"HR\", \"IMG\", \"INPUT\", \"LINK\", \"META\", \"SOURCE\", \"TRACK\", \"WBR\"]);\n\n// The one text node the SDK may write into, `null` for an element with no\n// text yet, or the reason the element's content is not one run of plain text.\n// Comment nodes are ignored: they hold no text and are left where they are.\nexport function textSlot(node: Element): { text: Text | null } | { unsupported: UnsupportedReason } {\n if (VOID_ELEMENTS.has(node.tagName.toUpperCase())) return { unsupported: \"void_element\" };\n let text: Text | null = null;\n for (const child of Array.from(node.childNodes)) {\n if (child.nodeType === ELEMENT_NODE) return { unsupported: \"child_elements\" };\n if (child.nodeType !== TEXT_NODE) continue;\n if (text !== null) return { unsupported: \"several_text_nodes\" };\n text = child as Text;\n }\n return { text };\n}\n\nexport type TagRuntimeOptions = {\n /** Called with the set of element names that became pending in one window. */\n onPending: (elements: string[]) => void;\n /** A node the page's framework rewrote after the SDK applied content. */\n onDrift: (element: string) => void;\n /** A tagged node whose content is not one run of plain text; reported once per node, never decided. */\n onUnsupported: (element: string, reason: UnsupportedReason) => void;\n rootMargin?: string;\n root?: ParentNode;\n};\n\nexport class TagRuntime {\n private readonly nodes = new Map<Element, TaggedNode>();\n private readonly byElement = new Map<string, Set<TaggedNode>>();\n private readonly pending = new Set<string>();\n // Nodes whose text the page took back after a decision. Kept apart from\n // `nodes` so the promise survives the node being removed and attached\n // again, and weakly so a discarded node can be collected.\n private released = new WeakSet<Element>();\n private readonly o: TagRuntimeOptions;\n private intersection: IntersectionObserver | null = null;\n private mutation: MutationObserver | null = null;\n private frame: ReturnType<typeof setTimeout> | null = null;\n\n constructor(options: TagRuntimeOptions) {\n this.o = options;\n }\n\n start(): void {\n if (typeof IntersectionObserver === \"function\") {\n this.intersection = new IntersectionObserver((entries) => {\n for (const entry of entries) {\n if (!entry.isIntersecting) continue;\n const tagged = this.nodes.get(entry.target);\n if (tagged === undefined || tagged.state !== \"idle\") continue;\n tagged.state = \"pending\";\n this.pending.add(tagged.element);\n this.intersection?.unobserve(entry.target);\n }\n this.schedule();\n }, { rootMargin: this.o.rootMargin ?? DEFAULT_ROOT_MARGIN, threshold: 0 });\n }\n if (typeof MutationObserver === \"function\") {\n this.mutation = new MutationObserver((records) => {\n for (const record of records) {\n if (record.type === \"childList\") {\n // Nodes the page removed are let go of, so a page that mounts\n // and unmounts sections does not accumulate them here.\n for (const removed of record.removedNodes) {\n if (removed instanceof Element) this.forgetRemoved(removed);\n }\n for (const added of record.addedNodes) {\n if (added instanceof Element) this.scan(added);\n }\n }\n // Text rewritten under an applied node by something else.\n const target = record.target instanceof Element ? record.target : record.target.parentElement;\n if (target !== null) this.detectDrift(target);\n }\n });\n const root = this.o.root ?? document;\n this.mutation.observe(root instanceof Document ? root.documentElement : (root as Node), {\n childList: true,\n subtree: true,\n characterData: true,\n });\n }\n this.scan(this.o.root ?? document);\n }\n\n stop(): void {\n this.intersection?.disconnect();\n this.mutation?.disconnect();\n this.intersection = null;\n this.mutation = null;\n if (this.frame !== null) clearTimeout(this.frame);\n this.frame = null;\n // Nothing is remembered across a stop: a later start() scans the page as\n // it then is. Remembered nodes would be skipped by that scan and never\n // watched by the new observers.\n this.nodes.clear();\n this.byElement.clear();\n this.pending.clear();\n this.released = new WeakSet();\n }\n\n /** Register every tagged node under `root` (the whole document by default). Safe to call repeatedly. */\n scan(root: ParentNode = this.o.root ?? document): void {\n const candidates: Element[] = [];\n if (root instanceof Element && root.hasAttribute(TAG_ATTRIBUTE)) candidates.push(root);\n candidates.push(...Array.from(root.querySelectorAll(`[${TAG_ATTRIBUTE}]`)));\n for (const node of candidates) {\n if (this.nodes.has(node) || this.released.has(node) || node.closest(`[${IGNORE_ATTRIBUTE}]`) !== null) continue;\n const element = (node.getAttribute(TAG_ATTRIBUTE) ?? \"\").trim();\n if (element.length === 0) continue;\n const tagged: TaggedNode = { element, node, control: node.textContent ?? \"\", applied: null, state: \"idle\", drifted: false };\n this.nodes.set(node, tagged);\n const slot = textSlot(node);\n if (\"unsupported\" in slot) {\n // Remembered, so a rescan does not report it again; never observed,\n // never pending, so no decision is requested on its account.\n this.refuse(tagged, slot.unsupported);\n continue;\n }\n let set = this.byElement.get(element);\n if (set === undefined) {\n set = new Set();\n this.byElement.set(element, set);\n }\n set.add(tagged);\n if (this.intersection !== null) this.intersection.observe(node);\n else {\n // No IntersectionObserver (an old or headless environment): decide on scan.\n tagged.state = \"pending\";\n this.pending.add(element);\n }\n }\n if (this.pending.size > 0) this.schedule();\n }\n\n /** Apply decided content to every node of an element that can take it. Non-string content leaves the control in place. */\n apply(element: string, content: unknown): ApplyOutcome {\n const set = this.byElement.get(element);\n if (set === undefined) return \"no_node\";\n if (typeof content !== \"string\") {\n for (const tagged of set) {\n if (!tagged.drifted) tagged.state = \"fallback\";\n }\n return \"not_text\";\n }\n let applied = false;\n for (const tagged of Array.from(set)) {\n // A node the page has removed shows nothing: writing to it is not\n // serving the content.\n if (!tagged.node.isConnected) {\n this.forget(tagged);\n continue;\n }\n // The page rewrote this node after an earlier decision: it owns the\n // text now, and a later decision for the same name (another node\n // mounting, a new user) does not take it back.\n if (tagged.drifted) continue;\n // The page may have changed the node since it was scanned.\n const slot = textSlot(tagged.node);\n if (\"unsupported\" in slot) {\n this.refuse(tagged, slot.unsupported);\n continue;\n }\n // Write into the existing text node, so whatever owns that node keeps\n // owning it. An element with no text yet gets a text node of its own.\n if (slot.text === null) tagged.node.appendChild(tagged.node.ownerDocument.createTextNode(content));\n else if (slot.text.data !== content) slot.text.data = content;\n tagged.applied = content;\n tagged.state = \"decided\";\n this.revealCritical(tagged.node);\n applied = true;\n }\n return applied ? \"applied\" : \"no_node\";\n }\n\n /** Leave the control visible and mark the element as decided against. */\n fallback(element: string): void {\n const set = this.byElement.get(element);\n if (set === undefined) return;\n for (const tagged of set) {\n tagged.state = \"fallback\";\n this.revealCritical(tagged.node);\n }\n }\n\n /** Forget decisions (identify/reset) so the nodes can be decided again for the new user. */\n resetDecisions(): void {\n for (const tagged of Array.from(this.nodes.values())) {\n if (!tagged.node.isConnected) {\n this.forget(tagged);\n continue;\n }\n // A node still waiting for the previous user's answer is decided again\n // too; that answer is discarded when it arrives.\n if ((tagged.state === \"decided\" || tagged.state === \"fallback\" || tagged.state === \"pending\") && !tagged.drifted) {\n tagged.state = \"idle\";\n tagged.applied = null;\n this.intersection?.observe(tagged.node);\n if (this.intersection === null) {\n tagged.state = \"pending\";\n this.pending.add(tagged.element);\n }\n }\n }\n if (this.pending.size > 0) this.schedule();\n }\n\n elements(): string[] {\n return Array.from(this.byElement.keys());\n }\n\n private schedule(): void {\n if (this.frame !== null || this.pending.size === 0) return;\n // A short window collects the tags that became pending together into one\n // batch request.\n this.frame = setTimeout(() => {\n this.frame = null;\n // A node may have changed since it was scanned (a framework rendering\n // children into it, or removing it, before it neared the viewport). Ask\n // only for names that a node near the viewport can still show.\n const batch = Array.from(this.pending).filter((element) => this.hasWritablePendingNode(element));\n this.pending.clear();\n if (batch.length > 0) this.o.onPending(batch);\n }, 0);\n }\n\n // True when a node that neared the viewport (state `pending`) is still on\n // the page and can still take text. A plain sibling that is still off\n // screen does not count: it asks for the decision when it gets near. Nodes\n // that can no longer take text are refused here, and removed ones\n // forgotten, before a decision is requested on their account.\n private hasWritablePendingNode(element: string): boolean {\n const set = this.byElement.get(element);\n if (set === undefined) return false;\n let writable = false;\n for (const tagged of Array.from(set)) {\n if (tagged.state !== \"pending\") continue;\n if (!tagged.node.isConnected) {\n this.forget(tagged);\n continue;\n }\n const slot = textSlot(tagged.node);\n if (\"unsupported\" in slot) this.refuse(tagged, slot.unsupported);\n else writable = true;\n }\n return writable;\n }\n\n private forgetRemoved(removed: Element): void {\n const candidates: Element[] = [removed, ...Array.from(removed.querySelectorAll(`[${TAG_ATTRIBUTE}]`))];\n for (const node of candidates) {\n const tagged = this.nodes.get(node);\n // Still connected means the page moved it; it stays known.\n if (tagged !== undefined && !node.isConnected) this.forget(tagged);\n }\n }\n\n // Drop a node the page has removed. If the same node is attached again, the\n // MutationObserver scans it afresh.\n private forget(tagged: TaggedNode): void {\n this.nodes.delete(tagged.node);\n this.byElement.get(tagged.element)?.delete(tagged);\n this.intersection?.unobserve(tagged.node);\n }\n\n // Take a node out of play for good: never observed, never decided, never\n // written, reported once.\n private refuse(tagged: TaggedNode, reason: UnsupportedReason): void {\n tagged.state = \"unsupported\";\n this.byElement.get(tagged.element)?.delete(tagged);\n this.intersection?.unobserve(tagged.node);\n this.revealCritical(tagged.node);\n this.o.onUnsupported(tagged.element, reason);\n }\n\n private detectDrift(target: Element): void {\n const node = target.closest(`[${TAG_ATTRIBUTE}]`);\n if (node === null) return;\n const tagged = this.nodes.get(node);\n if (tagged === undefined || tagged.state !== \"decided\" || tagged.drifted) return;\n if ((node.textContent ?? \"\") !== tagged.applied) {\n tagged.drifted = true;\n this.released.add(node);\n this.o.onDrift(tagged.element);\n }\n }\n\n private revealCritical(node: Element): void {\n if (node.hasAttribute(CRITICAL_ATTRIBUTE)) {\n document.documentElement.classList.remove(LOADING_CLASS);\n }\n }\n}\n","// Kept in step with package.json by the release checklist; sent as\n// `X-Curious-Client: browser-js/<version>` (docs/sdk.md §6).\nexport const SDK_VERSION = \"0.2.0\";\n","// The browser transport (docs/sdk.md §6, §16, §19): authenticated fetch with\n// the publishable key, a hard deadline, optional keepalive for lifecycle\n// flushes, and the region chosen through the query parameter Supabase\n// documents for callers that cannot add headers to a preflight.\n\nimport { CuriousError, summary } from \"./errors.ts\";\nimport { SDK_VERSION } from \"./version.ts\";\n\nexport type FetchLike = (input: string, init: RequestInit) => Promise<Response>;\n\nexport type TransportResponse = {\n status: number;\n requestId: string | null;\n retryAfterMs: number | null;\n body: unknown;\n};\n\nconst MAX_RESPONSE_BYTES = 1_048_576;\n\nexport class Transport {\n private readonly fetchImpl: FetchLike;\n private readonly baseUrl: string;\n private readonly headers: Record<string, string>;\n\n constructor(options: { publishableKey: string; baseUrl: string; fetch?: FetchLike | undefined }) {\n const fetchImpl = options.fetch ?? (typeof fetch === \"function\" ? fetch.bind(globalThis) : undefined);\n if (fetchImpl === undefined) {\n throw new CuriousError(summary(\"capability_unavailable\", \"fetch is not available\", { retryable: false }));\n }\n this.fetchImpl = fetchImpl;\n this.baseUrl = options.baseUrl.replace(/\\/+$/, \"\");\n this.headers = {\n authorization: `Bearer ${options.publishableKey}`,\n \"content-type\": \"application/json\",\n \"x-curious-client\": `browser-js/${SDK_VERSION}`,\n };\n }\n\n // POST one JSON body within the deadline. Throws for a timeout, a network\n // failure or an unreadable response; returns every HTTP status.\n async post(\n path: string,\n body: unknown,\n options: { timeoutMs: number; keepalive?: boolean },\n ): Promise<TransportResponse> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), options.timeoutMs);\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.baseUrl}${path}`, {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(body),\n signal: controller.signal,\n keepalive: options.keepalive === true,\n credentials: \"omit\",\n mode: \"cors\",\n });\n } catch (error) {\n if (controller.signal.aborted) {\n throw new CuriousError(summary(\"timeout\", `No response within ${options.timeoutMs}ms`));\n }\n throw new CuriousError(summary(\"network_error\", describe(error)));\n } finally {\n clearTimeout(timer);\n }\n const requestId = response.headers.get(\"x-request-id\");\n const retryAfterMs = parseRetryAfter(response.headers.get(\"retry-after\"));\n let text: string;\n try {\n text = await response.text();\n } catch (error) {\n throw new CuriousError(summary(\"network_error\", describe(error), { status: response.status }));\n }\n if (text.length > MAX_RESPONSE_BYTES) {\n throw new CuriousError(summary(\"protocol_error\", \"Response exceeds the size bound\", { status: response.status, retryable: false }));\n }\n let parsed: unknown = null;\n if (text.length > 0) {\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new CuriousError(summary(\"protocol_error\", `Response ${response.status} was not JSON`, {\n status: response.status,\n retryable: false,\n }));\n }\n }\n return { status: response.status, requestId, retryAfterMs, body: parsed };\n }\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error && error.message ? `Request failed: ${error.message}` : \"Request failed\";\n}\n\nexport function parseRetryAfter(value: string | null): number | null {\n if (value === null) return null;\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1000);\n const at = Date.parse(value);\n return Number.isNaN(at) ? null : Math.max(0, at - Date.now());\n}\n","// @trycurious/js — Curious in the browser (docs/sdk.md §13–§23). Publishable\n// keys only. Tagged text is decided when it approaches the viewport, in one\n// batch per frame, through the page's own text as the fallback; events batch\n// through a bounded queue that survives same-tab navigation; identity is an\n// anonymous first-party cookie until the customer's backend links it.\n\nimport { AssignmentCache } from \"./cache.ts\";\nimport { onHistoryChange } from \"./history.ts\";\nimport { CuriousError, summarizeHttpError, summary, type CuriousErrorSummary } from \"./errors.ts\";\nimport { EventQueue, type BrowserEventInput, type FlushSummary } from \"./events.ts\";\nimport { Identity } from \"./identity.ts\";\nimport { TagRuntime } from \"./tags.ts\";\nimport { Transport, type FetchLike } from \"./transport.ts\";\n\nexport type ConsentMode = \"implicit\" | \"required\" | \"denied\";\n\nexport type BrowserOptions = {\n /** A publishable key (`curious_pk_...`). A secret key is refused: it must never reach a browser. */\n publishableKey: string;\n /** Default `https://api.trycurious.ai/v1`. */\n baseUrl?: string;\n /** The decide deadline; the page's text stays when it passes. Default 1000, may be lowered, never removed. */\n decideTimeoutMs?: number;\n /** `implicit` starts at once; `required` does nothing until grantConsent(); `denied` serves controls and collects nothing. */\n consent?: ConsentMode;\n /**\n * The SDK's own events, on by default (docs/sdk.md §19, Autocapture V1): `$pageview` with the\n * normalized path on start and each time a client-side navigation changes the path, `$click` and\n * `$form_submit` on tagged nodes with the element name. `false` turns them all off; an object\n * turns individual ones off. `pageviews: { historyChanges: false }` keeps the page view on start\n * and leaves client-side navigation to your own `page()` calls. The API admits these events only\n * under a publishable key with the SDK's client header, which the transport always sends.\n */\n autocapture?: { pageviews?: boolean | { historyChanges?: boolean }; taggedClicks?: boolean; taggedFormSubmits?: boolean } | false;\n /** Context sent with every tagged decision; `path` and `locale` are added unless you set them. */\n context?: Record<string, unknown>;\n rootMargin?: string;\n /** Queue tuning; the defaults are the spec's (5 s, 20 events, 100 queued). */\n events?: { flushIntervalMs?: number; flushCount?: number; queueLimit?: number };\n cacheTtlMs?: number;\n cookieMaxAgeSeconds?: number;\n onDecision?: (element: string, result: DecisionResult<unknown>) => void;\n onFallback?: (element: string, error: CuriousErrorSummary) => void;\n onEventDrop?: (error: CuriousErrorSummary) => void;\n onIdentityChange?: (userId: string | null) => void;\n /** For tests. */\n fetch?: FetchLike;\n document?: Document;\n storage?: Storage | null;\n debug?: boolean;\n};\n\nexport type DecisionResult<T> = {\n content: T;\n served: \"curious\" | \"fallback\" | \"cache\";\n armId: string | null;\n armType: \"control\" | \"variant\" | null;\n experimentId: string | null;\n experimentStatus: string | null;\n error?: CuriousErrorSummary;\n requestId: string | null;\n};\n\nexport type BrowserDecisionInput<T> = {\n element: string;\n fallback: T;\n identifiers?: Record<string, unknown>;\n attributes?: Record<string, unknown>;\n context?: Record<string, unknown>;\n};\n\nexport type CuriousBrowser = {\n start(): void;\n stop(): void;\n scan(root?: ParentNode): void;\n decide<T>(input: BrowserDecisionInput<T>): Promise<DecisionResult<T>>;\n track(input: BrowserEventInput): { id: string; queued: boolean };\n flush(options?: { keepalive?: boolean }): Promise<FlushSummary>;\n /**\n * Record a page view for the current location. You need it only when you have turned automatic\n * detection off (`autocapture: { pageviews: { historyChanges: false } }`): by default the SDK\n * records a page view on start and whenever a client-side navigation changes the path, and then\n * this call records nothing for a path whose page view is already recorded. It records nothing\n * when page views are turned off through `autocapture`.\n */\n page(): { id: string; queued: boolean };\n identify(userId: string): Promise<{ userId: string }>;\n reset(): Promise<void>;\n grantConsent(): void;\n denyConsent(): void;\n readonly anonymousId: string | null;\n readonly userId: string | null;\n};\n\nconst DEFAULTS = { baseUrl: \"https://api.trycurious.ai/v1\", decideTimeoutMs: 1_000 } as const;\nconst PUBLISHABLE_PREFIX = \"curious_pk_\";\nconst DECIDE_BATCH_LIMIT = 50;\n\n// A batch item reports its error code without a status; these are the\n// statuses the same codes carry on a single decide, so both map alike. Kept\n// equal to the server package's table, plus `conflict` (an undeclared\n// element), which only a publishable key meets.\nconst BATCH_ITEM_STATUS: ReadonlyMap<string, number> = new Map([\n [\"internal_error\", 500],\n [\"decision_unavailable\", 503],\n [\"idempotency_error\", 409],\n [\"lock_timeout\", 409],\n [\"conflict\", 409],\n]);\n\nconst UNSUPPORTED_MESSAGE = {\n child_elements: \"The tagged element contains other elements; the SDK replaces plain text only. Tag the innermost element that holds only text\",\n several_text_nodes: \"The tagged element's text is made of several pieces (a template with expressions); the SDK replaces one run of plain text only\",\n void_element: \"The tagged element cannot hold text (an input, an image or another empty element); tag an element whose content is text\",\n} as const;\n\ntype ItemOk = { index: number; element: string; status: \"ok\"; content: unknown; arm_id: string; arm_type: \"control\" | \"variant\" | null; experiment_id: string; experiment_status: string };\ntype ItemError = { index: number; element?: string | null; status: \"error\"; error: string; message: string };\ntype DirectOutcome =\n | { ok: true; content: unknown; armId: string; armType: \"control\" | \"variant\" | null; experimentId: string | null; experimentStatus: string | null; requestId: string | null }\n | { ok: false; error: CuriousErrorSummary; requestId: string | null };\n\nexport function createCurious(options: BrowserOptions): CuriousBrowser {\n if (typeof options.publishableKey !== \"string\" || options.publishableKey.length === 0) {\n throw new CuriousError(summary(\"invalid_configuration\", \"publishableKey is required\", { retryable: false }));\n }\n if (!options.publishableKey.startsWith(PUBLISHABLE_PREFIX)) {\n // A secret key in a page is a leak; refuse without echoing it.\n throw new CuriousError(summary(\"invalid_key_type\", \"The browser SDK takes a publishable key (curious_pk_...). Never ship a secret key to a browser\", { retryable: false }));\n }\n const timeoutMs = Math.min(options.decideTimeoutMs ?? DEFAULTS.decideTimeoutMs, DEFAULTS.decideTimeoutMs * 10);\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new CuriousError(summary(\"invalid_configuration\", \"decideTimeoutMs must be a positive number\", { retryable: false }));\n }\n const onFallback = guarded(options.onFallback);\n const onDecision = guarded(options.onDecision);\n const onEventDrop = guarded(options.onEventDrop);\n const onIdentityChange = guarded(options.onIdentityChange);\n\n const transport = new Transport({ publishableKey: options.publishableKey, baseUrl: options.baseUrl ?? DEFAULTS.baseUrl, fetch: options.fetch });\n const identity = new Identity({\n ...(options.cookieMaxAgeSeconds === undefined ? {} : { cookieMaxAgeSeconds: options.cookieMaxAgeSeconds }),\n document: options.document,\n storage: options.storage,\n });\n const cache = new AssignmentCache({ publishableKey: options.publishableKey, ...(options.cacheTtlMs === undefined ? {} : { ttlMs: options.cacheTtlMs }), ...(options.storage === undefined ? {} : { storage: options.storage }) });\n let consent: ConsentMode = options.consent ?? \"implicit\";\n let started = false;\n let active = false;\n const inFlight = new Map<string, Promise<void>>();\n // The direct call's requests that are out, by visitor and element, so a\n // component that mounts twice in quick succession shares one decision.\n const directInFlight = new Map<string, Promise<DirectOutcome>>();\n let events: EventQueue | null = null;\n const listeners: Array<() => void> = [];\n // Page views: off, on start only, or on start and on client-side navigation.\n const pageviewSetting = options.autocapture === false ? false : options.autocapture?.pageviews ?? true;\n const pageviews = pageviewSetting !== false;\n const historyChanges = pageviews && (pageviewSetting === true || pageviewSetting.historyChanges !== false);\n // The path the visitor is on, and whether its page view reached the queue,\n // so one navigation is one page view however many times the History API is\n // called for it, and a page view dropped from a full queue can be tried\n // again without hiding the next navigation.\n let visitPath: string | null = null;\n let visitRecorded = false;\n\n const tags = new TagRuntime({\n ...(options.rootMargin === undefined ? {} : { rootMargin: options.rootMargin }),\n onPending: (elements) => void decideTagged(elements),\n onDrift: (element) => onFallback(element, summary(\"mutation_drift\", \"Applied content was rewritten by the page; the SDK will not reapply it\", { retryable: false })),\n onUnsupported: (element, reason) => onFallback(element, summary(\"content_shape_mismatch\", UNSUPPORTED_MESSAGE[reason], { retryable: false })),\n });\n\n function pageContext(): Record<string, unknown> {\n const base: Record<string, unknown> = {};\n if (typeof location !== \"undefined\") base.path = location.pathname;\n if (typeof navigator !== \"undefined\" && navigator.language) base.locale = navigator.language;\n return { ...base, ...(options.context ?? {}) };\n }\n\n // The path only: no query string, no hash (docs/sdk.md §19).\n function recordPageview(): { id: string; queued: boolean } {\n visitPath = location.pathname;\n const recorded = queue().system({ name: \"$pageview\", properties: { path: visitPath } });\n visitRecorded = recorded.queued;\n return recorded;\n }\n\n function pageviewRecorded(): boolean {\n return visitRecorded && location.pathname === visitPath;\n }\n\n function queue(): EventQueue {\n if (events === null) {\n const tuning = options.events ?? {};\n events = new EventQueue({\n transport,\n userId: () => identity.activeUserId,\n onEventDrop,\n storage: options.storage,\n ...(tuning.flushIntervalMs === undefined ? {} : { flushIntervalMs: tuning.flushIntervalMs }),\n ...(tuning.flushCount === undefined ? {} : { flushCount: tuning.flushCount }),\n ...(tuning.queueLimit === undefined ? {} : { queueLimit: tuning.queueLimit }),\n });\n }\n return events;\n }\n\n // One batch decide for the tags that became pending together; one in-flight\n // request per (user, element), cache hits applied without a call.\n async function decideTagged(elements: string[]): Promise<void> {\n if (!active) return;\n const userId = identity.activeUserId;\n const toRequest: string[] = [];\n for (const element of elements) {\n const hit = cache.get(userId, element);\n if (hit !== null) {\n // The direct call may have cached structured content under this\n // name; a tag shows text only. Reported as it would be from the\n // network, and a request would bring the same content back.\n if (typeof hit.content !== \"string\") {\n fallbackTag(element, summary(\"content_shape_mismatch\", \"Served content is not text\", { retryable: false, status: 200 }));\n continue;\n }\n // Reported as served only when a node took the text.\n if (tags.apply(element, hit.content) === \"applied\") {\n onDecision(element, { content: hit.content, served: \"cache\", armId: hit.armId, armType: hit.armType, experimentId: hit.experimentId, experimentStatus: hit.experimentStatus, requestId: null });\n }\n continue;\n }\n if (!inFlight.has(`${userId}:${element}`)) toRequest.push(element);\n }\n if (toRequest.length === 0) return;\n const run = (async () => {\n for (let i = 0; i < toRequest.length; i += DECIDE_BATCH_LIMIT) {\n const slice = toRequest.slice(i, i + DECIDE_BATCH_LIMIT);\n await decideBatch(userId, slice);\n }\n })();\n for (const element of toRequest) inFlight.set(`${userId}:${element}`, run);\n try {\n await run;\n } finally {\n for (const element of toRequest) inFlight.delete(`${userId}:${element}`);\n }\n }\n\n async function decideBatch(userId: string, elements: string[]): Promise<void> {\n // While the request was out the SDK may have been stopped (stop(),\n // denyConsent()) or the visitor may have become someone else (identify(),\n // reset()). An answer for the earlier state is discarded: it is not\n // written to the page, cached or reported. After an identity change the\n // tags have already been queued again for the new user.\n const stale = () => !active || identity.activeUserId !== userId;\n // A later slice of a large batch: nothing more is sent for a state that\n // has already ended.\n if (stale()) return;\n let response;\n try {\n response = await transport.post(\"/decide\", {\n user_id: userId,\n context: pageContext(),\n elements: elements.map((element) => ({ element })),\n }, { timeoutMs });\n } catch (error) {\n if (stale()) return;\n for (const element of elements) fallbackTag(element, (error as CuriousError).summary);\n return;\n }\n if (stale()) return;\n if (response.status !== 200) {\n const failure = summarizeHttpError(response.status, response.body, response.requestId);\n for (const element of elements) fallbackTag(element, failure);\n return;\n }\n const results = (response.body as { results?: unknown })?.results;\n elements.forEach((element, index) => {\n if (stale()) return;\n const item = Array.isArray(results) ? (results[index] as ItemOk | ItemError | null | undefined) : undefined;\n if (item === undefined || item === null || typeof item !== \"object\" || item.index !== index) {\n fallbackTag(element, summary(\"protocol_error\", \"Batch response had no result for this element\", { retryable: false, status: 200 }));\n return;\n }\n if (item.status === \"error\") {\n fallbackTag(element, summarizeHttpError(BATCH_ITEM_STATUS.get(item.error) ?? 400, item, response.requestId));\n return;\n }\n const outcome = tags.apply(element, item.content);\n // apply() can call the customer's onFallback hook, and a hook may stop\n // the SDK or withdraw consent; nothing is cached or reported after that.\n if (stale()) return;\n if (outcome === \"not_text\") {\n fallbackTag(element, summary(\"content_shape_mismatch\", \"Served content is not text\", { retryable: false, status: 200 }));\n return;\n }\n // The decision exists on the server whatever the page did meanwhile, so\n // it is kept for a node that mounts later. It is reported as served\n // only when a node took the text; a node that could not was already\n // reported through onFallback.\n cache.set(userId, element, { content: item.content, armId: item.arm_id, armType: item.arm_type ?? null, experimentId: item.experiment_id, experimentStatus: item.experiment_status });\n if (outcome === \"applied\") {\n onDecision(element, { content: item.content, served: \"curious\", armId: item.arm_id, armType: item.arm_type ?? null, experimentId: item.experiment_id, experimentStatus: item.experiment_status, requestId: response.requestId });\n }\n });\n }\n\n // One single-form decide request, never rejecting.\n async function requestDecision(userId: string, input: BrowserDecisionInput<unknown>): Promise<DirectOutcome> {\n const body: Record<string, unknown> = { element: input.element, user_id: userId, context: { ...pageContext(), ...(input.context ?? {}) } };\n if (input.identifiers !== undefined) body.identifiers = input.identifiers;\n if (input.attributes !== undefined) body.attributes = input.attributes;\n let response;\n try {\n response = await transport.post(\"/decide\", body, { timeoutMs });\n } catch (error) {\n return { ok: false, error: (error as CuriousError).summary, requestId: null };\n }\n if (response.status !== 200) return { ok: false, error: summarizeHttpError(response.status, response.body, response.requestId), requestId: response.requestId };\n const decision = response.body as Partial<ItemOk> | null;\n if (decision === null || typeof decision !== \"object\" || typeof decision.arm_id !== \"string\" || !(\"content\" in decision)) {\n return { ok: false, error: summary(\"protocol_error\", \"Decision response was missing required fields\", { retryable: false, status: 200 }), requestId: response.requestId };\n }\n return {\n ok: true,\n content: decision.content,\n armId: decision.arm_id,\n armType: decision.arm_type ?? null,\n experimentId: typeof decision.experiment_id === \"string\" ? decision.experiment_id : null,\n experimentStatus: typeof decision.experiment_status === \"string\" ? decision.experiment_status : null,\n requestId: response.requestId,\n };\n }\n\n function fallbackTag(element: string, error: CuriousErrorSummary): void {\n tags.fallback(element);\n onFallback(element, error);\n }\n\n function attachLifecycle(): void {\n if (typeof document === \"undefined\") return;\n const onVisibility = () => {\n if (document.visibilityState === \"hidden\" && events !== null) void events.flush({ keepalive: true });\n };\n const onPageHide = () => {\n if (events !== null) void events.flush({ keepalive: true });\n };\n document.addEventListener(\"visibilitychange\", onVisibility);\n addEventListener(\"pagehide\", onPageHide);\n listeners.push(() => document.removeEventListener(\"visibilitychange\", onVisibility));\n listeners.push(() => removeEventListener(\"pagehide\", onPageHide));\n\n if (options.autocapture === false) return;\n const capture = { taggedClicks: true, taggedFormSubmits: true, ...options.autocapture };\n // Not again for a page whose view is already recorded: a stop and a\n // start on the same page (an effect's cleanup and re-run) is one visit.\n if (pageviews && !pageviewRecorded()) recordPageview();\n if (historyChanges) {\n // A router may call the History API several times for one navigation,\n // and for changes that leave the path alone (a query string, a scroll\n // position): a page view is recorded only when the path has changed.\n listeners.push(\n onHistoryChange(() => {\n if (active && !pageviewRecorded()) recordPageview();\n }),\n );\n }\n if (capture.taggedClicks) {\n const onClick = (event: Event) => {\n const target = event.target instanceof Element ? event.target.closest(\"[data-curious]\") : null;\n if (target === null || target.closest(\"[data-curious-ignore]\") !== null) return;\n const element = target.getAttribute(\"data-curious\");\n if (element) queue().system({ name: \"$click\", properties: { element_name: element } });\n };\n document.addEventListener(\"click\", onClick, { capture: true, passive: true });\n listeners.push(() => document.removeEventListener(\"click\", onClick, { capture: true }));\n }\n if (capture.taggedFormSubmits) {\n const onSubmit = (event: Event) => {\n const target = event.target instanceof Element ? event.target.closest(\"[data-curious]\") : null;\n if (target === null || target.closest(\"[data-curious-ignore]\") !== null) return;\n const element = target.getAttribute(\"data-curious\");\n if (element) queue().system({ name: \"$form_submit\", properties: { element_name: element } });\n };\n document.addEventListener(\"submit\", onSubmit, { capture: true, passive: true });\n listeners.push(() => document.removeEventListener(\"submit\", onSubmit, { capture: true }));\n }\n }\n\n function activate(): void {\n if (active) return;\n identity.enable();\n active = true;\n attachLifecycle();\n tags.start();\n }\n\n const client: CuriousBrowser = {\n start() {\n started = true;\n if (consent === \"implicit\") activate();\n else if (consent === \"denied\" && typeof document !== \"undefined\") {\n document.documentElement.classList.remove(\"curious-loading\");\n }\n },\n stop() {\n started = false;\n active = false;\n tags.stop();\n for (const off of listeners.splice(0)) off();\n },\n scan(root) {\n if (active) tags.scan(root);\n },\n async decide<T>(input: BrowserDecisionInput<T>): Promise<DecisionResult<T>> {\n const fallback = (error: CuriousErrorSummary, requestId: string | null): DecisionResult<T> => {\n onFallback(input.element, error);\n return { content: input.fallback, served: \"fallback\", armId: null, armType: null, experimentId: null, experimentStatus: null, error, requestId };\n };\n if (!active) return fallback(summary(\"capability_unavailable\", \"The SDK is not active (consent or start)\", { retryable: false }), null);\n const userId = identity.activeUserId;\n // The same cache the tags use (docs/sdk.md §17): a component that\n // mounts again within the cache's lifetime shows the decision already\n // made, with no call and no new decision row. A call that carries\n // identifiers, attributes or its own context always goes out, alone:\n // it has profile data to deliver, or it asks about a situation an\n // earlier answer was not decided for.\n const plain = input.identifiers === undefined && input.attributes === undefined && input.context === undefined;\n const hit = plain ? cache.get(userId, input.element) : null;\n if (hit !== null && sameShape(hit.content, input.fallback)) {\n const cached: DecisionResult<T> = { content: hit.content as T, served: \"cache\", armId: hit.armId, armType: hit.armType, experimentId: hit.experimentId, experimentStatus: hit.experimentStatus, requestId: null };\n onDecision(input.element, cached);\n return cached;\n }\n // A second plain call while the first is out joins it: React runs an\n // effect twice on a development mount, and a component can unmount and\n // mount again before an answer arrives.\n const key = `${userId}:${input.element}`;\n const out = plain ? directInFlight.get(key) : undefined;\n const pending = out ?? requestDecision(userId, input);\n if (plain && out === undefined) {\n directInFlight.set(key, pending);\n void pending.then(() => {\n if (directInFlight.get(key) === pending) directInFlight.delete(key);\n });\n }\n const outcome = await pending;\n // The answer, or the failure, is for the visitor and the consent that\n // asked for it; neither is reported for anyone else.\n if (!active || identity.activeUserId !== userId) {\n return fallback(summary(\"capability_unavailable\", \"The SDK was stopped, or the visitor changed, while the decision was in flight\", { retryable: false }), outcome.requestId);\n }\n if (!outcome.ok) return fallback(outcome.error, outcome.requestId);\n if (!sameShape(outcome.content, input.fallback)) {\n return fallback(summary(\"content_shape_mismatch\", \"Served content does not match the fallback's shape\", { retryable: false, status: 200 }), outcome.requestId);\n }\n // A call that joined another's request made no decision of its own.\n const result: DecisionResult<T> = { content: outcome.content as T, served: out === undefined ? \"curious\" : \"cache\", armId: outcome.armId, armType: outcome.armType, experimentId: outcome.experimentId, experimentStatus: outcome.experimentStatus, requestId: outcome.requestId };\n // Only a plain call's answer is kept: one decided for a context the\n // caller supplied is not an answer for a call, or a tag, without it.\n if (plain && outcome.experimentId !== null && outcome.experimentStatus !== null) {\n cache.set(userId, input.element, { content: outcome.content, armId: outcome.armId, armType: outcome.armType, experimentId: outcome.experimentId, experimentStatus: outcome.experimentStatus });\n } else if (input.identifiers !== undefined || input.attributes !== undefined) {\n // The visitor's profile has just changed, and the answer kept from\n // before may no longer be theirs: the next plain call asks again.\n cache.remove(userId, input.element);\n }\n onDecision(input.element, result);\n return result;\n },\n track(input) {\n if (!active) {\n onEventDrop(summary(\"capability_unavailable\", \"Events are not collected before consent\", { retryable: false }));\n return { id: \"\", queued: false };\n }\n return queue().track(input);\n },\n flush(flushOptions) {\n if (events === null) return Promise.resolve({ sent: 0, duplicates: 0, failed: 0, pending: 0 });\n return events.flush(flushOptions);\n },\n page() {\n // The same switch as the page view on start: `autocapture: false` and\n // `autocapture: { pageviews: false }` turn this event off wherever it\n // would come from.\n if (!pageviews) return { id: \"\", queued: false };\n if (!active) {\n onEventDrop(summary(\"capability_unavailable\", \"Events are not collected before consent\", { retryable: false }));\n return { id: \"\", queued: false };\n }\n if (typeof location === \"undefined\") return { id: \"\", queued: false };\n // With automatic detection on, the navigation that brought the page\n // here has already been recorded; a second page view for the same path\n // would count it twice.\n if (historyChanges && pageviewRecorded()) return { id: \"\", queued: false };\n return recordPageview();\n },\n // After the customer's backend has linked the anonymous id with a secret\n // key: flush anonymous events, switch the active user, forget cached\n // assignments, decide tags again for the known user.\n async identify(userId) {\n if (typeof userId !== \"string\" || userId.trim().length === 0) {\n throw new CuriousError(summary(\"invalid_input\", \"identify: userId is required\", { retryable: false }));\n }\n if (!active) throw new CuriousError(summary(\"capability_unavailable\", \"The SDK is not active (consent or start)\", { retryable: false }));\n if (events !== null) await events.flush({ keepalive: true });\n identity.setKnown(userId);\n cache.clear();\n tags.resetDecisions();\n onIdentityChange(userId);\n return { userId };\n },\n // Logout: a bounded flush, then a fresh anonymous history. Never unlinks\n // anything server-side, and a failed flush never prevents the isolation.\n async reset() {\n if (events !== null) {\n try {\n await events.flush({ keepalive: true });\n } catch {\n // Best effort.\n }\n events.clear();\n }\n if (active) identity.reset();\n cache.clear();\n tags.resetDecisions();\n // The page view on record belongs to the visitor who has just left;\n // the next navigation, or page() call, records this page for the new one.\n visitRecorded = false;\n onIdentityChange(null);\n },\n grantConsent() {\n consent = \"implicit\";\n if (started) activate();\n },\n denyConsent() {\n consent = \"denied\";\n active = false;\n tags.stop();\n for (const off of listeners.splice(0)) off();\n events?.clear();\n cache.clear();\n identity.clear();\n visitRecorded = false;\n onIdentityChange(null);\n },\n get anonymousId() {\n return identity.anonymousId;\n },\n get userId() {\n return identity.knownUserId;\n },\n };\n return client;\n}\n\n// Whether served content can stand where the fallback would have: the same\n// kind of value, and for an object every field the fallback has, each of the\n// same kind in turn. A caller renders `content.headline` on the strength of\n// its fallback having one, so a missing field, or a null one where the\n// fallback has a value, is a mismatch, not something to hand over. Extra\n// fields are fine. A list is homogeneous (the format grammar's arrays are),\n// so the fallback's first item stands for every item; an empty fallback list\n// accepts any list. A null or undefined fallback value states no shape and\n// accepts any value, but the field itself must still be there.\nfunction sameShape(content: unknown, fallback: unknown): boolean {\n if (fallback === null || fallback === undefined) return true;\n if (content === null || content === undefined) return false;\n if (Array.isArray(fallback) || Array.isArray(content)) {\n if (!Array.isArray(fallback) || !Array.isArray(content)) return false;\n return fallback.length === 0 || content.every((item) => sameShape(item, fallback[0]));\n }\n if (typeof fallback !== \"object\") return typeof content === typeof fallback;\n if (typeof content !== \"object\") return false;\n for (const [key, want] of Object.entries(fallback as Record<string, unknown>)) {\n if (!Object.prototype.hasOwnProperty.call(content, key)) return false;\n if (!sameShape((content as Record<string, unknown>)[key], want)) return false;\n }\n return true;\n}\n\nfunction guarded<A extends unknown[]>(hook: ((...args: A) => void) | undefined): (...args: A) => void {\n return (...args) => {\n if (hook === undefined) return;\n try {\n hook(...args);\n } catch {\n // A customer hook never breaks serving or the queue.\n }\n };\n}\n"],"mappings":";AAmCO,IAAM,eAAN,cAA2B,MAAM;AAAA,EAEtC,YAAYA,UAA8B;AACxC,UAAMA,SAAQ,OAAO;AACrB,SAAK,OAAO;AACZ,SAAK,UAAUA;AAAA,EACjB;AAAA,EACA,IAAI,OAAyB;AAC3B,WAAO,KAAK,QAAQ;AAAA,EACtB;AACF;AAEA,IAAM,QAAQ;AAEP,SAAS,QACd,MACA,SACA,QAAgE,CAAC,GAC5C;AACrB,QAAM,YAAY,MAAM,cACrB,SAAS,aAAa,SAAS,mBAAmB,SAAS,kBAAkB,SAAS;AACzF,QAAM,MAA2B;AAAA,IAC/B;AAAA,IACA;AAAA,IACA,SAAS,QAAQ,SAAS,QAAQ,GAAG,QAAQ,MAAM,GAAG,KAAK,CAAC,WAAM;AAAA,EACpE;AACA,MAAI,MAAM,WAAW,OAAW,KAAI,SAAS,MAAM;AACnD,MAAI,MAAM,cAAc,OAAW,KAAI,YAAY,MAAM;AACzD,MAAI,MAAM,eAAe,OAAW,KAAI,aAAa,MAAM;AAC3D,SAAO;AACT;AAIA,SAAS,SAAS,MAAgC;AAChD,MACE,OAAO,SAAS,YAAY,SAAS,QACrC,OAAQ,KAAkB,UAAU,YAAY,OAAQ,KAAkB,YAAY,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,CAAC,OAAO,UAAU,eAAe,KAAK,SAAS,GAAG,EAAG,QAAO;AAChE,QAAI,CAAC,UAAW,QAAoC,GAAG,GAAG,IAAI,EAAG,QAAO;AAAA,EAC1E;AACA,SAAO;AACT;AAEA,SAAS,QAA6B,MAAgE;AACpG,SAAO,IAAI,SAAS;AAClB,QAAI,SAAS,OAAW;AACxB,QAAI;AACF,WAAK,GAAG,IAAI;AAAA,IACd,QAAQ;AAAA,IAER;AAAA,EACF;AACF;","names":["summary","DEFAULTS"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trycurious/js",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Curious browser SDK: tagged text replacement with the page's own text as the fallback, exposure-aware publishable-key decisions, anonymous identity, and an authenticated event queue. Publishable keys only.",
5
5
  "license": "MIT",
6
6
  "type": "module",