@traqio/web 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../sdk-core/src/skan.ts", "../../sdk-core/src/analytics.ts", "../../sdk-core/src/adservices.ts", "../../sdk-core/src/deeplink.ts", "../src/shims/empty.ts", "../../sdk-core/src/adRevenue.ts", "../../sdk-core/src/index.ts", "../src/index.ts", "../src/cookies.ts", "../src/storage.ts", "../src/kept.ts", "../src/source.ts", "../src/trackId.ts", "../src/vitals.ts", "../src/analytics.ts", "../src/snippet.ts"],
4
- "sourcesContent": ["// iOS SKAdNetwork conversion values \u2014 the JS half.\n//\n// Be clear about what this buys you: SKAN gives Apple SIX BITS about an install,\n// delivered to the ad network (and to Traqio's postback endpoint) at least 24h\n// after the conversion window closes, and withheld entirely when the campaign is\n// too small for Apple's crowd-anonymity threshold. It is aggregated, coarse and\n// late by construction \u2014 never per-user, never real-time. This file encodes a\n// number; it does not make iOS deterministic.\n//\n// The mapping is fetched from the API rather than hardcoded in the app: the\n// server decodes postbacks with the mapping it published, so a hardcoded copy in\n// the app drifts silently and you only find out 24h later when the values come\n// back meaning the wrong thing.\n\nexport type CoarseValue = \"low\" | \"medium\" | \"high\";\n\nexport type PostbackWindowIndex = 0 | 1 | 2;\n\n/**\n * When a conversion window is closed early. Mirrors `PostbackWindow` in the API\n * (apps/api/src/skan/conversion-value.ts).\n *\n * This used to be a parameter the HOST APP passed to `updateSkanConversionValue`,\n * which meant changing when a campaign reports required shipping an app release. It\n * is configuration now: the mapping carries it, the device obeys it.\n */\nexport interface PostbackWindow {\n window: PostbackWindowIndex;\n lock: boolean;\n /** Hours since install at which to lock. null = lock on the next value update. */\n lockAfterHours?: number | null;\n}\n\n/**\n * Apple's three conversion windows, in hours since install. Mirrors\n * CONVERSION_WINDOWS in the API \u2014 the device and the console must not disagree about\n * when a window closes.\n *\n * 0 \u2014 day 0-2 (0 \u2192 48 h), the only window carrying a FINE value\n * 1 \u2014 day 3-7 (48 \u2192 168 h), coarse only\n * 2 \u2014 day 8-35 (168 \u2192 840 h), coarse only\n */\nexport const CONVERSION_WINDOWS: { window: PostbackWindowIndex; startHours: number; endHours: number }[] = [\n { window: 0, startHours: 0, endHours: 48 },\n { window: 1, startHours: 48, endHours: 168 },\n { window: 2, startHours: 168, endHours: 840 },\n];\n\n/** What `GET /skan/mapping/<sdkKey>` returns (null when the app configured none). */\nexport interface SkanMapping {\n version: number;\n mode: \"revenue\" | \"events\";\n currency: string;\n /** revenue mode: ascending lower bounds, index = fine conversion value. */\n revenueBuckets?: number[] | null;\n /** events mode: bit index \u2192 event name (max 6). */\n eventBits?: string[] | null;\n /** Optional SKAN 4 coarse tiers, as revenue thresholds. */\n coarseRevenue?: Partial<Record<CoarseValue, number>> | null;\n /** The postback schedule. Absent = Apple's own timing, nothing locked early. */\n postbackWindows?: PostbackWindow[] | null;\n}\n\n/** The window an install of this age is inside, or null past day 35. */\nexport function windowForAge(hoursSinceInstall: number): PostbackWindowIndex | null {\n const found = CONVERSION_WINDOWS.find(\n (w) => hoursSinceInstall >= w.startHours && hoursSinceInstall < w.endHours,\n );\n return found ? found.window : null;\n}\n\n/**\n * Should this update carry `lockWindow: true`? Mirrors `shouldLockWindow` in the API.\n *\n * Locking closes the current window immediately: the postback arrives sooner, at the\n * cost of every conversion the rest of the window would have seen. The console shows\n * that cost as a measurement gap before anyone turns it on.\n */\nexport function shouldLockWindow(\n windows: PostbackWindow[] | null | undefined,\n hoursSinceInstall: number,\n): boolean {\n const current = windowForAge(hoursSinceInstall);\n if (current == null || !windows || !windows.length) return false;\n const rule = windows.find((w) => w.window === current);\n if (!rule || !rule.lock) return false;\n if (rule.lockAfterHours == null) return true;\n return hoursSinceInstall >= rule.lockAfterHours;\n}\n\n/** The native surface the Expo module exposes (no-op on Android). */\nexport interface SkanNative {\n updateConversionValue(fineValue: number, coarse?: CoarseValue, lockWindow?: boolean): void;\n}\n\nconst MAX_FINE_VALUE = 63;\nconst MAX_EVENT_BITS = 6;\n\n/**\n * Highest bucket whose lower bound the revenue has reached. Mirrors\n * `fineValueForRevenue` in the API (apps/api/src/skan/conversion-value.ts) \u2014 the\n * encode and decode sides of one mapping must never disagree.\n */\nexport function fineValueForRevenue(revenue: number, buckets: number[]): number {\n let value = 0;\n for (let i = 0; i < Math.min(buckets.length, MAX_FINE_VALUE + 1); i++) {\n if (revenue >= buckets[i]) value = i;\n }\n return value;\n}\n\n/** Milestone names \u2192 the 6-bit mask, in the bit order the mapping declares. */\nexport function fineValueForEvents(events: Iterable<string>, bits: string[]): number {\n const reached = new Set(events);\n let value = 0;\n bits.slice(0, MAX_EVENT_BITS).forEach((name, i) => {\n if (reached.has(name)) value |= 1 << i;\n });\n return value;\n}\n\n/**\n * Highest configured coarse tier the revenue has reached. Returns undefined when\n * the mapping declares no tiers \u2014 the native side then derives one from the fine\n * value rather than sending nothing.\n */\nexport function coarseValueForRevenue(\n revenue: number,\n tiers: Partial<Record<CoarseValue, number>> | null | undefined,\n): CoarseValue | undefined {\n if (!tiers) return undefined;\n let best: CoarseValue | undefined;\n let bestThreshold = -Infinity;\n for (const tier of [\"low\", \"medium\", \"high\"] as const) {\n const threshold = tiers[tier];\n if (threshold != null && revenue >= threshold && threshold >= bestThreshold) {\n best = tier;\n bestThreshold = threshold;\n }\n }\n return best;\n}\n\ninterface SkanState {\n /** Lifetime revenue this install has produced, as SKAN needs a running total. */\n revenue: number;\n /** Milestone names already reached (events mode). */\n events: string[];\n /** Last fine value we asked the device to send. */\n lastFine: number | null;\n /**\n * Unix ms of the first launch we saw. The conversion-window schedule is expressed\n * in hours SINCE INSTALL, and nothing on the device tells us the install time \u2014 so\n * this is our own stand-in, written once and never moved. It is later than the true\n * install by however long the user took to open the app, which makes a lock fire\n * slightly LATE rather than early: the safe direction, since an early lock throws\n * measurement away and a late one only delays the postback.\n */\n firstSeenAt?: number;\n}\n\nconst EMPTY_STATE: SkanState = { revenue: 0, events: [], lastFine: null };\n\nexport interface SkanOptions {\n endpoint: string;\n sdkKey: string;\n native?: SkanNative;\n /** Same store the event queue uses, so the running total survives a restart. */\n storage?: { getItem(key: string): Promise<string | null>; setItem(key: string, value: string): Promise<void> };\n /** Injectable for tests; defaults to the global fetch. */\n fetchFn?: typeof fetch;\n /** Injectable clock, so the window schedule is testable without waiting 48 hours. */\n nowFn?: () => number;\n}\n\nexport const SKAN_STATE_KEY = \"traq_skan_state\";\n\n/**\n * Owns the app's SKAN conversion value: fetch the mapping, keep the running\n * total across launches, and push a new value to the device when \u2014 and only\n * when \u2014 it actually changed upward.\n *\n * Inert unless everything is in place (iOS + a native bridge + a published\n * mapping). On Android and off-device it does nothing at all, so callers never\n * have to branch on platform.\n */\nexport class Skan {\n private opts!: SkanOptions;\n private mapping: SkanMapping | null = null;\n private state: SkanState = { ...EMPTY_STATE };\n private enabled = false;\n\n async init(opts: SkanOptions): Promise<void> {\n this.opts = opts;\n this.enabled = Boolean(opts.native);\n if (!this.enabled) return;\n await this.restore();\n if (this.state.firstSeenAt == null) {\n this.state.firstSeenAt = this.now();\n await this.persist();\n }\n this.mapping = await this.fetchMapping();\n // A mapping published (or changed) after the install still applies from now\n // on: re-encode the totals we already have so the first window isn't lost.\n if (this.mapping) this.push();\n }\n\n /**\n * Add revenue this install produced. SKAN encodes a LIFETIME total, not one\n * purchase, so amounts accumulate \u2014 passing a single sale twice double-counts\n * it, same as anywhere else.\n */\n addRevenue(amount: number): void {\n if (!this.enabled || !(amount > 0) || !Number.isFinite(amount)) return;\n this.state.revenue += amount;\n void this.persist();\n this.push();\n }\n\n /** Mark a milestone reached (events mode). Repeats are idempotent. */\n markEvent(name: string): void {\n if (!this.enabled || this.state.events.includes(name)) return;\n this.state.events.push(name);\n void this.persist();\n this.push();\n }\n\n /** The mapping in force, for callers that want to show it. Null until fetched. */\n get activeMapping(): SkanMapping | null {\n return this.mapping;\n }\n\n // \u2500\u2500 internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n private push(): void {\n const m = this.mapping;\n if (!m || !this.opts.native) return;\n\n let fine: number;\n let coarse: CoarseValue | undefined;\n if (m.mode === \"events\") {\n if (!m.eventBits?.length) return;\n fine = fineValueForEvents(this.state.events, m.eventBits);\n } else {\n if (!m.revenueBuckets?.length) return;\n fine = fineValueForRevenue(this.state.revenue, m.revenueBuckets);\n coarse = coarseValueForRevenue(this.state.revenue, m.coarseRevenue);\n }\n\n // Value 0 is already on the device: the native module registers the install\n // with it on create. Re-sending it would burn the first, most valuable\n // conversion window on \"nothing happened yet\".\n if (this.state.lastFine == null && fine === 0) return;\n // The native side enforces the increase rule too, but not crossing the bridge\n // at all is what keeps a chatty app from waking SKAdNetwork on every purchase.\n if (this.state.lastFine != null && fine <= this.state.lastFine) return;\n this.state.lastFine = fine;\n void this.persist();\n this.opts.native.updateConversionValue(fine, coarse, this.lockWindowNow());\n }\n\n /**\n * Whether this update closes the current conversion window, per the schedule the\n * mapping published. Without a mapping, or with no rule for the window we are in,\n * the answer is false \u2014 Apple's own timing, which gives nothing up.\n */\n private lockWindowNow(): boolean {\n const since = this.state.firstSeenAt;\n if (since == null) return false;\n const hours = (this.now() - since) / 3_600_000;\n return shouldLockWindow(this.mapping?.postbackWindows, hours);\n }\n\n private now(): number {\n return this.opts.nowFn ? this.opts.nowFn() : Date.now();\n }\n\n private async fetchMapping(): Promise<SkanMapping | null> {\n const doFetch = this.opts.fetchFn ?? (typeof fetch === \"function\" ? fetch : undefined);\n if (!doFetch) return null;\n try {\n const res = await doFetch(`${this.opts.endpoint}/skan/mapping/${encodeURIComponent(this.opts.sdkKey)}`);\n if (!res.ok) return null;\n const body = (await res.json()) as SkanMapping | null;\n return body && typeof body === \"object\" ? body : null;\n } catch {\n // Offline at launch is normal. No mapping \u2192 we simply never set a value;\n // the install itself is still registered natively on module create.\n return null;\n }\n }\n\n private async restore(): Promise<void> {\n try {\n const raw = await this.opts.storage?.getItem(SKAN_STATE_KEY);\n if (raw) this.state = { ...EMPTY_STATE, ...(JSON.parse(raw) as SkanState) };\n } catch {\n /* corrupt/absent \u2014 start from zero */\n }\n }\n\n private async persist(): Promise<void> {\n try {\n await this.opts.storage?.setItem(SKAN_STATE_KEY, JSON.stringify(this.state));\n } catch {\n /* storage full/unavailable */\n }\n }\n}\n", "// Product analytics on an app (HQ cmwr3thk) \u2014 `capture()` and screen views, posted to\n// `POST /ingest/analytics` with the app's mobile key: what replaces PostHog in a\n// React Native / Expo app. The engine (queue, batching, retry, persistence) is the\n// Client's; this file is the pure part \u2014 what an event is, what a session is \u2014 so\n// every rule is tested without a timer or a network.\n//\n// \u26A0\uFE0F An analytics event is never a conversion: `track()` stays the conversion door\n// (`/ingest`, metered, forwarded to ad networks); `capture()` and `screen()` go to\n// their own route and their own table, which billing and forwarding never read.\n\n/** What the server stores, one event at a time (apps/api/src/product-analytics/screen.ts). */\nexport interface QueuedAnalyticsEvent {\n /**\n * `identify` carries a user's properties (`userId`, `set`, `setOnce`), `group` an\n * account's (`groupType`, `groupKey`, `set`), `alias` two ids of one person\n * (`userId`, `previousId`) \u2014 none is ever an analytics row.\n */\n kind: \"pageview\" | \"custom\" | \"identify\" | \"group\" | \"alias\";\n /** Custom events only. */\n name?: string;\n /** Epoch ms, the device clock \u2014 the server clamps it. */\n ts: number;\n /** Page and screen views and custom events: their own id, so a re-sent batch is stored once (the server keys the row on it). */\n id?: string;\n sessionId: string;\n /** The screen shown: the subject of a screen view, the context of a custom event. */\n screen?: string;\n props?: Record<string, unknown>;\n /** `identify` only: the user, and the traits to overwrite / to write once. */\n userId?: string;\n set?: Traits;\n setOnce?: Traits;\n /** Analytics events only: the B2B accounts held when it was queued (`group()`) \u2014 `{ company: \"acme\" }`. */\n groups?: Groups;\n /** `group` only: the account. */\n groupType?: string;\n groupKey?: string;\n /** `alias` only: the id the user had before `userId`. */\n previousId?: string;\n /**\n * Device-side only, never sent: the user id an event was captured under, stamped by\n * `reset()` on what was still queued \u2014 so a sign-out never re-files the signed-out\n * user's last events under nobody (or under the next user). Absent = the current one.\n */\n asUser?: string;\n}\n\n/** A user id as the server takes it (alias.ts, identify.ts): trimmed text (or a number) of 1\u2013256 characters, or null. */\nexport function cleanUserId(v: unknown): string | null {\n if (typeof v === \"number\" && Number.isFinite(v)) return String(v);\n if (typeof v !== \"string\") return null;\n const t = v.trim();\n return t && t.length <= 256 ? t : null;\n}\n\n/** Entries that are not analytics rows: no session activity, no super-properties, no accounts, no `asUser` stamp. */\nexport function isEntry(kind: QueuedAnalyticsEvent[\"kind\"]): boolean {\n return kind === \"identify\" || kind === \"group\" || kind === \"alias\";\n}\n\n/**\n * The next batch to send: the leading events captured under ONE user id (their\n * `asUser` stamp, else `current`), at most `max`, and that user id \u2014 the batch's\n * `userId` on the wire. Entries (identify, group, alias) carry their own ids and ride\n * with any batch. The stamp is stripped from what travels.\n */\nexport function nextAnalyticsBatch(queue: readonly QueuedAnalyticsEvent[], current: string | undefined, max: number): { events: QueuedAnalyticsEvent[]; userId: string | undefined; taken: number } {\n let userId: string | undefined;\n let fixed = false;\n const events: QueuedAnalyticsEvent[] = [];\n for (const e of queue) {\n if (events.length >= max) break;\n if (!isEntry(e.kind)) {\n const who = e.asUser !== undefined ? e.asUser || undefined : current;\n if (!fixed) {\n userId = who;\n fixed = true;\n } else if (who !== userId) break;\n }\n const { asUser: _asUser, ...wire } = e;\n events.push(wire);\n }\n return { events, userId: fixed ? userId : current, taken: events.length };\n}\n\n/** Experiment name and variant as `$exposure` carries them: trimmed, 1\u2013200 characters; a number or a boolean variant as text. */\nconst MAX_EXPOSURE_TEXT = 200;\nfunction exposureText(v: unknown): string | null {\n const t = typeof v === \"string\" ? v.trim() : (typeof v === \"number\" && Number.isFinite(v)) || typeof v === \"boolean\" ? String(v) : \"\";\n return t && t.length <= MAX_EXPOSURE_TEXT ? t : null;\n}\n\n/**\n * `exposure(experiment, variant, props)`'s properties: `{ ...props, experiment,\n * variant }` \u2014 the two named ones win over a prop of the same name \u2014 or null when the\n * experiment or the variant is empty or over 200 characters. What the console's\n * experiment analysis reads by default (docs/PRODUCT_ANALYTICS.md, experiments).\n */\nexport function exposureProps(experiment: unknown, variant: unknown, props?: Record<string, unknown>): Record<string, unknown> | null {\n const e = exposureText(experiment);\n const v = exposureText(variant);\n if (!e || !v) return null;\n return { ...(props && typeof props === \"object\" && !Array.isArray(props) ? props : {}), experiment: e, variant: v };\n}\n\n/** The accounts a user belongs to, by group type: `{ company: \"acme\", workspace: \"w_1\" }`. */\nexport type Groups = Record<string, string>;\n\n/** The server's rule for a group type (apps/api/src/product-analytics/groups.ts). */\nconst GROUP_TYPE = /^[a-z][a-z0-9_]{0,29}$/;\n/** Group types held at once \u2014 a new one past it is ignored. */\nexport const MAX_GROUP_TYPES = 5;\nconst MAX_GROUP_KEY = 256;\n\n/** A group type as the server takes it (`company`, `workspace`), or null. */\nexport function cleanGroupType(v: unknown): string | null {\n if (typeof v !== \"string\") return null;\n const t = v.trim();\n return GROUP_TYPE.test(t) ? t : null;\n}\n\n/** An account key: trimmed text (or a number) of 1\u2013256 characters, or null. */\nexport function cleanGroupKey(v: unknown): string | null {\n if (typeof v === \"number\" && Number.isFinite(v)) return String(v);\n if (typeof v !== \"string\") return null;\n const t = v.trim();\n return t && t.length <= MAX_GROUP_KEY ? t : null;\n}\n\n/** Stored groups re-read through the same rules: valid pairs only, at most 5. */\nexport function cleanGroups(v: unknown): Groups {\n const out: Groups = {};\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) return out;\n for (const [t, k] of Object.entries(v as Record<string, unknown>)) {\n if (Object.keys(out).length >= MAX_GROUP_TYPES) break;\n const type = cleanGroupType(t);\n const key = cleanGroupKey(k);\n if (type && key) out[type] = key;\n }\n return out;\n}\n\n/**\n * The groups after `group(type, key)`: null when the call must be ignored (a bad type\n * or key, or a 6th NEW type). `changed` = the key of that type is new \u2014 with traits,\n * the only cases worth an entry on the wire.\n */\nexport function withGroup(groups: Groups, type: unknown, key: unknown): { groups: Groups; type: string; key: string; changed: boolean } | null {\n const t = cleanGroupType(type);\n const k = cleanGroupKey(key);\n if (!t || !k) return null;\n if (!(t in groups) && Object.keys(groups).length >= MAX_GROUP_TYPES) return null;\n return { groups: { ...groups, [t]: k }, type: t, key: k, changed: groups[t] !== k };\n}\n\n/** A user property or super-property value: text, a number or a boolean \u2014 a label to segment by. */\nexport type TraitValue = string | number | boolean;\nexport type Traits = Record<string, TraitValue>;\n\n/** The server's key rule for a property (apps/api/src/product-analytics/prop-key.ts). */\nconst TRAIT_KEY = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/;\n/** Traits one identify call carries at most, and super-properties kept at most. */\nexport const MAX_TRAITS = 50;\nconst MAX_TRAIT_TEXT = 200;\n\n/**\n * Traits as the server keeps them (identify.ts): valid keys, values that are text\n * (cut at 200), a finite number or a boolean. Anything else is dropped here rather\n * than on the server, so a nested object never travels. At most 50 keys.\n */\nexport function cleanTraits(v: unknown): Traits {\n const out: Traits = {};\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) return out;\n for (const [k, raw] of Object.entries(v as Record<string, unknown>)) {\n if (Object.keys(out).length >= MAX_TRAITS) break;\n if (!TRAIT_KEY.test(k)) continue;\n if (typeof raw === \"string\") {\n const t = raw.trim();\n if (t) out[k] = t.slice(0, MAX_TRAIT_TEXT);\n } else if ((typeof raw === \"number\" && Number.isFinite(raw)) || typeof raw === \"boolean\") {\n out[k] = raw;\n }\n }\n return out;\n}\n\n/**\n * An event's properties with the super-properties under them: the event's own win.\n * Over the 4 KB cap, the event's own properties alone.\n */\nexport function withSuperProps(own: Record<string, unknown> | undefined, sup: Traits): Record<string, unknown> | undefined {\n if (!Object.keys(sup).length) return own;\n return cleanProps({ ...sup, ...(own ?? {}) }) ?? own;\n}\n\nexport interface AnalyticsSession {\n id: string;\n /** Last activity, epoch ms. */\n last: number;\n}\n\n/** 30 minutes without activity end a session \u2014 the web SDK's and PostHog's rule. */\nexport const ANALYTICS_SESSION_IDLE_MS = 30 * 60 * 1000;\n/** The server's own caps (screen.ts): longer is refused or cut there. */\nexport const MAX_EVENT_NAME = 128;\nexport const MAX_SCREEN_NAME = 512;\nexport const MAX_PROPS_BYTES = 4096;\n\n/** The one `$` name a custom event may carry: an experiment exposure, `$exposure { experiment, variant }`. */\nexport const EXPOSURE_EVENT = \"$exposure\";\n\n/** A custom event name the server will take, or null: non-empty, \u2264 128, never `$\u2026` (reserved) but `$exposure`. */\nexport function cleanEventName(name: unknown): string | null {\n if (typeof name !== \"string\") return null;\n const n = name.trim();\n if (!n || n.length > MAX_EVENT_NAME || (n.startsWith(\"$\") && n !== EXPOSURE_EVENT)) return null;\n return n;\n}\n\n/** A screen name as stored in the `page` dimension, or null. */\nexport function cleanScreenName(name: unknown): string | null {\n if (typeof name !== \"string\") return null;\n const n = name.trim();\n return n ? n.slice(0, MAX_SCREEN_NAME) : null;\n}\n\n/**\n * Properties as they can travel: a plain object that survives JSON, under the\n * server's cap \u2014 else none. Checked at capture time, because a cyclic object or a\n * BigInt handed by the app would otherwise throw later, inside the persisted\n * queue's `JSON.stringify`, and take every queued event down with it.\n */\nexport function cleanProps(props: unknown): Record<string, unknown> | undefined {\n if (typeof props !== \"object\" || props === null || Array.isArray(props)) return undefined;\n try {\n const json = JSON.stringify(props);\n if (!json || json === \"{}\" || json.length > MAX_PROPS_BYTES) return undefined;\n return JSON.parse(json) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n\n/** The session this activity belongs to: the current one, touched, or a new one after 30 idle minutes. */\nexport function touchSession(current: AnalyticsSession | null, now: number, newId: () => string): AnalyticsSession {\n if (current && typeof current.id === \"string\" && typeof current.last === \"number\" && now - current.last <= ANALYTICS_SESSION_IDLE_MS && now >= current.last - 60_000) {\n return { id: current.id, last: Math.max(now, current.last) };\n }\n return { id: newId(), last: now };\n}\n\n/** A persisted session, read back \u2014 anything malformed is no session. */\nexport function parseSession(raw: string | null | undefined): AnalyticsSession | null {\n if (!raw) return null;\n try {\n const s = JSON.parse(raw) as Partial<AnalyticsSession>;\n return typeof s.id === \"string\" && typeof s.last === \"number\" ? { id: s.id, last: s.last } : null;\n } catch {\n return null;\n }\n}\n\n/**\n * React Navigation's container ref, as far as screen tracking needs it \u2014 typed by\n * shape so neither `@react-navigation/native` nor `expo-router` becomes a dependency.\n */\nexport interface NavigationRefLike {\n addListener(event: \"state\", listener: () => void): (() => void) | undefined | void;\n getCurrentRoute(): { name: string } | undefined | null;\n}\n", "// Apple Ads (Search Ads) attribution \u2014 the JS half.\n//\n// What it buys: the one DETERMINISTIC attribution iOS still allows. Every other iOS\n// signal is SKAdNetwork, which is aggregated, six bits wide and 24h+ late. Apple\n// Search Ads self-attributes through the AdServices framework, and any developer may\n// resolve their own app's tokens \u2014 no partner programme, no allowlist.\n//\n// What it is NOT: an identifier. `AAAttribution.attributionToken()` returns an\n// opaque, single-purpose claim ticket valid for **24 hours**. No IDFA, no ATT prompt\n// of our own, no fingerprinting. Apple decides how much of the answer to return from\n// the ATT status the user already chose \u2014 detailed with consent, standard without.\n//\n// Why the SERVER resolves it: Apple answers 404 until the token is known on its side,\n// which right after an install is the normal first answer. That retry has to outlive\n// the app process, so the device's only job is to hand the token over before it\n// expires. See apps/api/src/apple-ads/.\n//\n// https://developer.apple.com/documentation/adservices\n\n/** Native surface the Expo module exposes. Absent on Android and pre-iOS 14.3. */\nexport interface AdServicesNative {\n /** The opaque 24h token, or null when the framework has none on this device. */\n getAttributionToken(): Promise<string | null>;\n}\n\nexport interface AdServicesOptions {\n endpoint: string;\n sdkKey: string;\n deviceId?: string;\n userId?: string;\n native?: AdServicesNative;\n /** Same store the event queue uses, so \"already sent\" survives a restart. */\n storage?: { getItem(key: string): Promise<string | null>; setItem(key: string, value: string): Promise<void> };\n /** Injectable for tests; defaults to the global fetch. */\n fetchFn?: typeof fetch;\n /** A debug build (see `InitOptions.debug`): the server then drops the token. */\n debug?: boolean;\n}\n\nexport const ADSERVICES_SENT_KEY = \"traq_adservices_sent\";\nexport const ADSERVICES_ATTEMPTS_KEY = \"traq_adservices_attempts\";\n\n/**\n * How many launches we keep asking before giving up on this install. The framework\n * can answer later in an install's life, but on a device where it never will \u2014\n * a simulator, an install with no attribution record at all, which is MOST installs \u2014\n * asking forever is work with no answer to it.\n */\nconst MAX_ATTEMPTS = 5;\n\n/**\n * Hand the token over, at most once per install.\n *\n * Returns what happened, so a host app can debug the integration without reading our\n * logs. Never throws: there is no user-visible consequence to any outcome here, and\n * an exception in `init()` would take the whole SDK down for a signal most installs\n * do not have.\n */\nexport async function reportAdServicesToken(\n opts: AdServicesOptions,\n): Promise<\"sent\" | \"already-sent\" | \"no-token\" | \"unsupported\" | \"post-failed\"> {\n if (!opts.native?.getAttributionToken) return \"unsupported\";\n\n if (await read(opts, ADSERVICES_SENT_KEY)) return \"already-sent\";\n\n let token: string | null = null;\n try {\n token = await opts.native.getAttributionToken();\n } catch {\n // The framework throws on a device with nothing to give. Treated as \"no token\".\n }\n\n if (!token || !token.trim()) {\n const attempts = Number(await read(opts, ADSERVICES_ATTEMPTS_KEY)) || 0;\n await write(opts, ADSERVICES_ATTEMPTS_KEY, String(attempts + 1));\n // Bounded: stop asking a device that will never answer.\n if (attempts + 1 >= MAX_ATTEMPTS) await write(opts, ADSERVICES_SENT_KEY, \"1\");\n return \"no-token\";\n }\n\n const doFetch = opts.fetchFn ?? (typeof fetch === \"function\" ? fetch : undefined);\n if (!doFetch) return \"post-failed\";\n\n try {\n const res = await doFetch(`${opts.endpoint}/ingest/adservices`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n sdkKey: opts.sdkKey,\n token: token.trim(),\n deviceId: opts.deviceId,\n appUserId: opts.userId,\n ...(opts.debug ? { debug: true } : {}),\n }),\n });\n if (!res.ok) return \"post-failed\";\n } catch {\n return \"post-failed\";\n }\n\n // Only mark sent on success, so a failed post retries on the next launch \u2014 inside\n // the 24h window, which is what makes the retry worth anything.\n await write(opts, ADSERVICES_SENT_KEY, \"1\");\n return \"sent\";\n}\n\nasync function read(opts: AdServicesOptions, key: string): Promise<string | null> {\n try {\n return (await opts.storage?.getItem(key)) ?? null;\n } catch {\n return null;\n }\n}\n\nasync function write(opts: AdServicesOptions, key: string, value: string): Promise<void> {\n try {\n await opts.storage?.setItem(key, value);\n } catch {\n /* storage full/unavailable */\n }\n}\n", "// Deep linking \u2014 the SDK half (docs/DEEP_LINKING.md).\n//\n// Two moments, one callback:\n// - DIRECT: a universal link / App Link (`https://<your host>/c/<code>`) opened\n// the installed app. The OS never hit our server, so the SDK resolves the\n// code \u2014 which also records the click the OS skipped.\n// - DEFERRED: the app was installed FROM a link. On the very first launch the\n// SDK asks what that link carried. Three deterministic carriers, then one\n// probabilistic fallback (docs/DEEP_LINKING.md \u00A710):\n// \u00B7 `referrer` \u2014 Android: the Play Install Referrer;\n// \u00B7 `link` \u2014 iOS: the landing page's \u00AB Open in <app> \u00BB / Smart App Banner,\n// a universal link `https://<host>/o/<clickId>`;\n// \u00B7 `code` \u2014 the code the landing page showed, typed in the app\n// (`Traqio.redeemDeepLinkCode`);\n// \u00B7 `probabilistic` \u2014 same network + same coarse device inside the hour,\n// ONLY when the user consented (`setConsent(true)`) and the app turned\n// the IP match on in the console. Comes with a `confidence`.\n//\n// Privacy: no pasteboard, no IDFA. The referrer already travels with the install;\n// the URL is the one that opened the app; the device's OS version and model are\n// sent with the deferred ask so the server can compare them with the tap's.\n\n/** How the link was found. Everything but `probabilistic` is deterministic. */\nexport type DeepLinkMatchType = \"referrer\" | \"link\" | \"code\" | \"probabilistic\";\n\n/** What the link carried. */\nexport interface DeepLinkPayload {\n /**\n * The destination set on the link in the console \u2014 an in-app path (\"/invite\")\n * or an app URL (\"myapp://invite\"). Null when the link sets none.\n */\n deepLink: string | null;\n /** `deep_link_value` of the shared URL \u2014 e.g. an invite token. Null when absent. */\n value: string | null;\n /** `deep_link_sub1..10` of the shared URL, and `ref` for a short link's recipient. */\n params: Record<string, string>;\n}\n\n/** A resolved deep link, as `onDeepLink` and `getDeferredDeepLink` hand it to the app. */\nexport interface DeepLink {\n /** What the link carried \u2014 read `payload.value` for a per-share token. */\n payload: DeepLinkPayload;\n /** How it was found. Treat `probabilistic` as a guess (see `confidence`). */\n matchType: DeepLinkMatchType;\n /** `high` | `medium` | `low` on a probabilistic match, null on a deterministic one. */\n confidence: \"high\" | \"medium\" | \"low\" | null;\n /** True when the link was tapped BEFORE the install; false when it opened the installed app. */\n deferred: boolean;\n /** The link's slug (the `<code>` of `/c/<code>`). */\n code: string | null;\n /** The URL that opened the app (direct opens and `/o/` links only). */\n url?: string;\n /** @deprecated same as `payload.deepLink`. */\n deepLink: string | null;\n /** @deprecated read `matchType` \u2014 `ip_match` is the old name of `probabilistic`. */\n via: \"referrer\" | \"ip_match\" | \"link\" | \"code\";\n}\n\n/** What `/deeplink/deferred`, `/deeplink/open` and `/deeplink/code` answer. */\nexport interface DeepLinkAnswer {\n matched: boolean;\n matchType?: DeepLinkMatchType | null;\n payload?: DeepLinkPayload | null;\n confidence?: \"high\" | \"medium\" | \"low\" | null;\n via: \"referrer\" | \"ip_match\" | \"link\" | \"code\" | null;\n code: string | null;\n deepLink: string | null;\n}\n\n// Mirrors `parseDeepLinkUrl` in apps/api/src/tracking/link-rules.ts. Checked on\n// the device so the app's OWN URLs (most of what opens an app) never leave it.\nconst TRACKING_PATH = /^\\/c\\/[A-Za-z0-9_-]{1,50}\\/?$/;\nconst OPEN_PATH = /^\\/o\\/[0-9a-fA-F-]{36}\\/?$/;\n\nfunction pathOf(url: string): string | null {\n const m = /^https?:\\/\\/[^/?#]+(\\/[^?#]*)?/i.exec(url);\n return m ? (m[1] ?? \"\") : null;\n}\n\n/**\n * True when `url` is one of our links: a tracking link (`https://<host>/c/<code>`)\n * or the iOS landing page's \u00AB Open in app \u00BB link (`https://<host>/o/<clickId>`).\n */\nexport function isTrackingUrl(url: string): boolean {\n const path = pathOf(url);\n return path !== null && (TRACKING_PATH.test(path) || OPEN_PATH.test(path));\n}\n\n/** The landing page's universal link: it carries a click tapped BEFORE the install. */\nexport function isOpenUrl(url: string): boolean {\n const path = pathOf(url);\n return path !== null && OPEN_PATH.test(path);\n}\n\n/**\n * An API answer \u2192 the callback's shape, or null when nothing matched. Reads the\n * pre-0.2 answer too (no `matchType` / `payload`), so a newer SDK against an older\n * API still works.\n */\nexport function toDeepLink(answer: DeepLinkAnswer | null, deferred: boolean, url?: string): DeepLink | null {\n if (!answer?.matched || !answer.via) return null;\n const matchType: DeepLinkMatchType = answer.matchType ?? (answer.via === \"ip_match\" ? \"probabilistic\" : answer.via);\n const payload: DeepLinkPayload = answer.payload ?? { deepLink: answer.deepLink, value: null, params: {} };\n return {\n payload,\n matchType,\n confidence: matchType === \"probabilistic\" ? (answer.confidence ?? \"low\") : null,\n deferred,\n code: answer.code,\n deepLink: payload.deepLink,\n via: answer.via,\n ...(url ? { url } : {}),\n };\n}\n\n/** A deferred link stored by SDK 0.1.x (no `payload` / `matchType`) \u2192 today's shape. */\nexport function upgradeStoredDeepLink(stored: unknown): DeepLink | null {\n if (!stored || typeof stored !== \"object\") return null;\n const link = stored as Partial<DeepLink> & { via?: DeepLink[\"via\"] };\n if (link.payload && link.matchType) return link as DeepLink;\n if (!link.via) return null;\n return toDeepLink({ matched: true, via: link.via, code: link.code ?? null, deepLink: link.deepLink ?? null }, link.deferred ?? true, link.url);\n}\n", "// Stands in for `react-native` and `@react-native-async-storage/async-storage` in the\n// bundle. @traqio/core reaches for both inside try/catch (they are how it finds\n// AppState, Linking and AsyncStorage on React Native); in a browser they must resolve\n// to nothing, never to a bare `require` a consumer's bundler would try to follow.\nexport {};\n", "// Automatic ad revenue capture (HQ cmwfo9pd): `Traqio.init({ adRevenue: { admob: true,\n// applovinMax: true } })` and the paid events of the ad SDKs the app already uses reach\n// `trackAdRevenue` / `trackMaxAdRevenue` without a line per ad.\n//\n// Nothing here imports an ad SDK. React Native's own event channels are read, the\n// same channels the ad libraries' JS listens to, so an app without the library\n// simply never receives an event. The payload shapes are pinned by\n// adRevenue.test.ts against the libraries' native sources: if a library changes\n// them, the contract test is where it shows.\n\n// `require` is provided by the React Native / Metro runtime. A require inside\n// try/catch is an optional dependency for Metro.\ndeclare const require: (module: string) => any;\n\nimport type { AdRevenue, MaxAdRevenue } from \"./index\";\n\n/** `InitOptions.adRevenue`: which ad SDKs to listen to. */\nexport interface AdRevenueOptions {\n /** Google Mobile Ads (AdMob / Ad Manager). */\n admob?: boolean;\n /** AppLovin MAX. */\n applovinMax?: boolean;\n}\n\n/**\n * Where a watcher hands what it captured. `raw` is the ad library's own event\n * object, when there is one: the same object handed to two listeners is one\n * impression, never two (see `AdRevenueGate.first`).\n */\nexport interface AdRevenueSink {\n admob(ad: AdRevenue, raw?: unknown): void;\n applovinMax(ad: MaxAdRevenue, raw?: unknown): void;\n}\n\n/**\n * What a watcher actually captures, per network: `true` = every format, a list =\n * only those formats (React Native: a `<BannerAd>` reports through its own prop),\n * `false` / absent = nothing (the ad library is not there). `AdRevenueOptions`\n * itself is a valid coverage: a bridge that answers nothing covers what was asked.\n */\nexport interface AdRevenueCoverage {\n admob?: boolean | readonly string[];\n applovinMax?: boolean | readonly string[];\n}\n\nexport type AdNetwork = keyof AdRevenueCoverage;\n\n/** How an impression reached the queue \u2014 sent to the server's dedup net. */\nexport type AdRevenueOrigin = \"auto\" | \"manual\";\n\nfunction covers(c: boolean | readonly string[] | undefined): boolean {\n return Array.isArray(c) ? c.length > 0 : c === true;\n}\n\n/**\n * The one rule against double counting (HQ cmwfq3ij): once `adRevenue` captures a\n * network, Traqio owns that network's impressions.\n *\n * - A MANUAL call (`trackAdRevenue`, `trackMaxAdRevenue`) for a captured network is\n * ignored, with one warning in the log. Chosen over deduplicating per impression\n * because neither AdMob's AdValue nor MAX's AdInfo carries an impression id: a key\n * made of amount + ad unit + time would merge two real banners that happened to\n * pay the same in the same second \u2014 a silent undercount \u2014 where ignoring is\n * deterministic and says so in the log.\n * - A ONE-LINE HELPER (`admobPaid`, `maxRevenuePaid`) exists for the formats the\n * watcher cannot reach. Pointed at a format the watcher already captures, it is\n * ignored the same way.\n * - The same event OBJECT reaching both the watcher and a helper (an app that\n * plugged the helper into the global listener the watcher also hears) is one\n * impression: the first path takes it, the second sees it was taken.\n */\nexport class AdRevenueGate {\n private coverage: AdRevenueCoverage = {};\n private readonly warned = new Set<string>();\n private readonly seen = new WeakSet<object>();\n\n constructor(private readonly warn: (message: string) => void = (m) => console.warn(m)) {}\n\n arm(coverage: AdRevenueCoverage): void {\n this.coverage = { ...coverage };\n }\n\n /** Does the automatic capture own this network (any format)? */\n captures(network: AdNetwork): boolean {\n return covers(this.coverage[network]);\n }\n\n /** Does the automatic capture own this format of the network? */\n capturesFormat(network: AdNetwork, format: string | undefined): boolean {\n const c = this.coverage[network];\n if (c === true) return true;\n return Array.isArray(c) && format !== undefined && c.includes(format);\n }\n\n /** A public manual tracker: allowed only for a network nothing captures. */\n manual(network: AdNetwork, call: string): boolean {\n if (!this.captures(network)) return true;\n this.warnOnce(`manual:${network}`, `[traqio] adRevenue.${network} is on: manual ${call}() ignored \u2014 Traqio already captures this network, remove the call.`);\n return false;\n }\n\n /** A one-line helper: allowed for the formats the watcher does not capture, once per event. */\n helper(network: AdNetwork, format: string | undefined, raw: unknown, call: string): boolean {\n if (this.capturesFormat(network, format)) {\n this.warnOnce(`helper:${network}:${format}`, `[traqio] adRevenue.${network} already captures ${format} ads: ${call} ignored for them, keep it on the formats it is documented for.`);\n return false;\n }\n return this.first(raw);\n }\n\n /** True the first time this event object is seen (non-objects always pass). */\n first(raw: unknown): boolean {\n if (!raw || typeof raw !== \"object\") return true;\n if (this.seen.has(raw)) return false;\n this.seen.add(raw);\n return true;\n }\n\n private warnOnce(key: string, message: string): void {\n if (this.warned.has(key)) return;\n this.warned.add(key);\n try {\n this.warn(message);\n } catch {\n /* a logger that throws is not our concern */\n }\n }\n}\n\ntype AdFormat = NonNullable<AdRevenue[\"adFormat\"]>;\ntype Precision = NonNullable<AdRevenue[\"precision\"]>;\n\n// AdValue.PrecisionType (Android) and GADAdValuePrecision (iOS) share the numbering.\nconst PRECISION_BY_INDEX: readonly Precision[] = [\"unknown\", \"estimated\", \"publisher_provided\", \"precise\"];\n\nfunction precisionOf(raw: unknown): Precision {\n return typeof raw === \"number\" ? PRECISION_BY_INDEX[raw] ?? \"unknown\" : \"unknown\";\n}\n\nfunction text(raw: unknown): string | undefined {\n return typeof raw === \"string\" && raw.trim() ? raw : undefined;\n}\n\nfunction record(raw: unknown): Record<string, unknown> | undefined {\n return raw && typeof raw === \"object\" ? (raw as Record<string, unknown>) : undefined;\n}\n\n/** A non-negative integer amount of micros, from a number or a decimal string. */\nfunction micros(raw: unknown): number | undefined {\n const n = typeof raw === \"string\" && /^\\d+$/.test(raw.trim()) ? Number(raw) : raw;\n return typeof n === \"number\" && Number.isSafeInteger(n) && n >= 0 ? n : undefined;\n}\n\n// \u2500\u2500 react-native-google-mobile-ads \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * The four native channels react-native-google-mobile-ads emits EVERY full-screen\n * ad's events on (src/MobileAds.ts `nativeEvents`). React Native\n * prefixes them `rnapp_` (RNRCTEventEmitter.mm / ReactNativeEventEmitter.java).\n */\nexport const GMA_FULLSCREEN_CHANNELS: Readonly<Record<string, AdFormat>> = {\n rnapp_google_mobile_ads_app_open_event: \"app_open\",\n rnapp_google_mobile_ads_interstitial_event: \"interstitial\",\n rnapp_google_mobile_ads_rewarded_event: \"rewarded\",\n rnapp_google_mobile_ads_rewarded_interstitial_event: \"rewarded_interstitial\",\n};\n\n/** The first react-native-google-mobile-ads with `AdEventType.PAID` and `onPaid` (commit 969dbfac, 2023-11). */\nexport const GMA_MIN_VERSION = \"12.4.0\";\n\n/**\n * One PAID payload of react-native-google-mobile-ads \u2014 `AdEventType.PAID`, a\n * banner's `onPaid`, a native ad's `paid`. Every version sends `value` in currency\n * UNITS (the native side multiplied the micros by 1e-6) with `precision` as a\n * number; v17 adds the exact `valueMicros` (a string on Android, null on iOS) and a compact\n * `responseInfo`. The exact micros win when present, so nothing is lost twice.\n */\nexport function fromGoogleMobileAdsPaid(\n payload: unknown,\n meta: { adUnitId?: string; adFormat?: AdFormat } = {},\n): AdRevenue | undefined {\n const p = record(payload);\n if (!p) return undefined;\n const currency = text(p.currency);\n if (!currency) return undefined;\n let valueMicros = micros(p.valueMicros);\n if (valueMicros === undefined) {\n if (!(typeof p.value === \"number\" && Number.isFinite(p.value) && p.value >= 0)) return undefined;\n // Back to micros, rounded to the micro and never earlier: a banner is ~20 micros.\n valueMicros = Math.round(p.value * 1_000_000);\n }\n const loaded = record(record(p.responseInfo)?.loadedAdapterResponse);\n return {\n valueMicros,\n currency,\n precision: precisionOf(p.precision),\n adUnitId: meta.adUnitId,\n adFormat: meta.adFormat,\n adSourceName: text(loaded?.adSourceName),\n };\n}\n\n/**\n * One event of a full-screen channel: `{ adUnitId, requestId, body: { type, data } }`.\n * Only `type: \"paid\"` is revenue; loads, clicks and closes ride the same channel.\n */\nexport function fromGoogleMobileAdsChannel(channel: string, event: unknown): AdRevenue | undefined {\n const e = record(event);\n const body = record(e?.body);\n if (!e || body?.type !== \"paid\") return undefined;\n return fromGoogleMobileAdsPaid(body.data, { adUnitId: text(e.adUnitId), adFormat: GMA_FULLSCREEN_CHANNELS[channel] });\n}\n\n/** One native-ad event: `{ type, responseId, ...data }` (no ad unit id in it). */\nexport function fromGoogleMobileAdsNativeAd(event: unknown): AdRevenue | undefined {\n const e = record(event);\n if (e?.type !== \"paid\") return undefined;\n return fromGoogleMobileAdsPaid(e, { adFormat: \"native\" });\n}\n\n// \u2500\u2500 AppLovin MAX \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * react-native-applovin-max's global revenue events, one per format\n * (AppLovinMAXAdEvents.java). The library keeps ONE listener per event for the\n * app; Traqio subscribes to the module's emitter directly, beside it, so it never\n * replaces the app's own listener.\n */\nexport const MAX_RN_REVENUE_EVENTS = [\n \"OnBannerAdRevenuePaid\",\n \"OnMRecAdRevenuePaid\",\n \"OnInterstitialAdRevenuePaid\",\n \"OnRewardedAdRevenuePaid\",\n \"OnAppOpenAdRevenuePaid\",\n] as const;\n\n/** The oldest react-native-applovin-max whose revenue events and AdInfo the parser reads. */\nexport const MAX_RN_MIN_VERSION = \"5.0.0\";\n\n/**\n * MAX's AdInfo (`{ adUnitId, adFormat, networkName, revenue, revenuePrecision }`)\n * \u2014 the React Native, Capacitor and Cordova plugins all name it so.\n */\nexport function fromMaxAdInfo(info: unknown): MaxAdRevenue | undefined {\n const i = record(info);\n if (!i || typeof i.revenue !== \"number\") return undefined;\n return {\n revenue: i.revenue,\n revenuePrecision: text(i.revenuePrecision),\n adUnitId: text(i.adUnitId),\n format: text(i.adFormat),\n networkName: text(i.networkName),\n };\n}\n\n// \u2500\u2500 @capacitor-community/admob \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * @capacitor-community/admob (8.1.0+, \"impression-level ad revenue #433\") emits a paid event per format. The full-screen\n * formats file it under their `\u2026AdImpression` name, banner and native ads under\n * `\u2026AdPaid`. The banner ALSO fires an empty `bannerAdImpression`, which the parser\n * rejects for lack of an amount.\n */\nexport const CAPACITOR_ADMOB_PAID_EVENTS: Readonly<Record<string, AdFormat>> = {\n bannerAdPaid: \"banner\",\n nativeAdPaid: \"native\",\n interstitialAdImpression: \"interstitial\",\n onRewardedVideoAdImpression: \"rewarded\",\n onRewardedInterstitialAdImpression: \"rewarded_interstitial\",\n appOpenAdImpression: \"app_open\",\n};\n\n/** `AdMobRevenueData`: `{ adUnitId, valueMicros, currencyCode, precision, networkName }`. */\nexport function fromCapacitorAdMob(event: unknown, adFormat?: AdFormat): AdRevenue | undefined {\n const e = record(event);\n const valueMicros = micros(e?.valueMicros);\n const currency = text(e?.currencyCode);\n if (!e || valueMicros === undefined || !currency) return undefined;\n return {\n valueMicros,\n currency,\n precision: precisionOf(e.precision),\n adUnitId: text(e.adUnitId),\n adFormat,\n // The mediation ADAPTER class here, not the source's display name \u2014 still\n // the only thing telling AdMob's own demand from a mediated network.\n adSourceName: text(e.networkName),\n };\n}\n\n// \u2500\u2500 React Native watcher \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The slice of `react-native` the watcher uses \u2014 injected by the tests. */\nexport interface ReactNativeEvents {\n DeviceEventEmitter?: { addListener(event: string, cb: (e: unknown) => void): { remove(): void } };\n NativeEventEmitter?: new (module?: unknown) => { addListener(event: string, cb: (e: unknown) => void): { remove(): void } };\n NativeModules?: Record<string, any>;\n TurboModuleRegistry?: { get?(name: string): any };\n Platform?: { OS?: string };\n}\n\nfunction nativeModule(rn: ReactNativeEvents, name: string): any {\n try {\n return rn.TurboModuleRegistry?.get?.(name) ?? rn.NativeModules?.[name];\n } catch {\n return rn.NativeModules?.[name];\n }\n}\n\n/** What `watchReactNativeAds` captures, and how to stop it. */\nexport interface ReactNativeAdWatch {\n coverage: AdRevenueCoverage;\n stop(): void;\n}\n\n/** The full-screen formats a react-native-applovin-max global event always is. */\nconst MAX_RN_FULLSCREEN_FORMATS = [\"interstitial\", \"rewarded\", \"rewarded_interstitial\", \"app_open\"] as const;\n\n/**\n * Subscribes to the ad libraries' React Native channels. Returns what it covers\n * (the gate's input) and the unsubscribe. A library that is not installed has no\n * channel: nothing arrives, nothing fails.\n */\nexport function watchReactNativeAds(want: AdRevenueOptions, sink: AdRevenueSink, rn?: ReactNativeEvents): ReactNativeAdWatch {\n if (!rn) {\n try {\n rn = require(\"react-native\") as ReactNativeEvents;\n } catch {\n // Not React Native: Capacitor and the web bring their own.\n return { coverage: {}, stop: () => undefined };\n }\n }\n const subs: { remove(): void }[] = [];\n const coverage: { admob?: string[]; applovinMax?: string[] } = {};\n const guard =\n <T>(parse: (e: unknown) => T | undefined, deliver: (v: T, raw: unknown) => void, rawOf: (e: unknown) => unknown = (e) => e) =>\n (e: unknown): void => {\n try {\n const v = parse(e);\n if (v) deliver(v, rawOf(e));\n } catch {\n // Measurement is never worth a crash in the app's ad callback.\n }\n };\n // The PAID payload the library hands its own listeners is `body.data`.\n const paidData = (e: unknown): unknown => record(record(e)?.body)?.data;\n\n if (want.admob) {\n // Interstitial, rewarded, rewarded interstitial, app open: every ad, whatever\n // screen created it. Banners report through their own `onPaid` prop \u2014 see\n // `Traqio.admobPaid()`.\n coverage.admob = [];\n for (const [channel, format] of Object.entries(GMA_FULLSCREEN_CHANNELS)) {\n const sub = rn.DeviceEventEmitter?.addListener(channel, guard((e) => fromGoogleMobileAdsChannel(channel, e), sink.admob, paidData));\n if (sub) {\n subs.push(sub);\n coverage.admob.push(format);\n }\n }\n // Native ads: one module-wide emitter, filtered per ad by the library itself.\n const nativeAds = nativeModule(rn, \"RNGoogleMobileAdsNativeModule\");\n const onNative = guard(fromGoogleMobileAdsNativeAd, sink.admob);\n try {\n if (nativeAds && typeof nativeAds.onAdEvent === \"function\") {\n subs.push(nativeAds.onAdEvent(onNative));\n coverage.admob.push(\"native\");\n } else if (nativeAds && rn.NativeEventEmitter) {\n // Same branch the library takes on the old architecture.\n const emitter = new rn.NativeEventEmitter(rn.Platform?.OS === \"ios\" ? nativeAds : undefined);\n subs.push(emitter.addListener(\"RNGMANativeAdEvent\", onNative));\n coverage.admob.push(\"native\");\n }\n } catch {\n /* native ads unsupported by this build of the library */\n }\n }\n\n if (want.applovinMax) {\n const max = nativeModule(rn, \"AppLovinMAX\");\n if (max && rn.NativeEventEmitter) {\n try {\n let names: string[] = [...MAX_RN_REVENUE_EVENTS];\n try {\n const c = max.getConstants?.() ?? {};\n const fromModule = Object.keys(c)\n .filter((k) => /^ON_.*_AD_REVENUE_PAID$/.test(k))\n .map((k) => c[k])\n .filter((v): v is string => typeof v === \"string\");\n if (fromModule.length) names = [...new Set([...fromModule, ...names])];\n } catch {\n /* constants unavailable: the literal names are the library's */\n }\n const emitter = new rn.NativeEventEmitter(max);\n for (const name of names) subs.push(emitter.addListener(name, guard(fromMaxAdInfo, sink.applovinMax)));\n // Programmatic banners / MRECs ride these events too, but a `<AdView>`\n // banner does not: banners stay open to `maxRevenuePaid`, and the same\n // AdInfo object reaching both is caught by the gate's identity check.\n coverage.applovinMax = [...MAX_RN_FULLSCREEN_FORMATS];\n } catch {\n /* an emitter that cannot subscribe: the one-line prop remains */\n }\n }\n }\n\n return {\n coverage,\n stop: () => {\n for (const s of subs.splice(0)) {\n try {\n s.remove();\n } catch {\n /* already gone */\n }\n }\n },\n };\n}\n", "// @traqio/core \u2014 the platform-neutral engine. Android-first: reads the Play Install\n// Referrer from the native module, sends install + events to the ingestion API,\n// with a persisted offline queue, batching, and exponential-backoff retries.\n// On iOS: SKAdNetwork conversion values (./skan) plus Apple Ads self-attribution\n// through AdServices (./adservices) \u2014 the one deterministic iOS source.\n// Privacy: NO IDFA/GAID, no pasteboard, no fingerprinting. deviceId is a\n// first-party random id (persisted), not a cross-app identifier. Deep links\n// (./deeplink) send nothing new: the referrer already travels with the install,\n// and the iOS deferred IP match is the SERVER's, opt-in per app, routing only.\n\n// `require` is provided by the React Native / Metro runtime (used to lazily\n// wire AppState for lifecycle flush; absent off-device, hence the try/catch).\ndeclare const require: (module: string) => any;\n\nimport { Skan, type CoarseValue, type SkanMapping } from \"./skan\";\nimport {\n ANALYTICS_SESSION_IDLE_MS,\n cleanEventName,\n cleanProps,\n cleanScreenName,\n cleanGroups,\n cleanTraits,\n cleanUserId,\n EXPOSURE_EVENT,\n exposureProps,\n isEntry,\n nextAnalyticsBatch,\n parseSession,\n withGroup,\n type Groups,\n withSuperProps,\n type Traits,\n touchSession,\n type AnalyticsSession,\n type NavigationRefLike,\n type QueuedAnalyticsEvent,\n} from \"./analytics\";\nimport { reportAdServicesToken } from \"./adservices\";\nimport { isOpenUrl, isTrackingUrl, toDeepLink, upgradeStoredDeepLink, type DeepLink, type DeepLinkAnswer } from \"./deeplink\";\nimport {\n AdRevenueGate,\n fromGoogleMobileAdsPaid,\n fromMaxAdInfo,\n watchReactNativeAds,\n type AdRevenueCoverage,\n type AdRevenueOptions,\n type AdRevenueOrigin,\n type AdRevenueSink,\n} from \"./adRevenue\";\n\nexport const SDK_VERSION = \"0.9.0\";\nexport { Skan, type CoarseValue, type SkanMapping } from \"./skan\";\nexport { reportAdServicesToken, type AdServicesNative } from \"./adservices\";\nexport { ANALYTICS_SESSION_IDLE_MS, type Groups, type NavigationRefLike, type Traits, type TraitValue } from \"./analytics\";\nexport { isOpenUrl, isTrackingUrl, type DeepLink, type DeepLinkMatchType, type DeepLinkPayload } from \"./deeplink\";\nexport {\n CAPACITOR_ADMOB_PAID_EVENTS,\n GMA_FULLSCREEN_CHANNELS,\n GMA_MIN_VERSION,\n MAX_RN_MIN_VERSION,\n MAX_RN_REVENUE_EVENTS,\n fromCapacitorAdMob,\n fromGoogleMobileAdsChannel,\n fromGoogleMobileAdsNativeAd,\n fromGoogleMobileAdsPaid,\n fromMaxAdInfo,\n watchReactNativeAds,\n AdRevenueGate,\n type AdNetwork,\n type AdRevenueCoverage,\n type AdRevenueOptions,\n type AdRevenueOrigin,\n type AdRevenueSink,\n type ReactNativeAdWatch,\n type ReactNativeEvents,\n} from \"./adRevenue\";\n\nconst INSTALL_SENT_KEY = \"traq_install_sent\";\n// A debug build's own \"install sent\" flag. Separate on purpose: a release build\n// installed over a debug build on the same device (same storage) must still report\n// its install \u2014 the debug one is kept out of every report \u2014 and vice versa.\nconst INSTALL_SENT_DEBUG_KEY = \"traq_install_sent_debug\";\nconst INSTALL_ATTEMPTS_KEY = \"traq_install_attempts\";\n// The advertising id the server last acknowledged for this device (todo cmwlauev),\n// kept per mode like the install flag. Compared with what the OS hands out at each\n// start and foreground: a different (or first) id is posted once.\nconst AD_ID_SENT_KEY = \"traq_ad_id_sent\";\nconst AD_ID_SENT_DEBUG_KEY = \"traq_ad_id_sent_debug\";\nconst AD_ID_PATH = \"/ingest/advertising-id\";\nconst REFERRER_KEY = \"traq_referrer\";\nconst QUEUE_KEY = \"traq_queue\";\nconst AD_QUEUE_KEY = \"traq_ad_queue\";\nconst DEVICE_ID_KEY = \"traq_device_id\";\nconst LAST_SESSION_KEY = \"traq_last_session\";\n// Set once `forgetMe()` has been honoured by the server. Persisted, because the\n// whole point is that the NEXT launch stays silent too \u2014 the deviceId is still in\n// storage and an un-persisted flag would re-report the install tomorrow.\nconst ERASED_KEY = \"traq_erased\";\n// The deferred deep link, once the server has answered for this install\n// (\"null\" when it answered \"no link\"). Persisted so it is asked exactly once.\nconst DEFERRED_KEY = \"traq_deferred_link\";\n// Until when a \"no link\" answer given WITHOUT consent may be asked again once the\n// user consents (ms since epoch) \u2014 the probabilistic layer's one-hour window.\nconst DEFERRED_RETRY_KEY = \"traq_deferred_consent_retry_until\";\nconst DEFERRED_RETRY_WINDOW_MS = 60 * 60_000;\n// The user's answer to the app's consent prompt (\"granted\" | \"denied\"), once given.\nconst CONSENT_KEY = \"traq_consent\";\n// Product analytics (`capture()` / `screen()`): their own queue, their own route.\nconst ANALYTICS_QUEUE_KEY = \"traq_analytics_queue\";\nconst ANALYTICS_SESSION_KEY = \"traq_analytics_session\";\n/** `register()`'s super-properties, kept across launches. */\nconst SUPER_PROPS_KEY = \"traq_super_props\";\n/** `group()`'s accounts, kept across launches. */\nconst GROUPS_KEY = \"traq_groups\";\nconst ANALYTICS_PATH = \"/ingest/analytics\";\n/** Per request; the server takes 100. */\nconst MAX_ANALYTICS_BATCH = 50;\n/** Kept offline at most \u2014 the oldest go first, an analytics backlog is not money. */\nconst MAX_ANALYTICS_QUEUE = 1000;\n/** `capture()` / `screen()` calls made before `init()`: the first screen often renders first. */\nconst MAX_EARLY_ANALYTICS = 100;\nconst MAX_BATCH = 20;\n/** Statuses the same body gets on every retry \u2014 see Client.send. */\nconst NON_RETRYABLE_STATUS: ReadonlySet<number> = new Set([400, 413, 422]);\nconst MAX_QUEUE = 500;\n// Ad impressions are far more frequent than tracked events (a banner refreshes\n// every 30-60s), so they get their own, larger queue and batch.\nconst MAX_AD_BATCH = 100;\nconst MAX_AD_QUEUE = 1000;\nconst BASE_RETRY_MS = 1000;\nconst MAX_RETRY_MS = 5 * 60 * 1000;\nconst FLUSH_DELAY_MS = 3000;\n// How many launches we let the Play Install Referrer stay unavailable before\n// reporting the install anyway. See `sendInstallOnce`.\nconst MAX_INSTALL_ATTEMPTS = 3;\n\n// How long the app must have been away before coming back counts as a NEW session.\n// 30 minutes is the near-universal convention (GA4, Adjust, AppsFlyer all land\n// there) and the point of it is that a user switching to Maps and back has not\n// started a new session. It is also the debounce: without it, every\n// foreground/background flicker would post.\nconst SESSION_TIMEOUT_MS = 30 * 60 * 1000;\n\nexport interface KeyValueStore {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n}\n\nexport interface DeviceContext {\n deviceId?: string;\n deviceModel?: string;\n osVersion?: string;\n appVersion?: string;\n locale?: string;\n sdkVersion?: string;\n}\n\n/**\n * Why a Play Install Referrer read ended. Mirrors `ReferrerStatus` in the Kotlin\n * module, plus `unavailable` for \"the native module answered nothing\".\n */\nexport type InstallReferrerStatus =\n | \"ok\"\n | \"no_referrer\"\n | \"feature_not_supported\"\n | \"service_unavailable\"\n | \"service_disconnected\"\n | \"developer_error\"\n | \"permission_error\"\n | \"timeout\"\n | \"error\"\n | \"no_context\"\n | \"not_supported_platform\"\n | \"unavailable\";\n\nexport interface InstallReferrerResult {\n status: InstallReferrerStatus;\n /** True when a later launch could still produce a referrer (Play was busy/hung). */\n retryable: boolean;\n /** The raw referrer string, e.g. \"utm_source=meta&traq_click=abc123\". */\n referrer?: string;\n /** Unix seconds \u2014 when the ad click happened, per Play. */\n referrerClickTs?: number;\n /** Unix seconds \u2014 when the install began, per Play. */\n installBeginTs?: number;\n googlePlayInstant?: boolean;\n}\n\n/** iOS App Tracking Transparency status, as the APP obtained it (`ATTrackingManager`). */\nexport type TrackingAuthorization = \"not_determined\" | \"restricted\" | \"denied\" | \"authorized\";\nconst TRACKING_AUTHORIZATIONS: readonly (string | null | undefined)[] = [\"not_determined\", \"restricted\", \"denied\", \"authorized\"];\n\nexport interface NativeBridge {\n platform: \"ios\" | \"android\";\n /** Android: reads the Play Install Referrer. Never rejects \u2014 failure is a status. */\n getInstallReferrer(): Promise<InstallReferrerResult>;\n /** Optional native device context (model, OS version). */\n getContext?(): Promise<{ deviceModel?: string; osVersion?: string }>;\n /** iOS: hand a SKAdNetwork conversion value to the device. No-op on Android. */\n updateConversionValue?(fineValue: number, coarse?: CoarseValue, lockWindow?: boolean): void;\n /**\n * iOS 14.3+: the AdServices attribution token (Apple Ads self-attribution).\n * Resolves null when the framework has none on this device \u2014 which is the case for\n * most installs, since most installs are not Apple Search Ads. Absent on Android.\n */\n getAttributionToken?(): Promise<string | null>;\n /**\n * The device advertising id (IDFA / GAID), or null. Called ONLY when the host set\n * `collectAdvertisingId: true`. It NEVER prompts: on iOS it answers only when the\n * app itself already obtained ATT, on Android only when the app ships Google's\n * ads-identifier library and declares the AD_ID permission. Decision cmvjohk6.\n */\n getAdvertisingId?(): Promise<string | null>;\n /**\n * iOS: the ATT status the app ALREADY obtained, or null when it does not link\n * AppTrackingTransparency. A status, not an identifier: read by default, at send\n * time, and it NEVER prompts (decision cmvjohk6). The server tells Meta the truth\n * with it (`advertiser_tracking_enabled`): false unless `authorized` (todo cmwl6oko).\n */\n getTrackingAuthorization?(): Promise<TrackingAuthorization | null>;\n /**\n * Is the HOST app a development build \u2014 debuggable (Android), DEBUG configuration\n * (iOS), or running on a simulator / emulator? Read once at `init()` when the app\n * did not set `debug` itself. Absent = only the JS side decides (`__DEV__`).\n */\n isDebugBuild?(): Promise<boolean>;\n /**\n * Subscribe to the paid events of the ad SDKs the host app uses, when the app\n * set `adRevenue` (HQ cmwfo9pd). Called once from `init()`. Absent = the core's\n * React Native watcher (`watchReactNativeAds`); Capacitor brings its own.\n * Returns what it actually captures \u2014 the networks whose manual calls are then\n * ignored (`AdRevenueGate`); no answer = everything that was asked.\n */\n watchAdRevenue?(want: AdRevenueOptions, sink: AdRevenueSink): AdRevenueCoverage | void;\n}\n\n/** One AdMob paid event, as handed to the app by `OnPaidEventListener`. */\nexport interface AdRevenue {\n /** `AdValue.getValueMicros()` \u2014 millionths of `currency`. Never pre-round it. */\n valueMicros: number;\n /** `AdValue.getCurrencyCode()` \u2014 ISO 4217. */\n currency: string;\n /** `AdValue.getPrecisionType()`. ESTIMATED is the normal case, and still real money. */\n precision?: \"unknown\" | \"estimated\" | \"publisher_provided\" | \"precise\";\n adUnitId?: string;\n adFormat?: \"banner\" | \"interstitial\" | \"rewarded\" | \"rewarded_interstitial\" | \"native\" | \"app_open\";\n /** Mediation ad source that filled it (`ResponseInfo.getLoadedAdapterResponseInfo()`). */\n adSourceName?: string;\n /** Unix seconds. Defaults to now. */\n ts?: number;\n}\n\n/**\n * The store a purchase went through, spelled the way the server's revenue key\n * spells it (`apps/api/src/revenuecat/revenue-key.ts`). It is part of the key, so\n * the same transaction id from two stores can never collide.\n */\nexport type RevenueStore = \"app_store\" | \"play_store\" | \"mac_app_store\" | \"amazon\" | \"stripe\";\n\n/** What `track()` accepts beside the event name. */\nexport interface TrackProps {\n /** Revenue DECLARED by the app. The SDK does not verify it against any receipt. */\n value?: number;\n currency?: string;\n /**\n * The STORE's id for this purchase \u2014 StoreKit's `transactionId`, Play Billing's\n * `orderId` (GPA.\u2026). With it, the server keys the event on the SAME deterministic\n * id RevenueCat / App Store Server Notifications / Play RTDN produce for that\n * transaction, so the purchase is counted once however many of them report it.\n * Without it, a purchase also reported server-side is counted twice.\n */\n transactionId?: string;\n /** Defaults to the platform's store (`app_store` on iOS, `play_store` on Android). */\n store?: RevenueStore;\n}\n\nexport interface InitOptions {\n sdkKey: string;\n endpoint: string; // origin only, no path \u2014 the SDK posts to `${endpoint}/ingest`\n /** Host-provided persistence (e.g. AsyncStorage) so the queue + install flag survive restarts. */\n storage?: KeyValueStore;\n /** Native bridge; on Android this reads the Install Referrer. */\n native?: NativeBridge;\n /** Your user id \u2014 set the SAME value as RevenueCat's app_user_id for revenue matching. */\n userId?: string;\n /** Your app's version string (host provides it). */\n appVersion?: string;\n /** Collect basic, non-fingerprinting device context (default true). Never IDFA/GAID. */\n collectContext?: boolean;\n /**\n * Set true while the app serves AdMob TEST ad units. Ad revenue is then logged\n * by the API (so you can see the pipe working) but never counted as revenue \u2014\n * test impressions are not money.\n */\n testAds?: boolean;\n /**\n * Capture ad revenue by itself (HQ cmwfo9pd): `{ admob: true, applovinMax: true }`.\n * No ad library becomes a dependency \u2014 Traqio listens to the events the library\n * already emits, and a library the app does not use emits nothing.\n *\n * React Native: every interstitial, rewarded, rewarded interstitial, app open and\n * native ad of react-native-google-mobile-ads (12.4+, the version that added PAID), and every interstitial,\n * rewarded, app open and programmatic banner / MREC of react-native-applovin-max.\n * A `<BannerAd>` / MAX `<AdView>` reports through its own prop: one line,\n * `onPaid={Traqio.admobPaid(AD_UNIT_ID)}` / `onAdRevenuePaid={Traqio.maxRevenuePaid}`.\n * Capacitor: every format of @capacitor-community/admob (8.1+).\n *\n * Turn it on and call nothing by hand for that network: once a network is\n * captured, `trackAdRevenue` / `trackMaxAdRevenue` for it are ignored (one\n * warning in the log), so an impression can never be counted twice. The two\n * one-line props above stay valid \u2014 they cover what the capture cannot reach.\n */\n adRevenue?: AdRevenueOptions;\n /**\n * iOS only. Drive the SKAdNetwork conversion value from tracked revenue and\n * events, using the mapping published for this app (fetched from the API).\n * Default true \u2014 on Android and without a native bridge it is inert.\n *\n * SKAN is aggregated, coarse (six bits) and delayed 24h+ by design; this makes\n * iOS measurable, not deterministic. See docs/IOS_ATTRIBUTION.md.\n */\n skan?: boolean;\n /**\n * iOS only. Report the AdServices attribution token so the server can resolve\n * Apple Ads (Search Ads) attribution. Default true \u2014 on Android, pre-iOS 14.3 and\n * without a native bridge it is inert.\n *\n * This is the ONE deterministic attribution iOS allows, and it needs no IDFA and no\n * ATT prompt of our own: the token is an opaque 24h claim ticket, and Apple decides\n * how detailed an answer to give from the ATT status the user already chose. See\n * adservices.ts.\n */\n appleAds?: boolean;\n /**\n * Send the device advertising id (IDFA / GAID) with the install. Default FALSE \u2014\n * Traqio collects nothing of the kind unless you turn this on (decision cmvjohk6).\n *\n * It improves attribution precision for the networks that attribute by that id\n * and nothing else \u2014 Unity Ads and AppLovin: their click carries it, and the install\n * postback Unity expects needs it. It is never used as the user's identity.\n *\n * The SDK never shows a permission prompt. iOS: ask for App Tracking Transparency\n * yourself, whenever your onboarding does; the IDFA is read only if the user said\n * yes. Asked AFTER `init()` is fine: the SDK re-reads it at every start and return\n * to the foreground and sends it once, for the device's later conversions (todo\n * cmwlauev) \u2014 Meta then gets it as `madid`, with `advertiser_tracking_enabled`. Android: add `com.google.android.gms:play-services-ads-identifier`\n * and the `com.google.android.gms.permission.AD_ID` permission to your app.\n */\n collectAdvertisingId?: boolean;\n /**\n * Deep linking (docs/DEEP_LINKING.md). Default true.\n *\n * On the first launch of a fresh install, asks once where the link that brought\n * the user wanted them to land, and hands it to `onDeepLink`. On React Native it\n * also listens to `Linking` for universal / App Links that open the app; every\n * other host passes those URLs to `handleUrl()`.\n */\n deepLinking?: boolean;\n /**\n * The user's consent to SHARING with ad networks, when the app already knows it\n * at launch \u2014 see `setConsent()`. Omitted = unchanged (never collected, or the\n * answer persisted by an earlier `setConsent`).\n */\n consent?: boolean;\n /**\n * `\"web\"` = a browser (used by `@traqio/web`). A browser is not an install: no\n * install is reported, no Install Referrer is read and no deferred deep link is\n * asked for. The first visit of the day is a session like any other (debounced,\n * since a multi-page site re-runs `init()` on every page), and requests are sent\n * with `keepalive` so a flush on `pagehide` survives the page being torn down.\n * Omitted = an app: everything above behaves exactly as before.\n */\n platform?: \"web\";\n /**\n * Host-provided app lifecycle. Called once from `init()` with the two handlers;\n * the host invokes `background()` when the app/tab is hidden (the queue is\n * flushed) and `foreground()` when it comes back (a session, debounced by the\n * 30-minute timeout). Omitted = React Native's `AppState`, when present.\n */\n lifecycle?: (events: LifecycleEvents) => void;\n /**\n * Debug mode (docs/MEASUREMENT_TRUTH.md \u00A71.12). Every request then carries\n * `debug: true`, and the server keeps it apart: shown in the console's Live events\n * \u203A Debug view, never counted in a report, never attributed, never sent to an ad\n * network or a webhook, never billed.\n *\n * Omitted = detected: React Native `__DEV__`, the native bridge's debug/simulator\n * check (Expo, Capacitor), or a browser on `localhost` / `127.0.0.1` / `*.local`\n * / `file:`. `true` forces it (a staging build); `false` turns detection off (a\n * release build you test on a simulator and want counted).\n */\n debug?: boolean;\n}\n\n/** What `InitOptions.lifecycle` is handed. */\nexport interface LifecycleEvents {\n background(): void;\n foreground(): void;\n}\n\nexport type { DeepLinkAnswer };\n\ninterface QueuedEvent {\n name: string;\n /**\n * A random id: it only makes the SDK's own retries idempotent. When the event\n * carries `transactionId`, the server replaces it with the transaction's\n * deterministic key before anything is stored or forwarded.\n */\n eventId: string;\n value?: number;\n currency?: string;\n transactionId?: string;\n store?: RevenueStore;\n}\n\n/** The ad platform a queued impression came from \u2014 the server's `source`. */\ntype AdRevenueSource = \"admob\" | \"applovin_max\";\n\ninterface QueuedAdImpression extends AdRevenue {\n impressionId: string;\n /** Absent on impressions persisted before MAX support: those are AdMob's. */\n source?: AdRevenueSource;\n /** Captured by Traqio, or handed by the app \u2014 the server's last dedup net reads it. */\n origin?: AdRevenueOrigin;\n}\n\n/**\n * One AppLovin MAX impression, as `onAdRevenuePaid(MaxAd ad)` describes it.\n * Docs: https://support.applovin.com/en/max/android/overview/advanced-settings\n */\nexport interface MaxAdRevenue {\n /** `ad.getRevenue()` \u2014 in USD. MAX answers -1 when it has no value. */\n revenue: number;\n /** `ad.getRevenuePrecision()`: \"exact\" | \"publisher_defined\" | \"estimated\" | \"undefined\" | \"\". */\n revenuePrecision?: string;\n /** `ad.getAdUnitId()`. */\n adUnitId?: string;\n /** `ad.getFormat().getLabel()` \u2014 \"BANNER\", \"INTER\", \"REWARDED\", \"MREC\", \"NATIVE\", \"APPOPEN\"\u2026 */\n format?: string;\n /** `ad.getNetworkName()` \u2014 the mediated network that filled the impression. */\n networkName?: string;\n /** Unix seconds. Defaults to now. */\n ts?: number;\n}\n\nconst MAX_PRECISION: Record<string, AdRevenue[\"precision\"]> = {\n exact: \"precise\",\n publisher_defined: \"publisher_provided\",\n estimated: \"estimated\",\n};\n\nconst MAX_FORMAT: Record<string, AdRevenue[\"adFormat\"]> = {\n BANNER: \"banner\",\n LEADER: \"banner\",\n MREC: \"banner\",\n INTER: \"interstitial\",\n INTERSTITIAL: \"interstitial\",\n REWARDED: \"rewarded\",\n REWARDED_INTER: \"rewarded_interstitial\",\n NATIVE: \"native\",\n APPOPEN: \"app_open\",\n APP_OPEN: \"app_open\",\n};\n\n/**\n * MAX \u2192 the server's impression shape. Undefined for an impression with no\n * usable revenue (MAX's -1), which is skipped rather than recorded as zero.\n */\nconst ZERO_AD_ID = \"00000000-0000-0000-0000-000000000000\";\n\n/** A real IDFA / GAID, or undefined: the all-zeros id means the OS withheld it. */\nexport function normalizeAdvertisingId(raw: unknown): string | undefined {\n if (typeof raw !== \"string\") return undefined;\n const id = raw.trim();\n if (!/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(id)) return undefined;\n return id === ZERO_AD_ID ? undefined : id;\n}\n\nexport function fromMaxAd(ad: MaxAdRevenue): AdRevenue | undefined {\n if (!(typeof ad.revenue === \"number\" && Number.isFinite(ad.revenue) && ad.revenue >= 0)) return undefined;\n return {\n // Rounded to the micro, never earlier: a banner is worth ~0.00002 USD.\n valueMicros: Math.round(ad.revenue * 1_000_000),\n currency: \"USD\",\n precision: MAX_PRECISION[ad.revenuePrecision ?? \"\"] ?? \"unknown\",\n adUnitId: ad.adUnitId,\n adFormat: MAX_FORMAT[(ad.format ?? \"\").toUpperCase()],\n adSourceName: ad.networkName,\n ts: ad.ts,\n };\n}\n\n// The batch id travels WITH the queue: if the app is killed between \"request sent\"\n// and \"response received\", the retry must reuse the same id or the server counts\n// the revenue twice.\ninterface PersistedAdQueue {\n batchId: string | null;\n items: QueuedAdImpression[];\n}\n\nfunction uuid(): string {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\nfunction safeLocale(): string | undefined {\n try {\n return Intl.DateTimeFormat().resolvedOptions().locale;\n } catch {\n return undefined;\n }\n}\n\n// Persistence is what makes the install fire exactly once and keeps queued events\n// across a kill. A host that forgets to pass `storage` would silently re-send the\n// install at every launch, so we pick up AsyncStorage when the app has it.\nfunction defaultStorage(): KeyValueStore | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const mod = require(\"@react-native-async-storage/async-storage\");\n const store = mod?.default ?? mod;\n if (typeof store?.getItem === \"function\" && typeof store?.setItem === \"function\") {\n return {\n getItem: (key) => store.getItem(key),\n setItem: (key, value) => store.setItem(key, value),\n };\n }\n } catch {\n // Not installed (or not React Native) \u2014 caller must pass `storage`.\n }\n return undefined;\n}\n\n/**\n * The OS of a React Native host, read from RN itself \u2014 the fallback when the app\n * runs without the native module (Expo Go, a build where autolinking missed it:\n * every Expo iOS app on @traqio/react-native <= 0.2.2, todo cmwl6okm). Undefined\n * off React Native.\n */\nfunction reactNativeOs(): \"ios\" | \"android\" | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const os: unknown = require(\"react-native\")?.Platform?.OS;\n return os === \"ios\" || os === \"android\" ? os : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport class Client {\n private opts!: Required<Pick<InitOptions, \"collectContext\">> & InitOptions;\n private queue: QueuedEvent[] = [];\n private adQueue: QueuedAdImpression[] = [];\n // Once `adRevenue` captures a network, its manual calls are ignored (HQ cmwfq3ij).\n private readonly adGate = new AdRevenueGate();\n private adBatchId: string | null = null;\n private context: DeviceContext = { sdkVersion: SDK_VERSION };\n private referrer: InstallReferrerResult | null = null;\n private started = false;\n private flushing = false;\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n private retryMs = BASE_RETRY_MS;\n private skan = new Skan();\n private erased = false;\n private deepLinkListeners = new Set<(link: DeepLink) => void>();\n // Links resolved before anyone subscribed \u2014 a cold start resolves the opening\n // URL before the app has mounted the screen that registers `onDeepLink`.\n private undelivered: DeepLink[] = [];\n private deferred: Promise<DeepLink | null> | null = null;\n private consent: \"granted\" | \"denied\" | null = null;\n private att: TrackingAuthorization | null = null;\n private adIdSync: Promise<void> | null = null;\n private debug = false;\n private analyticsQueue: QueuedAnalyticsEvent[] = [];\n private analyticsSession: AnalyticsSession | null = null;\n /** Calls made before `init()`, stamped with a session once the stored one is read. */\n private earlyAnalytics: Array<Omit<QueuedAnalyticsEvent, \"sessionId\">> = [];\n private currentScreen: string | null = null;\n /** `register()`: properties added to every analytics event. */\n private superProps: Traits = {};\n /** `group()`: the accounts every analytics event is stamped with. */\n private groups: Groups = {};\n /** An `identify()` made before `init()` \u2014 its user id is the install's from the start. */\n private earlyUserId: string | undefined;\n /** A `reset()` made before `init()`: the super-properties and accounts kept from earlier launches are dropped, not restored. */\n private resetBeforeInit = false;\n\n /** Whether this run is in debug mode \u2014 see `InitOptions.debug`. Settled by `init()`. */\n get isDebug(): boolean {\n return this.debug;\n }\n\n async init(opts: InitOptions): Promise<void> {\n if (this.started) return; // idempotent\n this.started = true;\n this.opts = { collectContext: true, ...opts, userId: opts.userId ?? this.earlyUserId, storage: opts.storage ?? defaultStorage() };\n if (!this.opts.storage) {\n // Loud on purpose: without it the install is re-sent at every launch.\n console.warn(\n \"[traqio] no storage available \u2014 pass `storage` to init() or install \" +\n \"@react-native-async-storage/async-storage, otherwise the install is re-sent at every launch.\",\n );\n }\n // Before anything can be sent: the first request already carries the flag.\n this.debug = await detectDebug(opts);\n await this.restoreConsent(opts.consent);\n await this.restoreQueue();\n await this.restoreAdQueue();\n await this.restoreAnalytics();\n await this.buildContext();\n // A device that asked to be forgotten stays forgotten across launches. Checked\n // before anything is sent: the install, the SKAN mapping fetch and the\n // AdServices token all carry this device's identity to the server.\n if (await this.restoreErased()) {\n this.earlyAnalytics = [];\n return;\n }\n if (this.isWeb) {\n // `@traqio/web` has its own tracker (page views, clicks, scroll); this queue is the app's.\n this.earlyAnalytics = [];\n } else {\n // Not scheduled one by one: the end of init() flushes them right away.\n for (const e of this.earlyAnalytics.splice(0)) this.pushAnalytics(e, false);\n }\n // Read BEFORE the install is marked sent: only a fresh install may ask for a\n // deferred link. An existing user updating to this SDK version must not be\n // routed by somebody else's click from the same address.\n // A browser is not an install and has no store to defer a link through: the\n // whole install / Install Referrer / deferred-link path is for apps only.\n if (!this.isWeb) {\n const freshInstall = Boolean(this.opts.storage) && !(await this.opts.storage!.getItem(this.installSentKey).catch(() => \"1\"));\n await this.sendInstallOnce();\n // An IDFA the install could not carry (ATT asked at an earlier launch, after it).\n void this.syncAdvertisingId();\n if (this.opts.deepLinking !== false) {\n // A user who consented at an EARLIER launch, after a consent-less ask found\n // nothing, gets the one retry here.\n this.deferred = this.resolveDeferredOnce(freshInstall).then((link) => link ?? this.retryDeferredWithConsent());\n this.wireDeepLinks();\n }\n }\n // App: always, not debounced \u2014 init() means the app was opened, and the first\n // open of a day is the one the whole retention number rests on. Web: debounced,\n // because a multi-page site calls init() on every page load. After the erasure\n // check above, because a forgotten device must not report opens either.\n // Web: NOT awaited. On a new session it is a round trip to the API, and @traqio/web\n // starts its analytics tracker (the first page view) only once init() resolves: a\n // visitor who left before that answer on a slow mobile network was never counted\n // (D+2 comparison with PostHog, HQ cmwr4ml5: 117 one-page visitors vs 82).\n if (this.isWeb) void this.maybeStartSession(false);\n else await this.maybeStartSession(true);\n await this.initSkan();\n await this.initAppleAds();\n this.wireLifecycle();\n this.wireAdRevenue();\n if (this.queue.length || this.adQueue.length || this.analyticsQueue.length) this.scheduleFlush(0);\n }\n\n // `InitOptions.adRevenue`: hand the ad SDKs' own paid events to the trackers.\n private wireAdRevenue(): void {\n const want = this.opts.adRevenue;\n if (!want || this.isWeb || !(want.admob || want.applovinMax)) return;\n const sink: AdRevenueSink = {\n admob: (ad, raw) => {\n if (this.adGate.first(raw)) this.queueAdRevenue(ad, \"admob\", \"auto\");\n },\n applovinMax: (ad, raw) => {\n const converted = fromMaxAd(ad);\n if (converted && this.adGate.first(raw)) this.queueAdRevenue(converted, \"applovin_max\", \"auto\");\n },\n };\n try {\n const coverage = this.opts.native?.watchAdRevenue\n ? (this.opts.native.watchAdRevenue(want, sink) ?? want)\n : watchReactNativeAds(want, sink).coverage;\n // From here on, a network Traqio captures refuses the manual calls.\n this.adGate.arm(coverage);\n } catch {\n // An ad SDK we cannot listen to leaves the manual trackers, never a crash.\n }\n }\n\n track(name: string, props?: TrackProps): void {\n if (!this.started || this.erased) return; // call init() first\n const transactionId = props?.transactionId?.trim() || undefined;\n this.enqueue({\n name,\n eventId: uuid(),\n value: props?.value,\n currency: props?.currency,\n ...(transactionId ? { transactionId, store: props?.store ?? this.defaultStore() } : {}),\n });\n // Same event, second job: on iOS it also moves the SKAN conversion value. Kept\n // for EVERY valued event, keyed or not: the conversion value must be set before\n // Apple's window closes, and a server webhook arrives too late for that. What\n // the transaction id changes is the event's place in the revenue TOTAL, never\n // this on-device signal.\n this.skan.markEvent(name);\n if (props?.value) this.skan.addRevenue(props.value);\n }\n\n /**\n * A product-analytics event \u2014 `paywall_viewed`, `deck_built`, `search_performed`\u2026\n * \u2014 read in the console's Analytics section (events, funnels, property splits).\n * NOT a conversion: never billed, never sent to an ad network (that is `track()`).\n *\n * Batched, persisted while offline and retried like every other call; it never\n * throws. Names starting with `$` are reserved (but `$exposure { experiment, variant }`, an experiment exposure); properties must survive JSON and\n * stay under 4 KB, else they are dropped (the event is kept). Callable before\n * `init()`: the first 100 calls wait for it.\n *\n * Traqio.capture(\"lead_captured\", { magnet: \"starter-deck\" });\n */\n capture(name: string, props?: Record<string, unknown>): void {\n try {\n const n = cleanEventName(name);\n if (!n) return;\n const p = cleanProps(props);\n this.queueAnalytics({ kind: \"custom\", name: n, ts: Date.now(), ...(p ? { props: p } : {}) });\n } catch {\n // Analytics must never take the host app down.\n }\n }\n\n /**\n * Who the user is, and what they are: sets the user id (like `setUserId`) and, with\n * traits, the user's PROPERTIES \u2014 `plan`, `role`, `company_size` \u2014 read in the\n * console as a breakdown, a report dimension and a cohort condition.\n *\n * Traqio.identify(\"u_123\", { plan: \"pro\", seats: 12 }, { signup_platform: \"ios\" });\n *\n * `traits` overwrite what was set before; `traitsOnce` are written only where the\n * user has no value yet (a first plan, a sign-up source). Values are text, numbers\n * or booleans \u2014 never an email or a name: the docs say why. At most 50 keys.\n */\n identify(userId: string, traits?: Record<string, unknown>, traitsOnce?: Record<string, unknown>): void {\n try {\n const id = typeof userId === \"string\" ? userId.trim() : \"\";\n if (!id) return;\n if (this.opts) this.setUserId(id);\n else this.earlyUserId = id;\n const set = cleanTraits(traits);\n const setOnce = cleanTraits(traitsOnce);\n if (!Object.keys(set).length && !Object.keys(setOnce).length) return;\n this.queueAnalytics({ kind: \"identify\", ts: Date.now(), userId: id, ...(Object.keys(set).length ? { set } : {}), ...(Object.keys(setOnce).length ? { setOnce } : {}) });\n } catch {\n /* never crash the host app */\n }\n }\n\n /**\n * Super-properties: added to EVERY analytics event from now on (and across\n * launches) \u2014 an app version flavour, an A/B arm, a theme. An event's own property\n * of the same name wins. `unregister(key)` removes one.\n *\n * Traqio.register({ app_flavor: \"beta\", theme: \"dark\" });\n */\n register(props: Record<string, unknown>): void {\n try {\n this.superProps = cleanTraits({ ...this.superProps, ...cleanTraits(props) });\n void this.persistSuperProps();\n } catch {\n /* never crash the host app */\n }\n }\n\n /** Stop adding one super-property to the events. */\n unregister(key: string): void {\n if (typeof key !== \"string\" || !(key in this.superProps)) return;\n const rest = { ...this.superProps };\n delete rest[key];\n this.superProps = rest;\n void this.persistSuperProps();\n }\n\n /** The super-properties `register()` set \u2014 a copy. */\n getSuperProperties(): Traits {\n return { ...this.superProps };\n }\n\n /**\n * The B2B ACCOUNT the user works in (group analytics): every analytics event from now\n * on (and across launches) counts for it, so the console can count accounts \u2014 unique\n * accounts, funnels, retention and cohorts \u00AB by company \u00BB \u2014 and list them with their\n * traits. Call it after sign-in, and again when the user switches account.\n *\n * Traqio.group(\"company\", \"acc_42\", { plan: \"enterprise\", seats: 40 });\n *\n * `groupType` is lowercase (`company`, `workspace`, `team`; 5 types at most),\n * `groupKey` your own account id \u2014 never an email. Traits follow identify's rules.\n */\n group(groupType: string, groupKey: string | number, traits?: Record<string, unknown>, traitsOnce?: Record<string, unknown>): void {\n try {\n const next = withGroup(this.groups, groupType, groupKey);\n if (!next) return;\n this.groups = next.groups;\n void this.persistGroups();\n const set = cleanTraits(traits);\n const setOnce = cleanTraits(traitsOnce);\n // Same account, nothing new to say: no entry (a group() at every launch costs nothing).\n if (!next.changed && !Object.keys(set).length && !Object.keys(setOnce).length) return;\n this.queueAnalytics({\n kind: \"group\",\n ts: Date.now(),\n groupType: next.type,\n groupKey: next.key,\n ...(Object.keys(set).length ? { set } : {}),\n ...(Object.keys(setOnce).length ? { setOnce } : {}),\n });\n } catch {\n /* never crash the host app */\n }\n }\n\n /** Stop stamping the events with any account \u2014 call it on sign-out. */\n resetGroups(): void {\n this.groups = {};\n void this.persistGroups();\n }\n\n /** The accounts `group()` set, by type \u2014 a copy. */\n getGroups(): Groups {\n return { ...this.groups };\n }\n\n /**\n * Two ids, one person: the user known so far as `previousId` (a guest id, an id\n * from before sign-up, an older system's) IS the current user (`setUserId` /\n * `identify`). Their analytics history and properties are merged under the current\n * id \u2014 the current id's own properties win. From an app, only what THIS device sent\n * under `previousId` is merged; a backend (secret key) merges everything.\n *\n * Traqio.identify(\"u_123\");\n * Traqio.alias(\"guest_8f2c\");\n *\n * Ignored without a current user id, or when `previousId` is the current one.\n */\n alias(previousId: string): void {\n try {\n const userId = this.opts ? this.opts.userId : this.earlyUserId;\n const prev = cleanUserId(previousId);\n if (!userId || !prev || prev === userId) return;\n this.queueAnalytics({ kind: \"alias\", ts: Date.now(), userId, previousId: prev });\n } catch {\n /* never crash the host app */\n }\n }\n\n /**\n * Sign-out: forget who the user was on this device \u2014 the user id, the\n * super-properties (`register`), the accounts (`group`) \u2014 and end the analytics\n * session, so the next person's visit starts clean. Events already queued keep the\n * user they were captured under. The device id is KEPT: it is the install's\n * attribution identity, and a new one would read as a new install.\n */\n reset(): void {\n try {\n const userId = this.opts ? this.opts.userId : this.earlyUserId;\n // What is still queued was captured under the signed-out user: say so before forgetting it.\n if (userId) {\n for (const e of this.analyticsQueue) if (!isEntry(e.kind) && e.asUser === undefined) e.asUser = userId;\n for (const e of this.earlyAnalytics) if (!isEntry(e.kind) && e.asUser === undefined) e.asUser = userId;\n }\n if (this.opts) this.opts.userId = undefined;\n else {\n this.earlyUserId = undefined;\n this.resetBeforeInit = true;\n }\n this.superProps = {};\n this.groups = {};\n this.analyticsSession = null;\n this.currentScreen = null;\n // On the web, @traqio/web keeps its own analytics state: nothing of the app's to write.\n if (this.opts && this.isWeb) return;\n void this.persistSuperProps();\n void this.persistGroups();\n void this.forgetAnalyticsSession();\n } catch {\n /* never crash the host app */\n }\n }\n\n /**\n * An experiment exposure: the user SAW `variant` of `experiment` \u2014 what the console's\n * experiment analysis reads (uplift and significance per variant). Your app assigns\n * the variant (its own flags, a remote config, a hash); call this where the user\n * first meets it. Sends `$exposure { experiment, variant, ...props }`.\n *\n * Traqio.exposure(\"paywall_copy\", \"b\");\n */\n exposure(experiment: string, variant: string | number | boolean, props?: Record<string, unknown>): void {\n try {\n const p = exposureProps(experiment, variant, props);\n // Over the 4 KB cap, the exposure alone rather than an event without its experiment.\n if (p) this.capture(EXPOSURE_EVENT, cleanProps(p) ?? { experiment: p.experiment, variant: p.variant });\n } catch {\n /* never crash the host app */\n }\n }\n\n /**\n * A screen view \u2014 the app's page view, read under \u00AB Top pages \u00BB and usable as a\n * funnel step. Call it when a screen gets the focus, or let `trackScreens()` (React\n * Navigation) or Expo Router's `usePathname()` do it (docs: /docs/sdks/react-native).\n * The same screen reported twice in a row inside a session counts once (re-renders).\n * Custom events captured afterwards carry this screen as their page.\n */\n screen(name: string, props?: Record<string, unknown>): void {\n try {\n const s = cleanScreenName(name);\n if (!s) return;\n const now = Date.now();\n const sameVisit = this.analyticsSession !== null && now - this.analyticsSession.last <= ANALYTICS_SESSION_IDLE_MS;\n if (s === this.currentScreen && sameVisit) return;\n this.currentScreen = s;\n const p = cleanProps(props);\n this.queueAnalytics({ kind: \"pageview\", ts: now, screen: s, ...(p ? { props: p } : {}) });\n } catch {\n /* never crash the host app */\n }\n }\n\n /**\n * Screen views from a React Navigation container, by themselves:\n *\n * const navigationRef = useNavigationContainerRef();\n * useEffect(() => Traqio.trackScreens(navigationRef), [navigationRef]);\n *\n * Returns the unsubscribe. Typed by shape: no navigation library is a dependency.\n */\n trackScreens(navigation: NavigationRefLike): () => void {\n const report = (): void => {\n try {\n const route = navigation.getCurrentRoute();\n if (route?.name) this.screen(route.name);\n } catch {\n /* a container not mounted yet answers on its next state change */\n }\n };\n let off: (() => void) | undefined | void;\n try {\n off = navigation.addListener(\"state\", report);\n } catch {\n off = undefined;\n }\n report();\n return () => {\n try {\n if (typeof off === \"function\") off();\n } catch {\n /* already gone */\n }\n };\n }\n\n /**\n * The store this app runs on: the native bridge's word, else React Native's\n * `Platform.OS`, else UNKNOWN. Never a guess \u2014 until 2026-11 a missing bridge meant\n * \"android\", and every bridgeless iPhone was filed as an Android install whose\n * purchases then went to Meta with the Android package (todo cmwl6okn).\n */\n private get hostPlatform(): \"ios\" | \"android\" | undefined {\n return this.opts.native?.platform ?? reactNativeOs();\n }\n\n private defaultStore(): RevenueStore | undefined {\n const platform = this.hostPlatform;\n return platform === \"ios\" ? \"app_store\" : platform === \"android\" ? \"play_store\" : undefined;\n }\n\n /**\n * Report one AdMob impression's revenue. Call it from the paid-event callback:\n *\n * ad.setOnPaidEventListener(v => Traqio.trackAdRevenue({\n * valueMicros: v.valueMicros, currency: v.currencyCode, precision: \"estimated\",\n * adUnitId, adFormat: \"rewarded\", adSourceName,\n * }));\n *\n * Impressions are batched and sent to /ingest/ad-revenue, where they are matched\n * to this install and become the ad half of ROAS.\n *\n * Ignored (one warning) once `adRevenue: { admob: true }` captures AdMob: the\n * impression is already counted.\n */\n trackAdRevenue(ad: AdRevenue): void {\n if (!this.adGate.manual(\"admob\", \"trackAdRevenue\")) return;\n this.queueAdRevenue(ad, \"admob\", \"manual\");\n }\n\n /**\n * Report one AppLovin MAX impression's revenue. Call it from MAX's callback:\n *\n * onAdRevenuePaid(ad) { Traqio.trackMaxAdRevenue({\n * revenue: ad.getRevenue(), revenuePrecision: ad.getRevenuePrecision(),\n * adUnitId: ad.getAdUnitId(), format: ad.getFormat().getLabel(),\n * networkName: ad.getNetworkName(),\n * }); }\n *\n * Same batching, same endpoint and same ROAS numerator as AdMob, filed under\n * the `applovin_max` source. Ignored (one warning) once\n * `adRevenue: { applovinMax: true }` captures MAX.\n */\n trackMaxAdRevenue(ad: MaxAdRevenue): void {\n if (!this.adGate.manual(\"applovinMax\", \"trackMaxAdRevenue\")) return;\n const converted = fromMaxAd(ad);\n if (converted) this.queueAdRevenue(converted, \"applovin_max\", \"manual\");\n }\n\n /**\n * The one line for an ad that reports through its own callback \u2014 a\n * react-native-google-mobile-ads `<BannerAd>` (the full-screen formats are\n * captured by `adRevenue: { admob: true }`):\n *\n * <BannerAd unitId={AD_UNIT_ID} size={\u2026} onPaid={Traqio.admobPaid(AD_UNIT_ID)} />\n * ad.addAdEventListener(AdEventType.PAID, Traqio.admobPaid(AD_UNIT_ID, \"rewarded\"))\n *\n * Reads the library's PAID payload (`value` in currency units, or v17's exact\n * `valueMicros`) and reports it as AdMob revenue. With `adRevenue: { admob: true }`\n * it only counts the formats the capture does not reach (banners): on a\n * full-screen or native ad it is ignored, so the impression is never doubled.\n */\n admobPaid(adUnitId?: string, adFormat: NonNullable<AdRevenue[\"adFormat\"]> = \"banner\"): (event: unknown) => void {\n return (event) => {\n try {\n const ad = fromGoogleMobileAdsPaid(event, { adUnitId, adFormat });\n if (ad && this.adGate.helper(\"admob\", adFormat, event, \"Traqio.admobPaid()\")) this.queueAdRevenue(ad, \"admob\", \"auto\");\n } catch {\n // Measurement is never worth a crash in the app's ad callback.\n }\n };\n }\n\n /**\n * The one line for a react-native-applovin-max `<AdView>` or native ad, whose\n * revenue comes through a prop rather than the global events:\n *\n * <AdView adUnitId={\u2026} adFormat={AdFormat.BANNER} onAdRevenuePaid={Traqio.maxRevenuePaid} />\n */\n readonly maxRevenuePaid = (adInfo: unknown): void => {\n try {\n const max = fromMaxAdInfo(adInfo);\n const ad = max && fromMaxAd(max);\n if (ad && this.adGate.helper(\"applovinMax\", ad.adFormat, adInfo, \"Traqio.maxRevenuePaid\")) this.queueAdRevenue(ad, \"applovin_max\", \"auto\");\n } catch {\n // Measurement is never worth a crash in the app's ad callback.\n }\n };\n\n private queueAdRevenue(ad: AdRevenue, source: AdRevenueSource, origin: AdRevenueOrigin): void {\n if (!this.started || this.erased) return; // call init() first\n if (!(ad.valueMicros >= 0) || !ad.currency) return; // nothing to bill\n this.adQueue.push({ ...ad, source, origin, impressionId: uuid(), ts: ad.ts ?? Math.floor(Date.now() / 1000) });\n // Ad revenue is revenue: it feeds the iOS conversion value like a purchase\n // does. Assumed to be in the mapping's currency \u2014 SKAN carries none, so a\n // mixed-currency app should map its buckets in the currency it reports.\n this.skan.addRevenue(ad.valueMicros / 1_000_000);\n if (this.adQueue.length > MAX_AD_QUEUE) this.adQueue.splice(0, this.adQueue.length - MAX_AD_QUEUE);\n void this.persistAdQueue();\n this.scheduleFlush();\n }\n\n /**\n * The Play Install Referrer for this install \u2014 the raw string your tracking link\n * put there, so a host app can use it for deferred deep linking on top of the\n * attribution we already do server-side. Resolves from cache after the first read\n * (Play only serves it reliably once). On iOS it reports\n * `not_supported_platform`; attribution there is SKAN.\n */\n getInstallReferrer(): Promise<InstallReferrerResult> {\n if (!this.started) return Promise.resolve({ status: \"unavailable\", retryable: false });\n return this.readReferrer();\n }\n\n /**\n * Subscribe to deep links \u2014 direct opens AND the one deferred link of a fresh\n * install. Links resolved before the first subscriber are delivered to it on\n * subscription, so a cold start does not lose the link that opened the app.\n *\n * Traqio.onDeepLink(({ deepLink }) => { if (deepLink) router.push(deepLink); });\n *\n * Returns the unsubscribe function.\n */\n onDeepLink(listener: (link: DeepLink) => void): () => void {\n this.deepLinkListeners.add(listener);\n const pending = this.undelivered.splice(0);\n for (const link of pending) listener(link);\n return () => {\n this.deepLinkListeners.delete(listener);\n };\n }\n\n /**\n * A URL opened the app. React Native is wired automatically (`Linking`); every\n * other host (Capacitor's `appUrlOpen`, a native shell) calls this.\n *\n * Only our tracking URLs (`https://<host>/c/<code>`) leave the device; the\n * app's own URLs resolve to null without a request. Resolving also records\n * the click, which the OS skipped by opening the app directly.\n */\n async handleUrl(url: string): Promise<DeepLink | null> {\n if (!this.started || this.erased || this.opts.deepLinking === false || !isTrackingUrl(url)) return null;\n const answer = await this.postJson<DeepLinkAnswer>({ url }, \"/deeplink/open\");\n // `/o/<clickId>` is the iOS landing page's \u00AB Open in app \u00BB: a tap made BEFORE the\n // install, so it is this install's deferred link too.\n const deferred = isOpenUrl(url);\n const link = toDeepLink(answer, deferred, url);\n if (link && deferred) await this.keepDeferred(link);\n if (link) this.emitDeepLink(link);\n return link;\n }\n\n /**\n * The deferred deep link of this install, if it came from one \u2014 resolved on the\n * first launch and remembered. Null on every install that did not come from a\n * link. `matchType` says how it was found; read `payload.value` for the token the\n * shared URL carried (`deep_link_value`).\n *\n * iOS has no install referrer: the deterministic carriers there are the landing\n * page's \u00AB Open in app \u00BB link (delivered through `handleUrl` / `onDeepLink`) and\n * its code (`redeemDeepLinkCode`). The probabilistic fallback runs only when the\n * user consented \u2014 `setConsent(true)` or `consent: true` at init \u2014 and the app\n * turned the IP match on in the console.\n */\n getDeferredDeepLink(): Promise<DeepLink | null> {\n return this.deferred ?? Promise.resolve(null);\n }\n\n /**\n * The code the iOS landing page showed (\u00AB ABCD-EFGH \u00BB), typed by the user in the\n * app \u2014 the manual fallback when neither the store nor a link carried the click.\n * Case, spaces and the dash are forgiven. Resolves to the link (`matchType:\n * \"code\"`), delivered to `onDeepLink` too, or null for an unknown / expired code.\n */\n async redeemDeepLinkCode(code: string): Promise<DeepLink | null> {\n if (!this.started || this.erased || this.opts.deepLinking === false || !code.trim()) return null;\n const answer = await this.postJson<DeepLinkAnswer>({ code }, \"/deeplink/code\");\n const link = toDeepLink(answer, true);\n if (!link) return null;\n await this.keepDeferred(link);\n this.emitDeepLink(link);\n return link;\n }\n\n /**\n * GDPR Art. 17, from inside the app: delete everything the server holds about this\n * device and this user, and stop sending.\n *\n * \u26A0\uFE0F IRREVERSIBLE, on both sides. The server deletes the installs, events, clicks\n * and delivery payloads that name this subject and tombstones their identifiers,\n * so nothing this device sends afterwards is accepted. Locally the queue is\n * dropped and the SDK goes quiet for good \u2014 persisted, so the next launch does not\n * re-report the install. There is no way back on: an app that needs measurement\n * again has to be reinstalled.\n *\n * Wire it to your own \"delete my data\" control. Returns false when the call did\n * not reach the server, and in that case NOTHING has changed on either side \u2014 show\n * the user an error and let them try again, rather than a confirmation of a\n * deletion that did not happen.\n */\n async forgetMe(): Promise<boolean> {\n if (!this.started) return false;\n if (this.erased) return true; // already honoured \u2014 saying \"yes\" twice is correct\n const ok = await this.post(\n { deviceId: this.context.deviceId, appUserId: this.opts.userId },\n \"/privacy/forget\",\n );\n if (!ok) return false;\n await this.markErased();\n return true;\n }\n\n /**\n * The user's consent to SHARING their data with ad networks, as collected by the\n * app's own prompt \u2014 Traqio is not a CMP. Persisted, and sent with every install,\n * event batch and session from now on, events already queued included.\n *\n * `false` keeps first-party measurement (installs, events, retention and ROAS in\n * your dashboard), but the server forwards nothing about this device to Meta,\n * TikTok or any outbound postback. Never calling it = not collected: the app's\n * policy in the console decides (docs/PRIVACY.md \u00A7Consent).\n *\n * Traqio.setConsent(userAgreed);\n */\n async setConsent(granted: boolean): Promise<void> {\n this.consent = granted ? \"granted\" : \"denied\";\n await this.opts?.storage?.setItem(CONSENT_KEY, this.consent).catch(() => undefined);\n // After the first launch's ask (chained, never in parallel with it).\n if (granted && this.deferred && !this.erased) {\n this.deferred = this.deferred.then((link) => link ?? this.retryDeferredWithConsent());\n await this.deferred;\n }\n }\n\n /** True once `forgetMe()` has been honoured \u2014 this install sends nothing any more. */\n get forgotten(): boolean {\n return this.erased;\n }\n\n /** Set/override the user id (== RevenueCat app_user_id). Call after login. */\n setUserId(id: string): void {\n if (this.opts) this.opts.userId = id;\n }\n\n /** Force a flush now (e.g. on app background). RN wires this automatically. */\n flush(): void {\n if (this.erased) return;\n // NOW, even when a batching or back-off timer is already pending, and in this\n // very call stack: a host calls this because the app or tab is going away. A\n // timer \u2014 even a 0 ms one \u2014 may never run inside a `pagehide` handler, whereas\n // drain() starts its first request before its first await.\n if (this.flushTimer) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n void this.drain();\n }\n\n /**\n * Tell the SDK the app came back to the foreground. React Native is wired\n * automatically; every other host (a web view, a game loop, a custom shell) has\n * to call this or its users look like they never came back.\n *\n * Safe to call on every resume: it is debounced by the session timeout.\n */\n appOpened(): void {\n if (!this.started || this.erased) return;\n void this.maybeStartSession();\n void this.syncAdvertisingId();\n }\n\n /** The conversion-value mapping in force on this device, once fetched. */\n get skanMapping(): SkanMapping | null {\n return this.skan.activeMapping;\n }\n\n /**\n * Apple Ads self-attribution. Awaited rather than fired off, so a host that awaits\n * `init()` can be sure the token left the device before the app does anything\n * else \u2014 the window is 24 hours, but a user who installs from a Search Ads tap and\n * never reopens the app still has to be attributed.\n */\n private async initAppleAds(): Promise<void> {\n if (this.opts.appleAds === false) return;\n const native = this.opts.native;\n if (native?.platform !== \"ios\" || !native.getAttributionToken) return;\n await reportAdServicesToken({\n endpoint: this.opts.endpoint,\n sdkKey: this.opts.sdkKey,\n deviceId: this.context.deviceId,\n userId: this.opts.userId,\n storage: this.opts.storage,\n native: { getAttributionToken: () => native.getAttributionToken!() },\n debug: this.debug,\n });\n }\n\n private async initSkan(): Promise<void> {\n if (this.opts.skan === false) return;\n const native = this.opts.native;\n // iOS-only, and only when the native module is actually there to call.\n if (native?.platform !== \"ios\" || !native.updateConversionValue) return;\n await this.skan.init({\n endpoint: this.opts.endpoint,\n sdkKey: this.opts.sdkKey,\n storage: this.opts.storage,\n native: {\n updateConversionValue: (fine, coarse, lockWindow) =>\n native.updateConversionValue?.(fine, coarse, lockWindow),\n },\n });\n }\n\n /**\n * Asks `/deeplink/deferred` once per install. A settled answer \u2014 link or no\n * link \u2014 is persisted; a failed request is not, so the next launch retries\n * (still counted as fresh, since the flag is only written on an answer).\n */\n private async resolveDeferredOnce(freshInstall: boolean): Promise<DeepLink | null> {\n const store = this.opts.storage;\n try {\n const cached = await store?.getItem(DEFERRED_KEY);\n if (cached) return upgradeStoredDeepLink(JSON.parse(cached));\n } catch {\n /* corrupt \u2014 ask again if still a fresh install */\n }\n if (!freshInstall && !(await store?.getItem(`${DEFERRED_KEY}_pending`).catch(() => null))) return null;\n\n const platform = this.hostPlatform;\n const referrer = platform === \"android\" ? await this.readReferrer() : null;\n await store?.setItem(`${DEFERRED_KEY}_pending`, \"1\").catch(() => undefined);\n const answer = await this.askDeferred(platform, referrer?.referrer);\n if (!answer) return null; // unreachable \u2014 the pending flag makes the next launch retry\n const link = toDeepLink(answer, true);\n // A `/o/` link or a code may have landed while this was in flight: keep it.\n const kept = await this.storedDeferred();\n if (kept) return kept;\n try {\n await store?.setItem(DEFERRED_KEY, JSON.stringify(link));\n // Nothing found and the user had not consented: one more ask is allowed if they\n // consent inside the hour the server keeps its evidence.\n if (!link && this.consent !== \"granted\") {\n await store?.setItem(DEFERRED_RETRY_KEY, String(Date.now() + DEFERRED_RETRY_WINDOW_MS));\n }\n } catch {\n /* storage full \u2014 worst case the next launch asks again */\n }\n if (link) this.emitDeepLink(link);\n return link;\n }\n\n /** The deferred ask: the referrer (Android), the consent, and what the tap is compared with. */\n private askDeferred(platform: \"ios\" | \"android\" | undefined, installReferrer: string | undefined): Promise<DeepLinkAnswer | null> {\n return this.postJson<DeepLinkAnswer>(\n {\n platform,\n installReferrer,\n ...(this.consent ? { consent: this.consent } : {}),\n ...(this.context.osVersion ? { osVersion: this.context.osVersion } : {}),\n ...(this.context.deviceModel ? { deviceModel: this.context.deviceModel } : {}),\n },\n \"/deeplink/deferred\",\n );\n }\n\n /**\n * The user consented AFTER the first launch asked without consent and found\n * nothing: ask once more, inside the hour, so the probabilistic layer can run.\n * Never when a link is already known, never twice.\n */\n private async retryDeferredWithConsent(): Promise<DeepLink | null> {\n const store = this.opts?.storage;\n if (!store || this.consent !== \"granted\" || this.opts.deepLinking === false || this.isWeb) return null;\n const until = Number(await store.getItem(DEFERRED_RETRY_KEY).catch(() => null));\n if (!until) return null;\n await store.setItem(DEFERRED_RETRY_KEY, \"\").catch(() => undefined);\n if (Date.now() > until) return null;\n const known = await this.storedDeferred();\n if (known) return known;\n const link = toDeepLink(await this.askDeferred(this.hostPlatform, undefined), true);\n if (!link) return null;\n await this.opts.storage?.setItem(DEFERRED_KEY, JSON.stringify(link)).catch(() => undefined);\n this.emitDeepLink(link);\n return link;\n }\n\n /** The deferred link already stored for this install, if any. */\n private async storedDeferred(): Promise<DeepLink | null> {\n try {\n const raw = await this.opts.storage?.getItem(DEFERRED_KEY);\n return raw ? upgradeStoredDeepLink(JSON.parse(raw)) : null;\n } catch {\n return null;\n }\n }\n\n /** Remember `link` as this install's deferred link, unless one is already known. */\n private async keepDeferred(link: DeepLink): Promise<void> {\n if (await this.storedDeferred()) return;\n await this.opts.storage?.setItem(DEFERRED_KEY, JSON.stringify(link)).catch(() => undefined);\n this.deferred = Promise.resolve(link);\n }\n\n private emitDeepLink(link: DeepLink): void {\n if (!this.deepLinkListeners.size) {\n this.undelivered.push(link);\n return;\n }\n for (const listener of this.deepLinkListeners) {\n try {\n listener(link);\n } catch {\n /* a throwing listener must not stop the others */\n }\n }\n }\n\n private wireDeepLinks(): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { Linking } = require(\"react-native\");\n if (!Linking) return;\n void Linking.getInitialURL().then((url: string | null) => url && this.handleUrl(url)).catch(() => undefined);\n Linking.addEventListener(\"url\", ({ url }: { url: string }) => void this.handleUrl(url));\n } catch {\n // Not React Native \u2014 the host calls Traqio.handleUrl(url).\n }\n }\n\n private get isWeb(): boolean {\n // Read before `init()` too, by `capture()`: no options yet means not known as web.\n return this.opts?.platform === \"web\";\n }\n\n private get installSentKey(): string {\n return this.debug ? INSTALL_SENT_DEBUG_KEY : INSTALL_SENT_KEY;\n }\n\n private get adIdSentKey(): string {\n return this.debug ? AD_ID_SENT_DEBUG_KEY : AD_ID_SENT_KEY;\n }\n\n /** Spread into every body: present only in debug mode, so a release build's payload is unchanged. */\n private debugField(): { debug?: true } {\n return this.debug ? { debug: true } : {};\n }\n\n private wireLifecycle(): void {\n const events: LifecycleEvents = {\n background: () => this.flush(),\n // Debounced by SESSION_TIMEOUT_MS inside, so a flick to another app/tab and\n // straight back posts nothing.\n foreground: () => this.appOpened(),\n };\n if (this.opts.lifecycle) {\n this.opts.lifecycle(events);\n return;\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { AppState } = require(\"react-native\");\n AppState.addEventListener(\"change\", (state: string) => {\n if (state !== \"active\") {\n this.scheduleFlush(0);\n return;\n }\n // Back in the foreground. Debounced by SESSION_TIMEOUT_MS inside, so a\n // flick to another app and straight back posts nothing.\n void this.maybeStartSession();\n // Not debounced: the ATT alert itself sends the app through `inactive`, so\n // this is the moment right after the user answered it. Posts only on change.\n void this.syncAdvertisingId();\n });\n } catch {\n // Not React Native \u2014 host can call Traqio.flush() manually.\n }\n }\n\n // \u2500\u2500 internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Reads the persisted erasure flag. True \u21D2 this install must stay silent. */\n private async restoreErased(): Promise<boolean> {\n try {\n this.erased = (await this.opts.storage?.getItem(ERASED_KEY)) === \"1\";\n } catch {\n // Storage unreadable: assume not erased. The server's tombstone is the real\n // enforcement \u2014 this flag only saves the round trip.\n this.erased = false;\n }\n return this.erased;\n }\n\n /** Local half of forgetMe(): drop what is queued and never send again. */\n private async markErased(): Promise<void> {\n this.erased = true;\n if (this.flushTimer) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n // The queue holds events about the person who just asked to be forgotten;\n // flushing it later would post them to a server that would drop them anyway.\n this.queue = [];\n this.adQueue = [];\n this.adBatchId = null;\n this.analyticsQueue = [];\n this.earlyAnalytics = [];\n this.superProps = {};\n this.groups = {};\n await this.persistSuperProps();\n await this.persistGroups();\n await this.persistQueue();\n await this.persistAdQueue();\n await this.persistAnalyticsQueue();\n try {\n await this.opts.storage?.setItem(ERASED_KEY, \"1\");\n } catch {\n /* storage full/unavailable \u2014 the in-memory flag still holds for this run */\n }\n }\n\n private enqueue(e: QueuedEvent) {\n this.queue.push(e);\n if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE);\n void this.persistQueue();\n this.scheduleFlush();\n }\n\n /** Before `init()` the call waits in memory; after it, it is stamped and queued. */\n private queueAnalytics(event: Omit<QueuedAnalyticsEvent, \"sessionId\">): void {\n if (this.erased) return;\n let e = event;\n if (!isEntry(event.kind)) {\n // The screen in view NOW, not at replay: an early event keeps its own context.\n const screen = event.screen ?? this.currentScreen ?? undefined;\n // Super-properties and accounts as set NOW: an early event keeps them too.\n const props = withSuperProps(event.props, this.superProps);\n const groups = Object.keys(this.groups).length ? { ...this.groups } : undefined;\n e = { ...event, ...(screen ? { screen } : {}), ...(props ? { props } : {}), ...(groups ? { groups } : {}) };\n }\n if (!this.started) {\n if (this.earlyAnalytics.length < MAX_EARLY_ANALYTICS) this.earlyAnalytics.push(e);\n return;\n }\n if (this.isWeb) return;\n this.pushAnalytics(e);\n }\n\n private pushAnalytics(e: Omit<QueuedAnalyticsEvent, \"sessionId\">, schedule = true): void {\n // An identify, a group or an alias is not activity: it neither opens nor prolongs a visit.\n if (isEntry(e.kind)) this.analyticsQueue.push({ ...e, sessionId: this.analyticsSession?.id ?? \"\" });\n else {\n this.analyticsSession = touchSession(this.analyticsSession, e.ts, uuid);\n this.analyticsQueue.push({ ...e, id: e.id ?? uuid(), sessionId: this.analyticsSession.id });\n }\n if (this.analyticsQueue.length > MAX_ANALYTICS_QUEUE) this.analyticsQueue.splice(0, this.analyticsQueue.length - MAX_ANALYTICS_QUEUE);\n void this.persistAnalyticsQueue();\n if (schedule) this.scheduleFlush();\n }\n\n /** The persisted queue first (older), then whatever was captured while it was being read. */\n private async restoreAnalytics(): Promise<void> {\n try {\n const raw = await this.opts.storage?.getItem(ANALYTICS_QUEUE_KEY);\n const stored = raw ? (JSON.parse(raw) as unknown) : null;\n if (Array.isArray(stored)) this.analyticsQueue = [...(stored as QueuedAnalyticsEvent[]), ...this.analyticsQueue].slice(-MAX_ANALYTICS_QUEUE);\n } catch {\n /* corrupt/absent \u2014 start empty */\n }\n try {\n // A session left less than 30 minutes ago goes on: an app switch is not a new visit.\n // Not after a reset() before init(): that session was the signed-out user's.\n if (!this.resetBeforeInit) this.analyticsSession ??= parseSession(await this.opts.storage?.getItem(ANALYTICS_SESSION_KEY));\n } catch {\n /* none */\n }\n if (this.resetBeforeInit) {\n // reset() before init(): what earlier launches kept belongs to the signed-out user.\n this.resetBeforeInit = false;\n await this.persistSuperProps();\n await this.persistGroups();\n await this.forgetAnalyticsSession();\n return;\n }\n try {\n // Kept from earlier launches; a register() made before init() wins over them.\n const raw = await this.opts.storage?.getItem(SUPER_PROPS_KEY);\n const early = Object.keys(this.superProps).length > 0;\n if (raw) this.superProps = cleanTraits({ ...cleanTraits(JSON.parse(raw)), ...this.superProps });\n if (early) await this.persistSuperProps();\n } catch {\n /* corrupt/absent \u2014 none */\n }\n try {\n // Same rule for the accounts: a group() made before init() wins over the stored ones.\n const raw = await this.opts.storage?.getItem(GROUPS_KEY);\n const early = Object.keys(this.groups).length > 0;\n if (raw) this.groups = cleanGroups({ ...cleanGroups(JSON.parse(raw)), ...this.groups });\n if (early) await this.persistGroups();\n } catch {\n /* corrupt/absent \u2014 none */\n }\n }\n\n private async forgetAnalyticsSession(): Promise<void> {\n if (!this.opts) return;\n try {\n // No removeItem on the store: an empty value reads back as no session (parseSession).\n await this.opts.storage?.setItem(ANALYTICS_SESSION_KEY, \"\");\n // The queue, with the reset's `asUser` stamps, so a relaunch keeps them too.\n await this.persistAnalyticsQueue();\n } catch {\n /* storage unavailable \u2014 the in-memory session is gone anyway */\n }\n }\n\n private async persistGroups(): Promise<void> {\n if (!this.opts) return; // before init(): restoreAnalytics() merges, then the next group() persists\n try {\n await this.opts.storage?.setItem(GROUPS_KEY, JSON.stringify(this.groups));\n } catch {\n /* storage full/unavailable \u2014 kept in memory for this run */\n }\n }\n\n private async persistSuperProps(): Promise<void> {\n if (!this.opts) return; // before init(): restoreAnalytics() merges, then the next register() persists\n try {\n await this.opts.storage?.setItem(SUPER_PROPS_KEY, JSON.stringify(this.superProps));\n } catch {\n /* storage full/unavailable \u2014 kept in memory for this run */\n }\n }\n\n private async persistAnalyticsQueue(): Promise<void> {\n try {\n await this.opts.storage?.setItem(ANALYTICS_QUEUE_KEY, JSON.stringify(this.analyticsQueue));\n if (this.analyticsSession) await this.opts.storage?.setItem(ANALYTICS_SESSION_KEY, JSON.stringify(this.analyticsSession));\n } catch {\n /* storage full/unavailable \u2014 the in-memory queue still flushes this run */\n }\n }\n\n private async restoreQueue() {\n try {\n const raw = await this.opts.storage?.getItem(QUEUE_KEY);\n if (raw) this.queue = JSON.parse(raw) as QueuedEvent[];\n } catch {\n /* corrupt/absent \u2014 start empty */\n }\n }\n\n private async persistQueue() {\n try {\n await this.opts.storage?.setItem(QUEUE_KEY, JSON.stringify(this.queue));\n } catch {\n /* storage full/unavailable */\n }\n }\n\n private async restoreAdQueue() {\n try {\n const raw = await this.opts.storage?.getItem(AD_QUEUE_KEY);\n if (!raw) return;\n const parsed = JSON.parse(raw) as PersistedAdQueue;\n this.adQueue = parsed.items ?? [];\n this.adBatchId = parsed.batchId ?? null;\n } catch {\n /* corrupt/absent \u2014 start empty */\n }\n }\n\n private async persistAdQueue() {\n try {\n const state: PersistedAdQueue = { batchId: this.adBatchId, items: this.adQueue };\n await this.opts.storage?.setItem(AD_QUEUE_KEY, JSON.stringify(state));\n } catch {\n /* storage full/unavailable */\n }\n }\n\n /**\n * Report one app open \u2014 the signal that makes \"did the user come back on day n\"\n * answerable at all (docs/SESSIONS.md).\n *\n * Called on `init()` (the app was opened) and on returning to the foreground\n * after `SESSION_TIMEOUT_MS`.\n *\n * NO QUEUE, deliberately. A failed post does NOT persist the marker, so the next\n * foreground retries it. The signal is only ever read at DAY granularity, so a\n * post lost at 09:00 is recovered by any open before midnight \u2014 a far smaller\n * failure than a persisted queue that can replay yesterday's sessions into today,\n * which would be a retention chart that invents its own history.\n */\n private async maybeStartSession(force = false): Promise<void> {\n if (this.erased) return;\n const now = Date.now();\n if (!force) {\n const last = Number(await this.opts.storage?.getItem(LAST_SESSION_KEY).catch(() => null)) || 0;\n if (last && now - last < SESSION_TIMEOUT_MS) return;\n }\n\n const deviceId = this.context.deviceId ?? (await this.getOrCreateDeviceId());\n const ok = await this.post(\n {\n deviceId,\n appUserId: this.opts.userId,\n sessionId: uuid(),\n ts: Math.floor(now / 1000),\n context: this.context,\n },\n \"/ingest/session\",\n );\n // Only on success: a marker written for a post that never landed would suppress\n // the retry and lose the day.\n if (ok) {\n try {\n await this.opts.storage?.setItem(LAST_SESSION_KEY, String(now));\n } catch {\n /* storage full/unavailable \u2014 worst case we post one extra session */\n }\n }\n }\n\n private async buildContext() {\n if (!this.opts.collectContext) {\n this.context = { sdkVersion: SDK_VERSION };\n return;\n }\n let native: { deviceModel?: string; osVersion?: string } = {};\n try {\n native = (await this.opts.native?.getContext?.()) ?? {};\n } catch {\n /* native context unavailable */\n }\n this.context = {\n deviceId: await this.getOrCreateDeviceId(),\n deviceModel: native.deviceModel,\n osVersion: native.osVersion,\n appVersion: this.opts.appVersion,\n locale: safeLocale(),\n sdkVersion: SDK_VERSION,\n };\n }\n\n private async getOrCreateDeviceId(): Promise<string> {\n try {\n const existing = await this.opts.storage?.getItem(DEVICE_ID_KEY);\n if (existing) return existing;\n } catch {\n /* ignore */\n }\n const id = uuid();\n try {\n await this.opts.storage?.setItem(DEVICE_ID_KEY, id);\n } catch {\n /* ignore */\n }\n return id;\n }\n\n /**\n * Reads the Play Install Referrer, once per install, and caches a settled answer.\n * A retryable failure is deliberately NOT cached \u2014 freezing it would make the\n * install look organic for good.\n */\n private async readReferrer(): Promise<InstallReferrerResult> {\n if (this.referrer) return this.referrer;\n try {\n const raw = await this.opts.storage?.getItem(REFERRER_KEY);\n if (raw) return (this.referrer = JSON.parse(raw) as InstallReferrerResult);\n } catch {\n /* corrupt/absent \u2014 read it again */\n }\n\n const native = this.opts.native;\n if (native?.platform !== \"android\") {\n return { status: native ? \"not_supported_platform\" : \"unavailable\", retryable: false };\n }\n const result = await native\n .getInstallReferrer()\n .catch((): InstallReferrerResult => ({ status: \"error\", retryable: true }));\n if (!result.retryable) {\n this.referrer = result;\n try {\n await this.opts.storage?.setItem(REFERRER_KEY, JSON.stringify(result));\n } catch {\n /* storage full/unavailable */\n }\n }\n return result;\n }\n\n /** Only with the host's opt-in; a zeroed or malformed id is never sent. */\n private async readAdvertisingId(): Promise<string | undefined> {\n if (!this.opts.collectAdvertisingId || !this.opts.native?.getAdvertisingId) return undefined;\n try {\n return normalizeAdvertisingId(await this.opts.native.getAdvertisingId());\n } catch {\n return undefined;\n }\n }\n\n private async sendInstallOnce() {\n const store = this.opts.storage;\n if (store && (await store.getItem(this.installSentKey))) return; // already sent\n\n const platform = this.hostPlatform;\n if (!platform) {\n // Not React Native and no native bridge: nothing says which store this is. A\n // wrong label is worse than a late install \u2014 it stays pending (re-tried at the\n // next launch) instead of being filed under a guessed store.\n console.warn(\n \"[traqio] unknown platform \u2014 no native bridge and not React Native: the install is not reported. \" +\n \"Pass `native: getNativeBridge()` (React Native / Expo) or your SDK's bridge to init().\",\n );\n return;\n }\n if (!this.opts.native) {\n // React Native without the native module: the install is still counted under\n // the right store, but with no Install Referrer, no SKAN, no Apple Ads token.\n console.warn(\n `[traqio] the Traqio native module is missing on ${platform} (Expo Go, or not linked in this build): ` +\n \"install reported without its attribution signals. Use a development / EAS build.\",\n );\n }\n const referrer = await this.readReferrer();\n\n // The referrer IS the Android attribution. When Play couldn't serve it yet\n // (store updating itself, service still starting), reporting now would brand\n // the install organic forever \u2014 so we wait for a later launch instead. Bounded:\n // a device where it never works still gets its install counted.\n if (referrer.retryable && store) {\n const attempts = Number(await store.getItem(INSTALL_ATTEMPTS_KEY)) || 0;\n if (attempts + 1 < MAX_INSTALL_ATTEMPTS) {\n await store.setItem(INSTALL_ATTEMPTS_KEY, String(attempts + 1));\n return;\n }\n }\n\n const advertisingId = await this.readAdvertisingId();\n const ok = await this.post({\n install: {\n platform,\n installReferrer: referrer.referrer,\n appUserId: this.opts.userId,\n advertisingId,\n context: this.context,\n },\n });\n // Only mark sent on success \u2014 otherwise it retries on the next init().\n if (ok) {\n await store?.setItem(this.installSentKey, \"1\");\n if (advertisingId) await store?.setItem(this.adIdSentKey, advertisingId).catch(() => undefined);\n }\n }\n\n /**\n * The opted-in advertising id the install could not carry (todo cmwlauev). The\n * install leaves at first launch, before an app shows its own ATT prompt, so on iOS\n * it almost never has the IDFA. Re-read at every start and foreground \u2014 reading\n * never prompts (decision cmvjohk6) \u2014 and posted ONCE when it differs from the one\n * the server last acknowledged; a failure is retried at the next foreground.\n *\n * Only after the install is reported: the install itself carries an id it can read.\n */\n private syncAdvertisingId(): Promise<void> {\n if (this.adIdSync) return this.adIdSync; // one at a time: init and a foreground can race\n this.adIdSync = this.postAdvertisingIdIfChanged().finally(() => {\n this.adIdSync = null;\n });\n return this.adIdSync;\n }\n\n private async postAdvertisingIdIfChanged(): Promise<void> {\n const store = this.opts.storage;\n if (this.isWeb || this.erased || !store || !this.opts.collectAdvertisingId) return;\n try {\n if (!(await store.getItem(this.installSentKey))) return;\n const advertisingId = await this.readAdvertisingId();\n if (!advertisingId || (await store.getItem(this.adIdSentKey)) === advertisingId) return;\n const deviceId = this.context.deviceId ?? (await this.getOrCreateDeviceId());\n if (await this.post({ deviceId, appUserId: this.opts.userId, advertisingId }, AD_ID_PATH)) {\n await store.setItem(this.adIdSentKey, advertisingId);\n }\n } catch {\n // Storage unavailable: try again at the next foreground.\n }\n }\n\n private scheduleFlush(delay = FLUSH_DELAY_MS) {\n if (this.flushTimer) return;\n this.flushTimer = setTimeout(() => {\n this.flushTimer = null;\n void this.drain();\n }, delay);\n }\n\n private async drain() {\n if (this.erased) return;\n if (this.flushing || (!this.queue.length && !this.adQueue.length && !this.analyticsQueue.length)) return;\n this.flushing = true;\n try {\n while (this.queue.length) {\n const batch = this.queue.slice(0, MAX_BATCH);\n // Identity travels with every batch, not just the install: the API forwards\n // these events to Meta/TikTok, and both REJECT an event that carries no user\n // identifier. Still first-party only \u2014 deviceId is our own random id, and the\n // API hashes whatever it forwards. Never IDFA/GAID.\n const outcome = await this.send({\n events: batch,\n appUserId: this.opts.userId,\n deviceId: this.context.deviceId,\n });\n if (outcome === \"retry\") return this.backOff();\n if (outcome === \"refused\") {\n // The server says this batch is malformed and will say so forever; retrying\n // it would hold every event behind it hostage (audit cmw6ow5z M10). Since\n // API 2026-11 a bad EVENT is refused alone inside a 200 \u2014 this is the\n // safety net for a refusal of the whole body.\n console.warn(`[traqio] the server refused ${batch.length} event(s) as malformed \u2014 dropped, not retried`);\n }\n this.queue.splice(0, batch.length);\n await this.persistQueue();\n this.retryMs = BASE_RETRY_MS;\n }\n while (this.adQueue.length) {\n // One batch = one platform: the server files a whole batch under one source.\n const source = this.adQueue[0].source ?? \"admob\";\n const run = this.adQueue.findIndex((i) => (i.source ?? \"admob\") !== source);\n const batch = this.adQueue.slice(0, Math.min(MAX_AD_BATCH, run === -1 ? this.adQueue.length : run));\n // Mint the batch id BEFORE the request and persist it, so a crash mid-flight\n // retries under the same id and the server dedups instead of double-counting.\n if (!this.adBatchId) {\n this.adBatchId = uuid();\n await this.persistAdQueue();\n }\n const ok = await this.post(\n {\n batchId: this.adBatchId,\n source,\n environment: this.opts.testAds ? \"TEST\" : \"PRODUCTION\",\n deviceId: this.context.deviceId,\n appUserId: this.opts.userId,\n impressions: batch.map(({ source: _source, ...impression }) => impression),\n },\n \"/ingest/ad-revenue\",\n );\n if (!ok) return this.backOff();\n this.adQueue.splice(0, batch.length);\n this.adBatchId = null;\n await this.persistAdQueue();\n this.retryMs = BASE_RETRY_MS;\n }\n while (this.analyticsQueue.length) {\n // One user per batch: events still queued at a reset() keep the user they were captured under.\n const batch = nextAnalyticsBatch(this.analyticsQueue, this.opts.userId, MAX_ANALYTICS_BATCH);\n // `anonymousId` is the same first-party device id the install carries, so a\n // visitor in the Analytics page is a device in the attribution reports.\n const outcome = await this.send(\n {\n anonymousId: this.context.deviceId ?? (await this.getOrCreateDeviceId()),\n userId: batch.userId,\n platform: this.hostPlatform,\n events: batch.events,\n },\n ANALYTICS_PATH,\n );\n if (outcome === \"retry\") return this.backOff();\n if (outcome === \"refused\") console.warn(`[traqio] the server refused ${batch.taken} analytics event(s) as malformed \u2014 dropped, not retried`);\n this.analyticsQueue.splice(0, batch.taken);\n await this.persistAnalyticsQueue();\n this.retryMs = BASE_RETRY_MS;\n }\n } finally {\n this.flushing = false;\n }\n }\n\n // network/server failure \u2192 keep the queue, back off, retry later.\n private backOff(): void {\n this.retryMs = Math.min(this.retryMs * 2, MAX_RETRY_MS);\n this.scheduleFlush(this.retryMs);\n }\n\n /** Like `post`, for the two calls whose ANSWER matters. Null on any failure. */\n private async postJson<T>(body: Record<string, unknown>, path: string): Promise<T | null> {\n try {\n const res = await fetch(`${this.opts.endpoint}${path}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body, ...this.debugField() }),\n ...this.keepalive(),\n });\n return res.ok ? ((await res.json()) as T) : null;\n } catch {\n return null;\n }\n }\n\n /**\n * The init option wins over what is stored (it is the app's current answer); a\n * `setConsent()` made before `init()` survives too \u2014 it is only kept in memory\n * until there is a storage to write it to.\n */\n private async restoreConsent(fromInit: boolean | undefined): Promise<void> {\n if (fromInit !== undefined) return this.setConsent(fromInit);\n if (this.consent) return this.setConsent(this.consent === \"granted\");\n const stored = await this.opts.storage?.getItem(CONSENT_KEY).catch(() => null);\n if (stored === \"granted\" || stored === \"denied\") this.consent = stored;\n }\n\n /**\n * Web only: a request started on `pagehide` is otherwise cancelled with the page.\n * Not set for apps \u2014 their fetch is not torn down, and the request stays as it was.\n */\n private keepalive(): { keepalive?: boolean } {\n return this.isWeb ? { keepalive: true } : {};\n }\n\n private get asksTrackingAuthorization(): boolean {\n return this.opts.native?.platform === \"ios\" && typeof this.opts.native.getTrackingAuthorization === \"function\";\n }\n\n /** iOS only; the last good answer when the bridge cannot give one now. */\n private async readTrackingAuthorization(): Promise<TrackingAuthorization | null> {\n try {\n const status = await this.opts.native?.getTrackingAuthorization?.();\n if (TRACKING_AUTHORIZATIONS.includes(status)) this.att = status ?? null;\n } catch {\n /* keep the last answer */\n }\n return this.att;\n }\n\n private async post(body: Record<string, unknown>, path = \"/ingest\"): Promise<boolean> {\n return (await this.send(body, path)) === \"ok\";\n }\n\n /**\n * `post`, with the failure split in two: `refused` is a status the same body will\n * get again on every retry (400 malformed, 413 too large, 422 unprocessable);\n * `retry` is everything else \u2014 network down, 5xx, 429, and 401/403 too, since a\n * key fixed in the console makes the same queued batch succeed.\n */\n private async send(body: Record<string, unknown>, path = \"/ingest\"): Promise<\"ok\" | \"retry\" | \"refused\"> {\n // Read at SEND time, so a batch queued before a \"no\" goes out under the \"no\".\n const consent = this.consent && (path === \"/ingest\" || path === \"/ingest/session\" || path === AD_ID_PATH) ? { consent: this.consent } : {};\n // Same for ATT: an app that shows its prompt during onboarding has the answer by\n // the time the first purchase is flushed.\n // Awaited only on iOS with a bridge that answers: a web flush on `pagehide` must\n // start its request in this very call stack (no second tick).\n // On the advertising-id post too: the server keeps an IDFA only under `authorized`.\n const att = (path === \"/ingest\" || path === AD_ID_PATH) && this.asksTrackingAuthorization ? await this.readTrackingAuthorization() : null;\n try {\n const res = await fetch(`${this.opts.endpoint}${path}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n sdkKey: this.opts.sdkKey,\n ...body,\n ...consent,\n ...(att ? { att } : {}),\n ...this.debugField(),\n }),\n ...this.keepalive(),\n });\n if (res.ok) return \"ok\";\n return NON_RETRYABLE_STATUS.has(res.status) ? \"refused\" : \"retry\";\n } catch {\n return \"retry\";\n }\n }\n}\n\n/**\n * Debug mode, as `init()` settles it (`InitOptions.debug`). The explicit option\n * wins; otherwise any one signal is enough. Conservative on purpose \u2014 a false\n * positive takes a real user out of every report \u2014 so each signal is one the\n * platform itself sets for development only.\n */\nexport async function detectDebug(opts: Pick<InitOptions, \"debug\" | \"platform\" | \"native\">): Promise<boolean> {\n if (opts.debug !== undefined) return opts.debug;\n if (opts.platform === \"web\") return isLocalPage();\n // React Native / Expo: Metro sets it for a development bundle, false in release.\n if ((globalThis as { __DEV__?: unknown }).__DEV__ === true) return true;\n try {\n return (await opts.native?.isDebugBuild?.()) === true;\n } catch {\n // A bridge that cannot answer says nothing: production, as before the flag.\n return false;\n }\n}\n\n/** A page served from the developer's own machine \u2014 never a production origin. */\nexport function isLocalPage(loc: { protocol: string; hostname: string } | undefined = (globalThis as { location?: Location }).location): boolean {\n if (!loc) return false;\n if (loc.protocol === \"file:\") return true;\n const host = loc.hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n return (\n host === \"localhost\" ||\n host.endsWith(\".localhost\") ||\n host.endsWith(\".local\") ||\n host === \"::1\" ||\n host === \"0.0.0.0\" ||\n /^127\\.\\d+\\.\\d+\\.\\d+$/.test(host)\n );\n}\n\nexport const Traqio = new Client();\n", "// @traqio/web \u2014 the browser half of the Traqio web SDK.\n//\n// One job above all: keep the trackID (the ad click id Traqio's tracking link puts in\n// the landing URL as `traq_click`) from the landing page to the conversion, in\n// first-party storage, so the conversion can be tied to its click deterministically.\n// Around it: web events and visits, sent through the same engine as the mobile SDKs\n// (@traqio/core, bundled in), with consent and erasure.\n//\n// One package for every framework: it is plain JS with no UI, and a framework only\n// decides WHERE `init()` is called. SSR-safe: nothing touches `window` or `document`\n// at import time, and `init()` on a server is a no-op.\n//\n// What it deliberately does NOT do: report an install, or send the click id with an\n// event. A web key is public (it sits in the page), so it carries no attribution\n// authority \u2014 a conversion is tied to its click by the site's BACKEND, with a secret\n// key, reading the trackID this package kept (cookie `traq_click`, or `getTrackId()`).\nimport { Client } from \"@traqio/core\";\nimport { registrableDomain } from \"./cookies\";\nimport { BrowserStore, DEVICE_ID_KEY, INTERNAL_KEY } from \"./storage\";\nimport { SourceKeeper, type WebSource } from \"./source\";\nimport { TrackIdKeeper } from \"./trackId\";\nimport { AnalyticsTracker, cleanGroups, cleanTraits, cleanUserId, exposureProps, withGroup, type AnalyticsOptions, type Groups, type Traits } from \"./analytics\";\n\nexport type { WebSource } from \"./source\";\nexport type { AnalyticsOptions, Groups, Traits, TraitValue } from \"./analytics\";\nexport type { WebVitalsOptions } from \"./vitals\";\n\nexport const DEFAULT_ENDPOINT = \"https://api.traqio.app\";\n/** `register()`'s super-properties, kept across pages. */\nconst SUPER_PROPS_KEY = \"traq_super\";\n/** `group()`'s accounts, kept across pages. */\nconst GROUPS_KEY = \"traq_groups\";\nconst DEFAULT_TRACK_ID_DAYS = 30;\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\nexport interface WebInitOptions {\n /** The site's WEB key (`tq_web_\u2026`), from the console. Public by design: it is held to the site's origins. */\n sdkKey: string;\n /** Origin only, no path. Default `https://api.traqio.app`. */\n endpoint?: string;\n /** Your user id once known \u2014 the same id your backend sends with its conversions. */\n userId?: string;\n /**\n * The visitor's consent to SHARING with ad networks, if already known. Omitted =\n * not collected; the site's policy in the console decides.\n */\n consent?: boolean;\n /**\n * `true` = write nothing to the device (no localStorage, no cookie) until\n * `setConsent(true)`. The SDK still works for the current page, in memory. For\n * sites that must ask before storing anything (ePrivacy). Default `false`.\n */\n waitForConsent?: boolean;\n /**\n * How long the trackID \u2014 and the visit's source (`getSource()`) \u2014 is kept after\n * the landing, in days. Default 30. Keeping it\n * longer than the site's attribution window is harmless: the server refuses a\n * click outside the window.\n */\n trackIdDays?: number;\n /** `false` = never write a cookie, localStorage only (no sharing across subdomains). Default `true`. */\n cookies?: boolean;\n /**\n * Debug mode. Omitted = on when the page is served from your machine (`localhost`,\n * `127.0.0.1`, `*.localhost`, `*.local`, `file:`), off everywhere else. Debug\n * traffic shows in the console's Live events \u203A Debug view (its analytics events in\n * Analytics \u203A Realtime \u203A Debug, kept 24 h) and is never counted,\n * attributed, sent to an ad network or a webhook, or billed. `true` for a staging\n * site, `false` to count a local page.\n */\n debug?: boolean;\n /**\n * Product analytics \u2014 page views (route changes included), clicks, rage clicks,\n * scroll depth, front-end errors and the Core Web Vitals of a sample of page loads,\n * read in the console's Analytics section. `true` turns them all on; an object picks\n * (`{ webVitals: { sampleRate: 0.1 } }`). Default off. Never billed and never sent to an ad network:\n * analytics events have their own route and table, apart from conversions.\n */\n analytics?: boolean | AnalyticsOptions;\n}\n\n/** What `track()` accepts beside the event name. */\nexport interface WebTrackProps {\n /** Revenue DECLARED by the page. Prefer sending purchases from your backend, where they are known. */\n value?: number;\n currency?: string;\n /** The payment's id at your processor (e.g. a Stripe payment intent): the purchase is then counted once. */\n transactionId?: string;\n /** Where the payment went through \u2014 `\"stripe\"` for Stripe. */\n store?: \"stripe\" | \"app_store\" | \"play_store\" | \"mac_app_store\" | \"amazon\";\n}\n\nfunction inBrowser(): boolean {\n return typeof window !== \"undefined\" && typeof document !== \"undefined\";\n}\n\nfunction randomId(): string | null {\n try {\n return typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\" ? crypto.randomUUID() : null;\n } catch {\n return null;\n }\n}\n\n/**\n * `traqio_internal` in a URL's query: `1`/`true` \u2192 true, `0`/`false` \u2192 false, absent or\n * anything else \u2192 null (left as it was).\n */\nexport function internalParam(href: string): boolean | null {\n try {\n const v = new URL(href).searchParams.get(\"traqio_internal\");\n if (v === \"1\" || v === \"true\") return true;\n if (v === \"0\" || v === \"false\") return false;\n } catch {\n /* not a URL */\n }\n return null;\n}\n\nexport class TraqioWeb {\n private readonly core = new Client();\n private store: BrowserStore | null = null;\n private trackIds: TrackIdKeeper | null = null;\n private sources: SourceKeeper | null = null;\n private waitForConsent = false;\n private started = false;\n /** A `setConsent()` made before `init()` \u2014 it decides whether init may store. */\n private earlyConsent: boolean | undefined;\n private analytics: AnalyticsTracker | null = null;\n private userId: string | undefined;\n /** `capture()` calls made before `init()` finished \u2014 replayed once the tracker exists. */\n private earlyCaptures: Array<[string, Record<string, unknown> | undefined]> = [];\n /** `init()` has finished (or will never run here): early captures are no longer kept. */\n private ready = false;\n /** `register()`: properties added to every analytics event, kept in `traq_super`. */\n private superProps: Traits = {};\n /** `identify()` calls with traits made before `init()` \u2014 replayed once the tracker exists. */\n private earlyIdentifies: Array<[string, Traits, Traits]> = [];\n /** `group()`: the accounts every analytics event is stamped with, kept in `traq_groups`. */\n private groups: Groups = {};\n /** Group entries made before `init()` \u2014 replayed once the tracker exists. */\n private earlyGroups: Array<[string, string, Traits, Traits]> = [];\n /** `alias()` calls made before `init()`: [userId, previousId]. */\n private earlyAliases: Array<[string, string]> = [];\n /** A `reset()` before `init()`: what earlier pages kept (super-properties, accounts) is dropped, not restored. */\n private resetBeforeInit = false;\n\n /**\n * Call once, as early as possible on every page (or once in a single-page app).\n * Reads the trackID from the current URL first, synchronously, so even a visitor\n * who leaves before the network answers keeps it. Safe to call on a server: it\n * does nothing there.\n */\n async init(opts: WebInitOptions): Promise<void> {\n if (this.started || !inBrowser()) return;\n this.started = true;\n this.waitForConsent = opts.waitForConsent === true;\n\n const cookies = opts.cookies !== false;\n let domain: string | null | undefined;\n // Probed lazily, once: it writes a test cookie, which must not happen before consent.\n const cookieDomain = (): string | null => (domain === undefined ? (domain = registrableDomain(location.hostname)) : domain);\n\n const consent = opts.consent ?? this.earlyConsent;\n const persistent = !this.waitForConsent || consent === true;\n this.store = new BrowserStore(persistent, cookieDomain, cookies);\n const keepMs = (opts.trackIdDays ?? DEFAULT_TRACK_ID_DAYS) * DAY_MS;\n this.trackIds = new TrackIdKeeper(this.store, keepMs, cookieDomain, cookies);\n this.trackIds.capture(location.href);\n // The visitor's origin when no Traqio link was clicked: utm_*, gclid/fbclid/ttclid,\n // the referring site. Same lifetime and consent rules as the trackID.\n this.sources = new SourceKeeper(this.store, keepMs, cookieDomain, cookies);\n this.sources.capture(location.href, document.referrer);\n // `?traqio_internal=1` marks this browser as the team's own, `=0` releases it.\n const optOut = internalParam(location.href);\n if (optOut !== null) this.setInternal(optOut);\n\n // A real random id rather than core's Math.random one, when the browser has it.\n // Seeded before core reads it; core keeps whatever is already there.\n if (!this.store.getSync(DEVICE_ID_KEY)) {\n const id = randomId();\n if (id) this.store.setSync(DEVICE_ID_KEY, id);\n }\n\n // An identify() made before init() keeps its user id unless init names one.\n this.userId = opts.userId ?? this.userId;\n if (this.resetBeforeInit) {\n this.store.removeSync(SUPER_PROPS_KEY);\n this.store.removeSync(GROUPS_KEY);\n }\n // Super-properties kept from earlier pages; a register() made before init() wins.\n try {\n const raw = this.store.getSync(SUPER_PROPS_KEY);\n const early = Object.keys(this.superProps).length > 0;\n if (raw) this.superProps = cleanTraits({ ...cleanTraits(JSON.parse(raw)), ...this.superProps });\n if (early) this.store.setSync(SUPER_PROPS_KEY, JSON.stringify(this.superProps));\n } catch {\n /* corrupt: none */\n }\n // Same for the accounts: kept from earlier pages, a group() made before init() wins.\n try {\n const raw = this.store.getSync(GROUPS_KEY);\n const early = Object.keys(this.groups).length > 0;\n if (raw) this.groups = cleanGroups({ ...cleanGroups(JSON.parse(raw)), ...this.groups });\n if (early) this.store.setSync(GROUPS_KEY, JSON.stringify(this.groups));\n } catch {\n /* corrupt: none */\n }\n const endpoint = (opts.endpoint ?? DEFAULT_ENDPOINT).replace(/\\/+$/, \"\");\n await this.core.init({\n sdkKey: opts.sdkKey,\n endpoint,\n storage: this.store,\n platform: \"web\",\n userId: this.userId,\n consent,\n debug: opts.debug,\n lifecycle: ({ background, foreground }) => {\n // `visibilitychange` is the last event a page reliably gets (tab switch,\n // close, navigation, mobile app switch); `pagehide` covers the bfcache.\n document.addEventListener(\"visibilitychange\", () => (document.visibilityState === \"hidden\" ? background() : foreground()));\n window.addEventListener(\"pagehide\", background);\n },\n });\n\n if (opts.analytics) {\n const store = this.store;\n this.analytics = new AnalyticsTracker({\n store,\n endpoint,\n sdkKey: opts.sdkKey,\n anonymousId: () => store.getSync(DEVICE_ID_KEY),\n userId: () => this.userId,\n superProps: () => this.superProps,\n groups: () => this.groups,\n isDebug: () => this.core.isDebug,\n isForgotten: () => this.core.forgotten,\n isInternal: () => this.isInternal,\n options: opts.analytics === true ? {} : opts.analytics,\n });\n this.analytics.start();\n for (const [id, set, once] of this.earlyIdentifies) this.analytics.identify(id, set, once);\n for (const [type, key, set, once] of this.earlyGroups) this.analytics.group(type, key, set, once);\n for (const [user, prev] of this.earlyAliases) this.analytics.alias(user, prev);\n for (const [name, props] of this.earlyCaptures) this.analytics.capture(name, props);\n }\n this.earlyCaptures = [];\n this.earlyIdentifies = [];\n this.earlyGroups = [];\n this.earlyAliases = [];\n this.ready = true;\n }\n\n /**\n * Mark this browser as the team's own (`true`) or as a visitor again (`false`) \u2014 what\n * opening the site with `?traqio_internal=1` / `=0` does. Its analytics events are\n * still sent, flagged: the console leaves them out of every figure by default and\n * shows them under \u00AB Internal traffic only \u00BB. Conversions (`track()`) are not\n * affected. Kept on the device, like the visitor id (and under the same consent).\n */\n setInternal(on: boolean): void {\n if (!this.store) return;\n try {\n if (on) this.store.setSync(INTERNAL_KEY, \"1\");\n else this.store.removeSync(INTERNAL_KEY);\n } catch {\n /* storage refused: nothing kept */\n }\n }\n\n /** True when this browser opted itself out as internal traffic \u2014 see `setInternal()`. */\n get isInternal(): boolean {\n try {\n return this.store?.getSync(INTERNAL_KEY) === \"1\";\n } catch {\n return false;\n }\n }\n\n /** Whether this page runs in debug mode \u2014 see `WebInitOptions.debug`. Settled by `init()`. */\n get isDebug(): boolean {\n return this.core.isDebug;\n }\n\n /** Record an event \u2014 `signup`, `purchase`, `add_to_cart`\u2026 Batched, retried, kept across page loads. */\n track(name: string, props?: WebTrackProps): void {\n this.core.track(name, props);\n }\n\n /**\n * A product-analytics event \u2014 `search_performed`, `pricing_toggled`\u2026 \u2014 read in the\n * console's Analytics section (events, funnels). NOT a conversion: it is never\n * billed nor sent to an ad network. A conversion (sign-up, purchase) is `track()`.\n * Needs `analytics` at init; names starting with `$` are reserved, but for an\n * experiment exposure: `capture(\"$exposure\", { experiment, variant })`.\n */\n capture(name: string, props?: Record<string, unknown>): void {\n if (this.analytics) this.analytics.capture(name, props);\n else if (!this.ready && this.earlyCaptures.length < 50) this.earlyCaptures.push([name, props]);\n }\n\n /**\n * Record a page view now. Not needed with the history API (route changes are\n * caught by themselves); for a router that changes the page another way.\n */\n pageview(): void {\n this.analytics?.pageview();\n }\n\n /** Set the user id once known (after sign-in). */\n setUserId(id: string): void {\n this.userId = id;\n this.core.setUserId(id);\n }\n\n /**\n * Who the user is, and what they are: sets the user id (like `setUserId`) and, with\n * traits, the user's PROPERTIES \u2014 `plan`, `role`, `company_size` \u2014 read in the\n * console as a breakdown, a report dimension and a cohort condition. Needs\n * `analytics` at init for the traits.\n *\n * Traqio.identify(\"u_123\", { plan: \"pro\", seats: 12 }, { signup_source: \"webinar\" });\n *\n * `traits` overwrite what was set before; `traitsOnce` are written only where the\n * user has no value yet. Text, numbers, booleans \u2014 never an email or a name. At most 50 keys.\n */\n identify(userId: string, traits?: Record<string, unknown>, traitsOnce?: Record<string, unknown>): void {\n const id = typeof userId === \"string\" ? userId.trim() : \"\";\n if (!id) return;\n this.setUserId(id);\n const set = cleanTraits(traits);\n const once = cleanTraits(traitsOnce);\n if (!Object.keys(set).length && !Object.keys(once).length) return;\n if (this.analytics) this.analytics.identify(id, set, once);\n else if (!this.ready && this.earlyIdentifies.length < 10) this.earlyIdentifies.push([id, set, once]);\n }\n\n /**\n * Super-properties: added to EVERY analytics event from now on, on this page and the\n * next ones \u2014 an A/B arm, a pricing variant, a theme. An event's own property of the\n * same name wins. Kept with the visitor id (same consent rules). `unregister(key)` removes one.\n *\n * Traqio.register({ pricing_variant: \"b\" });\n */\n register(props: Record<string, unknown>): void {\n this.superProps = cleanTraits({ ...this.superProps, ...cleanTraits(props) });\n this.persistSuperProps();\n }\n\n /** Stop adding one super-property to the events. */\n unregister(key: string): void {\n if (typeof key !== \"string\" || !(key in this.superProps)) return;\n const rest = { ...this.superProps };\n delete rest[key];\n this.superProps = rest;\n this.persistSuperProps();\n }\n\n /** The super-properties `register()` set \u2014 a copy. */\n getSuperProperties(): Traits {\n return { ...this.superProps };\n }\n\n /**\n * The B2B ACCOUNT the visitor works in (group analytics): every analytics event from\n * now on \u2014 on this page and the next ones \u2014 counts for it, so the console can count\n * accounts (unique accounts, funnels, retention, cohorts \u00AB by company \u00BB) and list them\n * with their traits. Call it after sign-in, and again on an account switch. Needs\n * `analytics` at init.\n *\n * Traqio.group(\"company\", \"acc_42\", { plan: \"enterprise\", seats: 40 });\n *\n * `groupType` is lowercase (`company`, `workspace`; 5 types at most), `groupKey` your\n * own account id \u2014 never an email. Traits follow identify's rules.\n */\n group(groupType: string, groupKey: string | number, traits?: Record<string, unknown>, traitsOnce?: Record<string, unknown>): void {\n const next = withGroup(this.groups, groupType, groupKey);\n if (!next) return;\n this.groups = next.groups;\n this.persistGroups();\n const set = cleanTraits(traits);\n const once = cleanTraits(traitsOnce);\n // Same account, nothing new to say: no entry (a group() on every page costs nothing).\n if (!next.changed && !Object.keys(set).length && !Object.keys(once).length) return;\n if (this.analytics) this.analytics.group(next.type, next.key, set, once);\n else if (!this.ready && this.earlyGroups.length < 10) this.earlyGroups.push([next.type, next.key, set, once]);\n }\n\n /** Stop stamping the events with any account \u2014 call it on sign-out. */\n resetGroups(): void {\n this.groups = {};\n this.persistGroups();\n }\n\n /** The accounts `group()` set, by type \u2014 a copy. */\n getGroups(): Groups {\n return { ...this.groups };\n }\n\n /**\n * Two ids, one person: the user known so far as `previousId` (a guest id, an id\n * from before sign-up) IS the current user (`setUserId` / `identify`). Their\n * analytics history and properties are merged under the current id \u2014 its own\n * properties win. From the browser only what THIS visitor sent under `previousId`\n * is merged; a backend (`@traqio/node`, secret key) merges everything.\n *\n * Traqio.identify(\"u_123\");\n * Traqio.alias(\"guest_8f2c\");\n *\n * Ignored without a current user id, or when `previousId` is the current one. Needs `analytics` at init.\n */\n alias(previousId: string): void {\n const prev = cleanUserId(previousId);\n const user = this.userId;\n if (!user || !prev || prev === user) return;\n if (this.analytics) this.analytics.alias(user, prev);\n else if (!this.ready && this.earlyAliases.length < 10) this.earlyAliases.push([user, prev]);\n }\n\n /**\n * Sign-out: forget who the user was in this browser \u2014 the user id, the\n * super-properties, the accounts \u2014 and end the analytics session, so the next\n * person's visit starts clean. Events already queued keep the user they were\n * captured under. The visitor id is KEPT: it carries the visitor's attribution\n * (the click, the campaign) for the next sign-up.\n */\n reset(): void {\n const user = this.userId;\n this.analytics?.reset(user);\n this.userId = undefined;\n this.core.reset();\n this.superProps = {};\n this.groups = {};\n this.earlyIdentifies = [];\n this.earlyGroups = [];\n this.earlyAliases = [];\n if (this.store) {\n this.persistSuperProps();\n this.persistGroups();\n } else this.resetBeforeInit = true;\n }\n\n /**\n * An experiment exposure: the visitor SAW `variant` of `experiment` \u2014 what the\n * console's experiment analysis reads (uplift, significance per variant). Your site\n * assigns the variant (its own flags, an edge split, a cookie); call this where the\n * visitor first meets it. Sends `$exposure { experiment, variant, ...props }`.\n *\n * Traqio.exposure(\"pricing_page\", \"annual_first\");\n */\n exposure(experiment: string, variant: string | number | boolean, props?: Record<string, unknown>): void {\n const p = exposureProps(experiment, variant, props);\n if (!p) return;\n // Over the 4 KB cap, the exposure alone rather than an event without its experiment.\n let fits = false;\n try {\n fits = JSON.stringify(p).length <= 4096;\n } catch {\n fits = false;\n }\n this.capture(\"$exposure\", fits ? p : { experiment: p.experiment, variant: p.variant });\n }\n\n private persistGroups(): void {\n try {\n if (!this.store) return; // before init(): init() merges and writes them\n if (Object.keys(this.groups).length) this.store.setSync(GROUPS_KEY, JSON.stringify(this.groups));\n else this.store.removeSync(GROUPS_KEY);\n } catch {\n /* storage refused: kept for this page */\n }\n }\n\n private persistSuperProps(): void {\n try {\n if (!this.store) return; // before init(): init() merges and writes them\n if (Object.keys(this.superProps).length) this.store.setSync(SUPER_PROPS_KEY, JSON.stringify(this.superProps));\n else this.store.removeSync(SUPER_PROPS_KEY);\n } catch {\n /* storage refused: kept for this page */\n }\n }\n\n /**\n * The visitor's consent answer. Governs sharing with ad networks, and \u2014 with\n * `waitForConsent` \u2014 whether anything may be stored: `true` writes out what the\n * page kept in memory (the trackID included), `false` removes everything this SDK\n * stored on the device.\n */\n async setConsent(granted: boolean): Promise<void> {\n if (!this.started) this.earlyConsent = granted;\n if (this.store && this.waitForConsent) {\n if (granted) {\n this.store.enable();\n this.trackIds?.persistCookie();\n this.sources?.persistCookie();\n } else {\n this.store.disable();\n }\n }\n await this.core.setConsent(granted);\n }\n\n /**\n * The trackID kept for this visitor, or null (no ad click, or expired). Pass it to\n * your backend with the sign-up or checkout \u2014 a hidden form field, a header \u2014 if\n * your backend cannot read the `traq_click` cookie itself.\n */\n getTrackId(): string | null {\n return this.trackIds?.get() ?? null;\n }\n\n /**\n * Where the visitor came from when no Traqio link brought them \u2014 the landing's\n * `utm_*`, an ad network's click id (`gclid`, `fbclid`, `ttclid`), the referring\n * site \u2014 or null. Kept in the `traq_src` cookie your backend reads with the\n * sign-up (`@traqio/node`: `sourceFromRequest(req)`); pass this to it instead\n * when your backend is on another domain. A Traqio link click wins over it.\n */\n getSource(): WebSource | null {\n return this.sources?.get() ?? null;\n }\n\n /**\n * GDPR erasure from the page: the server deletes what it holds about this browser\n * and user, and this SDK stops sending and forgets the trackID. Irreversible.\n * Resolves false when the request did not reach the server \u2014 then nothing changed.\n */\n async forgetMe(): Promise<boolean> {\n const ok = await this.core.forgetMe();\n if (ok) {\n this.trackIds?.clear();\n this.sources?.clear();\n this.analytics?.stop();\n this.superProps = {};\n this.persistSuperProps();\n this.groups = {};\n this.persistGroups();\n }\n return ok;\n }\n\n /** Send what is queued now. Already wired to tab hide and page exit. */\n flush(): void {\n this.core.flush();\n this.analytics?.flush(false);\n }\n\n /** True once `forgetMe()` has been honoured: this browser sends nothing any more. */\n get forgotten(): boolean {\n return this.core.forgotten;\n }\n}\n\n/** The shared instance \u2014 `import { Traqio } from \"@traqio/web\"`. */\nexport const Traqio = new TraqioWeb();\n", "// First-party cookies, on the site's registrable domain when the browser allows it.\n//\n// Why a cookie at all, next to localStorage: localStorage is per ORIGIN, so a visitor\n// who lands on `www.example.com` and signs up on `app.example.com` would be two\n// strangers. A cookie on `example.com` is shared by both \u2014 and it reaches the site's\n// own backend with the sign-up request, which is how a server reads the trackID\n// without any JavaScript.\n\n/** Every cookie the SDK writes carries this prefix \u2014 the same namespace as the URL. */\nexport const COOKIE_PREFIX = \"traq_\";\n\nfunction doc(): Document | undefined {\n return typeof document === \"undefined\" ? undefined : document;\n}\n\nexport function readCookie(name: string): string | null {\n const d = doc();\n if (!d) return null;\n for (const part of d.cookie ? d.cookie.split(\";\") : []) {\n const eq = part.indexOf(\"=\");\n if (eq < 0) continue;\n if (part.slice(0, eq).trim() === name) {\n try {\n return decodeURIComponent(part.slice(eq + 1).trim());\n } catch {\n return null;\n }\n }\n }\n return null;\n}\n\nfunction serialize(name: string, value: string, maxAgeSeconds: number, domain: string | null): string {\n const secure = typeof location !== \"undefined\" && location.protocol === \"https:\" ? \"; Secure\" : \"\";\n const scope = domain ? `; Domain=${domain}` : \"\";\n return `${name}=${encodeURIComponent(value)}; Max-Age=${Math.floor(maxAgeSeconds)}; Path=/${scope}; SameSite=Lax${secure}`;\n}\n\n/**\n * The widest domain this page may set a cookie on \u2014 `example.co.uk` for\n * `shop.example.co.uk`. There is no public-suffix list in a browser, so ask the\n * browser itself: try the shortest candidates first, and keep the first one it\n * accepts (it refuses `co.uk`, a public suffix). Null on `localhost` and IP\n * addresses, where a host-only cookie is the only kind there is.\n */\nexport function registrableDomain(hostname: string): string | null {\n const d = doc();\n if (!d || !hostname.includes(\".\") || /^[\\d.]+$/.test(hostname) || hostname.includes(\":\")) return null;\n const labels = hostname.split(\".\");\n const probe = `${COOKIE_PREFIX}probe`;\n for (let i = labels.length - 2; i >= 0; i--) {\n const candidate = labels.slice(i).join(\".\");\n d.cookie = serialize(probe, \"1\", 10, candidate);\n if (readCookie(probe) === \"1\") {\n d.cookie = serialize(probe, \"\", 0, candidate);\n return candidate;\n }\n }\n return null;\n}\n\nexport function writeCookie(name: string, value: string, maxAgeSeconds: number, domain: string | null): void {\n const d = doc();\n if (!d) return;\n try {\n d.cookie = serialize(name, value, maxAgeSeconds, domain);\n } catch {\n /* cookies disabled \u2014 localStorage still holds it on this origin */\n }\n}\n\nexport function deleteCookie(name: string, domain: string | null): void {\n writeCookie(name, \"\", 0, domain);\n}\n", "import { COOKIE_PREFIX, deleteCookie, readCookie, writeCookie } from \"./cookies\";\n\n/**\n * Keys that are mirrored into a cookie on the registrable domain, so `www.` and\n * `app.` of the same site share them. Only identifiers \u2014 the event queue stays in\n * localStorage, where it belongs (a cookie rides along on every request).\n */\nexport const DEVICE_ID_KEY = \"traq_device_id\";\n/**\n * \u00AB This browser is the team's own \u00BB (`?traqio_internal=1`, HQ cmwv9c10). Mirrored so\n * opting out on `www.` also covers `app.` \u2014 it is a flag, not an identifier, and says\n * nothing about the visitor beyond that.\n */\nexport const INTERNAL_KEY = \"traq_internal\";\nconst MIRRORED = new Set([DEVICE_ID_KEY, INTERNAL_KEY]);\nconst MIRROR_MAX_AGE_SECONDS = 395 * 24 * 60 * 60; // 13 months, the CNIL ceiling for a measurement cookie\n\nfunction local(): Storage | undefined {\n try {\n return typeof localStorage === \"undefined\" ? undefined : localStorage;\n } catch {\n return undefined; // Safari with storage blocked throws on mere access\n }\n}\n\n/**\n * @traqio/core's `KeyValueStore`, restated so the published .d.ts files never name\n * @traqio/core: it is bundled into this package, not installed next to it.\n */\ninterface KeyValueStore {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n}\n\n/**\n * The browser persistence behind @traqio/core: localStorage, plus a cookie mirror for\n * identifiers \u2014 or memory only, until the visitor agrees.\n *\n * `persistent: false` is the \"nothing on the device before consent\" mode: every\n * value lives in memory for this page, the SDK still works for this page view, and\n * `enable()` writes it all out the moment consent is given. `disable()` is the way\n * back: everything this SDK wrote is removed from the device, and the page goes on\n * in memory.\n */\nexport class BrowserStore implements KeyValueStore {\n private readonly memory = new Map<string, string>();\n\n constructor(\n private persistent: boolean,\n private readonly cookieDomain: () => string | null,\n private readonly cookies: boolean,\n ) {}\n\n get isPersistent(): boolean {\n return this.persistent;\n }\n\n async getItem(key: string): Promise<string | null> {\n return this.getSync(key);\n }\n\n async setItem(key: string, value: string): Promise<void> {\n this.setSync(key, value);\n }\n\n getSync(key: string): string | null {\n if (this.memory.has(key)) return this.memory.get(key) ?? null;\n if (!this.persistent) return null;\n let value: string | null = null;\n try {\n value = local()?.getItem(key) ?? null;\n } catch {\n /* blocked */\n }\n if (value === null && this.cookies && MIRRORED.has(key)) value = readCookie(key);\n return value;\n }\n\n setSync(key: string, value: string): void {\n if (!this.persistent) {\n this.memory.set(key, value);\n return;\n }\n let stored = false;\n try {\n const ls = local();\n if (ls) {\n ls.setItem(key, value);\n stored = true;\n }\n } catch {\n /* quota or blocked \u2014 fall through to memory */\n }\n if (!stored) this.memory.set(key, value);\n if (this.cookies && MIRRORED.has(key)) writeCookie(key, value, MIRROR_MAX_AGE_SECONDS, this.cookieDomain());\n }\n\n removeSync(key: string): void {\n this.memory.delete(key);\n try {\n local()?.removeItem(key);\n } catch {\n /* blocked */\n }\n if (this.cookies) deleteCookie(key, this.cookieDomain());\n }\n\n /** Consent given: what this page kept in memory goes to the device. */\n enable(): void {\n if (this.persistent) return;\n this.persistent = true;\n const pending = [...this.memory];\n this.memory.clear();\n for (const [key, value] of pending) this.setSync(key, value);\n }\n\n /**\n * Consent withdrawn: every `traq_*` value leaves the device (localStorage and\n * cookies) and stays in memory for the rest of this page, so nothing breaks\n * mid-visit and nothing survives it.\n */\n disable(): void {\n if (!this.persistent) return;\n const ls = local();\n const keys: string[] = [];\n try {\n for (let i = 0; ls && i < ls.length; i++) {\n const k = ls.key(i);\n if (k && k.startsWith(COOKIE_PREFIX)) keys.push(k);\n }\n } catch {\n /* blocked */\n }\n for (const k of MIRRORED) if (!keys.includes(k)) keys.push(k);\n for (const k of keys) {\n const value = this.getSync(k);\n if (value !== null) this.memory.set(k, value);\n }\n this.persistent = false;\n for (const k of keys) {\n try {\n ls?.removeItem(k);\n } catch {\n /* blocked */\n }\n if (this.cookies) deleteCookie(k, this.cookieDomain());\n }\n }\n}\n", "import { deleteCookie, readCookie, writeCookie } from \"./cookies\";\nimport type { BrowserStore } from \"./storage\";\n\n/** What localStorage holds for a kept value. The `{ id, exp }` shape predates `traq_src`: browsers already hold it for `traq_click`. */\ninterface Stored {\n id: string;\n /** Epoch ms after which the value is no longer kept. */\n exp: number;\n}\n\n/**\n * One value kept twice, on purpose:\n * - localStorage `<key>` = `{ id, exp }`: survives navigation on this origin;\n * - cookie `<key>` = the bare value, on the registrable domain: shared with the\n * other subdomains, and sent by the browser to the site's OWN backend with the\n * sign-up request \u2014 where the conversion that counts is known.\n *\n * Both writes go through the store's consent mode: before consent (with\n * `waitForConsent`) the value lives in memory and no cookie is written.\n */\nexport class KeptValue {\n constructor(\n private readonly store: BrowserStore,\n private readonly key: string,\n private readonly cookieDomain: () => string | null,\n private readonly cookies: boolean,\n /** A cookie value that fails this is ignored (another script's cookie, a tampered one). */\n private readonly valid: (value: string) => boolean,\n ) {}\n\n /** The kept value, or null once it has expired or was never there. */\n get(now = Date.now()): string | null {\n const raw = this.store.getSync(this.key);\n if (raw) {\n try {\n const parsed = JSON.parse(raw) as Stored;\n if (parsed && typeof parsed.id === \"string\" && parsed.exp > now) return parsed.id;\n } catch {\n /* corrupt \u2014 fall back to the cookie */\n }\n }\n // Another subdomain set it (localStorage is per origin, the cookie is not). The\n // cookie's own Max-Age is its expiry, so a cookie that is still there is valid.\n if (this.cookies && this.store.isPersistent) {\n const fromCookie = readCookie(this.key);\n if (fromCookie && this.valid(fromCookie)) return fromCookie;\n }\n return null;\n }\n\n set(value: string, maxAgeMs: number, now = Date.now()): void {\n const record: Stored = { id: value, exp: now + maxAgeMs };\n this.store.setSync(this.key, JSON.stringify(record));\n if (this.cookies && this.store.isPersistent) writeCookie(this.key, value, maxAgeMs / 1000, this.cookieDomain());\n }\n\n /** Removes it everywhere \u2014 `forgetMe()`. */\n clear(): void {\n this.store.removeSync(this.key);\n if (this.cookies) deleteCookie(this.key, this.cookieDomain());\n }\n\n /** Writes the cookie half once storage becomes allowed (the localStorage half moves with the store). */\n persistCookie(now = Date.now()): void {\n const raw = this.store.getSync(this.key);\n if (!raw || !this.cookies || !this.store.isPersistent) return;\n try {\n const parsed = JSON.parse(raw) as Stored;\n if (parsed.exp > now) writeCookie(this.key, parsed.id, (parsed.exp - now) / 1000, this.cookieDomain());\n } catch {\n /* corrupt \u2014 nothing to mirror */\n }\n }\n}\n", "import { KeptValue } from \"./kept\";\nimport type { BrowserStore } from \"./storage\";\n\n/**\n * Where a visitor came from when there was no Traqio link to click: the `utm_*`\n * parameters of the landing URL (an Instagram bio, a newsletter, a LinkedIn post),\n * the ad networks' own click ids (`gclid`, `fbclid`, `ttclid`), and the host of the\n * page that sent them (`document.referrer`).\n *\n * Kept like the trackID (`traq_click`) \u2014 localStorage + a first-party cookie\n * `traq_src`, same lifetime, same consent rules \u2014 so the site's backend reads it\n * with the sign-up request and sends it with the sign-up (`@traqio/node`:\n * `sourceFromRequest(req)`). Traqio then reports the sign-up under that source and\n * campaign. A Traqio link click, when there is one, wins over it.\n *\n * The cookie holds a query string \u2014 `utm_source=instagram&utm_campaign=launch&ts=\u2026`\n * \u2014 so any backend language parses it with its standard library.\n */\nexport const SOURCE_KEY = \"traq_src\";\n\n/** The landing-URL parameters kept, as written in the URL. */\nexport const SOURCE_PARAMS = [\"utm_source\", \"utm_medium\", \"utm_campaign\", \"utm_content\", \"utm_term\", \"gclid\", \"fbclid\", \"ttclid\"] as const;\n\n/** Each value is cut to this length: a cookie has ~4 KB for all of them. */\nconst MAX_VALUE_LENGTH = 200;\n\n/** Where the visitor came from \u2014 see `getSource()`. Every field is optional. */\nexport interface WebSource {\n utmSource?: string;\n utmMedium?: string;\n utmCampaign?: string;\n utmContent?: string;\n utmTerm?: string;\n /** Host of the page that linked here (`l.instagram.com`) \u2014 never its path or query. */\n referrer?: string;\n /** Google Ads click id. */\n gclid?: string;\n /** Meta click id (Facebook and Instagram links, paid or not). */\n fbclid?: string;\n /** TikTok Ads click id. */\n ttclid?: string;\n /** When the visitor landed with it, epoch ms. */\n landedAt?: number;\n}\n\nconst FIELD: Record<(typeof SOURCE_PARAMS)[number] | \"referrer\", keyof WebSource> = {\n utm_source: \"utmSource\",\n utm_medium: \"utmMedium\",\n utm_campaign: \"utmCampaign\",\n utm_content: \"utmContent\",\n utm_term: \"utmTerm\",\n gclid: \"gclid\",\n fbclid: \"fbclid\",\n ttclid: \"ttclid\",\n referrer: \"referrer\",\n};\n\nconst clean = (v: string | null): string | null => {\n const t = v?.trim();\n return t ? t.slice(0, MAX_VALUE_LENGTH) : null;\n};\n\nconst bare = (host: string): string => host.toLowerCase().replace(/^www\\./, \"\");\n\n/** Is `other` this site \u2014 the same host, a subdomain of it, or a parent of it? */\nfunction sameSite(host: string, other: string): boolean {\n const a = bare(host);\n const b = bare(other);\n return a === b || a.endsWith(`.${b}`) || b.endsWith(`.${a}`);\n}\n\n/**\n * The host of an EXTERNAL referrer, or null (none, this site, not http(s)). Only the\n * host: a referrer's path and query can carry anything, a search, an email address.\n */\nexport function referrerHost(referrer: string | null | undefined, pageHref: string): string | null {\n if (!referrer) return null;\n try {\n const ref = new URL(referrer);\n if (ref.protocol !== \"http:\" && ref.protocol !== \"https:\") return null;\n if (sameSite(new URL(pageHref).hostname, ref.hostname)) return null;\n return clean(bare(ref.hostname));\n } catch {\n return null;\n }\n}\n\n/**\n * The source a landing carries, as the query string kept in `traq_src`, or null\n * when it carries none. `fromUrl` = the landing URL itself carried a parameter (a\n * referrer-only landing does not).\n */\nexport function sourceFromLanding(href: string, referrer: string | null | undefined, now: number): { query: string; fromUrl: boolean } | null {\n const out = new URLSearchParams();\n try {\n const params = new URL(href).searchParams;\n for (const key of SOURCE_PARAMS) {\n const v = clean(params.get(key));\n if (v) out.set(key, v);\n }\n } catch {\n return null;\n }\n const fromUrl = out.toString() !== \"\";\n const ref = referrerHost(referrer, href);\n if (ref) out.set(\"referrer\", ref);\n if (out.toString() === \"\") return null;\n out.set(\"ts\", String(now));\n return { query: out.toString(), fromUrl };\n}\n\n/** The kept query string, as a `WebSource`. Null when it holds nothing we know. */\nexport function parseSource(query: string): WebSource | null {\n let params: URLSearchParams;\n try {\n params = new URLSearchParams(query);\n } catch {\n return null;\n }\n const source: WebSource = {};\n for (const [param, field] of Object.entries(FIELD)) {\n const v = clean(params.get(param));\n if (v) (source as Record<string, string>)[field] = v;\n }\n if (!Object.keys(source).length) return null;\n const ts = Number(params.get(\"ts\"));\n if (Number.isFinite(ts) && ts > 0) source.landedAt = ts;\n return source;\n}\n\nexport class SourceKeeper {\n private readonly kept: KeptValue;\n\n constructor(\n store: BrowserStore,\n private readonly maxAgeMs: number,\n cookieDomain: () => string | null,\n cookies: boolean,\n ) {\n this.kept = new KeptValue(store, SOURCE_KEY, cookieDomain, cookies, (v) => parseSource(v) !== null);\n }\n\n /**\n * Reads the landing. URL parameters (`utm_*`, a click id) REPLACE what is kept:\n * the last campaign that brought the visitor is the one that counts, as for the\n * trackID. A referrer alone only fills an empty slot \u2014 the return from a payment\n * page or a webmail must not overwrite the campaign the visitor came from. A\n * landing with neither (a typed URL, an internal navigation) changes nothing.\n */\n capture(href: string, referrer: string | null | undefined, now = Date.now()): WebSource | null {\n const landing = sourceFromLanding(href, referrer, now);\n if (!landing) return null;\n if (!landing.fromUrl && this.kept.get(now) !== null) return null;\n this.kept.set(landing.query, this.maxAgeMs, now);\n return parseSource(landing.query);\n }\n\n /** The kept source, or null (none, or expired). */\n get(now = Date.now()): WebSource | null {\n const query = this.kept.get(now);\n return query === null ? null : parseSource(query);\n }\n\n clear(): void {\n this.kept.clear();\n }\n\n persistCookie(now = Date.now()): void {\n this.kept.persistCookie(now);\n }\n}\n", "import { KeptValue } from \"./kept\";\nimport type { BrowserStore } from \"./storage\";\n\n/**\n * The trackID \u2014 the click id Traqio's tracking link appends to the landing URL as\n * `traq_click` (the same `traq_` namespace as the Play Install Referrer, so it never\n * collides with the site's own `utm_*`).\n *\n * Kept twice, on purpose:\n * - localStorage `traq_click` = `{ id, exp }`: survives navigation on this origin;\n * - cookie `traq_click` = the bare id, on the registrable domain: shared with the\n * other subdomains, and sent by the browser to the site's OWN backend with the\n * sign-up or checkout request \u2014 where the conversion that counts is known.\n */\nexport const CLICK_PARAM = \"traq_click\";\nconst STORE_KEY = \"traq_click\";\n\n/** What a click id looks like: Traqio mints UUIDs; anything else is refused, not stored. */\nconst CLICK_ID = /^[A-Za-z0-9_-]{8,64}$/;\n\n/** The click id carried by a URL, or null. Never throws on a malformed URL. */\nexport function clickIdFromUrl(href: string): string | null {\n try {\n const raw = new URL(href).searchParams.get(CLICK_PARAM);\n return raw && CLICK_ID.test(raw) ? raw : null;\n } catch {\n return null;\n }\n}\n\nexport class TrackIdKeeper {\n private readonly kept: KeptValue;\n\n constructor(\n store: BrowserStore,\n private readonly maxAgeMs: number,\n cookieDomain: () => string | null,\n cookies: boolean,\n ) {\n this.kept = new KeptValue(store, STORE_KEY, cookieDomain, cookies, (v) => CLICK_ID.test(v));\n }\n\n /**\n * Reads the landing URL. A new click REPLACES the kept one: the last ad clicked is\n * the one that brought the visitor this time. A URL without a click id changes\n * nothing \u2014 an internal navigation must not wipe the id the landing brought.\n */\n capture(href: string, now = Date.now()): string | null {\n const id = clickIdFromUrl(href);\n if (id) this.kept.set(id, this.maxAgeMs, now);\n return id;\n }\n\n /** The kept click id, or null once it has expired or was never there. */\n get(now = Date.now()): string | null {\n return this.kept.get(now);\n }\n\n /** Removes it everywhere \u2014 `forgetMe()`. */\n clear(): void {\n this.kept.clear();\n }\n\n /** Writes the cookie half once storage becomes allowed (the localStorage half moves with the store). */\n persistCookie(now = Date.now()): void {\n this.kept.persistCookie(now);\n }\n}\n", "// Core Web Vitals (HQ cmwuue1b) \u2014 LCP, INP, CLS, FCP and TTFB of the page load, measured\n// with the browser's own PerformanceObserver entries, the way Google's `web-vitals`\n// library reads them, without adding it as a dependency (a few hundred bytes here\n// against ~2 KB, and nothing to keep in step).\n//\n// One `$web_vitals` event per SAMPLED page load, sent once, when the page is first\n// hidden (tab switched, closed, navigated away) \u2014 the moment LCP is final and CLS / INP\n// have seen most of the visit. A client-side route change is not a new load: its\n// shifts and interactions count toward the load's CLS and INP, as in Chrome's own field\n// data (CrUX). Nothing personal: five numbers and the page the load started on.\n//\n// Pure where it can be: `VitalsCollector` is fed entries and answers a snapshot, so every\n// rule (CLS session windows, the INP percentile) is tested without a browser.\n\nexport interface WebVitalsOptions {\n /**\n * The share of page loads measured, 0\u20131. Default 0.5: half the loads is plenty for a\n * stable p75 on a busy page and still readable on a small site; lower it on a site\n * with millions of views, 1 to measure every load.\n */\n sampleRate?: number;\n}\n\nexport const DEFAULT_VITALS_SAMPLE_RATE = 0.5;\n\nexport interface VitalsSnapshot {\n lcp?: number;\n inp?: number;\n cls?: number;\n fcp?: number;\n ttfb?: number;\n}\n\n/** Whether this page load is measured. A rate outside 0\u20131 (or not a number) falls back to the default. */\nexport function sampled(rate: number | undefined, random: () => number = Math.random): boolean {\n const r = typeof rate === \"number\" && Number.isFinite(rate) && rate >= 0 && rate <= 1 ? rate : DEFAULT_VITALS_SAMPLE_RATE;\n if (r <= 0) return false;\n return r >= 1 || random() < r;\n}\n\n/** A CLS session window: shifts less than 1 s apart, the window at most 5 s long. */\nconst CLS_GAP_MS = 1000;\nconst CLS_WINDOW_MS = 5000;\n/** INP ignores one outlier per 50 interactions; keeping the 10 longest is enough to answer for 500. */\nconst INP_KEEP = 10;\n\nexport class VitalsCollector {\n private lcp: number | undefined;\n private fcp: number | undefined;\n private ttfb: number | undefined;\n private clsMax = 0;\n private clsSeen = false;\n private clsWindow = { value: 0, first: 0, last: 0 };\n /** The longest interactions, by interactionId: their longest entry. */\n private longest = new Map<number, number>();\n private interactions = new Set<number>();\n private inpSeen = false;\n\n /** A `largest-contentful-paint` entry: the latest one is the LCP. */\n addLcp(startTime: number): void {\n if (Number.isFinite(startTime) && startTime >= 0) this.lcp = startTime;\n }\n\n /** The `first-contentful-paint` paint entry. */\n addFcp(startTime: number): void {\n if (this.fcp === undefined && Number.isFinite(startTime) && startTime >= 0) this.fcp = startTime;\n }\n\n /** The navigation entry's `responseStart` (minus `activationStart` for a prerendered page). */\n setTtfb(ms: number): void {\n if (Number.isFinite(ms) && ms >= 0) this.ttfb = ms;\n }\n\n /**\n * A `layout-shift` entry. Shifts right after an input are expected and skipped; the\n * rest are grouped in session windows and CLS is the largest window's sum.\n */\n addShift(value: number, startTime: number, hadRecentInput: boolean): void {\n this.clsSeen = true;\n if (hadRecentInput || !Number.isFinite(value) || value < 0) return;\n const w = this.clsWindow;\n if (w.value > 0 && startTime - w.last < CLS_GAP_MS && startTime - w.first < CLS_WINDOW_MS) {\n w.value += value;\n w.last = startTime;\n } else {\n this.clsWindow = { value, first: startTime, last: startTime };\n }\n this.clsMax = Math.max(this.clsMax, this.clsWindow.value);\n }\n\n /** The browser supports layout shifts: a page that never moved has a CLS of 0, not none. */\n clsObserved(): void {\n this.clsSeen = true;\n }\n\n /** An `event` (or `first-input`) entry with an interactionId: one interaction's latency. */\n addInteraction(interactionId: number, duration: number): void {\n if (!interactionId || !Number.isFinite(duration) || duration < 0) return;\n this.inpSeen = true;\n this.interactions.add(interactionId);\n const prev = this.longest.get(interactionId);\n if (prev !== undefined && prev >= duration) return;\n this.longest.set(interactionId, duration);\n if (this.longest.size > INP_KEEP) {\n let minId = 0;\n let min = Infinity;\n for (const [id, d] of this.longest) {\n if (d < min) {\n min = d;\n minId = id;\n }\n }\n this.longest.delete(minId);\n }\n }\n\n /**\n * INP: the longest interaction, ignoring one per 50 \u2014 the 98th percentile for a busy\n * page, the worst one for an ordinary visit.\n */\n private inp(): number | undefined {\n if (!this.inpSeen || !this.longest.size) return undefined;\n const sorted = [...this.longest.values()].sort((a, b) => b - a);\n return sorted[Math.min(sorted.length - 1, Math.floor(this.interactions.size / 50))];\n }\n\n /** What was measured, rounded: ms for the timings, 4 decimals for CLS. Null when nothing was. */\n snapshot(): VitalsSnapshot | null {\n const out: VitalsSnapshot = {};\n if (this.lcp !== undefined) out.lcp = Math.round(this.lcp);\n const inp = this.inp();\n if (inp !== undefined) out.inp = Math.round(inp);\n if (this.clsSeen) out.cls = Math.round(this.clsMax * 10_000) / 10_000;\n if (this.fcp !== undefined) out.fcp = Math.round(this.fcp);\n if (this.ttfb !== undefined) out.ttfb = Math.round(this.ttfb);\n return Object.keys(out).length ? out : null;\n }\n}\n\ntype Entry = PerformanceEntry & {\n value?: number;\n hadRecentInput?: boolean;\n interactionId?: number;\n responseStart?: number;\n activationStart?: number;\n};\n\n/** Observes one entry type, buffered (what happened before the SDK loaded counts). Silent where unsupported. */\nfunction observe(type: string, onEntries: (entries: Entry[]) => void, extra: Record<string, unknown> = {}): boolean {\n try {\n const PO = (globalThis as { PerformanceObserver?: typeof PerformanceObserver }).PerformanceObserver;\n if (!PO || !PO.supportedEntryTypes?.includes(type)) return false;\n const po = new PO((list) => onEntries(list.getEntries() as Entry[]));\n po.observe({ type, buffered: true, ...extra } as PerformanceObserverInit);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Wires the observers onto a collector. A page that loaded in the background (opened in a\n * new tab) has no meaningful LCP or FCP \u2014 they would measure when the tab was looked at \u2014\n * so those two are only kept when the page started visible, as `web-vitals` does.\n */\nexport function watchVitals(c: VitalsCollector): void {\n const startedVisible = typeof document === \"undefined\" || document.visibilityState !== \"hidden\";\n let activation = 0;\n try {\n const nav = performance.getEntriesByType(\"navigation\")[0] as Entry | undefined;\n if (nav) {\n activation = Math.max(0, nav.activationStart ?? 0);\n if (typeof nav.responseStart === \"number\" && nav.responseStart > 0) c.setTtfb(Math.max(0, nav.responseStart - activation));\n }\n } catch {\n /* no Navigation Timing: no TTFB */\n }\n if (startedVisible) {\n let lcpFinal = false;\n // LCP stops at the first input: what loads after a click is the visitor's doing.\n const finalize = (): void => {\n lcpFinal = true;\n };\n for (const type of [\"keydown\", \"click\", \"pointerdown\"]) window.addEventListener(type, finalize, { once: true, capture: true });\n observe(\"largest-contentful-paint\", (es) => {\n if (lcpFinal) return;\n for (const e of es) c.addLcp(Math.max(0, e.startTime - activation));\n });\n observe(\"paint\", (es) => {\n for (const e of es) if (e.name === \"first-contentful-paint\") c.addFcp(Math.max(0, e.startTime - activation));\n });\n }\n if (observe(\"layout-shift\", (es) => es.forEach((e) => c.addShift(e.value ?? 0, e.startTime, !!e.hadRecentInput)))) c.clsObserved();\n // 40 ms is the threshold `web-vitals` uses: shorter interactions never decide an INP.\n observe(\"event\", (es) => es.forEach((e) => c.addInteraction(e.interactionId ?? 0, e.duration)), { durationThreshold: 40 });\n observe(\"first-input\", (es) => es.forEach((e) => c.addInteraction(e.interactionId ?? 0, e.duration)));\n}\n", "// Product analytics \u2014 page views, clicks, scroll depth, errors and custom analytics\n// events, posted to `POST /ingest/analytics` (HQ cmwksiam). What replaces PostHog on a\n// site: the traffic its owner reads, NOT the conversions an ad network is paid on.\n//\n// \u26A0\uFE0F An analytics event is never a conversion. `track()` stays the conversion door\n// (`/ingest`, metered, forwarded); `capture()` and everything captured here go to their\n// own route and their own table, which billing and forwarding never read. A page view\n// can therefore never be billed, whatever the site sends.\n//\n// No replay, no fingerprint, no form value: a click records the element's visible text\n// and link, never what was typed. Off unless the site turns it on (`analytics: true`).\nimport type { KeyValueStore } from \"@traqio/core\";\nimport { DEFAULT_VITALS_SAMPLE_RATE, sampled, VitalsCollector, watchVitals, type WebVitalsOptions } from \"./vitals\";\n\nexport interface AnalyticsOptions {\n /** A page view on load and on every client-side route change (history API). Default true. */\n pageviews?: boolean;\n /** Clicks on links and buttons: their text and link. Default true. */\n clicks?: boolean;\n /**\n * Rage clicks: 3 or more clicks within a second on the same spot, on ANY element \u2014\n * a dead button, a picture that looks like a link. One `$rageclick` per burst, with\n * the element's text and tag. Default true.\n */\n rageClicks?: boolean;\n /** The deepest of 25/50/75/100 % each page view reached, sent once per page view. Default true. */\n scroll?: boolean;\n /** Uncaught errors and unhandled promise rejections. Default true. */\n errors?: boolean;\n /**\n * Core Web Vitals \u2014 LCP, INP, CLS, FCP, TTFB \u2014 of a SAMPLE of page loads: one\n * `$web_vitals` per measured load, sent when the page is first hidden. Default on, at\n * `sampleRate` 0.5; `{ sampleRate: 0.1 }` on a very busy site, `false` to turn it off.\n */\n webVitals?: boolean | WebVitalsOptions;\n}\n\ntype Kind = \"pageview\" | \"custom\" | \"click\" | \"rageclick\" | \"scroll\" | \"error\" | \"vitals\";\n\n/** `identify(userId, traits)`: a user's properties, never an analytics row (the server's identify.ts). */\ninterface IdentifyEntry {\n kind: \"identify\";\n ts: number;\n userId: string;\n set?: Traits;\n setOnce?: Traits;\n}\n\n/** `group(type, key, traits)`: an account's properties, never an analytics row (the server's groups.ts). */\ninterface GroupEntry {\n kind: \"group\";\n ts: number;\n groupType: string;\n groupKey: string;\n set?: Traits;\n setOnce?: Traits;\n}\n\n/** `alias(previousId)`: two ids of one person, never an analytics row (the server's alias.ts). */\ninterface AliasEntry {\n kind: \"alias\";\n ts: number;\n userId: string;\n previousId: string;\n}\n\ntype Entry = IdentifyEntry | GroupEntry | AliasEntry;\ntype Queued = QueuedEvent | Entry;\nconst isEntry = (e: Queued): e is Entry => e.kind === \"identify\" || e.kind === \"group\" || e.kind === \"alias\";\n\n/** The accounts a visitor belongs to, by group type: `{ company: \"acme\" }`. */\nexport type Groups = Record<string, string>;\n\nconst GROUP_TYPE = /^[a-z][a-z0-9_]{0,29}$/;\n/** Group types held at once (the server's cap) \u2014 a new one past it is ignored. */\nexport const MAX_GROUP_TYPES = 5;\n\n/** A group type as the server takes it (`company`, `workspace`), or null. */\nexport function cleanGroupType(v: unknown): string | null {\n if (typeof v !== \"string\") return null;\n const t = v.trim();\n return GROUP_TYPE.test(t) ? t : null;\n}\n\n/** An account key: trimmed text (or a number) of 1\u2013256 characters, or null. */\nexport function cleanGroupKey(v: unknown): string | null {\n if (typeof v === \"number\" && Number.isFinite(v)) return String(v);\n if (typeof v !== \"string\") return null;\n const t = v.trim();\n return t && t.length <= 256 ? t : null;\n}\n\n/** Stored groups re-read through the same rules: valid pairs only, at most 5. */\nexport function cleanGroups(v: unknown): Groups {\n const out: Groups = {};\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) return out;\n for (const [t, k] of Object.entries(v as Record<string, unknown>)) {\n if (Object.keys(out).length >= MAX_GROUP_TYPES) break;\n const type = cleanGroupType(t);\n const key = cleanGroupKey(k);\n if (type && key) out[type] = key;\n }\n return out;\n}\n\n/** The groups after `group(type, key)`, or null to ignore the call (bad type/key, a 6th new type); `changed` = a new key. */\nexport function withGroup(groups: Groups, type: unknown, key: unknown): { groups: Groups; type: string; key: string; changed: boolean } | null {\n const t = cleanGroupType(type);\n const k = cleanGroupKey(key);\n if (!t || !k) return null;\n if (!(t in groups) && Object.keys(groups).length >= MAX_GROUP_TYPES) return null;\n return { groups: { ...groups, [t]: k }, type: t, key: k, changed: groups[t] !== k };\n}\n\n/** A user property or super-property value: a label to segment by. */\nexport type TraitValue = string | number | boolean;\nexport type Traits = Record<string, TraitValue>;\n\nconst TRAIT_KEY = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/;\n/** Traits one identify call carries at most, and super-properties kept at most (the server's cap). */\nexport const MAX_TRAITS = 50;\n/** An event's properties, serialised, at most this long on the server \u2014 past it they are dropped. */\nconst MAX_PROPS_BYTES = 4096;\n\n/**\n * Traits as the server keeps them: valid keys, values that are text (cut at 200), a\n * finite number or a boolean \u2014 a nested object, null or a function never travels.\n */\nexport function cleanTraits(v: unknown): Traits {\n const out: Traits = {};\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) return out;\n for (const [k, raw] of Object.entries(v as Record<string, unknown>)) {\n if (Object.keys(out).length >= MAX_TRAITS) break;\n if (!TRAIT_KEY.test(k)) continue;\n if (typeof raw === \"string\") {\n const t = raw.trim();\n if (t) out[k] = t.slice(0, 200);\n } else if ((typeof raw === \"number\" && Number.isFinite(raw)) || typeof raw === \"boolean\") {\n out[k] = raw;\n }\n }\n return out;\n}\n\n/** An event's properties over the super-properties (the event's own win); past the server's cap, its own alone. */\nexport function withSuperProps(own: Record<string, unknown> | undefined, sup: Traits): Record<string, unknown> | undefined {\n if (!Object.keys(sup).length) return own;\n const merged = { ...sup, ...(own ?? {}) };\n try {\n return JSON.stringify(merged).length <= MAX_PROPS_BYTES ? merged : own;\n } catch {\n return own;\n }\n}\n\ninterface QueuedEvent {\n /**\n * The event's own id: a batch re-sent after a request that landed but reported a\n * failure (a keepalive fetch on a hidden Chrome Android page) is stored once \u2014 the\n * server derives the row's key from it and skips a key it already holds.\n */\n id: string;\n kind: Kind;\n name?: string;\n ts: number;\n url: string;\n title?: string;\n sessionId: string;\n src?: SessionSource;\n props?: Record<string, unknown>;\n /** The accounts held when it was queued (`group()`). */\n groups?: Groups;\n /**\n * Never sent: the user id it was captured under, stamped by `reset()` on what was\n * still queued \u2014 a sign-out never re-files the last events under nobody. Absent = the current one.\n */\n asUser?: string;\n}\n\n/** Where the SESSION landed from \u2014 copied on each of its events (the server stores it per row). */\nexport interface SessionSource {\n utmSource?: string;\n utmMedium?: string;\n utmCampaign?: string;\n utmContent?: string;\n utmTerm?: string;\n referrer?: string;\n gclid?: string;\n fbclid?: string;\n ttclid?: string;\n}\n\ninterface StoredSession {\n id: string;\n /** Last activity, epoch ms. */\n last: number;\n src?: SessionSource;\n}\n\nexport interface AnalyticsDeps {\n store: KeyValueStore & { getSync(key: string): string | null; setSync(key: string, value: string): void; removeSync(key: string): void };\n endpoint: string;\n sdkKey: string;\n anonymousId: () => string | null;\n userId: () => string | undefined;\n /** `group()`'s accounts, read at each event. */\n groups?: () => Groups;\n /** `register()`'s super-properties, read at each event. */\n superProps?: () => Traits;\n isDebug: () => boolean;\n isForgotten: () => boolean;\n /** The browser opted itself out as the team's own (`?traqio_internal=1`): batches say so. */\n isInternal?: () => boolean;\n options: AnalyticsOptions;\n}\n\nexport const SESSION_KEY = \"traq_session\";\n\n/** A user id as the server takes it (alias.ts): trimmed text (or a number) of 1\u2013256 characters, or null. */\nexport function cleanUserId(v: unknown): string | null {\n if (typeof v === \"number\" && Number.isFinite(v)) return String(v);\n if (typeof v !== \"string\") return null;\n const t = v.trim();\n return t && t.length <= 256 ? t : null;\n}\n\n/** Experiment and variant as `$exposure` carries them: trimmed text of 1\u2013200 characters (a number or boolean variant as text). */\nfunction exposureText(v: unknown): string | null {\n const t = typeof v === \"string\" ? v.trim() : (typeof v === \"number\" && Number.isFinite(v)) || typeof v === \"boolean\" ? String(v) : \"\";\n return t && t.length <= 200 ? t : null;\n}\n\n/** `exposure()`'s properties \u2014 `{ ...props, experiment, variant }`, the two named ones winning \u2014 or null to ignore the call. */\nexport function exposureProps(experiment: unknown, variant: unknown, props?: Record<string, unknown>): Record<string, unknown> | null {\n const e = exposureText(experiment);\n const v = exposureText(variant);\n if (!e || !v) return null;\n return { ...(props && typeof props === \"object\" && !Array.isArray(props) ? props : {}), experiment: e, variant: v };\n}\n\n/**\n * Takes (splices) the next batch off `queue`: the leading events captured under ONE\n * user (`asUser`, else `current`) \u2014 entries ride with any batch \u2014 and that user. The\n * events keep their stamp, so a requeued batch still knows its user; the request drops it.\n */\nexport function takeBatch<T extends { kind: string; asUser?: string }>(queue: T[], current: string | undefined, max: number): { events: T[]; userId: string | undefined } {\n let n = 0;\n let userId = current;\n let fixed = false;\n for (const e of queue) {\n if (n >= max) break;\n const entry = e.kind === \"identify\" || e.kind === \"group\" || e.kind === \"alias\";\n if (!entry) {\n const who = e.asUser !== undefined ? e.asUser || undefined : current;\n if (!fixed) {\n userId = who;\n fixed = true;\n } else if (who !== userId) break;\n }\n n++;\n }\n return { events: queue.splice(0, n), userId };\n}\n/** 30 minutes without activity end a session \u2014 the convention PostHog and GA share. */\nexport const SESSION_IDLE_MS = 30 * 60 * 1000;\nconst FLUSH_EVERY_MS = 5000;\nconst FLUSH_AT = 20;\nconst MAX_QUEUE = 200;\nconst MAX_ERRORS_PER_PAGE = 10;\n/**\n * The rejection a mail link scanner's harness throws (Outlook Safe Links / Microsoft\n * Defender, HQ cmwwyam8) \u2014 the server's link-scanner.ts holds the same signature.\n */\nconst LINK_SCANNER_ERROR = /^Object Not Found Matching Id:\\d+, MethodName:\\w+, ParamCount:\\d+$/;\nconst SCROLL_STEPS = [25, 50, 75, 100] as const;\nconst UTM: Array<[string, keyof SessionSource]> = [\n [\"utm_source\", \"utmSource\"],\n [\"utm_medium\", \"utmMedium\"],\n [\"utm_campaign\", \"utmCampaign\"],\n [\"utm_content\", \"utmContent\"],\n [\"utm_term\", \"utmTerm\"],\n [\"gclid\", \"gclid\"],\n [\"fbclid\", \"fbclid\"],\n [\"ttclid\", \"ttclid\"],\n];\n\nfunction newId(): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") return crypto.randomUUID();\n } catch {\n /* fall through */\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;\n}\n\n/** The landing's source: the URL's utm_* and click ids, and the referrer when it is another site. */\nexport function landingSource(href: string, referrer: string): SessionSource | undefined {\n const src: SessionSource = {};\n try {\n const u = new URL(href);\n for (const [param, key] of UTM) {\n const v = u.searchParams.get(param)?.trim();\n if (v) src[key] = v.slice(0, 200);\n }\n if (referrer) {\n const r = new URL(referrer);\n if (r.hostname.replace(/^www\\./, \"\") !== u.hostname.replace(/^www\\./, \"\")) src.referrer = `${r.protocol}//${r.host}/`;\n }\n } catch {\n /* an unparsable URL has no source */\n }\n return Object.keys(src).length ? src : undefined;\n}\n\n/** A URL without its query string or fragment \u2014 tokens and emails live there. */\nfunction bare(href: string | null | undefined): string | undefined {\n if (!href) return undefined;\n try {\n const u = new URL(href, typeof location !== \"undefined\" ? location.href : undefined);\n if (u.protocol !== \"http:\" && u.protocol !== \"https:\") return undefined;\n return `${u.origin}${u.pathname}`;\n } catch {\n return undefined;\n }\n}\n\n/** Clicks within this long of the burst's first one, and this close to it, are one burst. */\nexport const RAGE_WINDOW_MS = 1000;\nexport const RAGE_RADIUS_PX = 30;\nexport const RAGE_THRESHOLD = 3;\n\n/**\n * Rage-click detection, pure: feed it every click's position and time, it answers\n * `true` ONCE per burst \u2014 on the click that makes the third within a second and 30 px\n * of the burst's first. The burst then has to go quiet for a second before another\n * can be reported, so ten furious clicks are one rage click, not three.\n */\nexport class RageClickDetector {\n private burst: { x: number; y: number; first: number; last: number; count: number; reported: boolean } | null = null;\n\n hit(x: number, y: number, t: number): boolean {\n const b = this.burst;\n const near = b !== null && t - b.last <= RAGE_WINDOW_MS && Math.hypot(x - b.x, y - b.y) <= RAGE_RADIUS_PX;\n // A new spot, a pause, or three clicks that took longer than a second: a new burst.\n if (!near || (!b.reported && t - b.first > RAGE_WINDOW_MS)) {\n this.burst = { x, y, first: t, last: t, count: 1, reported: false };\n return false;\n }\n // A reported burst stays open (and silent) while clicks keep coming.\n b.count++;\n b.last = t;\n if (b.reported || b.count < RAGE_THRESHOLD) return false;\n b.reported = true;\n return true;\n }\n}\n\nexport class AnalyticsTracker {\n private queue: Queued[] = [];\n private timer: ReturnType<typeof setInterval> | null = null;\n private lastPath: string | null = null;\n private maxScroll = 0;\n private scrollUrl: string | null = null;\n private errorsThisPage = 0;\n private stopped = false;\n /** This page is driven by a mail link scanner: every later batch says so (the server keeps it out of the figures). */\n private scanner = false;\n private readonly rage = new RageClickDetector();\n private vitals: VitalsCollector | null = null;\n private vitalsUrl: string | null = null;\n\n constructor(private readonly deps: AnalyticsDeps) {}\n\n /** Wires the listeners the options ask for and records the first page view. */\n start(): void {\n const o = this.deps.options;\n this.timer = setInterval(() => this.flush(false), FLUSH_EVERY_MS);\n document.addEventListener(\"visibilitychange\", () => {\n if (document.visibilityState === \"hidden\") this.leave();\n });\n window.addEventListener(\"pagehide\", () => this.leave());\n\n if (o.pageviews !== false) {\n this.pageview();\n this.watchRoutes();\n }\n if (o.clicks !== false) document.addEventListener(\"click\", (e: Event) => this.onClick(e), true);\n if (o.rageClicks !== false) document.addEventListener(\"click\", (e: Event) => this.onRageClick(e as MouseEvent), true);\n if (o.scroll !== false) window.addEventListener(\"scroll\", () => this.onScroll(), { passive: true } as AddEventListenerOptions);\n if (o.errors !== false) {\n window.addEventListener(\"error\", (e: Event) => this.onError(e as ErrorEvent));\n window.addEventListener(\"unhandledrejection\", (e: Event) => this.onRejection(e as PromiseRejectionEvent));\n }\n if (o.webVitals !== false) {\n const rate = typeof o.webVitals === \"object\" ? o.webVitals.sampleRate : DEFAULT_VITALS_SAMPLE_RATE;\n // The draw is per page LOAD: a measured load is measured whole, an unmeasured one costs nothing.\n if (sampled(rate)) {\n this.vitals = new VitalsCollector();\n this.vitalsUrl = bare(location.href) ?? null;\n watchVitals(this.vitals);\n }\n }\n }\n\n /** A custom analytics event \u2014 never a conversion (that is `track()`). */\n capture(name: string, props?: Record<string, unknown>): void {\n // `$\u2026` is reserved, but for the experiment exposure `$exposure { experiment, variant }`.\n if (typeof name !== \"string\" || !name.trim() || (name.startsWith(\"$\") && name.trim() !== \"$exposure\")) return;\n this.enqueue({ kind: \"custom\", name: name.trim(), props });\n }\n\n /**\n * The user's properties (`identify(userId, traits, traitsOnce)`): one entry in the\n * batch, under its own user id. Not activity \u2014 it neither opens nor prolongs a session.\n */\n identify(userId: string, set: Traits, setOnce: Traits): void {\n if (this.stopped || !userId) return;\n const hasSet = Object.keys(set).length > 0;\n const hasOnce = Object.keys(setOnce).length > 0;\n if (!hasSet && !hasOnce) return;\n this.queue.push({ kind: \"identify\", ts: Date.now(), userId, ...(hasSet ? { set } : {}), ...(hasOnce ? { setOnce } : {}) });\n if (this.queue.length > MAX_QUEUE) this.queue.shift();\n if (this.queue.length >= FLUSH_AT) this.flush(false);\n }\n\n /** An account's properties (`group(type, key, traits)`): one entry in the batch. Not activity either. */\n group(groupType: string, groupKey: string, set: Traits, setOnce: Traits): void {\n if (this.stopped) return;\n const hasSet = Object.keys(set).length > 0;\n const hasOnce = Object.keys(setOnce).length > 0;\n this.queue.push({ kind: \"group\", ts: Date.now(), groupType, groupKey, ...(hasSet ? { set } : {}), ...(hasOnce ? { setOnce } : {}) });\n if (this.queue.length > MAX_QUEUE) this.queue.shift();\n if (this.queue.length >= FLUSH_AT) this.flush(false);\n }\n\n /** Two ids, one person (`alias(previousId)`): one entry in the batch, under the current user. Not activity. */\n alias(userId: string, previousId: string): void {\n if (this.stopped) return;\n this.queue.push({ kind: \"alias\", ts: Date.now(), userId, previousId });\n if (this.queue.length > MAX_QUEUE) this.queue.shift();\n if (this.queue.length >= FLUSH_AT) this.flush(false);\n }\n\n /**\n * Sign-out (`reset()`): what is queued keeps `userId`, the user it was captured\n * under, and the session ends \u2014 the next event opens a new one.\n */\n reset(userId: string | undefined): void {\n if (userId) for (const e of this.queue) if (!isEntry(e) && e.asUser === undefined) e.asUser = userId;\n try {\n this.deps.store.removeSync(SESSION_KEY);\n } catch {\n /* storage refused: nothing kept anyway */\n }\n }\n\n /** Records a page view of the current URL. Called by itself on route changes; exposed for routers that need it. */\n pageview(): void {\n const url = bare(location.href);\n if (!url) return;\n if (url === this.lastPath) return;\n this.sendScroll();\n this.lastPath = url;\n this.scrollUrl = url;\n this.maxScroll = 0;\n this.errorsThisPage = 0;\n this.enqueue({ kind: \"pageview\" });\n this.onScroll();\n }\n\n /** Sends what is queued. `leaving` = the page is going away: keepalive, so the request outlives it. */\n flush(leaving: boolean): void {\n if (!this.queue.length || this.stopped) return;\n if (this.deps.isForgotten()) {\n this.stop();\n return;\n }\n const anonymousId = this.deps.anonymousId();\n if (!anonymousId) return;\n // One user per request: events queued before a reset() keep the user they were captured under.\n const taken = takeBatch(this.queue, this.deps.userId(), 100);\n const userId = taken.userId;\n // A retried batch goes back under the user it was sent for, even if a reset() came in between.\n const events = userId ? taken.events.map((e) => (isEntry(e) || e.asUser !== undefined ? e : { ...e, asUser: userId })) : taken.events;\n const body = JSON.stringify({\n sdkKey: this.deps.sdkKey,\n anonymousId,\n userId,\n debug: this.deps.isDebug() || undefined,\n internal: this.deps.isInternal?.() || undefined,\n scanner: this.scanner || undefined,\n events: events.map((e) => (isEntry(e) ? e : { ...e, asUser: undefined })),\n });\n try {\n void fetch(`${this.deps.endpoint}/ingest/analytics`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body,\n keepalive: leaving,\n })\n .then((res) => {\n // A 5xx or a 429 is worth one more try; a 4xx is the batch's own fault and is dropped.\n if (!res.ok && (res.status >= 500 || res.status === 429)) this.requeue(events);\n })\n .catch(() => this.requeue(events));\n } catch {\n this.requeue(events);\n }\n }\n\n /** Forget everything and stop: after `forgetMe()`, or on a server. */\n stop(): void {\n this.stopped = true;\n this.queue = [];\n if (this.timer) clearInterval(this.timer);\n this.timer = null;\n }\n\n // \u2500\u2500 internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private requeue(events: Queued[]): void {\n if (this.stopped) return;\n this.queue = [...events, ...this.queue].slice(-MAX_QUEUE);\n }\n\n private session(): StoredSession {\n const now = Date.now();\n let s: StoredSession | null = null;\n try {\n const raw = this.deps.store.getSync(SESSION_KEY);\n s = raw ? (JSON.parse(raw) as StoredSession) : null;\n } catch {\n s = null;\n }\n if (!s || typeof s.id !== \"string\" || typeof s.last !== \"number\" || now - s.last > SESSION_IDLE_MS) {\n s = { id: newId(), last: now, src: landingSource(location.href, document.referrer) };\n } else {\n s.last = now;\n }\n try {\n this.deps.store.setSync(SESSION_KEY, JSON.stringify(s));\n } catch {\n /* storage refused: the session lives for this page */\n }\n return s;\n }\n\n private enqueue(e: Omit<QueuedEvent, \"id\" | \"ts\" | \"url\" | \"sessionId\" | \"src\" | \"title\"> & { url?: string }): void {\n if (this.stopped) return;\n const s = this.session();\n const title = typeof document.title === \"string\" && document.title ? document.title.slice(0, 200) : undefined;\n // Super-properties ride on every event whose properties the server keeps (a scroll\n // depth and a vitals sample are rebuilt there from their own fields).\n const props = e.kind === \"scroll\" || e.kind === \"vitals\" ? e.props : withSuperProps(e.props, this.deps.superProps?.() ?? {});\n // The accounts ride on EVERY row: a scroll or a vitals sample is the account's activity too.\n const g = this.deps.groups?.() ?? {};\n const groups = Object.keys(g).length ? { ...g } : undefined;\n this.queue.push({ ...e, ...(props ? { props } : {}), ...(groups ? { groups } : {}), id: newId(), ts: Date.now(), url: e.url ?? bare(location.href) ?? \"\", title, sessionId: s.id, ...(s.src ? { src: s.src } : {}) });\n if (this.queue.length > MAX_QUEUE) this.queue.shift();\n if (this.queue.length >= FLUSH_AT) this.flush(false);\n }\n\n private leave(): void {\n this.sendScroll();\n this.sendVitals();\n this.flush(true);\n }\n\n /** Once per load, at the first hide: LCP is final then, and CLS and INP have seen the visit. */\n private sendVitals(): void {\n const c = this.vitals;\n if (!c || !this.vitalsUrl) return;\n this.vitals = null;\n const props = c.snapshot();\n if (props) this.enqueue({ kind: \"vitals\", url: this.vitalsUrl, props: { ...props } });\n }\n\n /** Single-page apps change the URL through the history API: wrap it, and listen for back/forward. */\n private watchRoutes(): void {\n if (typeof history === \"undefined\") return;\n const after = (): void => {\n // The router updates the title right after the URL: read it on the next tick.\n setTimeout(() => this.pageview(), 0);\n };\n for (const method of [\"pushState\", \"replaceState\"] as const) {\n const original = history[method];\n if (typeof original !== \"function\") continue;\n history[method] = function (this: History, ...args: Parameters<History[\"pushState\"]>) {\n const out = original.apply(this, args);\n after();\n return out;\n } as History[\"pushState\"];\n }\n window.addEventListener(\"popstate\", after);\n }\n\n private onScroll(): void {\n if (typeof document.documentElement === \"undefined\" || !document.documentElement) return;\n const doc = document.documentElement;\n const viewport = window.innerHeight || doc.clientHeight || 0;\n const height = Math.max(doc.scrollHeight || 0, document.body?.scrollHeight || 0);\n if (!height) return;\n // A page shorter than the screen has been read to the bottom by being shown.\n const seen = height <= viewport ? 1 : Math.min(1, ((window.scrollY || doc.scrollTop || 0) + viewport) / height);\n const pct = Math.round(seen * 100);\n for (const step of SCROLL_STEPS) if (pct >= step && step > this.maxScroll) this.maxScroll = step;\n }\n\n private sendScroll(): void {\n if (this.deps.options.scroll === false || !this.scrollUrl || this.maxScroll < 25) return;\n this.enqueue({ kind: \"scroll\", url: this.scrollUrl, props: { depth: this.maxScroll } });\n this.scrollUrl = null;\n this.maxScroll = 0;\n }\n\n private onClick(e: Event): void {\n const target = e.target as Element | null;\n const el = target && typeof target.closest === \"function\" ? target.closest(\"a, button, [role='button'], input[type='submit'], input[type='button']\") : null;\n if (!el || el.closest(\"[data-traqio-ignore]\")) return;\n const input = el as HTMLInputElement;\n const text = (el.tagName === \"INPUT\" ? input.value : (el as HTMLElement).innerText || el.textContent || \"\").replace(/\\s+/g, \" \").trim().slice(0, 100);\n const href = el.tagName === \"A\" ? bare((el as HTMLAnchorElement).getAttribute(\"href\")) : undefined;\n const props: Record<string, unknown> = { tag: el.tagName.toLowerCase() };\n if (text) props.text = text;\n if (href) props.href = href;\n if (el.id) props.id = el.id.slice(0, 100);\n this.enqueue({ kind: \"click\", props });\n }\n\n /** Any element: frustration is most telling where nothing was clickable. */\n private onRageClick(e: MouseEvent): void {\n const x = typeof e.clientX === \"number\" ? e.clientX : 0;\n const y = typeof e.clientY === \"number\" ? e.clientY : 0;\n if (!this.rage.hit(x, y, Date.now())) return;\n const target = e.target as Element | null;\n if (!target || typeof target.closest !== \"function\" || target.closest(\"[data-traqio-ignore]\")) return;\n const el = (target.closest(\"a, button, [role='button'], input[type='submit'], input[type='button']\") ?? target) as HTMLElement;\n const text = (el.tagName === \"INPUT\" ? (el as HTMLInputElement).value : el.innerText || el.textContent || \"\").replace(/\\s+/g, \" \").trim().slice(0, 100);\n const props: Record<string, unknown> = { tag: el.tagName.toLowerCase(), count: RAGE_THRESHOLD };\n if (text) props.text = text;\n const href = el.tagName === \"A\" ? bare((el as HTMLAnchorElement).getAttribute(\"href\")) : undefined;\n if (href) props.href = href;\n if (el.id) props.id = el.id.slice(0, 100);\n this.enqueue({ kind: \"rageclick\", props });\n }\n\n private onError(e: ErrorEvent): void {\n if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;\n const message = (e.message || (e.error instanceof Error ? e.error.message : \"\") || \"Script error\").slice(0, 300);\n if (LINK_SCANNER_ERROR.test(message.replace(/^Uncaught (?:Error: )?/, \"\"))) this.scanner = true;\n this.errorsThisPage++;\n const stack = e.error instanceof Error && typeof e.error.stack === \"string\" ? e.error.stack.slice(0, 1500) : undefined;\n this.enqueue({ kind: \"error\", props: { message, ...(stack ? { stack } : {}), ...(e.filename ? { source: bare(e.filename) } : {}), ...(e.lineno ? { line: e.lineno } : {}) } });\n }\n\n private onRejection(e: PromiseRejectionEvent): void {\n if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;\n const reason = e.reason;\n const message = (reason instanceof Error ? reason.message : typeof reason === \"string\" ? reason : \"Unhandled promise rejection\").slice(0, 300);\n if (LINK_SCANNER_ERROR.test(message)) this.scanner = true;\n this.errorsThisPage++;\n const stack = reason instanceof Error && typeof reason.stack === \"string\" ? reason.stack.slice(0, 1500) : undefined;\n this.enqueue({ kind: \"error\", props: { message, unhandledRejection: true, ...(stack ? { stack } : {}) } });\n }\n}\n", "// The <script>-tag build (build/traqio.min.js): sets `window.Traqio`, and initialises\n// itself when the tag carries a key \u2014\n//\n// <script src=\".../traqio.min.js\" data-sdk-key=\"tq_web_\u2026\" async></script>\n//\n// Optional: data-endpoint, data-wait-for-consent=\"true\", data-analytics=\"true\" (product analytics).\nimport { Traqio, TraqioWeb } from \"./index\";\n\ndeclare global {\n interface Window {\n Traqio: TraqioWeb;\n }\n}\n\nwindow.Traqio = Traqio;\n\nconst tag = document.currentScript as HTMLScriptElement | null;\nconst sdkKey = tag?.dataset.sdkKey;\nif (sdkKey) {\n void Traqio.init({\n sdkKey,\n endpoint: tag?.dataset.endpoint || undefined,\n waitForConsent: tag?.dataset.waitForConsent === \"true\",\n analytics: tag?.dataset.analytics === \"true\",\n });\n}\n"],
5
- "mappings": "+0BAgEAA,EAAA,aAAAC,GAcAD,EAAA,iBAAAE,GAyBAF,EAAA,oBAAAG,GASAH,EAAA,mBAAAI,GAcAJ,EAAA,sBAAAK,GApFaL,EAAA,mBAA8F,CACzG,CAAE,OAAQ,EAAG,WAAY,EAAG,SAAU,EAAE,EACxC,CAAE,OAAQ,EAAG,WAAY,GAAI,SAAU,GAAG,EAC1C,CAAE,OAAQ,EAAG,WAAY,IAAK,SAAU,GAAG,GAmB7C,SAAgBC,GAAaK,EAAyB,CACpD,IAAMC,EAAQP,EAAA,mBAAmB,KAC9BQ,GAAMF,GAAqBE,EAAE,YAAcF,EAAoBE,EAAE,QAAQ,EAE5E,OAAOD,EAAQA,EAAM,OAAS,IAChC,CASA,SAAgBL,GACdO,EACAH,EAAyB,CAEzB,IAAMI,EAAUT,GAAaK,CAAiB,EAC9C,GAAII,GAAW,MAAQ,CAACD,GAAW,CAACA,EAAQ,OAAQ,MAAO,GAC3D,IAAME,EAAOF,EAAQ,KAAMD,GAAMA,EAAE,SAAWE,CA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e,iBACfC,EAAA,KAAK,UAAL,MAAAA,EAAc,iBAEd,KAAK,MAAM,QAAQ,GAGvB,MAAM,KAAK,KAAK,WAAWkD,CAAO,CACpC,CAOA,YAA4B,CA5f9B,IAAAnD,EAAAC,EA6fI,OAAOA,GAAAD,EAAA,KAAK,WAAL,YAAAA,EAAe,QAAf,KAAAC,EAAwB,IACjC,CASA,WAA8B,CAvgBhC,IAAAD,EAAAC,EAwgBI,OAAOA,GAAAD,EAAA,KAAK,UAAL,YAAAA,EAAc,QAAd,KAAAC,EAAuB,IAChC,CAOA,MAAM,UAA6B,CAhhBrC,IAAAD,EAAAC,EAAAC,EAihBI,IAAMkD,EAAK,MAAM,KAAK,KAAK,SAAS,EACpC,OAAIA,KACFpD,EAAA,KAAK,WAAL,MAAAA,EAAe,SACfC,EAAA,KAAK,UAAL,MAAAA,EAAc,SACdC,EAAA,KAAK,YAAL,MAAAA,EAAgB,OAChB,KAAK,WAAa,CAAC,EACnB,KAAK,kBAAkB,EACvB,KAAK,OAAS,CAAC,EACf,KAAK,cAAc,GAEdkD,CACT,CAGA,OAAc,CA/hBhB,IAAApD,EAgiBI,KAAK,KAAK,MAAM,GAChBA,EAAA,KAAK,YAAL,MAAAA,EAAgB,MAAM,GACxB,CAGA,IAAI,WAAqB,CACvB,OAAO,KAAK,KAAK,SACnB,CACF,EAGaqD,GAAS,IAAIvD,GQ7hB1B,OAAO,OAASwD,GAEhB,IAAMC,EAAM,SAAS,cACfC,GAASD,GAAA,YAAAA,EAAK,QAAQ,OACxBC,IACGF,GAAO,KAAK,CACf,OAAAE,GACA,UAAUD,GAAA,YAAAA,EAAK,QAAQ,WAAY,OACnC,gBAAgBA,GAAA,YAAAA,EAAK,QAAQ,kBAAmB,OAChD,WAAWA,GAAA,YAAAA,EAAK,QAAQ,aAAc,MACxC,CAAC",
6
- "names": ["exports", "windowForAge", "shouldLockWindow", "fineValueForRevenue", "fineValueForEvents", "coarseValueForRevenue", "hoursSinceInstall", "found", "w", "windows", "current", "rule", "MAX_FINE_VALUE", "MAX_EVENT_BITS", "revenue", "buckets", "value", "i", "events", "bits", "reached", "name", "tiers", "best", "bestThreshold", "tier", "threshold", "EMPTY_STATE", "Skan", "opts", "amount", "m", "fine", "coarse", "_a", "_b", "since", "hours", "doFetch", "res", "body", "raw", "exports", "cleanUserId", "isEntry", "nextAnalyticsBatch", "exposureProps", "cleanGroupType", "cleanGroupKey", "cleanGroups", "withGroup", "cleanTraits", "withSuperProps", "cleanEventName", "cleanScreenName", "cleanProps", "touchSession", "parseSession", "v", "t", "kind", "queue", "current", "max", "userId", "fixed", "events", "e", "who", "_asUser", "wire", "MAX_EXPOSURE_TEXT", "exposureText", "experiment", "variant", "props", "GROUP_TYPE", "MAX_GROUP_KEY", "out", "k", "type", "key", "groups", "TRAIT_KEY", "MAX_TRAIT_TEXT", "raw", "own", "sup", "_a", "name", "n", "json", "now", "newId", "s", "exports", "reportAdServicesToken", "MAX_ATTEMPTS", "opts", "_a", "read", "token", "attempts", "write", "doFetch", "_b", "key", "value", "exports", "isTrackingUrl", "isOpenUrl", "toDeepLink", "upgradeStoredDeepLink", "TRACKING_PATH", "OPEN_PATH", "pathOf", "url", "m", "_a", "path", "answer", "deferred", "matchType", "payload", "_b", "_c", "stored", "link", "empty_exports", "init_empty", "__esmMin", "exports", "fromGoogleMobileAdsPaid", "fromGoogleMobileAdsChannel", "fromGoogleMobileAdsNativeAd", "fromMaxAdInfo", "fromCapacitorAdMob", "watchReactNativeAds", "covers", "c", "AdRevenueGate", "warn", "m", "coverage", "network", "format", "call", "raw", "key", "message", "PRECISION_BY_INDEX", "precisionOf", "_a", "text", "record", "micros", "n", "payload", "meta", "p", "currency", "valueMicros", "loaded", "channel", "event", "e", "body", "info", "i", "adFormat", "nativeModule", "rn", "name", "_d", "_b", "_c", "_e", "MAX_RN_FULLSCREEN_FORMATS", "want", "sink", "subs", "guard", "parse", "deliver", "rawOf", "v", "paidData", "sub", "nativeAds", "onNative", "emitter", "max", "names", "fromModule", "k", "s", "exports", "normalizeAdvertisingId", "fromMaxAd", "detectDebug", "isLocalPage", "skan_1", "analytics_1", "adservices_1", "deeplink_1", "adRevenue_1", "skan_2", "adservices_2", "analytics_2", "deeplink_2", "adRevenue_2", "INSTALL_SENT_KEY", "INSTALL_SENT_DEBUG_KEY", "INSTALL_ATTEMPTS_KEY", "AD_ID_SENT_KEY", "AD_ID_SENT_DEBUG_KEY", "AD_ID_PATH", "REFERRER_KEY", "QUEUE_KEY", "AD_QUEUE_KEY", "DEVICE_ID_KEY", "LAST_SESSION_KEY", "ERASED_KEY", "DEFERRED_KEY", "DEFERRED_RETRY_KEY", "DEFERRED_RETRY_WINDOW_MS", "CONSENT_KEY", "ANALYTICS_QUEUE_KEY", "ANALYTICS_SESSION_KEY", "SUPER_PROPS_KEY", "GROUPS_KEY", "ANALYTICS_PATH", "MAX_ANALYTICS_BATCH", "MAX_ANALYTICS_QUEUE", "MAX_EARLY_ANALYTICS", "MAX_BATCH", "NON_RETRYABLE_STATUS", "MAX_QUEUE", "MAX_AD_BATCH", "MAX_AD_QUEUE", "BASE_RETRY_MS", "MAX_RETRY_MS", "FLUSH_DELAY_MS", "MAX_INSTALL_ATTEMPTS", "SESSION_TIMEOUT_MS", "TRACKING_AUTHORIZATIONS", "MAX_PRECISION", "MAX_FORMAT", "ZERO_AD_ID", "raw", "id", "ad", "_b", "_a", "_c", "uuid", "c", "r", "safeLocale", "defaultStorage", "mod", "store", "key", "value", "reactNativeOs", "os", "Client", "adInfo", "max", "opts", "e", "freshInstall", "link", "want", "sink", "converted", "coverage", "name", "props", "transactionId", "n", "p", "userId", "traits", "traitsOnce", "set", "setOnce", "rest", "groupType", "groupKey", "next", "previousId", "prev", "experiment", "variant", "now", "sameVisit", "navigation", "report", "route", "off", "platform", "adUnitId", "adFormat", "event", "source", "origin", "listener", "pending", "url", "answer", "deferred", "code", "granted", "native", "fine", "coarse", "lockWindow", "cached", "referrer", "kept", "installReferrer", "until", "known", "Linking", "events", "AppState", "state", "screen", "groups", "schedule", "stored", "_d", "early", "_e", "parsed", "force", "last", "deviceId", "existing", "result", "attempts", "advertisingId", "delay", "batch", "outcome", "run", "i", "_source", "impression", "body", "path", "res", "fromInit", "status", "consent", "att", "loc", "host", "import_core", "COOKIE_PREFIX", "doc", "readCookie", "name", "d", "part", "eq", "serialize", "value", "maxAgeSeconds", "domain", "secure", "scope", "registrableDomain", "hostname", "labels", "probe", "candidate", "writeCookie", "deleteCookie", "DEVICE_ID_KEY", "INTERNAL_KEY", "MIRRORED", "MIRROR_MAX_AGE_SECONDS", "local", "BrowserStore", "persistent", "cookieDomain", "cookies", "key", "value", "_a", "_b", "_c", "readCookie", "stored", "ls", "writeCookie", "deleteCookie", "pending", "keys", "i", "k", "COOKIE_PREFIX", "KeptValue", "store", "key", "cookieDomain", "cookies", "valid", "now", "raw", "parsed", "fromCookie", "readCookie", "value", "maxAgeMs", "record", "writeCookie", "deleteCookie", "SOURCE_KEY", "SOURCE_PARAMS", "MAX_VALUE_LENGTH", "FIELD", "clean", "v", "t", "bare", "host", "sameSite", "other", "a", "b", "referrerHost", "referrer", "pageHref", "ref", "sourceFromLanding", "href", "now", "out", "params", "key", "fromUrl", "parseSource", "query", "source", "param", "field", "ts", "SourceKeeper", "store", "maxAgeMs", "cookieDomain", "cookies", "KeptValue", "landing", "CLICK_PARAM", "STORE_KEY", "CLICK_ID", "clickIdFromUrl", "href", "raw", "TrackIdKeeper", "store", "maxAgeMs", "cookieDomain", "cookies", "KeptValue", "v", "now", "id", "sampled", "rate", "random", "r", "CLS_GAP_MS", "CLS_WINDOW_MS", "INP_KEEP", "VitalsCollector", "startTime", "ms", "value", "hadRecentInput", "w", "interactionId", "duration", "prev", "minId", "min", "id", "d", "sorted", "a", "b", "out", "inp", "observe", "type", "onEntries", "extra", "_a", "PO", "list", "watchVitals", "c", "startedVisible", "activation", "nav", "lcpFinal", "finalize", "es", "e", "isEntry", "e", "GROUP_TYPE", "MAX_GROUP_TYPES", "cleanGroupType", "v", "t", "cleanGroupKey", "cleanGroups", "out", "k", "type", "key", "withGroup", "groups", "TRAIT_KEY", "MAX_TRAITS", "MAX_PROPS_BYTES", "cleanTraits", "raw", "withSuperProps", "own", "sup", "merged", "SESSION_KEY", "cleanUserId", "exposureText", "exposureProps", "experiment", "variant", "props", "takeBatch", "queue", "current", "max", "n", "userId", "fixed", "who", "SESSION_IDLE_MS", "FLUSH_EVERY_MS", "FLUSH_AT", "MAX_QUEUE", "MAX_ERRORS_PER_PAGE", "LINK_SCANNER_ERROR", "SCROLL_STEPS", "UTM", "newId", "landingSource", "href", "referrer", "_a", "src", "u", "param", "bare", "RAGE_WINDOW_MS", "RAGE_RADIUS_PX", "RAGE_THRESHOLD", "RageClickDetector", "x", "y", "b", "AnalyticsTracker", "deps", "o", "rate", "sampled", "VitalsCollector", "watchVitals", "name", "set", "setOnce", "hasSet", "hasOnce", "groupType", "groupKey", "previousId", "url", "leaving", "_b", "anonymousId", "taken", "events", "body", "res", "now", "s", "_c", "_d", "_e", "_f", "_g", "_h", "title", "g", "c", "after", "method", "original", "args", "doc", "viewport", "height", "seen", "pct", "step", "target", "el", "input", "text", "message", "stack", "reason", "DEFAULT_ENDPOINT", "SUPER_PROPS_KEY", "GROUPS_KEY", "DEFAULT_TRACK_ID_DAYS", "DAY_MS", "inBrowser", "randomId", "internalParam", "href", "v", "TraqioWeb", "opts", "_a", "_b", "_c", "_d", "cookies", "domain", "cookieDomain", "registrableDomain", "consent", "persistent", "BrowserStore", "keepMs", "TrackIdKeeper", "SourceKeeper", "optOut", "DEVICE_ID_KEY", "id", "raw", "early", "cleanTraits", "cleanGroups", "endpoint", "background", "foreground", "store", "AnalyticsTracker", "set", "once", "type", "key", "user", "prev", "name", "props", "on", "INTERNAL_KEY", "userId", "traits", "traitsOnce", "rest", "groupType", "groupKey", "next", "withGroup", "previousId", "cleanUserId", "experiment", "variant", "p", "exposureProps", "fits", "granted", "ok", "Traqio", "Traqio", "tag", "sdkKey"]
4
+ "sourcesContent": ["// iOS SKAdNetwork conversion values \u2014 the JS half.\n//\n// Be clear about what this buys you: SKAN gives Apple SIX BITS about an install,\n// delivered to the ad network (and to Traqio's postback endpoint) at least 24h\n// after the conversion window closes, and withheld entirely when the campaign is\n// too small for Apple's crowd-anonymity threshold. It is aggregated, coarse and\n// late by construction \u2014 never per-user, never real-time. This file encodes a\n// number; it does not make iOS deterministic.\n//\n// The mapping is fetched from the API rather than hardcoded in the app: the\n// server decodes postbacks with the mapping it published, so a hardcoded copy in\n// the app drifts silently and you only find out 24h later when the values come\n// back meaning the wrong thing.\n\nexport type CoarseValue = \"low\" | \"medium\" | \"high\";\n\nexport type PostbackWindowIndex = 0 | 1 | 2;\n\n/**\n * When a conversion window is closed early. Mirrors `PostbackWindow` in the API\n * (apps/api/src/skan/conversion-value.ts).\n *\n * This used to be a parameter the HOST APP passed to `updateSkanConversionValue`,\n * which meant changing when a campaign reports required shipping an app release. It\n * is configuration now: the mapping carries it, the device obeys it.\n */\nexport interface PostbackWindow {\n window: PostbackWindowIndex;\n lock: boolean;\n /** Hours since install at which to lock. null = lock on the next value update. */\n lockAfterHours?: number | null;\n}\n\n/**\n * Apple's three conversion windows, in hours since install. Mirrors\n * CONVERSION_WINDOWS in the API \u2014 the device and the console must not disagree about\n * when a window closes.\n *\n * 0 \u2014 day 0-2 (0 \u2192 48 h), the only window carrying a FINE value\n * 1 \u2014 day 3-7 (48 \u2192 168 h), coarse only\n * 2 \u2014 day 8-35 (168 \u2192 840 h), coarse only\n */\nexport const CONVERSION_WINDOWS: { window: PostbackWindowIndex; startHours: number; endHours: number }[] = [\n { window: 0, startHours: 0, endHours: 48 },\n { window: 1, startHours: 48, endHours: 168 },\n { window: 2, startHours: 168, endHours: 840 },\n];\n\n/** What `GET /skan/mapping/<sdkKey>` returns (null when the app configured none). */\nexport interface SkanMapping {\n version: number;\n mode: \"revenue\" | \"events\";\n currency: string;\n /** revenue mode: ascending lower bounds, index = fine conversion value. */\n revenueBuckets?: number[] | null;\n /** events mode: bit index \u2192 event name (max 6). */\n eventBits?: string[] | null;\n /** Optional SKAN 4 coarse tiers, as revenue thresholds. */\n coarseRevenue?: Partial<Record<CoarseValue, number>> | null;\n /** The postback schedule. Absent = Apple's own timing, nothing locked early. */\n postbackWindows?: PostbackWindow[] | null;\n}\n\n/** The window an install of this age is inside, or null past day 35. */\nexport function windowForAge(hoursSinceInstall: number): PostbackWindowIndex | null {\n const found = CONVERSION_WINDOWS.find(\n (w) => hoursSinceInstall >= w.startHours && hoursSinceInstall < w.endHours,\n );\n return found ? found.window : null;\n}\n\n/**\n * Should this update carry `lockWindow: true`? Mirrors `shouldLockWindow` in the API.\n *\n * Locking closes the current window immediately: the postback arrives sooner, at the\n * cost of every conversion the rest of the window would have seen. The console shows\n * that cost as a measurement gap before anyone turns it on.\n */\nexport function shouldLockWindow(\n windows: PostbackWindow[] | null | undefined,\n hoursSinceInstall: number,\n): boolean {\n const current = windowForAge(hoursSinceInstall);\n if (current == null || !windows || !windows.length) return false;\n const rule = windows.find((w) => w.window === current);\n if (!rule || !rule.lock) return false;\n if (rule.lockAfterHours == null) return true;\n return hoursSinceInstall >= rule.lockAfterHours;\n}\n\n/** The native surface the Expo module exposes (no-op on Android). */\nexport interface SkanNative {\n updateConversionValue(fineValue: number, coarse?: CoarseValue, lockWindow?: boolean): void;\n}\n\nconst MAX_FINE_VALUE = 63;\nconst MAX_EVENT_BITS = 6;\n\n/**\n * Highest bucket whose lower bound the revenue has reached. Mirrors\n * `fineValueForRevenue` in the API (apps/api/src/skan/conversion-value.ts) \u2014 the\n * encode and decode sides of one mapping must never disagree.\n */\nexport function fineValueForRevenue(revenue: number, buckets: number[]): number {\n let value = 0;\n for (let i = 0; i < Math.min(buckets.length, MAX_FINE_VALUE + 1); i++) {\n if (revenue >= buckets[i]) value = i;\n }\n return value;\n}\n\n/** Milestone names \u2192 the 6-bit mask, in the bit order the mapping declares. */\nexport function fineValueForEvents(events: Iterable<string>, bits: string[]): number {\n const reached = new Set(events);\n let value = 0;\n bits.slice(0, MAX_EVENT_BITS).forEach((name, i) => {\n if (reached.has(name)) value |= 1 << i;\n });\n return value;\n}\n\n/**\n * Highest configured coarse tier the revenue has reached. Returns undefined when\n * the mapping declares no tiers \u2014 the native side then derives one from the fine\n * value rather than sending nothing.\n */\nexport function coarseValueForRevenue(\n revenue: number,\n tiers: Partial<Record<CoarseValue, number>> | null | undefined,\n): CoarseValue | undefined {\n if (!tiers) return undefined;\n let best: CoarseValue | undefined;\n let bestThreshold = -Infinity;\n for (const tier of [\"low\", \"medium\", \"high\"] as const) {\n const threshold = tiers[tier];\n if (threshold != null && revenue >= threshold && threshold >= bestThreshold) {\n best = tier;\n bestThreshold = threshold;\n }\n }\n return best;\n}\n\ninterface SkanState {\n /** Lifetime revenue this install has produced, as SKAN needs a running total. */\n revenue: number;\n /** Milestone names already reached (events mode). */\n events: string[];\n /** Last fine value we asked the device to send. */\n lastFine: number | null;\n /**\n * Unix ms of the first launch we saw. The conversion-window schedule is expressed\n * in hours SINCE INSTALL, and nothing on the device tells us the install time \u2014 so\n * this is our own stand-in, written once and never moved. It is later than the true\n * install by however long the user took to open the app, which makes a lock fire\n * slightly LATE rather than early: the safe direction, since an early lock throws\n * measurement away and a late one only delays the postback.\n */\n firstSeenAt?: number;\n}\n\nconst EMPTY_STATE: SkanState = { revenue: 0, events: [], lastFine: null };\n\nexport interface SkanOptions {\n endpoint: string;\n sdkKey: string;\n native?: SkanNative;\n /** Same store the event queue uses, so the running total survives a restart. */\n storage?: { getItem(key: string): Promise<string | null>; setItem(key: string, value: string): Promise<void> };\n /** Injectable for tests; defaults to the global fetch. */\n fetchFn?: typeof fetch;\n /** Injectable clock, so the window schedule is testable without waiting 48 hours. */\n nowFn?: () => number;\n}\n\nexport const SKAN_STATE_KEY = \"traq_skan_state\";\n\n/**\n * Owns the app's SKAN conversion value: fetch the mapping, keep the running\n * total across launches, and push a new value to the device when \u2014 and only\n * when \u2014 it actually changed upward.\n *\n * Inert unless everything is in place (iOS + a native bridge + a published\n * mapping). On Android and off-device it does nothing at all, so callers never\n * have to branch on platform.\n */\nexport class Skan {\n private opts!: SkanOptions;\n private mapping: SkanMapping | null = null;\n private state: SkanState = { ...EMPTY_STATE };\n private enabled = false;\n\n async init(opts: SkanOptions): Promise<void> {\n this.opts = opts;\n this.enabled = Boolean(opts.native);\n if (!this.enabled) return;\n await this.restore();\n if (this.state.firstSeenAt == null) {\n this.state.firstSeenAt = this.now();\n await this.persist();\n }\n this.mapping = await this.fetchMapping();\n // A mapping published (or changed) after the install still applies from now\n // on: re-encode the totals we already have so the first window isn't lost.\n if (this.mapping) this.push();\n }\n\n /**\n * Add revenue this install produced. SKAN encodes a LIFETIME total, not one\n * purchase, so amounts accumulate \u2014 passing a single sale twice double-counts\n * it, same as anywhere else.\n */\n addRevenue(amount: number): void {\n if (!this.enabled || !(amount > 0) || !Number.isFinite(amount)) return;\n this.state.revenue += amount;\n void this.persist();\n this.push();\n }\n\n /** Mark a milestone reached (events mode). Repeats are idempotent. */\n markEvent(name: string): void {\n if (!this.enabled || this.state.events.includes(name)) return;\n this.state.events.push(name);\n void this.persist();\n this.push();\n }\n\n /** The mapping in force, for callers that want to show it. Null until fetched. */\n get activeMapping(): SkanMapping | null {\n return this.mapping;\n }\n\n // \u2500\u2500 internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n private push(): void {\n const m = this.mapping;\n if (!m || !this.opts.native) return;\n\n let fine: number;\n let coarse: CoarseValue | undefined;\n if (m.mode === \"events\") {\n if (!m.eventBits?.length) return;\n fine = fineValueForEvents(this.state.events, m.eventBits);\n } else {\n if (!m.revenueBuckets?.length) return;\n fine = fineValueForRevenue(this.state.revenue, m.revenueBuckets);\n coarse = coarseValueForRevenue(this.state.revenue, m.coarseRevenue);\n }\n\n // Value 0 is already on the device: the native module registers the install\n // with it on create. Re-sending it would burn the first, most valuable\n // conversion window on \"nothing happened yet\".\n if (this.state.lastFine == null && fine === 0) return;\n // The native side enforces the increase rule too, but not crossing the bridge\n // at all is what keeps a chatty app from waking SKAdNetwork on every purchase.\n if (this.state.lastFine != null && fine <= this.state.lastFine) return;\n this.state.lastFine = fine;\n void this.persist();\n this.opts.native.updateConversionValue(fine, coarse, this.lockWindowNow());\n }\n\n /**\n * Whether this update closes the current conversion window, per the schedule the\n * mapping published. Without a mapping, or with no rule for the window we are in,\n * the answer is false \u2014 Apple's own timing, which gives nothing up.\n */\n private lockWindowNow(): boolean {\n const since = this.state.firstSeenAt;\n if (since == null) return false;\n const hours = (this.now() - since) / 3_600_000;\n return shouldLockWindow(this.mapping?.postbackWindows, hours);\n }\n\n private now(): number {\n return this.opts.nowFn ? this.opts.nowFn() : Date.now();\n }\n\n private async fetchMapping(): Promise<SkanMapping | null> {\n const doFetch = this.opts.fetchFn ?? (typeof fetch === \"function\" ? fetch : undefined);\n if (!doFetch) return null;\n try {\n const res = await doFetch(`${this.opts.endpoint}/skan/mapping/${encodeURIComponent(this.opts.sdkKey)}`);\n if (!res.ok) return null;\n const body = (await res.json()) as SkanMapping | null;\n return body && typeof body === \"object\" ? body : null;\n } catch {\n // Offline at launch is normal. No mapping \u2192 we simply never set a value;\n // the install itself is still registered natively on module create.\n return null;\n }\n }\n\n private async restore(): Promise<void> {\n try {\n const raw = await this.opts.storage?.getItem(SKAN_STATE_KEY);\n if (raw) this.state = { ...EMPTY_STATE, ...(JSON.parse(raw) as SkanState) };\n } catch {\n /* corrupt/absent \u2014 start from zero */\n }\n }\n\n private async persist(): Promise<void> {\n try {\n await this.opts.storage?.setItem(SKAN_STATE_KEY, JSON.stringify(this.state));\n } catch {\n /* storage full/unavailable */\n }\n }\n}\n", "// Product analytics on an app (HQ cmwr3thk) \u2014 `capture()` and screen views, posted to\n// `POST /ingest/analytics` with the app's mobile key: what replaces PostHog in a\n// React Native / Expo app. The engine (queue, batching, retry, persistence) is the\n// Client's; this file is the pure part \u2014 what an event is, what a session is \u2014 so\n// every rule is tested without a timer or a network.\n//\n// \u26A0\uFE0F An analytics event is never a conversion: `track()` stays the conversion door\n// (`/ingest`, metered, forwarded to ad networks); `capture()` and `screen()` go to\n// their own route and their own table, which billing and forwarding never read.\n\n/** What the server stores, one event at a time (apps/api/src/product-analytics/screen.ts). */\nexport interface QueuedAnalyticsEvent {\n /**\n * `identify` carries a user's properties (`userId`, `set`, `setOnce`), `group` an\n * account's (`groupType`, `groupKey`, `set`), `alias` two ids of one person\n * (`userId`, `previousId`) \u2014 none is ever an analytics row.\n */\n kind: \"pageview\" | \"custom\" | \"identify\" | \"group\" | \"alias\";\n /** Custom events only. */\n name?: string;\n /** Epoch ms, the device clock \u2014 the server clamps it. */\n ts: number;\n /** Page and screen views and custom events: their own id, so a re-sent batch is stored once (the server keys the row on it). */\n id?: string;\n sessionId: string;\n /** The screen shown: the subject of a screen view, the context of a custom event. */\n screen?: string;\n props?: Record<string, unknown>;\n /** `identify` only: the user, and the traits to overwrite / to write once. */\n userId?: string;\n set?: Traits;\n setOnce?: Traits;\n /** Analytics events only: the B2B accounts held when it was queued (`group()`) \u2014 `{ company: \"acme\" }`. */\n groups?: Groups;\n /** `group` only: the account. */\n groupType?: string;\n groupKey?: string;\n /** `alias` only: the id the user had before `userId`. */\n previousId?: string;\n /**\n * Device-side only, never sent: the user id an event was captured under, stamped by\n * `reset()` on what was still queued \u2014 so a sign-out never re-files the signed-out\n * user's last events under nobody (or under the next user). Absent = the current one.\n */\n asUser?: string;\n}\n\n/** A user id as the server takes it (alias.ts, identify.ts): trimmed text (or a number) of 1\u2013256 characters, or null. */\nexport function cleanUserId(v: unknown): string | null {\n if (typeof v === \"number\" && Number.isFinite(v)) return String(v);\n if (typeof v !== \"string\") return null;\n const t = v.trim();\n return t && t.length <= 256 ? t : null;\n}\n\n/** Entries that are not analytics rows: no session activity, no super-properties, no accounts, no `asUser` stamp. */\nexport function isEntry(kind: QueuedAnalyticsEvent[\"kind\"]): boolean {\n return kind === \"identify\" || kind === \"group\" || kind === \"alias\";\n}\n\n/**\n * The next batch to send: the leading events captured under ONE user id (their\n * `asUser` stamp, else `current`), at most `max`, and that user id \u2014 the batch's\n * `userId` on the wire. Entries (identify, group, alias) carry their own ids and ride\n * with any batch. The stamp is stripped from what travels.\n */\nexport function nextAnalyticsBatch(queue: readonly QueuedAnalyticsEvent[], current: string | undefined, max: number): { events: QueuedAnalyticsEvent[]; userId: string | undefined; taken: number } {\n let userId: string | undefined;\n let fixed = false;\n const events: QueuedAnalyticsEvent[] = [];\n for (const e of queue) {\n if (events.length >= max) break;\n if (!isEntry(e.kind)) {\n const who = e.asUser !== undefined ? e.asUser || undefined : current;\n if (!fixed) {\n userId = who;\n fixed = true;\n } else if (who !== userId) break;\n }\n const { asUser: _asUser, ...wire } = e;\n events.push(wire);\n }\n return { events, userId: fixed ? userId : current, taken: events.length };\n}\n\n/** Experiment name and variant as `$exposure` carries them: trimmed, 1\u2013200 characters; a number or a boolean variant as text. */\nconst MAX_EXPOSURE_TEXT = 200;\nfunction exposureText(v: unknown): string | null {\n const t = typeof v === \"string\" ? v.trim() : (typeof v === \"number\" && Number.isFinite(v)) || typeof v === \"boolean\" ? String(v) : \"\";\n return t && t.length <= MAX_EXPOSURE_TEXT ? t : null;\n}\n\n/**\n * `exposure(experiment, variant, props)`'s properties: `{ ...props, experiment,\n * variant }` \u2014 the two named ones win over a prop of the same name \u2014 or null when the\n * experiment or the variant is empty or over 200 characters. What the console's\n * experiment analysis reads by default (docs/PRODUCT_ANALYTICS.md, experiments).\n */\nexport function exposureProps(experiment: unknown, variant: unknown, props?: Record<string, unknown>): Record<string, unknown> | null {\n const e = exposureText(experiment);\n const v = exposureText(variant);\n if (!e || !v) return null;\n return { ...(props && typeof props === \"object\" && !Array.isArray(props) ? props : {}), experiment: e, variant: v };\n}\n\n/** The accounts a user belongs to, by group type: `{ company: \"acme\", workspace: \"w_1\" }`. */\nexport type Groups = Record<string, string>;\n\n/** The server's rule for a group type (apps/api/src/product-analytics/groups.ts). */\nconst GROUP_TYPE = /^[a-z][a-z0-9_]{0,29}$/;\n/** Group types held at once \u2014 a new one past it is ignored. */\nexport const MAX_GROUP_TYPES = 5;\nconst MAX_GROUP_KEY = 256;\n\n/** A group type as the server takes it (`company`, `workspace`), or null. */\nexport function cleanGroupType(v: unknown): string | null {\n if (typeof v !== \"string\") return null;\n const t = v.trim();\n return GROUP_TYPE.test(t) ? t : null;\n}\n\n/** An account key: trimmed text (or a number) of 1\u2013256 characters, or null. */\nexport function cleanGroupKey(v: unknown): string | null {\n if (typeof v === \"number\" && Number.isFinite(v)) return String(v);\n if (typeof v !== \"string\") return null;\n const t = v.trim();\n return t && t.length <= MAX_GROUP_KEY ? t : null;\n}\n\n/** Stored groups re-read through the same rules: valid pairs only, at most 5. */\nexport function cleanGroups(v: unknown): Groups {\n const out: Groups = {};\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) return out;\n for (const [t, k] of Object.entries(v as Record<string, unknown>)) {\n if (Object.keys(out).length >= MAX_GROUP_TYPES) break;\n const type = cleanGroupType(t);\n const key = cleanGroupKey(k);\n if (type && key) out[type] = key;\n }\n return out;\n}\n\n/**\n * The groups after `group(type, key)`: null when the call must be ignored (a bad type\n * or key, or a 6th NEW type). `changed` = the key of that type is new \u2014 with traits,\n * the only cases worth an entry on the wire.\n */\nexport function withGroup(groups: Groups, type: unknown, key: unknown): { groups: Groups; type: string; key: string; changed: boolean } | null {\n const t = cleanGroupType(type);\n const k = cleanGroupKey(key);\n if (!t || !k) return null;\n if (!(t in groups) && Object.keys(groups).length >= MAX_GROUP_TYPES) return null;\n return { groups: { ...groups, [t]: k }, type: t, key: k, changed: groups[t] !== k };\n}\n\n/** A user property or super-property value: text, a number or a boolean \u2014 a label to segment by. */\nexport type TraitValue = string | number | boolean;\nexport type Traits = Record<string, TraitValue>;\n\n/** The server's key rule for a property (apps/api/src/product-analytics/prop-key.ts). */\nconst TRAIT_KEY = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/;\n/** Traits one identify call carries at most, and super-properties kept at most. */\nexport const MAX_TRAITS = 50;\nconst MAX_TRAIT_TEXT = 200;\n\n/**\n * Traits as the server keeps them (identify.ts): valid keys, values that are text\n * (cut at 200), a finite number or a boolean. Anything else is dropped here rather\n * than on the server, so a nested object never travels. At most 50 keys.\n */\nexport function cleanTraits(v: unknown): Traits {\n const out: Traits = {};\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) return out;\n for (const [k, raw] of Object.entries(v as Record<string, unknown>)) {\n if (Object.keys(out).length >= MAX_TRAITS) break;\n if (!TRAIT_KEY.test(k)) continue;\n if (typeof raw === \"string\") {\n const t = raw.trim();\n if (t) out[k] = t.slice(0, MAX_TRAIT_TEXT);\n } else if ((typeof raw === \"number\" && Number.isFinite(raw)) || typeof raw === \"boolean\") {\n out[k] = raw;\n }\n }\n return out;\n}\n\n/**\n * An event's properties with the super-properties under them: the event's own win.\n * Over the 4 KB cap, the event's own properties alone.\n */\nexport function withSuperProps(own: Record<string, unknown> | undefined, sup: Traits): Record<string, unknown> | undefined {\n if (!Object.keys(sup).length) return own;\n return cleanProps({ ...sup, ...(own ?? {}) }) ?? own;\n}\n\nexport interface AnalyticsSession {\n id: string;\n /** Last activity, epoch ms. */\n last: number;\n}\n\n/** 30 minutes without activity end a session \u2014 the web SDK's and PostHog's rule. */\nexport const ANALYTICS_SESSION_IDLE_MS = 30 * 60 * 1000;\n/** The server's own caps (screen.ts): longer is refused or cut there. */\nexport const MAX_EVENT_NAME = 128;\nexport const MAX_SCREEN_NAME = 512;\nexport const MAX_PROPS_BYTES = 4096;\n\n/** The one `$` name a custom event may carry: an experiment exposure, `$exposure { experiment, variant }`. */\nexport const EXPOSURE_EVENT = \"$exposure\";\n\n/** A custom event name the server will take, or null: non-empty, \u2264 128, never `$\u2026` (reserved) but `$exposure`. */\nexport function cleanEventName(name: unknown): string | null {\n if (typeof name !== \"string\") return null;\n const n = name.trim();\n if (!n || n.length > MAX_EVENT_NAME || (n.startsWith(\"$\") && n !== EXPOSURE_EVENT)) return null;\n return n;\n}\n\n/** A screen name as stored in the `page` dimension, or null. */\nexport function cleanScreenName(name: unknown): string | null {\n if (typeof name !== \"string\") return null;\n const n = name.trim();\n return n ? n.slice(0, MAX_SCREEN_NAME) : null;\n}\n\n/**\n * Properties as they can travel: a plain object that survives JSON, under the\n * server's cap \u2014 else none. Checked at capture time, because a cyclic object or a\n * BigInt handed by the app would otherwise throw later, inside the persisted\n * queue's `JSON.stringify`, and take every queued event down with it.\n */\nexport function cleanProps(props: unknown): Record<string, unknown> | undefined {\n if (typeof props !== \"object\" || props === null || Array.isArray(props)) return undefined;\n try {\n const json = JSON.stringify(props);\n if (!json || json === \"{}\" || json.length > MAX_PROPS_BYTES) return undefined;\n return JSON.parse(json) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n\n/** The session this activity belongs to: the current one, touched, or a new one after 30 idle minutes. */\nexport function touchSession(current: AnalyticsSession | null, now: number, newId: () => string): AnalyticsSession {\n if (current && typeof current.id === \"string\" && typeof current.last === \"number\" && now - current.last <= ANALYTICS_SESSION_IDLE_MS && now >= current.last - 60_000) {\n return { id: current.id, last: Math.max(now, current.last) };\n }\n return { id: newId(), last: now };\n}\n\n/** A persisted session, read back \u2014 anything malformed is no session. */\nexport function parseSession(raw: string | null | undefined): AnalyticsSession | null {\n if (!raw) return null;\n try {\n const s = JSON.parse(raw) as Partial<AnalyticsSession>;\n return typeof s.id === \"string\" && typeof s.last === \"number\" ? { id: s.id, last: s.last } : null;\n } catch {\n return null;\n }\n}\n\n/**\n * React Navigation's container ref, as far as screen tracking needs it \u2014 typed by\n * shape so neither `@react-navigation/native` nor `expo-router` becomes a dependency.\n */\nexport interface NavigationRefLike {\n addListener(event: \"state\", listener: () => void): (() => void) | undefined | void;\n getCurrentRoute(): { name: string } | undefined | null;\n}\n", "// Apple Ads (Search Ads) attribution \u2014 the JS half.\n//\n// What it buys: the one DETERMINISTIC attribution iOS still allows. Every other iOS\n// signal is SKAdNetwork, which is aggregated, six bits wide and 24h+ late. Apple\n// Search Ads self-attributes through the AdServices framework, and any developer may\n// resolve their own app's tokens \u2014 no partner programme, no allowlist.\n//\n// What it is NOT: an identifier. `AAAttribution.attributionToken()` returns an\n// opaque, single-purpose claim ticket valid for **24 hours**. No IDFA, no ATT prompt\n// of our own, no fingerprinting. Apple decides how much of the answer to return from\n// the ATT status the user already chose \u2014 detailed with consent, standard without.\n//\n// Why the SERVER resolves it: Apple answers 404 until the token is known on its side,\n// which right after an install is the normal first answer. That retry has to outlive\n// the app process, so the device's only job is to hand the token over before it\n// expires. See apps/api/src/apple-ads/.\n//\n// https://developer.apple.com/documentation/adservices\n\n/** Native surface the Expo module exposes. Absent on Android and pre-iOS 14.3. */\nexport interface AdServicesNative {\n /** The opaque 24h token, or null when the framework has none on this device. */\n getAttributionToken(): Promise<string | null>;\n}\n\nexport interface AdServicesOptions {\n endpoint: string;\n sdkKey: string;\n deviceId?: string;\n userId?: string;\n native?: AdServicesNative;\n /** Same store the event queue uses, so \"already sent\" survives a restart. */\n storage?: { getItem(key: string): Promise<string | null>; setItem(key: string, value: string): Promise<void> };\n /** Injectable for tests; defaults to the global fetch. */\n fetchFn?: typeof fetch;\n /** A debug build (see `InitOptions.debug`): the server then drops the token. */\n debug?: boolean;\n}\n\nexport const ADSERVICES_SENT_KEY = \"traq_adservices_sent\";\nexport const ADSERVICES_ATTEMPTS_KEY = \"traq_adservices_attempts\";\n\n/**\n * How many launches we keep asking before giving up on this install. The framework\n * can answer later in an install's life, but on a device where it never will \u2014\n * a simulator, an install with no attribution record at all, which is MOST installs \u2014\n * asking forever is work with no answer to it.\n */\nconst MAX_ATTEMPTS = 5;\n\n/**\n * Hand the token over, at most once per install.\n *\n * Returns what happened, so a host app can debug the integration without reading our\n * logs. Never throws: there is no user-visible consequence to any outcome here, and\n * an exception in `init()` would take the whole SDK down for a signal most installs\n * do not have.\n */\nexport async function reportAdServicesToken(\n opts: AdServicesOptions,\n): Promise<\"sent\" | \"already-sent\" | \"no-token\" | \"unsupported\" | \"post-failed\"> {\n if (!opts.native?.getAttributionToken) return \"unsupported\";\n\n if (await read(opts, ADSERVICES_SENT_KEY)) return \"already-sent\";\n\n let token: string | null = null;\n try {\n token = await opts.native.getAttributionToken();\n } catch {\n // The framework throws on a device with nothing to give. Treated as \"no token\".\n }\n\n if (!token || !token.trim()) {\n const attempts = Number(await read(opts, ADSERVICES_ATTEMPTS_KEY)) || 0;\n await write(opts, ADSERVICES_ATTEMPTS_KEY, String(attempts + 1));\n // Bounded: stop asking a device that will never answer.\n if (attempts + 1 >= MAX_ATTEMPTS) await write(opts, ADSERVICES_SENT_KEY, \"1\");\n return \"no-token\";\n }\n\n const doFetch = opts.fetchFn ?? (typeof fetch === \"function\" ? fetch : undefined);\n if (!doFetch) return \"post-failed\";\n\n try {\n const res = await doFetch(`${opts.endpoint}/ingest/adservices`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n sdkKey: opts.sdkKey,\n token: token.trim(),\n deviceId: opts.deviceId,\n appUserId: opts.userId,\n ...(opts.debug ? { debug: true } : {}),\n }),\n });\n if (!res.ok) return \"post-failed\";\n } catch {\n return \"post-failed\";\n }\n\n // Only mark sent on success, so a failed post retries on the next launch \u2014 inside\n // the 24h window, which is what makes the retry worth anything.\n await write(opts, ADSERVICES_SENT_KEY, \"1\");\n return \"sent\";\n}\n\nasync function read(opts: AdServicesOptions, key: string): Promise<string | null> {\n try {\n return (await opts.storage?.getItem(key)) ?? null;\n } catch {\n return null;\n }\n}\n\nasync function write(opts: AdServicesOptions, key: string, value: string): Promise<void> {\n try {\n await opts.storage?.setItem(key, value);\n } catch {\n /* storage full/unavailable */\n }\n}\n", "// Deep linking \u2014 the SDK half (docs/DEEP_LINKING.md).\n//\n// Two moments, one callback:\n// - DIRECT: a universal link / App Link (`https://<your host>/c/<code>`) opened\n// the installed app. The OS never hit our server, so the SDK resolves the\n// code \u2014 which also records the click the OS skipped.\n// - DEFERRED: the app was installed FROM a link. On the very first launch the\n// SDK asks what that link carried. Three deterministic carriers, then one\n// probabilistic fallback (docs/DEEP_LINKING.md \u00A710):\n// \u00B7 `referrer` \u2014 Android: the Play Install Referrer;\n// \u00B7 `link` \u2014 iOS: the landing page's \u00AB Open in <app> \u00BB / Smart App Banner,\n// a universal link `https://<host>/o/<clickId>`;\n// \u00B7 `code` \u2014 the code the landing page showed, typed in the app\n// (`Traqio.redeemDeepLinkCode`);\n// \u00B7 `probabilistic` \u2014 same network + same coarse device inside the hour,\n// ONLY when the user consented (`setConsent(true)`) and the app turned\n// the IP match on in the console. Comes with a `confidence`.\n//\n// Privacy: no pasteboard, no IDFA. The referrer already travels with the install;\n// the URL is the one that opened the app; the device's OS version and model are\n// sent with the deferred ask so the server can compare them with the tap's.\n\n/** How the link was found. Everything but `probabilistic` is deterministic. */\nexport type DeepLinkMatchType = \"referrer\" | \"link\" | \"code\" | \"probabilistic\";\n\n/** What the link carried. */\nexport interface DeepLinkPayload {\n /**\n * The destination set on the link in the console \u2014 an in-app path (\"/invite\")\n * or an app URL (\"myapp://invite\"). Null when the link sets none.\n */\n deepLink: string | null;\n /** `deep_link_value` of the shared URL \u2014 e.g. an invite token. Null when absent. */\n value: string | null;\n /** `deep_link_sub1..10` of the shared URL, and `ref` for a short link's recipient. */\n params: Record<string, string>;\n}\n\n/** A resolved deep link, as `onDeepLink` and `getDeferredDeepLink` hand it to the app. */\nexport interface DeepLink {\n /** What the link carried \u2014 read `payload.value` for a per-share token. */\n payload: DeepLinkPayload;\n /** How it was found. Treat `probabilistic` as a guess (see `confidence`). */\n matchType: DeepLinkMatchType;\n /** `high` | `medium` | `low` on a probabilistic match, null on a deterministic one. */\n confidence: \"high\" | \"medium\" | \"low\" | null;\n /** True when the link was tapped BEFORE the install; false when it opened the installed app. */\n deferred: boolean;\n /** The link's slug (the `<code>` of `/c/<code>`). */\n code: string | null;\n /** The URL that opened the app (direct opens and `/o/` links only). */\n url?: string;\n /** @deprecated same as `payload.deepLink`. */\n deepLink: string | null;\n /** @deprecated read `matchType` \u2014 `ip_match` is the old name of `probabilistic`. */\n via: \"referrer\" | \"ip_match\" | \"link\" | \"code\";\n}\n\n/** What `/deeplink/deferred`, `/deeplink/open` and `/deeplink/code` answer. */\nexport interface DeepLinkAnswer {\n matched: boolean;\n matchType?: DeepLinkMatchType | null;\n payload?: DeepLinkPayload | null;\n confidence?: \"high\" | \"medium\" | \"low\" | null;\n via: \"referrer\" | \"ip_match\" | \"link\" | \"code\" | null;\n code: string | null;\n deepLink: string | null;\n}\n\n// Mirrors `parseDeepLinkUrl` in apps/api/src/tracking/link-rules.ts. Checked on\n// the device so the app's OWN URLs (most of what opens an app) never leave it.\nconst TRACKING_PATH = /^\\/c\\/[A-Za-z0-9_-]{1,50}\\/?$/;\nconst OPEN_PATH = /^\\/o\\/[0-9a-fA-F-]{36}\\/?$/;\n\nfunction pathOf(url: string): string | null {\n const m = /^https?:\\/\\/[^/?#]+(\\/[^?#]*)?/i.exec(url);\n return m ? (m[1] ?? \"\") : null;\n}\n\n/**\n * True when `url` is one of our links: a tracking link (`https://<host>/c/<code>`)\n * or the iOS landing page's \u00AB Open in app \u00BB link (`https://<host>/o/<clickId>`).\n */\nexport function isTrackingUrl(url: string): boolean {\n const path = pathOf(url);\n return path !== null && (TRACKING_PATH.test(path) || OPEN_PATH.test(path));\n}\n\n/** The landing page's universal link: it carries a click tapped BEFORE the install. */\nexport function isOpenUrl(url: string): boolean {\n const path = pathOf(url);\n return path !== null && OPEN_PATH.test(path);\n}\n\n/**\n * An API answer \u2192 the callback's shape, or null when nothing matched. Reads the\n * pre-0.2 answer too (no `matchType` / `payload`), so a newer SDK against an older\n * API still works.\n */\nexport function toDeepLink(answer: DeepLinkAnswer | null, deferred: boolean, url?: string): DeepLink | null {\n if (!answer?.matched || !answer.via) return null;\n const matchType: DeepLinkMatchType = answer.matchType ?? (answer.via === \"ip_match\" ? \"probabilistic\" : answer.via);\n const payload: DeepLinkPayload = answer.payload ?? { deepLink: answer.deepLink, value: null, params: {} };\n return {\n payload,\n matchType,\n confidence: matchType === \"probabilistic\" ? (answer.confidence ?? \"low\") : null,\n deferred,\n code: answer.code,\n deepLink: payload.deepLink,\n via: answer.via,\n ...(url ? { url } : {}),\n };\n}\n\n/** A deferred link stored by SDK 0.1.x (no `payload` / `matchType`) \u2192 today's shape. */\nexport function upgradeStoredDeepLink(stored: unknown): DeepLink | null {\n if (!stored || typeof stored !== \"object\") return null;\n const link = stored as Partial<DeepLink> & { via?: DeepLink[\"via\"] };\n if (link.payload && link.matchType) return link as DeepLink;\n if (!link.via) return null;\n return toDeepLink({ matched: true, via: link.via, code: link.code ?? null, deepLink: link.deepLink ?? null }, link.deferred ?? true, link.url);\n}\n", "// Stands in for `react-native` and `@react-native-async-storage/async-storage` in the\n// bundle. @traqio/core reaches for both inside try/catch (they are how it finds\n// AppState, Linking and AsyncStorage on React Native); in a browser they must resolve\n// to nothing, never to a bare `require` a consumer's bundler would try to follow.\nexport {};\n", "// Automatic ad revenue capture (HQ cmwfo9pd): `Traqio.init({ adRevenue: { admob: true,\n// applovinMax: true } })` and the paid events of the ad SDKs the app already uses reach\n// `trackAdRevenue` / `trackMaxAdRevenue` without a line per ad.\n//\n// Nothing here imports an ad SDK. React Native's own event channels are read, the\n// same channels the ad libraries' JS listens to, so an app without the library\n// simply never receives an event. The payload shapes are pinned by\n// adRevenue.test.ts against the libraries' native sources: if a library changes\n// them, the contract test is where it shows.\n\n// `require` is provided by the React Native / Metro runtime. A require inside\n// try/catch is an optional dependency for Metro.\ndeclare const require: (module: string) => any;\n\nimport type { AdRevenue, MaxAdRevenue } from \"./index\";\n\n/** `InitOptions.adRevenue`: which ad SDKs to listen to. */\nexport interface AdRevenueOptions {\n /** Google Mobile Ads (AdMob / Ad Manager). */\n admob?: boolean;\n /** AppLovin MAX. */\n applovinMax?: boolean;\n}\n\n/**\n * Where a watcher hands what it captured. `raw` is the ad library's own event\n * object, when there is one: the same object handed to two listeners is one\n * impression, never two (see `AdRevenueGate.first`).\n */\nexport interface AdRevenueSink {\n admob(ad: AdRevenue, raw?: unknown): void;\n applovinMax(ad: MaxAdRevenue, raw?: unknown): void;\n}\n\n/**\n * What a watcher actually captures, per network: `true` = every format, a list =\n * only those formats (React Native: a `<BannerAd>` reports through its own prop),\n * `false` / absent = nothing (the ad library is not there). `AdRevenueOptions`\n * itself is a valid coverage: a bridge that answers nothing covers what was asked.\n */\nexport interface AdRevenueCoverage {\n admob?: boolean | readonly string[];\n applovinMax?: boolean | readonly string[];\n}\n\nexport type AdNetwork = keyof AdRevenueCoverage;\n\n/** How an impression reached the queue \u2014 sent to the server's dedup net. */\nexport type AdRevenueOrigin = \"auto\" | \"manual\";\n\nfunction covers(c: boolean | readonly string[] | undefined): boolean {\n return Array.isArray(c) ? c.length > 0 : c === true;\n}\n\n/**\n * The one rule against double counting (HQ cmwfq3ij): once `adRevenue` captures a\n * network, Traqio owns that network's impressions.\n *\n * - A MANUAL call (`trackAdRevenue`, `trackMaxAdRevenue`) for a captured network is\n * ignored, with one warning in the log. Chosen over deduplicating per impression\n * because neither AdMob's AdValue nor MAX's AdInfo carries an impression id: a key\n * made of amount + ad unit + time would merge two real banners that happened to\n * pay the same in the same second \u2014 a silent undercount \u2014 where ignoring is\n * deterministic and says so in the log.\n * - A ONE-LINE HELPER (`admobPaid`, `maxRevenuePaid`) exists for the formats the\n * watcher cannot reach. Pointed at a format the watcher already captures, it is\n * ignored the same way.\n * - The same event OBJECT reaching both the watcher and a helper (an app that\n * plugged the helper into the global listener the watcher also hears) is one\n * impression: the first path takes it, the second sees it was taken.\n */\nexport class AdRevenueGate {\n private coverage: AdRevenueCoverage = {};\n private readonly warned = new Set<string>();\n private readonly seen = new WeakSet<object>();\n\n constructor(private readonly warn: (message: string) => void = (m) => console.warn(m)) {}\n\n arm(coverage: AdRevenueCoverage): void {\n this.coverage = { ...coverage };\n }\n\n /** Does the automatic capture own this network (any format)? */\n captures(network: AdNetwork): boolean {\n return covers(this.coverage[network]);\n }\n\n /** Does the automatic capture own this format of the network? */\n capturesFormat(network: AdNetwork, format: string | undefined): boolean {\n const c = this.coverage[network];\n if (c === true) return true;\n return Array.isArray(c) && format !== undefined && c.includes(format);\n }\n\n /** A public manual tracker: allowed only for a network nothing captures. */\n manual(network: AdNetwork, call: string): boolean {\n if (!this.captures(network)) return true;\n this.warnOnce(`manual:${network}`, `[traqio] adRevenue.${network} is on: manual ${call}() ignored \u2014 Traqio already captures this network, remove the call.`);\n return false;\n }\n\n /** A one-line helper: allowed for the formats the watcher does not capture, once per event. */\n helper(network: AdNetwork, format: string | undefined, raw: unknown, call: string): boolean {\n if (this.capturesFormat(network, format)) {\n this.warnOnce(`helper:${network}:${format}`, `[traqio] adRevenue.${network} already captures ${format} ads: ${call} ignored for them, keep it on the formats it is documented for.`);\n return false;\n }\n return this.first(raw);\n }\n\n /** True the first time this event object is seen (non-objects always pass). */\n first(raw: unknown): boolean {\n if (!raw || typeof raw !== \"object\") return true;\n if (this.seen.has(raw)) return false;\n this.seen.add(raw);\n return true;\n }\n\n private warnOnce(key: string, message: string): void {\n if (this.warned.has(key)) return;\n this.warned.add(key);\n try {\n this.warn(message);\n } catch {\n /* a logger that throws is not our concern */\n }\n }\n}\n\ntype AdFormat = NonNullable<AdRevenue[\"adFormat\"]>;\ntype Precision = NonNullable<AdRevenue[\"precision\"]>;\n\n// AdValue.PrecisionType (Android) and GADAdValuePrecision (iOS) share the numbering.\nconst PRECISION_BY_INDEX: readonly Precision[] = [\"unknown\", \"estimated\", \"publisher_provided\", \"precise\"];\n\nfunction precisionOf(raw: unknown): Precision {\n return typeof raw === \"number\" ? PRECISION_BY_INDEX[raw] ?? \"unknown\" : \"unknown\";\n}\n\nfunction text(raw: unknown): string | undefined {\n return typeof raw === \"string\" && raw.trim() ? raw : undefined;\n}\n\nfunction record(raw: unknown): Record<string, unknown> | undefined {\n return raw && typeof raw === \"object\" ? (raw as Record<string, unknown>) : undefined;\n}\n\n/** A non-negative integer amount of micros, from a number or a decimal string. */\nfunction micros(raw: unknown): number | undefined {\n const n = typeof raw === \"string\" && /^\\d+$/.test(raw.trim()) ? Number(raw) : raw;\n return typeof n === \"number\" && Number.isSafeInteger(n) && n >= 0 ? n : undefined;\n}\n\n// \u2500\u2500 react-native-google-mobile-ads \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * The four native channels react-native-google-mobile-ads emits EVERY full-screen\n * ad's events on (src/MobileAds.ts `nativeEvents`). React Native\n * prefixes them `rnapp_` (RNRCTEventEmitter.mm / ReactNativeEventEmitter.java).\n */\nexport const GMA_FULLSCREEN_CHANNELS: Readonly<Record<string, AdFormat>> = {\n rnapp_google_mobile_ads_app_open_event: \"app_open\",\n rnapp_google_mobile_ads_interstitial_event: \"interstitial\",\n rnapp_google_mobile_ads_rewarded_event: \"rewarded\",\n rnapp_google_mobile_ads_rewarded_interstitial_event: \"rewarded_interstitial\",\n};\n\n/** The first react-native-google-mobile-ads with `AdEventType.PAID` and `onPaid` (commit 969dbfac, 2023-11). */\nexport const GMA_MIN_VERSION = \"12.4.0\";\n\n/**\n * One PAID payload of react-native-google-mobile-ads \u2014 `AdEventType.PAID`, a\n * banner's `onPaid`, a native ad's `paid`. Every version sends `value` in currency\n * UNITS (the native side multiplied the micros by 1e-6) with `precision` as a\n * number; v17 adds the exact `valueMicros` (a string on Android, null on iOS) and a compact\n * `responseInfo`. The exact micros win when present, so nothing is lost twice.\n */\nexport function fromGoogleMobileAdsPaid(\n payload: unknown,\n meta: { adUnitId?: string; adFormat?: AdFormat } = {},\n): AdRevenue | undefined {\n const p = record(payload);\n if (!p) return undefined;\n const currency = text(p.currency);\n if (!currency) return undefined;\n let valueMicros = micros(p.valueMicros);\n if (valueMicros === undefined) {\n if (!(typeof p.value === \"number\" && Number.isFinite(p.value) && p.value >= 0)) return undefined;\n // Back to micros, rounded to the micro and never earlier: a banner is ~20 micros.\n valueMicros = Math.round(p.value * 1_000_000);\n }\n const loaded = record(record(p.responseInfo)?.loadedAdapterResponse);\n return {\n valueMicros,\n currency,\n precision: precisionOf(p.precision),\n adUnitId: meta.adUnitId,\n adFormat: meta.adFormat,\n adSourceName: text(loaded?.adSourceName),\n };\n}\n\n/**\n * One event of a full-screen channel: `{ adUnitId, requestId, body: { type, data } }`.\n * Only `type: \"paid\"` is revenue; loads, clicks and closes ride the same channel.\n */\nexport function fromGoogleMobileAdsChannel(channel: string, event: unknown): AdRevenue | undefined {\n const e = record(event);\n const body = record(e?.body);\n if (!e || body?.type !== \"paid\") return undefined;\n return fromGoogleMobileAdsPaid(body.data, { adUnitId: text(e.adUnitId), adFormat: GMA_FULLSCREEN_CHANNELS[channel] });\n}\n\n/** One native-ad event: `{ type, responseId, ...data }` (no ad unit id in it). */\nexport function fromGoogleMobileAdsNativeAd(event: unknown): AdRevenue | undefined {\n const e = record(event);\n if (e?.type !== \"paid\") return undefined;\n return fromGoogleMobileAdsPaid(e, { adFormat: \"native\" });\n}\n\n// \u2500\u2500 AppLovin MAX \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * react-native-applovin-max's global revenue events, one per format\n * (AppLovinMAXAdEvents.java). The library keeps ONE listener per event for the\n * app; Traqio subscribes to the module's emitter directly, beside it, so it never\n * replaces the app's own listener.\n */\nexport const MAX_RN_REVENUE_EVENTS = [\n \"OnBannerAdRevenuePaid\",\n \"OnMRecAdRevenuePaid\",\n \"OnInterstitialAdRevenuePaid\",\n \"OnRewardedAdRevenuePaid\",\n \"OnAppOpenAdRevenuePaid\",\n] as const;\n\n/** The oldest react-native-applovin-max whose revenue events and AdInfo the parser reads. */\nexport const MAX_RN_MIN_VERSION = \"5.0.0\";\n\n/**\n * MAX's AdInfo (`{ adUnitId, adFormat, networkName, revenue, revenuePrecision }`)\n * \u2014 the React Native, Capacitor and Cordova plugins all name it so.\n */\nexport function fromMaxAdInfo(info: unknown): MaxAdRevenue | undefined {\n const i = record(info);\n if (!i || typeof i.revenue !== \"number\") return undefined;\n return {\n revenue: i.revenue,\n revenuePrecision: text(i.revenuePrecision),\n adUnitId: text(i.adUnitId),\n format: text(i.adFormat),\n networkName: text(i.networkName),\n };\n}\n\n// \u2500\u2500 @capacitor-community/admob \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * @capacitor-community/admob (8.1.0+, \"impression-level ad revenue #433\") emits a paid event per format. The full-screen\n * formats file it under their `\u2026AdImpression` name, banner and native ads under\n * `\u2026AdPaid`. The banner ALSO fires an empty `bannerAdImpression`, which the parser\n * rejects for lack of an amount.\n */\nexport const CAPACITOR_ADMOB_PAID_EVENTS: Readonly<Record<string, AdFormat>> = {\n bannerAdPaid: \"banner\",\n nativeAdPaid: \"native\",\n interstitialAdImpression: \"interstitial\",\n onRewardedVideoAdImpression: \"rewarded\",\n onRewardedInterstitialAdImpression: \"rewarded_interstitial\",\n appOpenAdImpression: \"app_open\",\n};\n\n/** `AdMobRevenueData`: `{ adUnitId, valueMicros, currencyCode, precision, networkName }`. */\nexport function fromCapacitorAdMob(event: unknown, adFormat?: AdFormat): AdRevenue | undefined {\n const e = record(event);\n const valueMicros = micros(e?.valueMicros);\n const currency = text(e?.currencyCode);\n if (!e || valueMicros === undefined || !currency) return undefined;\n return {\n valueMicros,\n currency,\n precision: precisionOf(e.precision),\n adUnitId: text(e.adUnitId),\n adFormat,\n // The mediation ADAPTER class here, not the source's display name \u2014 still\n // the only thing telling AdMob's own demand from a mediated network.\n adSourceName: text(e.networkName),\n };\n}\n\n// \u2500\u2500 React Native watcher \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The slice of `react-native` the watcher uses \u2014 injected by the tests. */\nexport interface ReactNativeEvents {\n DeviceEventEmitter?: { addListener(event: string, cb: (e: unknown) => void): { remove(): void } };\n NativeEventEmitter?: new (module?: unknown) => { addListener(event: string, cb: (e: unknown) => void): { remove(): void } };\n NativeModules?: Record<string, any>;\n TurboModuleRegistry?: { get?(name: string): any };\n Platform?: { OS?: string };\n}\n\nfunction nativeModule(rn: ReactNativeEvents, name: string): any {\n try {\n return rn.TurboModuleRegistry?.get?.(name) ?? rn.NativeModules?.[name];\n } catch {\n return rn.NativeModules?.[name];\n }\n}\n\n/** What `watchReactNativeAds` captures, and how to stop it. */\nexport interface ReactNativeAdWatch {\n coverage: AdRevenueCoverage;\n stop(): void;\n}\n\n/** The full-screen formats a react-native-applovin-max global event always is. */\nconst MAX_RN_FULLSCREEN_FORMATS = [\"interstitial\", \"rewarded\", \"rewarded_interstitial\", \"app_open\"] as const;\n\n/**\n * Subscribes to the ad libraries' React Native channels. Returns what it covers\n * (the gate's input) and the unsubscribe. A library that is not installed has no\n * channel: nothing arrives, nothing fails.\n */\nexport function watchReactNativeAds(want: AdRevenueOptions, sink: AdRevenueSink, rn?: ReactNativeEvents): ReactNativeAdWatch {\n if (!rn) {\n try {\n rn = require(\"react-native\") as ReactNativeEvents;\n } catch {\n // Not React Native: Capacitor and the web bring their own.\n return { coverage: {}, stop: () => undefined };\n }\n }\n const subs: { remove(): void }[] = [];\n const coverage: { admob?: string[]; applovinMax?: string[] } = {};\n const guard =\n <T>(parse: (e: unknown) => T | undefined, deliver: (v: T, raw: unknown) => void, rawOf: (e: unknown) => unknown = (e) => e) =>\n (e: unknown): void => {\n try {\n const v = parse(e);\n if (v) deliver(v, rawOf(e));\n } catch {\n // Measurement is never worth a crash in the app's ad callback.\n }\n };\n // The PAID payload the library hands its own listeners is `body.data`.\n const paidData = (e: unknown): unknown => record(record(e)?.body)?.data;\n\n if (want.admob) {\n // Interstitial, rewarded, rewarded interstitial, app open: every ad, whatever\n // screen created it. Banners report through their own `onPaid` prop \u2014 see\n // `Traqio.admobPaid()`.\n coverage.admob = [];\n for (const [channel, format] of Object.entries(GMA_FULLSCREEN_CHANNELS)) {\n const sub = rn.DeviceEventEmitter?.addListener(channel, guard((e) => fromGoogleMobileAdsChannel(channel, e), sink.admob, paidData));\n if (sub) {\n subs.push(sub);\n coverage.admob.push(format);\n }\n }\n // Native ads: one module-wide emitter, filtered per ad by the library itself.\n const nativeAds = nativeModule(rn, \"RNGoogleMobileAdsNativeModule\");\n const onNative = guard(fromGoogleMobileAdsNativeAd, sink.admob);\n try {\n if (nativeAds && typeof nativeAds.onAdEvent === \"function\") {\n subs.push(nativeAds.onAdEvent(onNative));\n coverage.admob.push(\"native\");\n } else if (nativeAds && rn.NativeEventEmitter) {\n // Same branch the library takes on the old architecture.\n const emitter = new rn.NativeEventEmitter(rn.Platform?.OS === \"ios\" ? nativeAds : undefined);\n subs.push(emitter.addListener(\"RNGMANativeAdEvent\", onNative));\n coverage.admob.push(\"native\");\n }\n } catch {\n /* native ads unsupported by this build of the library */\n }\n }\n\n if (want.applovinMax) {\n const max = nativeModule(rn, \"AppLovinMAX\");\n if (max && rn.NativeEventEmitter) {\n try {\n let names: string[] = [...MAX_RN_REVENUE_EVENTS];\n try {\n const c = max.getConstants?.() ?? {};\n const fromModule = Object.keys(c)\n .filter((k) => /^ON_.*_AD_REVENUE_PAID$/.test(k))\n .map((k) => c[k])\n .filter((v): v is string => typeof v === \"string\");\n if (fromModule.length) names = [...new Set([...fromModule, ...names])];\n } catch {\n /* constants unavailable: the literal names are the library's */\n }\n const emitter = new rn.NativeEventEmitter(max);\n for (const name of names) subs.push(emitter.addListener(name, guard(fromMaxAdInfo, sink.applovinMax)));\n // Programmatic banners / MRECs ride these events too, but a `<AdView>`\n // banner does not: banners stay open to `maxRevenuePaid`, and the same\n // AdInfo object reaching both is caught by the gate's identity check.\n coverage.applovinMax = [...MAX_RN_FULLSCREEN_FORMATS];\n } catch {\n /* an emitter that cannot subscribe: the one-line prop remains */\n }\n }\n }\n\n return {\n coverage,\n stop: () => {\n for (const s of subs.splice(0)) {\n try {\n s.remove();\n } catch {\n /* already gone */\n }\n }\n },\n };\n}\n", "// @traqio/core \u2014 the platform-neutral engine. Android-first: reads the Play Install\n// Referrer from the native module, sends install + events to the ingestion API,\n// with a persisted offline queue, batching, and exponential-backoff retries.\n// On iOS: SKAdNetwork conversion values (./skan) plus Apple Ads self-attribution\n// through AdServices (./adservices) \u2014 the one deterministic iOS source.\n// Privacy: NO IDFA/GAID, no pasteboard, no fingerprinting. deviceId is a\n// first-party random id (persisted), not a cross-app identifier. Deep links\n// (./deeplink) send nothing new: the referrer already travels with the install,\n// and the iOS deferred IP match is the SERVER's, opt-in per app, routing only.\n\n// `require` is provided by the React Native / Metro runtime (used to lazily\n// wire AppState for lifecycle flush; absent off-device, hence the try/catch).\ndeclare const require: (module: string) => any;\n\nimport { Skan, type CoarseValue, type SkanMapping } from \"./skan\";\nimport {\n ANALYTICS_SESSION_IDLE_MS,\n cleanEventName,\n cleanProps,\n cleanScreenName,\n cleanGroups,\n cleanTraits,\n cleanUserId,\n EXPOSURE_EVENT,\n exposureProps,\n isEntry,\n nextAnalyticsBatch,\n parseSession,\n withGroup,\n type Groups,\n withSuperProps,\n type Traits,\n touchSession,\n type AnalyticsSession,\n type NavigationRefLike,\n type QueuedAnalyticsEvent,\n} from \"./analytics\";\nimport { reportAdServicesToken } from \"./adservices\";\nimport { isOpenUrl, isTrackingUrl, toDeepLink, upgradeStoredDeepLink, type DeepLink, type DeepLinkAnswer } from \"./deeplink\";\nimport {\n AdRevenueGate,\n fromGoogleMobileAdsPaid,\n fromMaxAdInfo,\n watchReactNativeAds,\n type AdRevenueCoverage,\n type AdRevenueOptions,\n type AdRevenueOrigin,\n type AdRevenueSink,\n} from \"./adRevenue\";\n\nexport const SDK_VERSION = \"0.10.0\";\nexport { Skan, type CoarseValue, type SkanMapping } from \"./skan\";\nexport { reportAdServicesToken, type AdServicesNative } from \"./adservices\";\nexport { ANALYTICS_SESSION_IDLE_MS, type Groups, type NavigationRefLike, type Traits, type TraitValue } from \"./analytics\";\nexport { isOpenUrl, isTrackingUrl, type DeepLink, type DeepLinkMatchType, type DeepLinkPayload } from \"./deeplink\";\nexport {\n CAPACITOR_ADMOB_PAID_EVENTS,\n GMA_FULLSCREEN_CHANNELS,\n GMA_MIN_VERSION,\n MAX_RN_MIN_VERSION,\n MAX_RN_REVENUE_EVENTS,\n fromCapacitorAdMob,\n fromGoogleMobileAdsChannel,\n fromGoogleMobileAdsNativeAd,\n fromGoogleMobileAdsPaid,\n fromMaxAdInfo,\n watchReactNativeAds,\n AdRevenueGate,\n type AdNetwork,\n type AdRevenueCoverage,\n type AdRevenueOptions,\n type AdRevenueOrigin,\n type AdRevenueSink,\n type ReactNativeAdWatch,\n type ReactNativeEvents,\n} from \"./adRevenue\";\n\nconst INSTALL_SENT_KEY = \"traq_install_sent\";\n// A debug build's own \"install sent\" flag. Separate on purpose: a release build\n// installed over a debug build on the same device (same storage) must still report\n// its install \u2014 the debug one is kept out of every report \u2014 and vice versa.\nconst INSTALL_SENT_DEBUG_KEY = \"traq_install_sent_debug\";\nconst INSTALL_ATTEMPTS_KEY = \"traq_install_attempts\";\n// The advertising id the server last acknowledged for this device (todo cmwlauev),\n// kept per mode like the install flag. Compared with what the OS hands out at each\n// start and foreground: a different (or first) id is posted once.\nconst AD_ID_SENT_KEY = \"traq_ad_id_sent\";\nconst AD_ID_SENT_DEBUG_KEY = \"traq_ad_id_sent_debug\";\nconst AD_ID_PATH = \"/ingest/advertising-id\";\nconst REFERRER_KEY = \"traq_referrer\";\nconst QUEUE_KEY = \"traq_queue\";\nconst AD_QUEUE_KEY = \"traq_ad_queue\";\nconst DEVICE_ID_KEY = \"traq_device_id\";\nconst LAST_SESSION_KEY = \"traq_last_session\";\n// Set once `forgetMe()` has been honoured by the server. Persisted, because the\n// whole point is that the NEXT launch stays silent too \u2014 the deviceId is still in\n// storage and an un-persisted flag would re-report the install tomorrow.\nconst ERASED_KEY = \"traq_erased\";\n// The deferred deep link, once the server has answered for this install\n// (\"null\" when it answered \"no link\"). Persisted so it is asked exactly once.\nconst DEFERRED_KEY = \"traq_deferred_link\";\n// Until when a \"no link\" answer given WITHOUT consent may be asked again once the\n// user consents (ms since epoch) \u2014 the probabilistic layer's one-hour window.\nconst DEFERRED_RETRY_KEY = \"traq_deferred_consent_retry_until\";\nconst DEFERRED_RETRY_WINDOW_MS = 60 * 60_000;\n// The user's answer to the app's consent prompt (\"granted\" | \"denied\"), once given.\nconst CONSENT_KEY = \"traq_consent\";\n// Product analytics (`capture()` / `screen()`): their own queue, their own route.\nconst ANALYTICS_QUEUE_KEY = \"traq_analytics_queue\";\nconst ANALYTICS_SESSION_KEY = \"traq_analytics_session\";\n/** `register()`'s super-properties, kept across launches. */\nconst SUPER_PROPS_KEY = \"traq_super_props\";\n/** `group()`'s accounts, kept across launches. */\nconst GROUPS_KEY = \"traq_groups\";\nconst ANALYTICS_PATH = \"/ingest/analytics\";\n/** Per request; the server takes 100. */\nconst MAX_ANALYTICS_BATCH = 50;\n/** Kept offline at most \u2014 the oldest go first, an analytics backlog is not money. */\nconst MAX_ANALYTICS_QUEUE = 1000;\n/** `capture()` / `screen()` calls made before `init()`: the first screen often renders first. */\nconst MAX_EARLY_ANALYTICS = 100;\nconst MAX_BATCH = 20;\n/** Statuses the same body gets on every retry \u2014 see Client.send. */\nconst NON_RETRYABLE_STATUS: ReadonlySet<number> = new Set([400, 413, 422]);\nconst MAX_QUEUE = 500;\n// Ad impressions are far more frequent than tracked events (a banner refreshes\n// every 30-60s), so they get their own, larger queue and batch.\nconst MAX_AD_BATCH = 100;\nconst MAX_AD_QUEUE = 1000;\nconst BASE_RETRY_MS = 1000;\nconst MAX_RETRY_MS = 5 * 60 * 1000;\nconst FLUSH_DELAY_MS = 3000;\n// How many launches we let the Play Install Referrer stay unavailable before\n// reporting the install anyway. See `sendInstallOnce`.\nconst MAX_INSTALL_ATTEMPTS = 3;\n\n// How long the app must have been away before coming back counts as a NEW session.\n// 30 minutes is the near-universal convention (GA4, Adjust, AppsFlyer all land\n// there) and the point of it is that a user switching to Maps and back has not\n// started a new session. It is also the debounce: without it, every\n// foreground/background flicker would post.\nconst SESSION_TIMEOUT_MS = 30 * 60 * 1000;\n\nexport interface KeyValueStore {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n}\n\nexport interface DeviceContext {\n deviceId?: string;\n deviceModel?: string;\n osVersion?: string;\n appVersion?: string;\n locale?: string;\n sdkVersion?: string;\n}\n\n/**\n * Why a Play Install Referrer read ended. Mirrors `ReferrerStatus` in the Kotlin\n * module, plus `unavailable` for \"the native module answered nothing\".\n */\nexport type InstallReferrerStatus =\n | \"ok\"\n | \"no_referrer\"\n | \"feature_not_supported\"\n | \"service_unavailable\"\n | \"service_disconnected\"\n | \"developer_error\"\n | \"permission_error\"\n | \"timeout\"\n | \"error\"\n | \"no_context\"\n | \"not_supported_platform\"\n | \"unavailable\";\n\nexport interface InstallReferrerResult {\n status: InstallReferrerStatus;\n /** True when a later launch could still produce a referrer (Play was busy/hung). */\n retryable: boolean;\n /** The raw referrer string, e.g. \"utm_source=meta&traq_click=abc123\". */\n referrer?: string;\n /** Unix seconds \u2014 when the ad click happened, per Play. */\n referrerClickTs?: number;\n /** Unix seconds \u2014 when the install began, per Play. */\n installBeginTs?: number;\n googlePlayInstant?: boolean;\n}\n\n/**\n * One answer of Meta's own Install Referrer \u2014 the content provider the Facebook,\n * Instagram and Facebook Lite apps expose (todo cmwy39da). Per\n * https://developers.facebook.com/docs/app-ads/meta-install-referrer the provider\n * returns `install_referrer` (serialized, encrypted with the app's \u00AB Install\n * Referrer Decryption Key \u00BB), `is_ct` (1 = click-through, 0 = view-through) and\n * `actual_timestamp` (seconds of the click / impression). The SDK forwards them\n * as read; the server decrypts and attributes.\n */\nexport interface MetaInstallReferrer {\n provider: \"facebook\" | \"instagram\" | \"facebook_lite\";\n installReferrer: string;\n isCt: 0 | 1;\n actualTimestamp?: number;\n}\n\nconst META_PROVIDERS: readonly string[] = [\"facebook\", \"instagram\", \"facebook_lite\"];\n\n/**\n * Screens what a native bridge answered: anything that is not a well-formed entry\n * is dropped, never the install it would travel with. Exported for the bridges.\n */\nexport function normalizeMetaInstallReferrers(raw: unknown): MetaInstallReferrer[] {\n if (!Array.isArray(raw)) return [];\n const out: MetaInstallReferrer[] = [];\n for (const item of raw) {\n if (!item || typeof item !== \"object\") continue;\n const r = item as Record<string, unknown>;\n if (typeof r.provider !== \"string\" || !META_PROVIDERS.includes(r.provider)) continue;\n if (typeof r.installReferrer !== \"string\" || !r.installReferrer.trim()) continue;\n const isCt = r.isCt === 1 || r.isCt === true ? 1 : r.isCt === 0 || r.isCt === false ? 0 : null;\n if (isCt === null) continue;\n const ts = typeof r.actualTimestamp === \"number\" && Number.isFinite(r.actualTimestamp) && r.actualTimestamp > 0 ? r.actualTimestamp : undefined;\n out.push({\n provider: r.provider as MetaInstallReferrer[\"provider\"],\n installReferrer: r.installReferrer,\n isCt,\n ...(ts !== undefined ? { actualTimestamp: ts } : {}),\n });\n }\n return out;\n}\n\n/** iOS App Tracking Transparency status, as the APP obtained it (`ATTrackingManager`). */\nexport type TrackingAuthorization = \"not_determined\" | \"restricted\" | \"denied\" | \"authorized\";\nconst TRACKING_AUTHORIZATIONS: readonly (string | null | undefined)[] = [\"not_determined\", \"restricted\", \"denied\", \"authorized\"];\n\nexport interface NativeBridge {\n platform: \"ios\" | \"android\";\n /** Android: reads the Play Install Referrer. Never rejects \u2014 failure is a status. */\n getInstallReferrer(): Promise<InstallReferrerResult>;\n /** Optional native device context (model, OS version). */\n getContext?(): Promise<{ deviceModel?: string; osVersion?: string }>;\n /**\n * Android: what Meta's Install Referrer providers (Facebook, Instagram, Facebook\n * Lite apps) answer for this Facebook App ID \u2014 `metaAppId`, or the host manifest's\n * `com.facebook.sdk.ApplicationId` when omitted. Never rejects; an empty list\n * when no Meta app is installed or none knows this install. Absent on a native\n * build that predates it. https://developers.facebook.com/docs/app-ads/meta-install-referrer\n */\n getMetaInstallReferrers?(metaAppId?: string): Promise<MetaInstallReferrer[]>;\n /** iOS: hand a SKAdNetwork conversion value to the device. No-op on Android. */\n updateConversionValue?(fineValue: number, coarse?: CoarseValue, lockWindow?: boolean): void;\n /**\n * iOS 14.3+: the AdServices attribution token (Apple Ads self-attribution).\n * Resolves null when the framework has none on this device \u2014 which is the case for\n * most installs, since most installs are not Apple Search Ads. Absent on Android.\n */\n getAttributionToken?(): Promise<string | null>;\n /**\n * The device advertising id (IDFA / GAID), or null. Called ONLY when the host set\n * `collectAdvertisingId: true`. It NEVER prompts: on iOS it answers only when the\n * app itself already obtained ATT, on Android only when the app ships Google's\n * ads-identifier library and declares the AD_ID permission. Decision cmvjohk6.\n */\n getAdvertisingId?(): Promise<string | null>;\n /**\n * iOS: the ATT status the app ALREADY obtained, or null when it does not link\n * AppTrackingTransparency. A status, not an identifier: read by default, at send\n * time, and it NEVER prompts (decision cmvjohk6). The server tells Meta the truth\n * with it (`advertiser_tracking_enabled`): false unless `authorized` (todo cmwl6oko).\n */\n getTrackingAuthorization?(): Promise<TrackingAuthorization | null>;\n /**\n * Is the HOST app a development build \u2014 debuggable (Android), DEBUG configuration\n * (iOS), or running on a simulator / emulator? Read once at `init()` when the app\n * did not set `debug` itself. Absent = only the JS side decides (`__DEV__`).\n */\n isDebugBuild?(): Promise<boolean>;\n /**\n * Subscribe to the paid events of the ad SDKs the host app uses, when the app\n * set `adRevenue` (HQ cmwfo9pd). Called once from `init()`. Absent = the core's\n * React Native watcher (`watchReactNativeAds`); Capacitor brings its own.\n * Returns what it actually captures \u2014 the networks whose manual calls are then\n * ignored (`AdRevenueGate`); no answer = everything that was asked.\n */\n watchAdRevenue?(want: AdRevenueOptions, sink: AdRevenueSink): AdRevenueCoverage | void;\n}\n\n/** One AdMob paid event, as handed to the app by `OnPaidEventListener`. */\nexport interface AdRevenue {\n /** `AdValue.getValueMicros()` \u2014 millionths of `currency`. Never pre-round it. */\n valueMicros: number;\n /** `AdValue.getCurrencyCode()` \u2014 ISO 4217. */\n currency: string;\n /** `AdValue.getPrecisionType()`. ESTIMATED is the normal case, and still real money. */\n precision?: \"unknown\" | \"estimated\" | \"publisher_provided\" | \"precise\";\n adUnitId?: string;\n adFormat?: \"banner\" | \"interstitial\" | \"rewarded\" | \"rewarded_interstitial\" | \"native\" | \"app_open\";\n /** Mediation ad source that filled it (`ResponseInfo.getLoadedAdapterResponseInfo()`). */\n adSourceName?: string;\n /** Unix seconds. Defaults to now. */\n ts?: number;\n}\n\n/**\n * The store a purchase went through, spelled the way the server's revenue key\n * spells it (`apps/api/src/revenuecat/revenue-key.ts`). It is part of the key, so\n * the same transaction id from two stores can never collide.\n */\nexport type RevenueStore = \"app_store\" | \"play_store\" | \"mac_app_store\" | \"amazon\" | \"stripe\";\n\n/** What `track()` accepts beside the event name. */\nexport interface TrackProps {\n /** Revenue DECLARED by the app. The SDK does not verify it against any receipt. */\n value?: number;\n currency?: string;\n /**\n * The STORE's id for this purchase \u2014 StoreKit's `transactionId`, Play Billing's\n * `orderId` (GPA.\u2026). With it, the server keys the event on the SAME deterministic\n * id RevenueCat / App Store Server Notifications / Play RTDN produce for that\n * transaction, so the purchase is counted once however many of them report it.\n * Without it, a purchase also reported server-side is counted twice.\n */\n transactionId?: string;\n /** Defaults to the platform's store (`app_store` on iOS, `play_store` on Android). */\n store?: RevenueStore;\n}\n\nexport interface InitOptions {\n sdkKey: string;\n endpoint: string; // origin only, no path \u2014 the SDK posts to `${endpoint}/ingest`\n /** Host-provided persistence (e.g. AsyncStorage) so the queue + install flag survive restarts. */\n storage?: KeyValueStore;\n /** Native bridge; on Android this reads the Install Referrer. */\n native?: NativeBridge;\n /** Your user id \u2014 set the SAME value as RevenueCat's app_user_id for revenue matching. */\n userId?: string;\n /** Your app's version string (host provides it). */\n appVersion?: string;\n /** Collect basic, non-fingerprinting device context (default true). Never IDFA/GAID. */\n collectContext?: boolean;\n /**\n * Set true while the app serves AdMob TEST ad units. Ad revenue is then logged\n * by the API (so you can see the pipe working) but never counted as revenue \u2014\n * test impressions are not money.\n */\n testAds?: boolean;\n /**\n * Capture ad revenue by itself (HQ cmwfo9pd): `{ admob: true, applovinMax: true }`.\n * No ad library becomes a dependency \u2014 Traqio listens to the events the library\n * already emits, and a library the app does not use emits nothing.\n *\n * React Native: every interstitial, rewarded, rewarded interstitial, app open and\n * native ad of react-native-google-mobile-ads (12.4+, the version that added PAID), and every interstitial,\n * rewarded, app open and programmatic banner / MREC of react-native-applovin-max.\n * A `<BannerAd>` / MAX `<AdView>` reports through its own prop: one line,\n * `onPaid={Traqio.admobPaid(AD_UNIT_ID)}` / `onAdRevenuePaid={Traqio.maxRevenuePaid}`.\n * Capacitor: every format of @capacitor-community/admob (8.1+).\n *\n * Turn it on and call nothing by hand for that network: once a network is\n * captured, `trackAdRevenue` / `trackMaxAdRevenue` for it are ignored (one\n * warning in the log), so an impression can never be counted twice. The two\n * one-line props above stay valid \u2014 they cover what the capture cannot reach.\n */\n adRevenue?: AdRevenueOptions;\n /**\n * iOS only. Drive the SKAdNetwork conversion value from tracked revenue and\n * events, using the mapping published for this app (fetched from the API).\n * Default true \u2014 on Android and without a native bridge it is inert.\n *\n * SKAN is aggregated, coarse (six bits) and delayed 24h+ by design; this makes\n * iOS measurable, not deterministic. See docs/IOS_ATTRIBUTION.md.\n */\n skan?: boolean;\n /**\n * iOS only. Report the AdServices attribution token so the server can resolve\n * Apple Ads (Search Ads) attribution. Default true \u2014 on Android, pre-iOS 14.3 and\n * without a native bridge it is inert.\n *\n * This is the ONE deterministic attribution iOS allows, and it needs no IDFA and no\n * ATT prompt of our own: the token is an opaque 24h claim ticket, and Apple decides\n * how detailed an answer to give from the ATT status the user already chose. See\n * adservices.ts.\n */\n appleAds?: boolean;\n /**\n * Send the device advertising id (IDFA / GAID) with the install. Default FALSE \u2014\n * Traqio collects nothing of the kind unless you turn this on (decision cmvjohk6).\n *\n * It improves attribution precision for the networks that attribute by that id\n * and nothing else \u2014 Unity Ads and AppLovin: their click carries it, and the install\n * postback Unity expects needs it. It is never used as the user's identity.\n *\n * The SDK never shows a permission prompt. iOS: ask for App Tracking Transparency\n * yourself, whenever your onboarding does; the IDFA is read only if the user said\n * yes. Asked AFTER `init()` is fine: the SDK re-reads it at every start and return\n * to the foreground and sends it once, for the device's later conversions (todo\n * cmwlauev) \u2014 Meta then gets it as `madid`, with `advertiser_tracking_enabled`. Android: add `com.google.android.gms:play-services-ads-identifier`\n * and the `com.google.android.gms.permission.AD_ID` permission to your app.\n */\n collectAdvertisingId?: boolean;\n /**\n * Android. Your Facebook App ID, for Meta's own Install Referrer (todo cmwy39da):\n * on the first launch the SDK asks the Facebook, Instagram and Facebook Lite apps\n * whether a Meta ad \u2014 a click OR a view \u2014 led to this install, and the server\n * decrypts the answer with the same \u00AB Install Referrer Decryption Key \u00BB as the Play\n * referrer. Omitted = the `com.facebook.sdk.ApplicationId` meta-data of your\n * manifest (set by the Facebook SDK), else nothing is read.\n * https://developers.facebook.com/docs/app-ads/meta-install-referrer\n */\n metaAppId?: string;\n /**\n * Deep linking (docs/DEEP_LINKING.md). Default true.\n *\n * On the first launch of a fresh install, asks once where the link that brought\n * the user wanted them to land, and hands it to `onDeepLink`. On React Native it\n * also listens to `Linking` for universal / App Links that open the app; every\n * other host passes those URLs to `handleUrl()`.\n */\n deepLinking?: boolean;\n /**\n * The user's consent to SHARING with ad networks, when the app already knows it\n * at launch \u2014 see `setConsent()`. Omitted = unchanged (never collected, or the\n * answer persisted by an earlier `setConsent`).\n */\n consent?: boolean;\n /**\n * `\"web\"` = a browser (used by `@traqio/web`). A browser is not an install: no\n * install is reported, no Install Referrer is read and no deferred deep link is\n * asked for. The first visit of the day is a session like any other (debounced,\n * since a multi-page site re-runs `init()` on every page), and requests are sent\n * with `keepalive` so a flush on `pagehide` survives the page being torn down.\n * Omitted = an app: everything above behaves exactly as before.\n */\n platform?: \"web\";\n /**\n * Host-provided app lifecycle. Called once from `init()` with the two handlers;\n * the host invokes `background()` when the app/tab is hidden (the queue is\n * flushed) and `foreground()` when it comes back (a session, debounced by the\n * 30-minute timeout). Omitted = React Native's `AppState`, when present.\n */\n lifecycle?: (events: LifecycleEvents) => void;\n /**\n * Debug mode (docs/MEASUREMENT_TRUTH.md \u00A71.12). Every request then carries\n * `debug: true`, and the server keeps it apart: shown in the console's Live events\n * \u203A Debug view, never counted in a report, never attributed, never sent to an ad\n * network or a webhook, never billed.\n *\n * Omitted = detected: React Native `__DEV__`, the native bridge's debug/simulator\n * check (Expo, Capacitor), or a browser on `localhost` / `127.0.0.1` / `*.local`\n * / `file:`. `true` forces it (a staging build); `false` turns detection off (a\n * release build you test on a simulator and want counted).\n */\n debug?: boolean;\n}\n\n/** What `InitOptions.lifecycle` is handed. */\nexport interface LifecycleEvents {\n background(): void;\n foreground(): void;\n}\n\nexport type { DeepLinkAnswer };\n\ninterface QueuedEvent {\n name: string;\n /**\n * A random id: it only makes the SDK's own retries idempotent. When the event\n * carries `transactionId`, the server replaces it with the transaction's\n * deterministic key before anything is stored or forwarded.\n */\n eventId: string;\n value?: number;\n currency?: string;\n transactionId?: string;\n store?: RevenueStore;\n}\n\n/** The ad platform a queued impression came from \u2014 the server's `source`. */\ntype AdRevenueSource = \"admob\" | \"applovin_max\";\n\ninterface QueuedAdImpression extends AdRevenue {\n impressionId: string;\n /** Absent on impressions persisted before MAX support: those are AdMob's. */\n source?: AdRevenueSource;\n /** Captured by Traqio, or handed by the app \u2014 the server's last dedup net reads it. */\n origin?: AdRevenueOrigin;\n}\n\n/**\n * One AppLovin MAX impression, as `onAdRevenuePaid(MaxAd ad)` describes it.\n * Docs: https://support.applovin.com/en/max/android/overview/advanced-settings\n */\nexport interface MaxAdRevenue {\n /** `ad.getRevenue()` \u2014 in USD. MAX answers -1 when it has no value. */\n revenue: number;\n /** `ad.getRevenuePrecision()`: \"exact\" | \"publisher_defined\" | \"estimated\" | \"undefined\" | \"\". */\n revenuePrecision?: string;\n /** `ad.getAdUnitId()`. */\n adUnitId?: string;\n /** `ad.getFormat().getLabel()` \u2014 \"BANNER\", \"INTER\", \"REWARDED\", \"MREC\", \"NATIVE\", \"APPOPEN\"\u2026 */\n format?: string;\n /** `ad.getNetworkName()` \u2014 the mediated network that filled the impression. */\n networkName?: string;\n /** Unix seconds. Defaults to now. */\n ts?: number;\n}\n\nconst MAX_PRECISION: Record<string, AdRevenue[\"precision\"]> = {\n exact: \"precise\",\n publisher_defined: \"publisher_provided\",\n estimated: \"estimated\",\n};\n\nconst MAX_FORMAT: Record<string, AdRevenue[\"adFormat\"]> = {\n BANNER: \"banner\",\n LEADER: \"banner\",\n MREC: \"banner\",\n INTER: \"interstitial\",\n INTERSTITIAL: \"interstitial\",\n REWARDED: \"rewarded\",\n REWARDED_INTER: \"rewarded_interstitial\",\n NATIVE: \"native\",\n APPOPEN: \"app_open\",\n APP_OPEN: \"app_open\",\n};\n\n/**\n * MAX \u2192 the server's impression shape. Undefined for an impression with no\n * usable revenue (MAX's -1), which is skipped rather than recorded as zero.\n */\nconst ZERO_AD_ID = \"00000000-0000-0000-0000-000000000000\";\n\n/** A real IDFA / GAID, or undefined: the all-zeros id means the OS withheld it. */\nexport function normalizeAdvertisingId(raw: unknown): string | undefined {\n if (typeof raw !== \"string\") return undefined;\n const id = raw.trim();\n if (!/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(id)) return undefined;\n return id === ZERO_AD_ID ? undefined : id;\n}\n\nexport function fromMaxAd(ad: MaxAdRevenue): AdRevenue | undefined {\n if (!(typeof ad.revenue === \"number\" && Number.isFinite(ad.revenue) && ad.revenue >= 0)) return undefined;\n return {\n // Rounded to the micro, never earlier: a banner is worth ~0.00002 USD.\n valueMicros: Math.round(ad.revenue * 1_000_000),\n currency: \"USD\",\n precision: MAX_PRECISION[ad.revenuePrecision ?? \"\"] ?? \"unknown\",\n adUnitId: ad.adUnitId,\n adFormat: MAX_FORMAT[(ad.format ?? \"\").toUpperCase()],\n adSourceName: ad.networkName,\n ts: ad.ts,\n };\n}\n\n// The batch id travels WITH the queue: if the app is killed between \"request sent\"\n// and \"response received\", the retry must reuse the same id or the server counts\n// the revenue twice.\ninterface PersistedAdQueue {\n batchId: string | null;\n items: QueuedAdImpression[];\n}\n\nfunction uuid(): string {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\nfunction safeLocale(): string | undefined {\n try {\n return Intl.DateTimeFormat().resolvedOptions().locale;\n } catch {\n return undefined;\n }\n}\n\n// Persistence is what makes the install fire exactly once and keeps queued events\n// across a kill. A host that forgets to pass `storage` would silently re-send the\n// install at every launch, so we pick up AsyncStorage when the app has it.\nfunction defaultStorage(): KeyValueStore | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const mod = require(\"@react-native-async-storage/async-storage\");\n const store = mod?.default ?? mod;\n if (typeof store?.getItem === \"function\" && typeof store?.setItem === \"function\") {\n return {\n getItem: (key) => store.getItem(key),\n setItem: (key, value) => store.setItem(key, value),\n };\n }\n } catch {\n // Not installed (or not React Native) \u2014 caller must pass `storage`.\n }\n return undefined;\n}\n\n/**\n * The OS of a React Native host, read from RN itself \u2014 the fallback when the app\n * runs without the native module (Expo Go, a build where autolinking missed it:\n * every Expo iOS app on @traqio/react-native <= 0.2.2, todo cmwl6okm). Undefined\n * off React Native.\n */\nfunction reactNativeOs(): \"ios\" | \"android\" | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const os: unknown = require(\"react-native\")?.Platform?.OS;\n return os === \"ios\" || os === \"android\" ? os : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport class Client {\n private opts!: Required<Pick<InitOptions, \"collectContext\">> & InitOptions;\n private queue: QueuedEvent[] = [];\n private adQueue: QueuedAdImpression[] = [];\n // Once `adRevenue` captures a network, its manual calls are ignored (HQ cmwfq3ij).\n private readonly adGate = new AdRevenueGate();\n private adBatchId: string | null = null;\n private context: DeviceContext = { sdkVersion: SDK_VERSION };\n private referrer: InstallReferrerResult | null = null;\n private started = false;\n private flushing = false;\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n private retryMs = BASE_RETRY_MS;\n private skan = new Skan();\n private erased = false;\n private deepLinkListeners = new Set<(link: DeepLink) => void>();\n // Links resolved before anyone subscribed \u2014 a cold start resolves the opening\n // URL before the app has mounted the screen that registers `onDeepLink`.\n private undelivered: DeepLink[] = [];\n private deferred: Promise<DeepLink | null> | null = null;\n private consent: \"granted\" | \"denied\" | null = null;\n private att: TrackingAuthorization | null = null;\n private adIdSync: Promise<void> | null = null;\n private debug = false;\n private analyticsQueue: QueuedAnalyticsEvent[] = [];\n private analyticsSession: AnalyticsSession | null = null;\n /** Calls made before `init()`, stamped with a session once the stored one is read. */\n private earlyAnalytics: Array<Omit<QueuedAnalyticsEvent, \"sessionId\">> = [];\n private currentScreen: string | null = null;\n /** `register()`: properties added to every analytics event. */\n private superProps: Traits = {};\n /** `group()`: the accounts every analytics event is stamped with. */\n private groups: Groups = {};\n /** An `identify()` made before `init()` \u2014 its user id is the install's from the start. */\n private earlyUserId: string | undefined;\n /** A `reset()` made before `init()`: the super-properties and accounts kept from earlier launches are dropped, not restored. */\n private resetBeforeInit = false;\n\n /** Whether this run is in debug mode \u2014 see `InitOptions.debug`. Settled by `init()`. */\n get isDebug(): boolean {\n return this.debug;\n }\n\n async init(opts: InitOptions): Promise<void> {\n if (this.started) return; // idempotent\n this.started = true;\n this.opts = { collectContext: true, ...opts, userId: opts.userId ?? this.earlyUserId, storage: opts.storage ?? defaultStorage() };\n if (!this.opts.storage) {\n // Loud on purpose: without it the install is re-sent at every launch.\n console.warn(\n \"[traqio] no storage available \u2014 pass `storage` to init() or install \" +\n \"@react-native-async-storage/async-storage, otherwise the install is re-sent at every launch.\",\n );\n }\n // Before anything can be sent: the first request already carries the flag.\n this.debug = await detectDebug(opts);\n await this.restoreConsent(opts.consent);\n await this.restoreQueue();\n await this.restoreAdQueue();\n await this.restoreAnalytics();\n await this.buildContext();\n // A device that asked to be forgotten stays forgotten across launches. Checked\n // before anything is sent: the install, the SKAN mapping fetch and the\n // AdServices token all carry this device's identity to the server.\n if (await this.restoreErased()) {\n this.earlyAnalytics = [];\n return;\n }\n if (this.isWeb) {\n // `@traqio/web` has its own tracker (page views, clicks, scroll); this queue is the app's.\n this.earlyAnalytics = [];\n } else {\n // Not scheduled one by one: the end of init() flushes them right away.\n for (const e of this.earlyAnalytics.splice(0)) this.pushAnalytics(e, false);\n }\n // Read BEFORE the install is marked sent: only a fresh install may ask for a\n // deferred link. An existing user updating to this SDK version must not be\n // routed by somebody else's click from the same address.\n // A browser is not an install and has no store to defer a link through: the\n // whole install / Install Referrer / deferred-link path is for apps only.\n if (!this.isWeb) {\n const freshInstall = Boolean(this.opts.storage) && !(await this.opts.storage!.getItem(this.installSentKey).catch(() => \"1\"));\n await this.sendInstallOnce();\n // An IDFA the install could not carry (ATT asked at an earlier launch, after it).\n void this.syncAdvertisingId();\n if (this.opts.deepLinking !== false) {\n // A user who consented at an EARLIER launch, after a consent-less ask found\n // nothing, gets the one retry here.\n this.deferred = this.resolveDeferredOnce(freshInstall).then((link) => link ?? this.retryDeferredWithConsent());\n this.wireDeepLinks();\n }\n }\n // App: always, not debounced \u2014 init() means the app was opened, and the first\n // open of a day is the one the whole retention number rests on. Web: debounced,\n // because a multi-page site calls init() on every page load. After the erasure\n // check above, because a forgotten device must not report opens either.\n // Web: NOT awaited. On a new session it is a round trip to the API, and @traqio/web\n // starts its analytics tracker (the first page view) only once init() resolves: a\n // visitor who left before that answer on a slow mobile network was never counted\n // (D+2 comparison with PostHog, HQ cmwr4ml5: 117 one-page visitors vs 82).\n if (this.isWeb) void this.maybeStartSession(false);\n else await this.maybeStartSession(true);\n await this.initSkan();\n await this.initAppleAds();\n this.wireLifecycle();\n this.wireAdRevenue();\n if (this.queue.length || this.adQueue.length || this.analyticsQueue.length) this.scheduleFlush(0);\n }\n\n // `InitOptions.adRevenue`: hand the ad SDKs' own paid events to the trackers.\n private wireAdRevenue(): void {\n const want = this.opts.adRevenue;\n if (!want || this.isWeb || !(want.admob || want.applovinMax)) return;\n const sink: AdRevenueSink = {\n admob: (ad, raw) => {\n if (this.adGate.first(raw)) this.queueAdRevenue(ad, \"admob\", \"auto\");\n },\n applovinMax: (ad, raw) => {\n const converted = fromMaxAd(ad);\n if (converted && this.adGate.first(raw)) this.queueAdRevenue(converted, \"applovin_max\", \"auto\");\n },\n };\n try {\n const coverage = this.opts.native?.watchAdRevenue\n ? (this.opts.native.watchAdRevenue(want, sink) ?? want)\n : watchReactNativeAds(want, sink).coverage;\n // From here on, a network Traqio captures refuses the manual calls.\n this.adGate.arm(coverage);\n } catch {\n // An ad SDK we cannot listen to leaves the manual trackers, never a crash.\n }\n }\n\n track(name: string, props?: TrackProps): void {\n if (!this.started || this.erased) return; // call init() first\n const transactionId = props?.transactionId?.trim() || undefined;\n this.enqueue({\n name,\n eventId: uuid(),\n value: props?.value,\n currency: props?.currency,\n ...(transactionId ? { transactionId, store: props?.store ?? this.defaultStore() } : {}),\n });\n // Same event, second job: on iOS it also moves the SKAN conversion value. Kept\n // for EVERY valued event, keyed or not: the conversion value must be set before\n // Apple's window closes, and a server webhook arrives too late for that. What\n // the transaction id changes is the event's place in the revenue TOTAL, never\n // this on-device signal.\n this.skan.markEvent(name);\n if (props?.value) this.skan.addRevenue(props.value);\n }\n\n /**\n * A product-analytics event \u2014 `paywall_viewed`, `deck_built`, `search_performed`\u2026\n * \u2014 read in the console's Analytics section (events, funnels, property splits).\n * NOT a conversion: never billed, never sent to an ad network (that is `track()`).\n *\n * Batched, persisted while offline and retried like every other call; it never\n * throws. Names starting with `$` are reserved (but `$exposure { experiment, variant }`, an experiment exposure); properties must survive JSON and\n * stay under 4 KB, else they are dropped (the event is kept). Callable before\n * `init()`: the first 100 calls wait for it.\n *\n * Traqio.capture(\"lead_captured\", { magnet: \"starter-deck\" });\n */\n capture(name: string, props?: Record<string, unknown>): void {\n try {\n const n = cleanEventName(name);\n if (!n) return;\n const p = cleanProps(props);\n this.queueAnalytics({ kind: \"custom\", name: n, ts: Date.now(), ...(p ? { props: p } : {}) });\n } catch {\n // Analytics must never take the host app down.\n }\n }\n\n /**\n * Who the user is, and what they are: sets the user id (like `setUserId`) and, with\n * traits, the user's PROPERTIES \u2014 `plan`, `role`, `company_size` \u2014 read in the\n * console as a breakdown, a report dimension and a cohort condition.\n *\n * Traqio.identify(\"u_123\", { plan: \"pro\", seats: 12 }, { signup_platform: \"ios\" });\n *\n * `traits` overwrite what was set before; `traitsOnce` are written only where the\n * user has no value yet (a first plan, a sign-up source). Values are text, numbers\n * or booleans \u2014 never an email or a name: the docs say why. At most 50 keys.\n */\n identify(userId: string, traits?: Record<string, unknown>, traitsOnce?: Record<string, unknown>): void {\n try {\n const id = typeof userId === \"string\" ? userId.trim() : \"\";\n if (!id) return;\n if (this.opts) this.setUserId(id);\n else this.earlyUserId = id;\n const set = cleanTraits(traits);\n const setOnce = cleanTraits(traitsOnce);\n if (!Object.keys(set).length && !Object.keys(setOnce).length) return;\n this.queueAnalytics({ kind: \"identify\", ts: Date.now(), userId: id, ...(Object.keys(set).length ? { set } : {}), ...(Object.keys(setOnce).length ? { setOnce } : {}) });\n } catch {\n /* never crash the host app */\n }\n }\n\n /**\n * Super-properties: added to EVERY analytics event from now on (and across\n * launches) \u2014 an app version flavour, an A/B arm, a theme. An event's own property\n * of the same name wins. `unregister(key)` removes one.\n *\n * Traqio.register({ app_flavor: \"beta\", theme: \"dark\" });\n */\n register(props: Record<string, unknown>): void {\n try {\n this.superProps = cleanTraits({ ...this.superProps, ...cleanTraits(props) });\n void this.persistSuperProps();\n } catch {\n /* never crash the host app */\n }\n }\n\n /** Stop adding one super-property to the events. */\n unregister(key: string): void {\n if (typeof key !== \"string\" || !(key in this.superProps)) return;\n const rest = { ...this.superProps };\n delete rest[key];\n this.superProps = rest;\n void this.persistSuperProps();\n }\n\n /** The super-properties `register()` set \u2014 a copy. */\n getSuperProperties(): Traits {\n return { ...this.superProps };\n }\n\n /**\n * The B2B ACCOUNT the user works in (group analytics): every analytics event from now\n * on (and across launches) counts for it, so the console can count accounts \u2014 unique\n * accounts, funnels, retention and cohorts \u00AB by company \u00BB \u2014 and list them with their\n * traits. Call it after sign-in, and again when the user switches account.\n *\n * Traqio.group(\"company\", \"acc_42\", { plan: \"enterprise\", seats: 40 });\n *\n * `groupType` is lowercase (`company`, `workspace`, `team`; 5 types at most),\n * `groupKey` your own account id \u2014 never an email. Traits follow identify's rules.\n */\n group(groupType: string, groupKey: string | number, traits?: Record<string, unknown>, traitsOnce?: Record<string, unknown>): void {\n try {\n const next = withGroup(this.groups, groupType, groupKey);\n if (!next) return;\n this.groups = next.groups;\n void this.persistGroups();\n const set = cleanTraits(traits);\n const setOnce = cleanTraits(traitsOnce);\n // Same account, nothing new to say: no entry (a group() at every launch costs nothing).\n if (!next.changed && !Object.keys(set).length && !Object.keys(setOnce).length) return;\n this.queueAnalytics({\n kind: \"group\",\n ts: Date.now(),\n groupType: next.type,\n groupKey: next.key,\n ...(Object.keys(set).length ? { set } : {}),\n ...(Object.keys(setOnce).length ? { setOnce } : {}),\n });\n } catch {\n /* never crash the host app */\n }\n }\n\n /** Stop stamping the events with any account \u2014 call it on sign-out. */\n resetGroups(): void {\n this.groups = {};\n void this.persistGroups();\n }\n\n /** The accounts `group()` set, by type \u2014 a copy. */\n getGroups(): Groups {\n return { ...this.groups };\n }\n\n /**\n * Two ids, one person: the user known so far as `previousId` (a guest id, an id\n * from before sign-up, an older system's) IS the current user (`setUserId` /\n * `identify`). Their analytics history and properties are merged under the current\n * id \u2014 the current id's own properties win. From an app, only what THIS device sent\n * under `previousId` is merged; a backend (secret key) merges everything.\n *\n * Traqio.identify(\"u_123\");\n * Traqio.alias(\"guest_8f2c\");\n *\n * Ignored without a current user id, or when `previousId` is the current one.\n */\n alias(previousId: string): void {\n try {\n const userId = this.opts ? this.opts.userId : this.earlyUserId;\n const prev = cleanUserId(previousId);\n if (!userId || !prev || prev === userId) return;\n this.queueAnalytics({ kind: \"alias\", ts: Date.now(), userId, previousId: prev });\n } catch {\n /* never crash the host app */\n }\n }\n\n /**\n * Sign-out: forget who the user was on this device \u2014 the user id, the\n * super-properties (`register`), the accounts (`group`) \u2014 and end the analytics\n * session, so the next person's visit starts clean. Events already queued keep the\n * user they were captured under. The device id is KEPT: it is the install's\n * attribution identity, and a new one would read as a new install.\n */\n reset(): void {\n try {\n const userId = this.opts ? this.opts.userId : this.earlyUserId;\n // What is still queued was captured under the signed-out user: say so before forgetting it.\n if (userId) {\n for (const e of this.analyticsQueue) if (!isEntry(e.kind) && e.asUser === undefined) e.asUser = userId;\n for (const e of this.earlyAnalytics) if (!isEntry(e.kind) && e.asUser === undefined) e.asUser = userId;\n }\n if (this.opts) this.opts.userId = undefined;\n else {\n this.earlyUserId = undefined;\n this.resetBeforeInit = true;\n }\n this.superProps = {};\n this.groups = {};\n this.analyticsSession = null;\n this.currentScreen = null;\n // On the web, @traqio/web keeps its own analytics state: nothing of the app's to write.\n if (this.opts && this.isWeb) return;\n void this.persistSuperProps();\n void this.persistGroups();\n void this.forgetAnalyticsSession();\n } catch {\n /* never crash the host app */\n }\n }\n\n /**\n * An experiment exposure: the user SAW `variant` of `experiment` \u2014 what the console's\n * experiment analysis reads (uplift and significance per variant). Your app assigns\n * the variant (its own flags, a remote config, a hash); call this where the user\n * first meets it. Sends `$exposure { experiment, variant, ...props }`.\n *\n * Traqio.exposure(\"paywall_copy\", \"b\");\n */\n exposure(experiment: string, variant: string | number | boolean, props?: Record<string, unknown>): void {\n try {\n const p = exposureProps(experiment, variant, props);\n // Over the 4 KB cap, the exposure alone rather than an event without its experiment.\n if (p) this.capture(EXPOSURE_EVENT, cleanProps(p) ?? { experiment: p.experiment, variant: p.variant });\n } catch {\n /* never crash the host app */\n }\n }\n\n /**\n * A screen view \u2014 the app's page view, read under \u00AB Top pages \u00BB and usable as a\n * funnel step. Call it when a screen gets the focus, or let `trackScreens()` (React\n * Navigation) or Expo Router's `usePathname()` do it (docs: /docs/sdks/react-native).\n * The same screen reported twice in a row inside a session counts once (re-renders).\n * Custom events captured afterwards carry this screen as their page.\n */\n screen(name: string, props?: Record<string, unknown>): void {\n try {\n const s = cleanScreenName(name);\n if (!s) return;\n const now = Date.now();\n const sameVisit = this.analyticsSession !== null && now - this.analyticsSession.last <= ANALYTICS_SESSION_IDLE_MS;\n if (s === this.currentScreen && sameVisit) return;\n this.currentScreen = s;\n const p = cleanProps(props);\n this.queueAnalytics({ kind: \"pageview\", ts: now, screen: s, ...(p ? { props: p } : {}) });\n } catch {\n /* never crash the host app */\n }\n }\n\n /**\n * Screen views from a React Navigation container, by themselves:\n *\n * const navigationRef = useNavigationContainerRef();\n * useEffect(() => Traqio.trackScreens(navigationRef), [navigationRef]);\n *\n * Returns the unsubscribe. Typed by shape: no navigation library is a dependency.\n */\n trackScreens(navigation: NavigationRefLike): () => void {\n const report = (): void => {\n try {\n const route = navigation.getCurrentRoute();\n if (route?.name) this.screen(route.name);\n } catch {\n /* a container not mounted yet answers on its next state change */\n }\n };\n let off: (() => void) | undefined | void;\n try {\n off = navigation.addListener(\"state\", report);\n } catch {\n off = undefined;\n }\n report();\n return () => {\n try {\n if (typeof off === \"function\") off();\n } catch {\n /* already gone */\n }\n };\n }\n\n /**\n * The store this app runs on: the native bridge's word, else React Native's\n * `Platform.OS`, else UNKNOWN. Never a guess \u2014 until 2026-11 a missing bridge meant\n * \"android\", and every bridgeless iPhone was filed as an Android install whose\n * purchases then went to Meta with the Android package (todo cmwl6okn).\n */\n private get hostPlatform(): \"ios\" | \"android\" | undefined {\n return this.opts.native?.platform ?? reactNativeOs();\n }\n\n private defaultStore(): RevenueStore | undefined {\n const platform = this.hostPlatform;\n return platform === \"ios\" ? \"app_store\" : platform === \"android\" ? \"play_store\" : undefined;\n }\n\n /**\n * Report one AdMob impression's revenue. Call it from the paid-event callback:\n *\n * ad.setOnPaidEventListener(v => Traqio.trackAdRevenue({\n * valueMicros: v.valueMicros, currency: v.currencyCode, precision: \"estimated\",\n * adUnitId, adFormat: \"rewarded\", adSourceName,\n * }));\n *\n * Impressions are batched and sent to /ingest/ad-revenue, where they are matched\n * to this install and become the ad half of ROAS.\n *\n * Ignored (one warning) once `adRevenue: { admob: true }` captures AdMob: the\n * impression is already counted.\n */\n trackAdRevenue(ad: AdRevenue): void {\n if (!this.adGate.manual(\"admob\", \"trackAdRevenue\")) return;\n this.queueAdRevenue(ad, \"admob\", \"manual\");\n }\n\n /**\n * Report one AppLovin MAX impression's revenue. Call it from MAX's callback:\n *\n * onAdRevenuePaid(ad) { Traqio.trackMaxAdRevenue({\n * revenue: ad.getRevenue(), revenuePrecision: ad.getRevenuePrecision(),\n * adUnitId: ad.getAdUnitId(), format: ad.getFormat().getLabel(),\n * networkName: ad.getNetworkName(),\n * }); }\n *\n * Same batching, same endpoint and same ROAS numerator as AdMob, filed under\n * the `applovin_max` source. Ignored (one warning) once\n * `adRevenue: { applovinMax: true }` captures MAX.\n */\n trackMaxAdRevenue(ad: MaxAdRevenue): void {\n if (!this.adGate.manual(\"applovinMax\", \"trackMaxAdRevenue\")) return;\n const converted = fromMaxAd(ad);\n if (converted) this.queueAdRevenue(converted, \"applovin_max\", \"manual\");\n }\n\n /**\n * The one line for an ad that reports through its own callback \u2014 a\n * react-native-google-mobile-ads `<BannerAd>` (the full-screen formats are\n * captured by `adRevenue: { admob: true }`):\n *\n * <BannerAd unitId={AD_UNIT_ID} size={\u2026} onPaid={Traqio.admobPaid(AD_UNIT_ID)} />\n * ad.addAdEventListener(AdEventType.PAID, Traqio.admobPaid(AD_UNIT_ID, \"rewarded\"))\n *\n * Reads the library's PAID payload (`value` in currency units, or v17's exact\n * `valueMicros`) and reports it as AdMob revenue. With `adRevenue: { admob: true }`\n * it only counts the formats the capture does not reach (banners): on a\n * full-screen or native ad it is ignored, so the impression is never doubled.\n */\n admobPaid(adUnitId?: string, adFormat: NonNullable<AdRevenue[\"adFormat\"]> = \"banner\"): (event: unknown) => void {\n return (event) => {\n try {\n const ad = fromGoogleMobileAdsPaid(event, { adUnitId, adFormat });\n if (ad && this.adGate.helper(\"admob\", adFormat, event, \"Traqio.admobPaid()\")) this.queueAdRevenue(ad, \"admob\", \"auto\");\n } catch {\n // Measurement is never worth a crash in the app's ad callback.\n }\n };\n }\n\n /**\n * The one line for a react-native-applovin-max `<AdView>` or native ad, whose\n * revenue comes through a prop rather than the global events:\n *\n * <AdView adUnitId={\u2026} adFormat={AdFormat.BANNER} onAdRevenuePaid={Traqio.maxRevenuePaid} />\n */\n readonly maxRevenuePaid = (adInfo: unknown): void => {\n try {\n const max = fromMaxAdInfo(adInfo);\n const ad = max && fromMaxAd(max);\n if (ad && this.adGate.helper(\"applovinMax\", ad.adFormat, adInfo, \"Traqio.maxRevenuePaid\")) this.queueAdRevenue(ad, \"applovin_max\", \"auto\");\n } catch {\n // Measurement is never worth a crash in the app's ad callback.\n }\n };\n\n private queueAdRevenue(ad: AdRevenue, source: AdRevenueSource, origin: AdRevenueOrigin): void {\n if (!this.started || this.erased) return; // call init() first\n if (!(ad.valueMicros >= 0) || !ad.currency) return; // nothing to bill\n this.adQueue.push({ ...ad, source, origin, impressionId: uuid(), ts: ad.ts ?? Math.floor(Date.now() / 1000) });\n // Ad revenue is revenue: it feeds the iOS conversion value like a purchase\n // does. Assumed to be in the mapping's currency \u2014 SKAN carries none, so a\n // mixed-currency app should map its buckets in the currency it reports.\n this.skan.addRevenue(ad.valueMicros / 1_000_000);\n if (this.adQueue.length > MAX_AD_QUEUE) this.adQueue.splice(0, this.adQueue.length - MAX_AD_QUEUE);\n void this.persistAdQueue();\n this.scheduleFlush();\n }\n\n /**\n * The Play Install Referrer for this install \u2014 the raw string your tracking link\n * put there, so a host app can use it for deferred deep linking on top of the\n * attribution we already do server-side. Resolves from cache after the first read\n * (Play only serves it reliably once). On iOS it reports\n * `not_supported_platform`; attribution there is SKAN.\n */\n getInstallReferrer(): Promise<InstallReferrerResult> {\n if (!this.started) return Promise.resolve({ status: \"unavailable\", retryable: false });\n return this.readReferrer();\n }\n\n /**\n * Subscribe to deep links \u2014 direct opens AND the one deferred link of a fresh\n * install. Links resolved before the first subscriber are delivered to it on\n * subscription, so a cold start does not lose the link that opened the app.\n *\n * Traqio.onDeepLink(({ deepLink }) => { if (deepLink) router.push(deepLink); });\n *\n * Returns the unsubscribe function.\n */\n onDeepLink(listener: (link: DeepLink) => void): () => void {\n this.deepLinkListeners.add(listener);\n const pending = this.undelivered.splice(0);\n for (const link of pending) listener(link);\n return () => {\n this.deepLinkListeners.delete(listener);\n };\n }\n\n /**\n * A URL opened the app. React Native is wired automatically (`Linking`); every\n * other host (Capacitor's `appUrlOpen`, a native shell) calls this.\n *\n * Only our tracking URLs (`https://<host>/c/<code>`) leave the device; the\n * app's own URLs resolve to null without a request. Resolving also records\n * the click, which the OS skipped by opening the app directly.\n */\n async handleUrl(url: string): Promise<DeepLink | null> {\n if (!this.started || this.erased || this.opts.deepLinking === false || !isTrackingUrl(url)) return null;\n const answer = await this.postJson<DeepLinkAnswer>({ url }, \"/deeplink/open\");\n // `/o/<clickId>` is the iOS landing page's \u00AB Open in app \u00BB: a tap made BEFORE the\n // install, so it is this install's deferred link too.\n const deferred = isOpenUrl(url);\n const link = toDeepLink(answer, deferred, url);\n if (link && deferred) await this.keepDeferred(link);\n if (link) this.emitDeepLink(link);\n return link;\n }\n\n /**\n * The deferred deep link of this install, if it came from one \u2014 resolved on the\n * first launch and remembered. Null on every install that did not come from a\n * link. `matchType` says how it was found; read `payload.value` for the token the\n * shared URL carried (`deep_link_value`).\n *\n * iOS has no install referrer: the deterministic carriers there are the landing\n * page's \u00AB Open in app \u00BB link (delivered through `handleUrl` / `onDeepLink`) and\n * its code (`redeemDeepLinkCode`). The probabilistic fallback runs only when the\n * user consented \u2014 `setConsent(true)` or `consent: true` at init \u2014 and the app\n * turned the IP match on in the console.\n */\n getDeferredDeepLink(): Promise<DeepLink | null> {\n return this.deferred ?? Promise.resolve(null);\n }\n\n /**\n * The code the iOS landing page showed (\u00AB ABCD-EFGH \u00BB), typed by the user in the\n * app \u2014 the manual fallback when neither the store nor a link carried the click.\n * Case, spaces and the dash are forgiven. Resolves to the link (`matchType:\n * \"code\"`), delivered to `onDeepLink` too, or null for an unknown / expired code.\n */\n async redeemDeepLinkCode(code: string): Promise<DeepLink | null> {\n if (!this.started || this.erased || this.opts.deepLinking === false || !code.trim()) return null;\n const answer = await this.postJson<DeepLinkAnswer>({ code }, \"/deeplink/code\");\n const link = toDeepLink(answer, true);\n if (!link) return null;\n await this.keepDeferred(link);\n this.emitDeepLink(link);\n return link;\n }\n\n /**\n * GDPR Art. 17, from inside the app: delete everything the server holds about this\n * device and this user, and stop sending.\n *\n * \u26A0\uFE0F IRREVERSIBLE, on both sides. The server deletes the installs, events, clicks\n * and delivery payloads that name this subject and tombstones their identifiers,\n * so nothing this device sends afterwards is accepted. Locally the queue is\n * dropped and the SDK goes quiet for good \u2014 persisted, so the next launch does not\n * re-report the install. There is no way back on: an app that needs measurement\n * again has to be reinstalled.\n *\n * Wire it to your own \"delete my data\" control. Returns false when the call did\n * not reach the server, and in that case NOTHING has changed on either side \u2014 show\n * the user an error and let them try again, rather than a confirmation of a\n * deletion that did not happen.\n */\n async forgetMe(): Promise<boolean> {\n if (!this.started) return false;\n if (this.erased) return true; // already honoured \u2014 saying \"yes\" twice is correct\n const ok = await this.post(\n { deviceId: this.context.deviceId, appUserId: this.opts.userId },\n \"/privacy/forget\",\n );\n if (!ok) return false;\n await this.markErased();\n return true;\n }\n\n /**\n * The user's consent to SHARING their data with ad networks, as collected by the\n * app's own prompt \u2014 Traqio is not a CMP. Persisted, and sent with every install,\n * event batch and session from now on, events already queued included.\n *\n * `false` keeps first-party measurement (installs, events, retention and ROAS in\n * your dashboard), but the server forwards nothing about this device to Meta,\n * TikTok or any outbound postback. Never calling it = not collected: the app's\n * policy in the console decides (docs/PRIVACY.md \u00A7Consent).\n *\n * Traqio.setConsent(userAgreed);\n */\n async setConsent(granted: boolean): Promise<void> {\n this.consent = granted ? \"granted\" : \"denied\";\n await this.opts?.storage?.setItem(CONSENT_KEY, this.consent).catch(() => undefined);\n // After the first launch's ask (chained, never in parallel with it).\n if (granted && this.deferred && !this.erased) {\n this.deferred = this.deferred.then((link) => link ?? this.retryDeferredWithConsent());\n await this.deferred;\n }\n }\n\n /** True once `forgetMe()` has been honoured \u2014 this install sends nothing any more. */\n get forgotten(): boolean {\n return this.erased;\n }\n\n /** Set/override the user id (== RevenueCat app_user_id). Call after login. */\n setUserId(id: string): void {\n if (this.opts) this.opts.userId = id;\n }\n\n /** Force a flush now (e.g. on app background). RN wires this automatically. */\n flush(): void {\n if (this.erased) return;\n // NOW, even when a batching or back-off timer is already pending, and in this\n // very call stack: a host calls this because the app or tab is going away. A\n // timer \u2014 even a 0 ms one \u2014 may never run inside a `pagehide` handler, whereas\n // drain() starts its first request before its first await.\n if (this.flushTimer) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n void this.drain();\n }\n\n /**\n * Tell the SDK the app came back to the foreground. React Native is wired\n * automatically; every other host (a web view, a game loop, a custom shell) has\n * to call this or its users look like they never came back.\n *\n * Safe to call on every resume: it is debounced by the session timeout.\n */\n appOpened(): void {\n if (!this.started || this.erased) return;\n void this.maybeStartSession();\n void this.syncAdvertisingId();\n }\n\n /** The conversion-value mapping in force on this device, once fetched. */\n get skanMapping(): SkanMapping | null {\n return this.skan.activeMapping;\n }\n\n /**\n * Apple Ads self-attribution. Awaited rather than fired off, so a host that awaits\n * `init()` can be sure the token left the device before the app does anything\n * else \u2014 the window is 24 hours, but a user who installs from a Search Ads tap and\n * never reopens the app still has to be attributed.\n */\n private async initAppleAds(): Promise<void> {\n if (this.opts.appleAds === false) return;\n const native = this.opts.native;\n if (native?.platform !== \"ios\" || !native.getAttributionToken) return;\n await reportAdServicesToken({\n endpoint: this.opts.endpoint,\n sdkKey: this.opts.sdkKey,\n deviceId: this.context.deviceId,\n userId: this.opts.userId,\n storage: this.opts.storage,\n native: { getAttributionToken: () => native.getAttributionToken!() },\n debug: this.debug,\n });\n }\n\n private async initSkan(): Promise<void> {\n if (this.opts.skan === false) return;\n const native = this.opts.native;\n // iOS-only, and only when the native module is actually there to call.\n if (native?.platform !== \"ios\" || !native.updateConversionValue) return;\n await this.skan.init({\n endpoint: this.opts.endpoint,\n sdkKey: this.opts.sdkKey,\n storage: this.opts.storage,\n native: {\n updateConversionValue: (fine, coarse, lockWindow) =>\n native.updateConversionValue?.(fine, coarse, lockWindow),\n },\n });\n }\n\n /**\n * Asks `/deeplink/deferred` once per install. A settled answer \u2014 link or no\n * link \u2014 is persisted; a failed request is not, so the next launch retries\n * (still counted as fresh, since the flag is only written on an answer).\n */\n private async resolveDeferredOnce(freshInstall: boolean): Promise<DeepLink | null> {\n const store = this.opts.storage;\n try {\n const cached = await store?.getItem(DEFERRED_KEY);\n if (cached) return upgradeStoredDeepLink(JSON.parse(cached));\n } catch {\n /* corrupt \u2014 ask again if still a fresh install */\n }\n if (!freshInstall && !(await store?.getItem(`${DEFERRED_KEY}_pending`).catch(() => null))) return null;\n\n const platform = this.hostPlatform;\n const referrer = platform === \"android\" ? await this.readReferrer() : null;\n await store?.setItem(`${DEFERRED_KEY}_pending`, \"1\").catch(() => undefined);\n const answer = await this.askDeferred(platform, referrer?.referrer);\n if (!answer) return null; // unreachable \u2014 the pending flag makes the next launch retry\n const link = toDeepLink(answer, true);\n // A `/o/` link or a code may have landed while this was in flight: keep it.\n const kept = await this.storedDeferred();\n if (kept) return kept;\n try {\n await store?.setItem(DEFERRED_KEY, JSON.stringify(link));\n // Nothing found and the user had not consented: one more ask is allowed if they\n // consent inside the hour the server keeps its evidence.\n if (!link && this.consent !== \"granted\") {\n await store?.setItem(DEFERRED_RETRY_KEY, String(Date.now() + DEFERRED_RETRY_WINDOW_MS));\n }\n } catch {\n /* storage full \u2014 worst case the next launch asks again */\n }\n if (link) this.emitDeepLink(link);\n return link;\n }\n\n /** The deferred ask: the referrer (Android), the consent, and what the tap is compared with. */\n private askDeferred(platform: \"ios\" | \"android\" | undefined, installReferrer: string | undefined): Promise<DeepLinkAnswer | null> {\n return this.postJson<DeepLinkAnswer>(\n {\n platform,\n installReferrer,\n ...(this.consent ? { consent: this.consent } : {}),\n ...(this.context.osVersion ? { osVersion: this.context.osVersion } : {}),\n ...(this.context.deviceModel ? { deviceModel: this.context.deviceModel } : {}),\n },\n \"/deeplink/deferred\",\n );\n }\n\n /**\n * The user consented AFTER the first launch asked without consent and found\n * nothing: ask once more, inside the hour, so the probabilistic layer can run.\n * Never when a link is already known, never twice.\n */\n private async retryDeferredWithConsent(): Promise<DeepLink | null> {\n const store = this.opts?.storage;\n if (!store || this.consent !== \"granted\" || this.opts.deepLinking === false || this.isWeb) return null;\n const until = Number(await store.getItem(DEFERRED_RETRY_KEY).catch(() => null));\n if (!until) return null;\n await store.setItem(DEFERRED_RETRY_KEY, \"\").catch(() => undefined);\n if (Date.now() > until) return null;\n const known = await this.storedDeferred();\n if (known) return known;\n const link = toDeepLink(await this.askDeferred(this.hostPlatform, undefined), true);\n if (!link) return null;\n await this.opts.storage?.setItem(DEFERRED_KEY, JSON.stringify(link)).catch(() => undefined);\n this.emitDeepLink(link);\n return link;\n }\n\n /** The deferred link already stored for this install, if any. */\n private async storedDeferred(): Promise<DeepLink | null> {\n try {\n const raw = await this.opts.storage?.getItem(DEFERRED_KEY);\n return raw ? upgradeStoredDeepLink(JSON.parse(raw)) : null;\n } catch {\n return null;\n }\n }\n\n /** Remember `link` as this install's deferred link, unless one is already known. */\n private async keepDeferred(link: DeepLink): Promise<void> {\n if (await this.storedDeferred()) return;\n await this.opts.storage?.setItem(DEFERRED_KEY, JSON.stringify(link)).catch(() => undefined);\n this.deferred = Promise.resolve(link);\n }\n\n private emitDeepLink(link: DeepLink): void {\n if (!this.deepLinkListeners.size) {\n this.undelivered.push(link);\n return;\n }\n for (const listener of this.deepLinkListeners) {\n try {\n listener(link);\n } catch {\n /* a throwing listener must not stop the others */\n }\n }\n }\n\n private wireDeepLinks(): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { Linking } = require(\"react-native\");\n if (!Linking) return;\n void Linking.getInitialURL().then((url: string | null) => url && this.handleUrl(url)).catch(() => undefined);\n Linking.addEventListener(\"url\", ({ url }: { url: string }) => void this.handleUrl(url));\n } catch {\n // Not React Native \u2014 the host calls Traqio.handleUrl(url).\n }\n }\n\n private get isWeb(): boolean {\n // Read before `init()` too, by `capture()`: no options yet means not known as web.\n return this.opts?.platform === \"web\";\n }\n\n private get installSentKey(): string {\n return this.debug ? INSTALL_SENT_DEBUG_KEY : INSTALL_SENT_KEY;\n }\n\n private get adIdSentKey(): string {\n return this.debug ? AD_ID_SENT_DEBUG_KEY : AD_ID_SENT_KEY;\n }\n\n /** Spread into every body: present only in debug mode, so a release build's payload is unchanged. */\n private debugField(): { debug?: true } {\n return this.debug ? { debug: true } : {};\n }\n\n private wireLifecycle(): void {\n const events: LifecycleEvents = {\n background: () => this.flush(),\n // Debounced by SESSION_TIMEOUT_MS inside, so a flick to another app/tab and\n // straight back posts nothing.\n foreground: () => this.appOpened(),\n };\n if (this.opts.lifecycle) {\n this.opts.lifecycle(events);\n return;\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { AppState } = require(\"react-native\");\n AppState.addEventListener(\"change\", (state: string) => {\n if (state !== \"active\") {\n this.scheduleFlush(0);\n return;\n }\n // Back in the foreground. Debounced by SESSION_TIMEOUT_MS inside, so a\n // flick to another app and straight back posts nothing.\n void this.maybeStartSession();\n // Not debounced: the ATT alert itself sends the app through `inactive`, so\n // this is the moment right after the user answered it. Posts only on change.\n void this.syncAdvertisingId();\n });\n } catch {\n // Not React Native \u2014 host can call Traqio.flush() manually.\n }\n }\n\n // \u2500\u2500 internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Reads the persisted erasure flag. True \u21D2 this install must stay silent. */\n private async restoreErased(): Promise<boolean> {\n try {\n this.erased = (await this.opts.storage?.getItem(ERASED_KEY)) === \"1\";\n } catch {\n // Storage unreadable: assume not erased. The server's tombstone is the real\n // enforcement \u2014 this flag only saves the round trip.\n this.erased = false;\n }\n return this.erased;\n }\n\n /** Local half of forgetMe(): drop what is queued and never send again. */\n private async markErased(): Promise<void> {\n this.erased = true;\n if (this.flushTimer) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n // The queue holds events about the person who just asked to be forgotten;\n // flushing it later would post them to a server that would drop them anyway.\n this.queue = [];\n this.adQueue = [];\n this.adBatchId = null;\n this.analyticsQueue = [];\n this.earlyAnalytics = [];\n this.superProps = {};\n this.groups = {};\n await this.persistSuperProps();\n await this.persistGroups();\n await this.persistQueue();\n await this.persistAdQueue();\n await this.persistAnalyticsQueue();\n try {\n await this.opts.storage?.setItem(ERASED_KEY, \"1\");\n } catch {\n /* storage full/unavailable \u2014 the in-memory flag still holds for this run */\n }\n }\n\n private enqueue(e: QueuedEvent) {\n this.queue.push(e);\n if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE);\n void this.persistQueue();\n this.scheduleFlush();\n }\n\n /** Before `init()` the call waits in memory; after it, it is stamped and queued. */\n private queueAnalytics(event: Omit<QueuedAnalyticsEvent, \"sessionId\">): void {\n if (this.erased) return;\n let e = event;\n if (!isEntry(event.kind)) {\n // The screen in view NOW, not at replay: an early event keeps its own context.\n const screen = event.screen ?? this.currentScreen ?? undefined;\n // Super-properties and accounts as set NOW: an early event keeps them too.\n const props = withSuperProps(event.props, this.superProps);\n const groups = Object.keys(this.groups).length ? { ...this.groups } : undefined;\n e = { ...event, ...(screen ? { screen } : {}), ...(props ? { props } : {}), ...(groups ? { groups } : {}) };\n }\n if (!this.started) {\n if (this.earlyAnalytics.length < MAX_EARLY_ANALYTICS) this.earlyAnalytics.push(e);\n return;\n }\n if (this.isWeb) return;\n this.pushAnalytics(e);\n }\n\n private pushAnalytics(e: Omit<QueuedAnalyticsEvent, \"sessionId\">, schedule = true): void {\n // An identify, a group or an alias is not activity: it neither opens nor prolongs a visit.\n if (isEntry(e.kind)) this.analyticsQueue.push({ ...e, sessionId: this.analyticsSession?.id ?? \"\" });\n else {\n this.analyticsSession = touchSession(this.analyticsSession, e.ts, uuid);\n this.analyticsQueue.push({ ...e, id: e.id ?? uuid(), sessionId: this.analyticsSession.id });\n }\n if (this.analyticsQueue.length > MAX_ANALYTICS_QUEUE) this.analyticsQueue.splice(0, this.analyticsQueue.length - MAX_ANALYTICS_QUEUE);\n void this.persistAnalyticsQueue();\n if (schedule) this.scheduleFlush();\n }\n\n /** The persisted queue first (older), then whatever was captured while it was being read. */\n private async restoreAnalytics(): Promise<void> {\n try {\n const raw = await this.opts.storage?.getItem(ANALYTICS_QUEUE_KEY);\n const stored = raw ? (JSON.parse(raw) as unknown) : null;\n if (Array.isArray(stored)) this.analyticsQueue = [...(stored as QueuedAnalyticsEvent[]), ...this.analyticsQueue].slice(-MAX_ANALYTICS_QUEUE);\n } catch {\n /* corrupt/absent \u2014 start empty */\n }\n try {\n // A session left less than 30 minutes ago goes on: an app switch is not a new visit.\n // Not after a reset() before init(): that session was the signed-out user's.\n if (!this.resetBeforeInit) this.analyticsSession ??= parseSession(await this.opts.storage?.getItem(ANALYTICS_SESSION_KEY));\n } catch {\n /* none */\n }\n if (this.resetBeforeInit) {\n // reset() before init(): what earlier launches kept belongs to the signed-out user.\n this.resetBeforeInit = false;\n await this.persistSuperProps();\n await this.persistGroups();\n await this.forgetAnalyticsSession();\n return;\n }\n try {\n // Kept from earlier launches; a register() made before init() wins over them.\n const raw = await this.opts.storage?.getItem(SUPER_PROPS_KEY);\n const early = Object.keys(this.superProps).length > 0;\n if (raw) this.superProps = cleanTraits({ ...cleanTraits(JSON.parse(raw)), ...this.superProps });\n if (early) await this.persistSuperProps();\n } catch {\n /* corrupt/absent \u2014 none */\n }\n try {\n // Same rule for the accounts: a group() made before init() wins over the stored ones.\n const raw = await this.opts.storage?.getItem(GROUPS_KEY);\n const early = Object.keys(this.groups).length > 0;\n if (raw) this.groups = cleanGroups({ ...cleanGroups(JSON.parse(raw)), ...this.groups });\n if (early) await this.persistGroups();\n } catch {\n /* corrupt/absent \u2014 none */\n }\n }\n\n private async forgetAnalyticsSession(): Promise<void> {\n if (!this.opts) return;\n try {\n // No removeItem on the store: an empty value reads back as no session (parseSession).\n await this.opts.storage?.setItem(ANALYTICS_SESSION_KEY, \"\");\n // The queue, with the reset's `asUser` stamps, so a relaunch keeps them too.\n await this.persistAnalyticsQueue();\n } catch {\n /* storage unavailable \u2014 the in-memory session is gone anyway */\n }\n }\n\n private async persistGroups(): Promise<void> {\n if (!this.opts) return; // before init(): restoreAnalytics() merges, then the next group() persists\n try {\n await this.opts.storage?.setItem(GROUPS_KEY, JSON.stringify(this.groups));\n } catch {\n /* storage full/unavailable \u2014 kept in memory for this run */\n }\n }\n\n private async persistSuperProps(): Promise<void> {\n if (!this.opts) return; // before init(): restoreAnalytics() merges, then the next register() persists\n try {\n await this.opts.storage?.setItem(SUPER_PROPS_KEY, JSON.stringify(this.superProps));\n } catch {\n /* storage full/unavailable \u2014 kept in memory for this run */\n }\n }\n\n private async persistAnalyticsQueue(): Promise<void> {\n try {\n await this.opts.storage?.setItem(ANALYTICS_QUEUE_KEY, JSON.stringify(this.analyticsQueue));\n if (this.analyticsSession) await this.opts.storage?.setItem(ANALYTICS_SESSION_KEY, JSON.stringify(this.analyticsSession));\n } catch {\n /* storage full/unavailable \u2014 the in-memory queue still flushes this run */\n }\n }\n\n private async restoreQueue() {\n try {\n const raw = await this.opts.storage?.getItem(QUEUE_KEY);\n if (raw) this.queue = JSON.parse(raw) as QueuedEvent[];\n } catch {\n /* corrupt/absent \u2014 start empty */\n }\n }\n\n private async persistQueue() {\n try {\n await this.opts.storage?.setItem(QUEUE_KEY, JSON.stringify(this.queue));\n } catch {\n /* storage full/unavailable */\n }\n }\n\n private async restoreAdQueue() {\n try {\n const raw = await this.opts.storage?.getItem(AD_QUEUE_KEY);\n if (!raw) return;\n const parsed = JSON.parse(raw) as PersistedAdQueue;\n this.adQueue = parsed.items ?? [];\n this.adBatchId = parsed.batchId ?? null;\n } catch {\n /* corrupt/absent \u2014 start empty */\n }\n }\n\n private async persistAdQueue() {\n try {\n const state: PersistedAdQueue = { batchId: this.adBatchId, items: this.adQueue };\n await this.opts.storage?.setItem(AD_QUEUE_KEY, JSON.stringify(state));\n } catch {\n /* storage full/unavailable */\n }\n }\n\n /**\n * Report one app open \u2014 the signal that makes \"did the user come back on day n\"\n * answerable at all (docs/SESSIONS.md).\n *\n * Called on `init()` (the app was opened) and on returning to the foreground\n * after `SESSION_TIMEOUT_MS`.\n *\n * NO QUEUE, deliberately. A failed post does NOT persist the marker, so the next\n * foreground retries it. The signal is only ever read at DAY granularity, so a\n * post lost at 09:00 is recovered by any open before midnight \u2014 a far smaller\n * failure than a persisted queue that can replay yesterday's sessions into today,\n * which would be a retention chart that invents its own history.\n */\n private async maybeStartSession(force = false): Promise<void> {\n if (this.erased) return;\n const now = Date.now();\n if (!force) {\n const last = Number(await this.opts.storage?.getItem(LAST_SESSION_KEY).catch(() => null)) || 0;\n if (last && now - last < SESSION_TIMEOUT_MS) return;\n }\n\n const deviceId = this.context.deviceId ?? (await this.getOrCreateDeviceId());\n const ok = await this.post(\n {\n deviceId,\n appUserId: this.opts.userId,\n sessionId: uuid(),\n ts: Math.floor(now / 1000),\n context: this.context,\n },\n \"/ingest/session\",\n );\n // Only on success: a marker written for a post that never landed would suppress\n // the retry and lose the day.\n if (ok) {\n try {\n await this.opts.storage?.setItem(LAST_SESSION_KEY, String(now));\n } catch {\n /* storage full/unavailable \u2014 worst case we post one extra session */\n }\n }\n }\n\n private async buildContext() {\n if (!this.opts.collectContext) {\n this.context = { sdkVersion: SDK_VERSION };\n return;\n }\n let native: { deviceModel?: string; osVersion?: string } = {};\n try {\n native = (await this.opts.native?.getContext?.()) ?? {};\n } catch {\n /* native context unavailable */\n }\n this.context = {\n deviceId: await this.getOrCreateDeviceId(),\n deviceModel: native.deviceModel,\n osVersion: native.osVersion,\n appVersion: this.opts.appVersion,\n locale: safeLocale(),\n sdkVersion: SDK_VERSION,\n };\n }\n\n private async getOrCreateDeviceId(): Promise<string> {\n try {\n const existing = await this.opts.storage?.getItem(DEVICE_ID_KEY);\n if (existing) return existing;\n } catch {\n /* ignore */\n }\n const id = uuid();\n try {\n await this.opts.storage?.setItem(DEVICE_ID_KEY, id);\n } catch {\n /* ignore */\n }\n return id;\n }\n\n /**\n * Reads the Play Install Referrer, once per install, and caches a settled answer.\n * A retryable failure is deliberately NOT cached \u2014 freezing it would make the\n * install look organic for good.\n */\n private async readReferrer(): Promise<InstallReferrerResult> {\n if (this.referrer) return this.referrer;\n try {\n const raw = await this.opts.storage?.getItem(REFERRER_KEY);\n if (raw) return (this.referrer = JSON.parse(raw) as InstallReferrerResult);\n } catch {\n /* corrupt/absent \u2014 read it again */\n }\n\n const native = this.opts.native;\n if (native?.platform !== \"android\") {\n return { status: native ? \"not_supported_platform\" : \"unavailable\", retryable: false };\n }\n const result = await native\n .getInstallReferrer()\n .catch((): InstallReferrerResult => ({ status: \"error\", retryable: true }));\n if (!result.retryable) {\n this.referrer = result;\n try {\n await this.opts.storage?.setItem(REFERRER_KEY, JSON.stringify(result));\n } catch {\n /* storage full/unavailable */\n }\n }\n return result;\n }\n\n /**\n * Meta's Install Referrer answers, Android only, read just before the install\n * leaves. Never throws: an old native build, a bridge teardown or no Meta app\n * installed all mean \u00AB no field \u00BB.\n */\n private async readMetaInstallReferrers(platform: \"ios\" | \"android\"): Promise<MetaInstallReferrer[] | undefined> {\n const read = this.opts.native?.getMetaInstallReferrers;\n if (platform !== \"android\" || !read) return undefined;\n try {\n const appId = this.opts.metaAppId?.trim() || undefined;\n const list = normalizeMetaInstallReferrers(await read.call(this.opts.native, appId));\n return list.length ? list : undefined;\n } catch {\n return undefined;\n }\n }\n\n /** Only with the host's opt-in; a zeroed or malformed id is never sent. */\n private async readAdvertisingId(): Promise<string | undefined> {\n if (!this.opts.collectAdvertisingId || !this.opts.native?.getAdvertisingId) return undefined;\n try {\n return normalizeAdvertisingId(await this.opts.native.getAdvertisingId());\n } catch {\n return undefined;\n }\n }\n\n private async sendInstallOnce() {\n const store = this.opts.storage;\n if (store && (await store.getItem(this.installSentKey))) return; // already sent\n\n const platform = this.hostPlatform;\n if (!platform) {\n // Not React Native and no native bridge: nothing says which store this is. A\n // wrong label is worse than a late install \u2014 it stays pending (re-tried at the\n // next launch) instead of being filed under a guessed store.\n console.warn(\n \"[traqio] unknown platform \u2014 no native bridge and not React Native: the install is not reported. \" +\n \"Pass `native: getNativeBridge()` (React Native / Expo) or your SDK's bridge to init().\",\n );\n return;\n }\n if (!this.opts.native) {\n // React Native without the native module: the install is still counted under\n // the right store, but with no Install Referrer, no SKAN, no Apple Ads token.\n console.warn(\n `[traqio] the Traqio native module is missing on ${platform} (Expo Go, or not linked in this build): ` +\n \"install reported without its attribution signals. Use a development / EAS build.\",\n );\n }\n const referrer = await this.readReferrer();\n\n // The referrer IS the Android attribution. When Play couldn't serve it yet\n // (store updating itself, service still starting), reporting now would brand\n // the install organic forever \u2014 so we wait for a later launch instead. Bounded:\n // a device where it never works still gets its install counted.\n if (referrer.retryable && store) {\n const attempts = Number(await store.getItem(INSTALL_ATTEMPTS_KEY)) || 0;\n if (attempts + 1 < MAX_INSTALL_ATTEMPTS) {\n await store.setItem(INSTALL_ATTEMPTS_KEY, String(attempts + 1));\n return;\n }\n }\n\n const advertisingId = await this.readAdvertisingId();\n const metaInstallReferrers = await this.readMetaInstallReferrers(platform);\n const ok = await this.post({\n install: {\n platform,\n installReferrer: referrer.referrer,\n ...(metaInstallReferrers ? { metaInstallReferrers } : {}),\n appUserId: this.opts.userId,\n advertisingId,\n context: this.context,\n },\n });\n // Only mark sent on success \u2014 otherwise it retries on the next init().\n if (ok) {\n await store?.setItem(this.installSentKey, \"1\");\n if (advertisingId) await store?.setItem(this.adIdSentKey, advertisingId).catch(() => undefined);\n }\n }\n\n /**\n * The opted-in advertising id the install could not carry (todo cmwlauev). The\n * install leaves at first launch, before an app shows its own ATT prompt, so on iOS\n * it almost never has the IDFA. Re-read at every start and foreground \u2014 reading\n * never prompts (decision cmvjohk6) \u2014 and posted ONCE when it differs from the one\n * the server last acknowledged; a failure is retried at the next foreground.\n *\n * Only after the install is reported: the install itself carries an id it can read.\n */\n private syncAdvertisingId(): Promise<void> {\n if (this.adIdSync) return this.adIdSync; // one at a time: init and a foreground can race\n this.adIdSync = this.postAdvertisingIdIfChanged().finally(() => {\n this.adIdSync = null;\n });\n return this.adIdSync;\n }\n\n private async postAdvertisingIdIfChanged(): Promise<void> {\n const store = this.opts.storage;\n if (this.isWeb || this.erased || !store || !this.opts.collectAdvertisingId) return;\n try {\n if (!(await store.getItem(this.installSentKey))) return;\n const advertisingId = await this.readAdvertisingId();\n if (!advertisingId || (await store.getItem(this.adIdSentKey)) === advertisingId) return;\n const deviceId = this.context.deviceId ?? (await this.getOrCreateDeviceId());\n if (await this.post({ deviceId, appUserId: this.opts.userId, advertisingId }, AD_ID_PATH)) {\n await store.setItem(this.adIdSentKey, advertisingId);\n }\n } catch {\n // Storage unavailable: try again at the next foreground.\n }\n }\n\n private scheduleFlush(delay = FLUSH_DELAY_MS) {\n if (this.flushTimer) return;\n this.flushTimer = setTimeout(() => {\n this.flushTimer = null;\n void this.drain();\n }, delay);\n }\n\n private async drain() {\n if (this.erased) return;\n if (this.flushing || (!this.queue.length && !this.adQueue.length && !this.analyticsQueue.length)) return;\n this.flushing = true;\n try {\n while (this.queue.length) {\n const batch = this.queue.slice(0, MAX_BATCH);\n // Identity travels with every batch, not just the install: the API forwards\n // these events to Meta/TikTok, and both REJECT an event that carries no user\n // identifier. Still first-party only \u2014 deviceId is our own random id, and the\n // API hashes whatever it forwards. Never IDFA/GAID.\n const outcome = await this.send({\n events: batch,\n appUserId: this.opts.userId,\n deviceId: this.context.deviceId,\n });\n if (outcome === \"retry\") return this.backOff();\n if (outcome === \"refused\") {\n // The server says this batch is malformed and will say so forever; retrying\n // it would hold every event behind it hostage (audit cmw6ow5z M10). Since\n // API 2026-11 a bad EVENT is refused alone inside a 200 \u2014 this is the\n // safety net for a refusal of the whole body.\n console.warn(`[traqio] the server refused ${batch.length} event(s) as malformed \u2014 dropped, not retried`);\n }\n this.queue.splice(0, batch.length);\n await this.persistQueue();\n this.retryMs = BASE_RETRY_MS;\n }\n while (this.adQueue.length) {\n // One batch = one platform: the server files a whole batch under one source.\n const source = this.adQueue[0].source ?? \"admob\";\n const run = this.adQueue.findIndex((i) => (i.source ?? \"admob\") !== source);\n const batch = this.adQueue.slice(0, Math.min(MAX_AD_BATCH, run === -1 ? this.adQueue.length : run));\n // Mint the batch id BEFORE the request and persist it, so a crash mid-flight\n // retries under the same id and the server dedups instead of double-counting.\n if (!this.adBatchId) {\n this.adBatchId = uuid();\n await this.persistAdQueue();\n }\n const ok = await this.post(\n {\n batchId: this.adBatchId,\n source,\n environment: this.opts.testAds ? \"TEST\" : \"PRODUCTION\",\n deviceId: this.context.deviceId,\n appUserId: this.opts.userId,\n impressions: batch.map(({ source: _source, ...impression }) => impression),\n },\n \"/ingest/ad-revenue\",\n );\n if (!ok) return this.backOff();\n this.adQueue.splice(0, batch.length);\n this.adBatchId = null;\n await this.persistAdQueue();\n this.retryMs = BASE_RETRY_MS;\n }\n while (this.analyticsQueue.length) {\n // One user per batch: events still queued at a reset() keep the user they were captured under.\n const batch = nextAnalyticsBatch(this.analyticsQueue, this.opts.userId, MAX_ANALYTICS_BATCH);\n // `anonymousId` is the same first-party device id the install carries, so a\n // visitor in the Analytics page is a device in the attribution reports.\n const outcome = await this.send(\n {\n anonymousId: this.context.deviceId ?? (await this.getOrCreateDeviceId()),\n userId: batch.userId,\n platform: this.hostPlatform,\n events: batch.events,\n },\n ANALYTICS_PATH,\n );\n if (outcome === \"retry\") return this.backOff();\n if (outcome === \"refused\") console.warn(`[traqio] the server refused ${batch.taken} analytics event(s) as malformed \u2014 dropped, not retried`);\n this.analyticsQueue.splice(0, batch.taken);\n await this.persistAnalyticsQueue();\n this.retryMs = BASE_RETRY_MS;\n }\n } finally {\n this.flushing = false;\n }\n }\n\n // network/server failure \u2192 keep the queue, back off, retry later.\n private backOff(): void {\n this.retryMs = Math.min(this.retryMs * 2, MAX_RETRY_MS);\n this.scheduleFlush(this.retryMs);\n }\n\n /** Like `post`, for the two calls whose ANSWER matters. Null on any failure. */\n private async postJson<T>(body: Record<string, unknown>, path: string): Promise<T | null> {\n try {\n const res = await fetch(`${this.opts.endpoint}${path}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body, ...this.debugField() }),\n ...this.keepalive(),\n });\n return res.ok ? ((await res.json()) as T) : null;\n } catch {\n return null;\n }\n }\n\n /**\n * The init option wins over what is stored (it is the app's current answer); a\n * `setConsent()` made before `init()` survives too \u2014 it is only kept in memory\n * until there is a storage to write it to.\n */\n private async restoreConsent(fromInit: boolean | undefined): Promise<void> {\n if (fromInit !== undefined) return this.setConsent(fromInit);\n if (this.consent) return this.setConsent(this.consent === \"granted\");\n const stored = await this.opts.storage?.getItem(CONSENT_KEY).catch(() => null);\n if (stored === \"granted\" || stored === \"denied\") this.consent = stored;\n }\n\n /**\n * Web only: a request started on `pagehide` is otherwise cancelled with the page.\n * Not set for apps \u2014 their fetch is not torn down, and the request stays as it was.\n */\n private keepalive(): { keepalive?: boolean } {\n return this.isWeb ? { keepalive: true } : {};\n }\n\n private get asksTrackingAuthorization(): boolean {\n return this.opts.native?.platform === \"ios\" && typeof this.opts.native.getTrackingAuthorization === \"function\";\n }\n\n /** iOS only; the last good answer when the bridge cannot give one now. */\n private async readTrackingAuthorization(): Promise<TrackingAuthorization | null> {\n try {\n const status = await this.opts.native?.getTrackingAuthorization?.();\n if (TRACKING_AUTHORIZATIONS.includes(status)) this.att = status ?? null;\n } catch {\n /* keep the last answer */\n }\n return this.att;\n }\n\n private async post(body: Record<string, unknown>, path = \"/ingest\"): Promise<boolean> {\n return (await this.send(body, path)) === \"ok\";\n }\n\n /**\n * `post`, with the failure split in two: `refused` is a status the same body will\n * get again on every retry (400 malformed, 413 too large, 422 unprocessable);\n * `retry` is everything else \u2014 network down, 5xx, 429, and 401/403 too, since a\n * key fixed in the console makes the same queued batch succeed.\n */\n private async send(body: Record<string, unknown>, path = \"/ingest\"): Promise<\"ok\" | \"retry\" | \"refused\"> {\n // Read at SEND time, so a batch queued before a \"no\" goes out under the \"no\".\n const consent = this.consent && (path === \"/ingest\" || path === \"/ingest/session\" || path === AD_ID_PATH) ? { consent: this.consent } : {};\n // Same for ATT: an app that shows its prompt during onboarding has the answer by\n // the time the first purchase is flushed.\n // Awaited only on iOS with a bridge that answers: a web flush on `pagehide` must\n // start its request in this very call stack (no second tick).\n // On the advertising-id post too: the server keeps an IDFA only under `authorized`.\n const att = (path === \"/ingest\" || path === AD_ID_PATH) && this.asksTrackingAuthorization ? await this.readTrackingAuthorization() : null;\n try {\n const res = await fetch(`${this.opts.endpoint}${path}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n sdkKey: this.opts.sdkKey,\n ...body,\n ...consent,\n ...(att ? { att } : {}),\n ...this.debugField(),\n }),\n ...this.keepalive(),\n });\n if (res.ok) return \"ok\";\n return NON_RETRYABLE_STATUS.has(res.status) ? \"refused\" : \"retry\";\n } catch {\n return \"retry\";\n }\n }\n}\n\n/**\n * Debug mode, as `init()` settles it (`InitOptions.debug`). The explicit option\n * wins; otherwise any one signal is enough. Conservative on purpose \u2014 a false\n * positive takes a real user out of every report \u2014 so each signal is one the\n * platform itself sets for development only.\n */\nexport async function detectDebug(opts: Pick<InitOptions, \"debug\" | \"platform\" | \"native\">): Promise<boolean> {\n if (opts.debug !== undefined) return opts.debug;\n if (opts.platform === \"web\") return isLocalPage();\n // React Native / Expo: Metro sets it for a development bundle, false in release.\n if ((globalThis as { __DEV__?: unknown }).__DEV__ === true) return true;\n try {\n return (await opts.native?.isDebugBuild?.()) === true;\n } catch {\n // A bridge that cannot answer says nothing: production, as before the flag.\n return false;\n }\n}\n\n/** A page served from the developer's own machine \u2014 never a production origin. */\nexport function isLocalPage(loc: { protocol: string; hostname: string } | undefined = (globalThis as { location?: Location }).location): boolean {\n if (!loc) return false;\n if (loc.protocol === \"file:\") return true;\n const host = loc.hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n return (\n host === \"localhost\" ||\n host.endsWith(\".localhost\") ||\n host.endsWith(\".local\") ||\n host === \"::1\" ||\n host === \"0.0.0.0\" ||\n /^127\\.\\d+\\.\\d+\\.\\d+$/.test(host)\n );\n}\n\nexport const Traqio = new Client();\n", "// @traqio/web \u2014 the browser half of the Traqio web SDK.\n//\n// One job above all: keep the trackID (the ad click id Traqio's tracking link puts in\n// the landing URL as `traq_click`) from the landing page to the conversion, in\n// first-party storage, so the conversion can be tied to its click deterministically.\n// Around it: web events and visits, sent through the same engine as the mobile SDKs\n// (@traqio/core, bundled in), with consent and erasure.\n//\n// One package for every framework: it is plain JS with no UI, and a framework only\n// decides WHERE `init()` is called. SSR-safe: nothing touches `window` or `document`\n// at import time, and `init()` on a server is a no-op.\n//\n// What it deliberately does NOT do: report an install, or send the click id with an\n// event. A web key is public (it sits in the page), so it carries no attribution\n// authority \u2014 a conversion is tied to its click by the site's BACKEND, with a secret\n// key, reading the trackID this package kept (cookie `traq_click`, or `getTrackId()`).\nimport { Client } from \"@traqio/core\";\nimport { registrableDomain } from \"./cookies\";\nimport { BrowserStore, DEVICE_ID_KEY, INTERNAL_KEY } from \"./storage\";\nimport { SourceKeeper, type WebSource } from \"./source\";\nimport { TrackIdKeeper } from \"./trackId\";\nimport { AnalyticsTracker, cleanGroups, cleanTraits, cleanUserId, exposureProps, withGroup, type AnalyticsOptions, type Groups, type Traits } from \"./analytics\";\n\nexport type { WebSource } from \"./source\";\nexport type { AnalyticsOptions, Groups, Traits, TraitValue } from \"./analytics\";\nexport type { WebVitalsOptions } from \"./vitals\";\n\nexport const DEFAULT_ENDPOINT = \"https://api.traqio.app\";\n/** `register()`'s super-properties, kept across pages. */\nconst SUPER_PROPS_KEY = \"traq_super\";\n/** `group()`'s accounts, kept across pages. */\nconst GROUPS_KEY = \"traq_groups\";\nconst DEFAULT_TRACK_ID_DAYS = 30;\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\nexport interface WebInitOptions {\n /** The site's WEB key (`tq_web_\u2026`), from the console. Public by design: it is held to the site's origins. */\n sdkKey: string;\n /** Origin only, no path. Default `https://api.traqio.app`. */\n endpoint?: string;\n /** Your user id once known \u2014 the same id your backend sends with its conversions. */\n userId?: string;\n /**\n * The visitor's consent to SHARING with ad networks, if already known. Omitted =\n * not collected; the site's policy in the console decides.\n */\n consent?: boolean;\n /**\n * `true` = write nothing to the device (no localStorage, no cookie) until\n * `setConsent(true)`. The SDK still works for the current page, in memory. For\n * sites that must ask before storing anything (ePrivacy). Default `false`.\n */\n waitForConsent?: boolean;\n /**\n * How long the trackID \u2014 and the visit's source (`getSource()`) \u2014 is kept after\n * the landing, in days. Default 30. Keeping it\n * longer than the site's attribution window is harmless: the server refuses a\n * click outside the window.\n */\n trackIdDays?: number;\n /** `false` = never write a cookie, localStorage only (no sharing across subdomains). Default `true`. */\n cookies?: boolean;\n /**\n * Debug mode. Omitted = on when the page is served from your machine (`localhost`,\n * `127.0.0.1`, `*.localhost`, `*.local`, `file:`), off everywhere else. Debug\n * traffic shows in the console's Live events \u203A Debug view (its analytics events in\n * Analytics \u203A Realtime \u203A Debug, kept 24 h) and is never counted,\n * attributed, sent to an ad network or a webhook, or billed. `true` for a staging\n * site, `false` to count a local page.\n */\n debug?: boolean;\n /**\n * Product analytics \u2014 page views (route changes included), clicks, rage clicks,\n * scroll depth, front-end errors and the Core Web Vitals of a sample of page loads,\n * read in the console's Analytics section. `true` turns them all on; an object picks\n * (`{ webVitals: { sampleRate: 0.1 } }`). Default off. Never billed and never sent to an ad network:\n * analytics events have their own route and table, apart from conversions.\n */\n analytics?: boolean | AnalyticsOptions;\n}\n\n/** What `track()` accepts beside the event name. */\nexport interface WebTrackProps {\n /** Revenue DECLARED by the page. Prefer sending purchases from your backend, where they are known. */\n value?: number;\n currency?: string;\n /** The payment's id at your processor (e.g. a Stripe payment intent): the purchase is then counted once. */\n transactionId?: string;\n /** Where the payment went through \u2014 `\"stripe\"` for Stripe. */\n store?: \"stripe\" | \"app_store\" | \"play_store\" | \"mac_app_store\" | \"amazon\";\n}\n\nfunction inBrowser(): boolean {\n return typeof window !== \"undefined\" && typeof document !== \"undefined\";\n}\n\nfunction randomId(): string | null {\n try {\n return typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\" ? crypto.randomUUID() : null;\n } catch {\n return null;\n }\n}\n\n/**\n * `traqio_internal` in a URL's query: `1`/`true` \u2192 true, `0`/`false` \u2192 false, absent or\n * anything else \u2192 null (left as it was).\n */\nexport function internalParam(href: string): boolean | null {\n try {\n const v = new URL(href).searchParams.get(\"traqio_internal\");\n if (v === \"1\" || v === \"true\") return true;\n if (v === \"0\" || v === \"false\") return false;\n } catch {\n /* not a URL */\n }\n return null;\n}\n\nexport class TraqioWeb {\n private readonly core = new Client();\n private store: BrowserStore | null = null;\n private trackIds: TrackIdKeeper | null = null;\n private sources: SourceKeeper | null = null;\n private waitForConsent = false;\n private started = false;\n /** A `setConsent()` made before `init()` \u2014 it decides whether init may store. */\n private earlyConsent: boolean | undefined;\n private analytics: AnalyticsTracker | null = null;\n private userId: string | undefined;\n /** `capture()` calls made before `init()` finished \u2014 replayed once the tracker exists. */\n private earlyCaptures: Array<[string, Record<string, unknown> | undefined]> = [];\n /** `init()` has finished (or will never run here): early captures are no longer kept. */\n private ready = false;\n /** `register()`: properties added to every analytics event, kept in `traq_super`. */\n private superProps: Traits = {};\n /** `identify()` calls with traits made before `init()` \u2014 replayed once the tracker exists. */\n private earlyIdentifies: Array<[string, Traits, Traits]> = [];\n /** `group()`: the accounts every analytics event is stamped with, kept in `traq_groups`. */\n private groups: Groups = {};\n /** Group entries made before `init()` \u2014 replayed once the tracker exists. */\n private earlyGroups: Array<[string, string, Traits, Traits]> = [];\n /** `alias()` calls made before `init()`: [userId, previousId]. */\n private earlyAliases: Array<[string, string]> = [];\n /** A `reset()` before `init()`: what earlier pages kept (super-properties, accounts) is dropped, not restored. */\n private resetBeforeInit = false;\n\n /**\n * Call once, as early as possible on every page (or once in a single-page app).\n * Reads the trackID from the current URL first, synchronously, so even a visitor\n * who leaves before the network answers keeps it. Safe to call on a server: it\n * does nothing there.\n */\n async init(opts: WebInitOptions): Promise<void> {\n if (this.started || !inBrowser()) return;\n this.started = true;\n this.waitForConsent = opts.waitForConsent === true;\n\n const cookies = opts.cookies !== false;\n let domain: string | null | undefined;\n // Probed lazily, once: it writes a test cookie, which must not happen before consent.\n const cookieDomain = (): string | null => (domain === undefined ? (domain = registrableDomain(location.hostname)) : domain);\n\n const consent = opts.consent ?? this.earlyConsent;\n const persistent = !this.waitForConsent || consent === true;\n this.store = new BrowserStore(persistent, cookieDomain, cookies);\n const keepMs = (opts.trackIdDays ?? DEFAULT_TRACK_ID_DAYS) * DAY_MS;\n this.trackIds = new TrackIdKeeper(this.store, keepMs, cookieDomain, cookies);\n this.trackIds.capture(location.href);\n // The visitor's origin when no Traqio link was clicked: utm_*, gclid/fbclid/ttclid,\n // the referring site. Same lifetime and consent rules as the trackID.\n this.sources = new SourceKeeper(this.store, keepMs, cookieDomain, cookies);\n this.sources.capture(location.href, document.referrer);\n // `?traqio_internal=1` marks this browser as the team's own, `=0` releases it.\n const optOut = internalParam(location.href);\n if (optOut !== null) this.setInternal(optOut);\n\n // A real random id rather than core's Math.random one, when the browser has it.\n // Seeded before core reads it; core keeps whatever is already there.\n if (!this.store.getSync(DEVICE_ID_KEY)) {\n const id = randomId();\n if (id) this.store.setSync(DEVICE_ID_KEY, id);\n }\n\n // An identify() made before init() keeps its user id unless init names one.\n this.userId = opts.userId ?? this.userId;\n if (this.resetBeforeInit) {\n this.store.removeSync(SUPER_PROPS_KEY);\n this.store.removeSync(GROUPS_KEY);\n }\n // Super-properties kept from earlier pages; a register() made before init() wins.\n try {\n const raw = this.store.getSync(SUPER_PROPS_KEY);\n const early = Object.keys(this.superProps).length > 0;\n if (raw) this.superProps = cleanTraits({ ...cleanTraits(JSON.parse(raw)), ...this.superProps });\n if (early) this.store.setSync(SUPER_PROPS_KEY, JSON.stringify(this.superProps));\n } catch {\n /* corrupt: none */\n }\n // Same for the accounts: kept from earlier pages, a group() made before init() wins.\n try {\n const raw = this.store.getSync(GROUPS_KEY);\n const early = Object.keys(this.groups).length > 0;\n if (raw) this.groups = cleanGroups({ ...cleanGroups(JSON.parse(raw)), ...this.groups });\n if (early) this.store.setSync(GROUPS_KEY, JSON.stringify(this.groups));\n } catch {\n /* corrupt: none */\n }\n const endpoint = (opts.endpoint ?? DEFAULT_ENDPOINT).replace(/\\/+$/, \"\");\n await this.core.init({\n sdkKey: opts.sdkKey,\n endpoint,\n storage: this.store,\n platform: \"web\",\n userId: this.userId,\n consent,\n debug: opts.debug,\n lifecycle: ({ background, foreground }) => {\n // `visibilitychange` is the last event a page reliably gets (tab switch,\n // close, navigation, mobile app switch); `pagehide` covers the bfcache.\n document.addEventListener(\"visibilitychange\", () => (document.visibilityState === \"hidden\" ? background() : foreground()));\n window.addEventListener(\"pagehide\", background);\n },\n });\n\n if (opts.analytics) {\n const store = this.store;\n this.analytics = new AnalyticsTracker({\n store,\n endpoint,\n sdkKey: opts.sdkKey,\n anonymousId: () => store.getSync(DEVICE_ID_KEY),\n userId: () => this.userId,\n superProps: () => this.superProps,\n groups: () => this.groups,\n isDebug: () => this.core.isDebug,\n isForgotten: () => this.core.forgotten,\n isInternal: () => this.isInternal,\n options: opts.analytics === true ? {} : opts.analytics,\n });\n this.analytics.start();\n for (const [id, set, once] of this.earlyIdentifies) this.analytics.identify(id, set, once);\n for (const [type, key, set, once] of this.earlyGroups) this.analytics.group(type, key, set, once);\n for (const [user, prev] of this.earlyAliases) this.analytics.alias(user, prev);\n for (const [name, props] of this.earlyCaptures) this.analytics.capture(name, props);\n }\n this.earlyCaptures = [];\n this.earlyIdentifies = [];\n this.earlyGroups = [];\n this.earlyAliases = [];\n this.ready = true;\n }\n\n /**\n * Mark this browser as the team's own (`true`) or as a visitor again (`false`) \u2014 what\n * opening the site with `?traqio_internal=1` / `=0` does. Its analytics events are\n * still sent, flagged: the console leaves them out of every figure by default and\n * shows them under \u00AB Internal traffic only \u00BB. Conversions (`track()`) are not\n * affected. Kept on the device, like the visitor id (and under the same consent).\n */\n setInternal(on: boolean): void {\n if (!this.store) return;\n try {\n if (on) this.store.setSync(INTERNAL_KEY, \"1\");\n else this.store.removeSync(INTERNAL_KEY);\n } catch {\n /* storage refused: nothing kept */\n }\n }\n\n /** True when this browser opted itself out as internal traffic \u2014 see `setInternal()`. */\n get isInternal(): boolean {\n try {\n return this.store?.getSync(INTERNAL_KEY) === \"1\";\n } catch {\n return false;\n }\n }\n\n /** Whether this page runs in debug mode \u2014 see `WebInitOptions.debug`. Settled by `init()`. */\n get isDebug(): boolean {\n return this.core.isDebug;\n }\n\n /** Record an event \u2014 `signup`, `purchase`, `add_to_cart`\u2026 Batched, retried, kept across page loads. */\n track(name: string, props?: WebTrackProps): void {\n this.core.track(name, props);\n }\n\n /**\n * A product-analytics event \u2014 `search_performed`, `pricing_toggled`\u2026 \u2014 read in the\n * console's Analytics section (events, funnels). NOT a conversion: it is never\n * billed nor sent to an ad network. A conversion (sign-up, purchase) is `track()`.\n * Needs `analytics` at init; names starting with `$` are reserved, but for an\n * experiment exposure: `capture(\"$exposure\", { experiment, variant })`.\n */\n capture(name: string, props?: Record<string, unknown>): void {\n if (this.analytics) this.analytics.capture(name, props);\n else if (!this.ready && this.earlyCaptures.length < 50) this.earlyCaptures.push([name, props]);\n }\n\n /**\n * Record a page view now. Not needed with the history API (route changes are\n * caught by themselves); for a router that changes the page another way.\n */\n pageview(): void {\n this.analytics?.pageview();\n }\n\n /** Set the user id once known (after sign-in). */\n setUserId(id: string): void {\n this.userId = id;\n this.core.setUserId(id);\n }\n\n /**\n * Who the user is, and what they are: sets the user id (like `setUserId`) and, with\n * traits, the user's PROPERTIES \u2014 `plan`, `role`, `company_size` \u2014 read in the\n * console as a breakdown, a report dimension and a cohort condition. Needs\n * `analytics` at init for the traits.\n *\n * Traqio.identify(\"u_123\", { plan: \"pro\", seats: 12 }, { signup_source: \"webinar\" });\n *\n * `traits` overwrite what was set before; `traitsOnce` are written only where the\n * user has no value yet. Text, numbers, booleans \u2014 never an email or a name. At most 50 keys.\n */\n identify(userId: string, traits?: Record<string, unknown>, traitsOnce?: Record<string, unknown>): void {\n const id = typeof userId === \"string\" ? userId.trim() : \"\";\n if (!id) return;\n this.setUserId(id);\n const set = cleanTraits(traits);\n const once = cleanTraits(traitsOnce);\n if (!Object.keys(set).length && !Object.keys(once).length) return;\n if (this.analytics) this.analytics.identify(id, set, once);\n else if (!this.ready && this.earlyIdentifies.length < 10) this.earlyIdentifies.push([id, set, once]);\n }\n\n /**\n * Super-properties: added to EVERY analytics event from now on, on this page and the\n * next ones \u2014 an A/B arm, a pricing variant, a theme. An event's own property of the\n * same name wins. Kept with the visitor id (same consent rules). `unregister(key)` removes one.\n *\n * Traqio.register({ pricing_variant: \"b\" });\n */\n register(props: Record<string, unknown>): void {\n this.superProps = cleanTraits({ ...this.superProps, ...cleanTraits(props) });\n this.persistSuperProps();\n }\n\n /** Stop adding one super-property to the events. */\n unregister(key: string): void {\n if (typeof key !== \"string\" || !(key in this.superProps)) return;\n const rest = { ...this.superProps };\n delete rest[key];\n this.superProps = rest;\n this.persistSuperProps();\n }\n\n /** The super-properties `register()` set \u2014 a copy. */\n getSuperProperties(): Traits {\n return { ...this.superProps };\n }\n\n /**\n * The B2B ACCOUNT the visitor works in (group analytics): every analytics event from\n * now on \u2014 on this page and the next ones \u2014 counts for it, so the console can count\n * accounts (unique accounts, funnels, retention, cohorts \u00AB by company \u00BB) and list them\n * with their traits. Call it after sign-in, and again on an account switch. Needs\n * `analytics` at init.\n *\n * Traqio.group(\"company\", \"acc_42\", { plan: \"enterprise\", seats: 40 });\n *\n * `groupType` is lowercase (`company`, `workspace`; 5 types at most), `groupKey` your\n * own account id \u2014 never an email. Traits follow identify's rules.\n */\n group(groupType: string, groupKey: string | number, traits?: Record<string, unknown>, traitsOnce?: Record<string, unknown>): void {\n const next = withGroup(this.groups, groupType, groupKey);\n if (!next) return;\n this.groups = next.groups;\n this.persistGroups();\n const set = cleanTraits(traits);\n const once = cleanTraits(traitsOnce);\n // Same account, nothing new to say: no entry (a group() on every page costs nothing).\n if (!next.changed && !Object.keys(set).length && !Object.keys(once).length) return;\n if (this.analytics) this.analytics.group(next.type, next.key, set, once);\n else if (!this.ready && this.earlyGroups.length < 10) this.earlyGroups.push([next.type, next.key, set, once]);\n }\n\n /** Stop stamping the events with any account \u2014 call it on sign-out. */\n resetGroups(): void {\n this.groups = {};\n this.persistGroups();\n }\n\n /** The accounts `group()` set, by type \u2014 a copy. */\n getGroups(): Groups {\n return { ...this.groups };\n }\n\n /**\n * Two ids, one person: the user known so far as `previousId` (a guest id, an id\n * from before sign-up) IS the current user (`setUserId` / `identify`). Their\n * analytics history and properties are merged under the current id \u2014 its own\n * properties win. From the browser only what THIS visitor sent under `previousId`\n * is merged; a backend (`@traqio/node`, secret key) merges everything.\n *\n * Traqio.identify(\"u_123\");\n * Traqio.alias(\"guest_8f2c\");\n *\n * Ignored without a current user id, or when `previousId` is the current one. Needs `analytics` at init.\n */\n alias(previousId: string): void {\n const prev = cleanUserId(previousId);\n const user = this.userId;\n if (!user || !prev || prev === user) return;\n if (this.analytics) this.analytics.alias(user, prev);\n else if (!this.ready && this.earlyAliases.length < 10) this.earlyAliases.push([user, prev]);\n }\n\n /**\n * Sign-out: forget who the user was in this browser \u2014 the user id, the\n * super-properties, the accounts \u2014 and end the analytics session, so the next\n * person's visit starts clean. Events already queued keep the user they were\n * captured under. The visitor id is KEPT: it carries the visitor's attribution\n * (the click, the campaign) for the next sign-up.\n */\n reset(): void {\n const user = this.userId;\n this.analytics?.reset(user);\n this.userId = undefined;\n this.core.reset();\n this.superProps = {};\n this.groups = {};\n this.earlyIdentifies = [];\n this.earlyGroups = [];\n this.earlyAliases = [];\n if (this.store) {\n this.persistSuperProps();\n this.persistGroups();\n } else this.resetBeforeInit = true;\n }\n\n /**\n * An experiment exposure: the visitor SAW `variant` of `experiment` \u2014 what the\n * console's experiment analysis reads (uplift, significance per variant). Your site\n * assigns the variant (its own flags, an edge split, a cookie); call this where the\n * visitor first meets it. Sends `$exposure { experiment, variant, ...props }`.\n *\n * Traqio.exposure(\"pricing_page\", \"annual_first\");\n */\n exposure(experiment: string, variant: string | number | boolean, props?: Record<string, unknown>): void {\n const p = exposureProps(experiment, variant, props);\n if (!p) return;\n // Over the 4 KB cap, the exposure alone rather than an event without its experiment.\n let fits = false;\n try {\n fits = JSON.stringify(p).length <= 4096;\n } catch {\n fits = false;\n }\n this.capture(\"$exposure\", fits ? p : { experiment: p.experiment, variant: p.variant });\n }\n\n private persistGroups(): void {\n try {\n if (!this.store) return; // before init(): init() merges and writes them\n if (Object.keys(this.groups).length) this.store.setSync(GROUPS_KEY, JSON.stringify(this.groups));\n else this.store.removeSync(GROUPS_KEY);\n } catch {\n /* storage refused: kept for this page */\n }\n }\n\n private persistSuperProps(): void {\n try {\n if (!this.store) return; // before init(): init() merges and writes them\n if (Object.keys(this.superProps).length) this.store.setSync(SUPER_PROPS_KEY, JSON.stringify(this.superProps));\n else this.store.removeSync(SUPER_PROPS_KEY);\n } catch {\n /* storage refused: kept for this page */\n }\n }\n\n /**\n * The visitor's consent answer. Governs sharing with ad networks, and \u2014 with\n * `waitForConsent` \u2014 whether anything may be stored: `true` writes out what the\n * page kept in memory (the trackID included), `false` removes everything this SDK\n * stored on the device.\n */\n async setConsent(granted: boolean): Promise<void> {\n if (!this.started) this.earlyConsent = granted;\n if (this.store && this.waitForConsent) {\n if (granted) {\n this.store.enable();\n this.trackIds?.persistCookie();\n this.sources?.persistCookie();\n } else {\n this.store.disable();\n }\n }\n await this.core.setConsent(granted);\n }\n\n /**\n * The trackID kept for this visitor, or null (no ad click, or expired). Pass it to\n * your backend with the sign-up or checkout \u2014 a hidden form field, a header \u2014 if\n * your backend cannot read the `traq_click` cookie itself.\n */\n getTrackId(): string | null {\n return this.trackIds?.get() ?? null;\n }\n\n /**\n * Where the visitor came from when no Traqio link brought them \u2014 the landing's\n * `utm_*`, an ad network's click id (`gclid`, `fbclid`, `ttclid`), the referring\n * site \u2014 or null. Kept in the `traq_src` cookie your backend reads with the\n * sign-up (`@traqio/node`: `sourceFromRequest(req)`); pass this to it instead\n * when your backend is on another domain. A Traqio link click wins over it.\n */\n getSource(): WebSource | null {\n return this.sources?.get() ?? null;\n }\n\n /**\n * GDPR erasure from the page: the server deletes what it holds about this browser\n * and user, and this SDK stops sending and forgets the trackID. Irreversible.\n * Resolves false when the request did not reach the server \u2014 then nothing changed.\n */\n async forgetMe(): Promise<boolean> {\n const ok = await this.core.forgetMe();\n if (ok) {\n this.trackIds?.clear();\n this.sources?.clear();\n this.analytics?.stop();\n this.superProps = {};\n this.persistSuperProps();\n this.groups = {};\n this.persistGroups();\n }\n return ok;\n }\n\n /** Send what is queued now. Already wired to tab hide and page exit. */\n flush(): void {\n this.core.flush();\n this.analytics?.flush(false);\n }\n\n /** True once `forgetMe()` has been honoured: this browser sends nothing any more. */\n get forgotten(): boolean {\n return this.core.forgotten;\n }\n}\n\n/** The shared instance \u2014 `import { Traqio } from \"@traqio/web\"`. */\nexport const Traqio = new TraqioWeb();\n", "// First-party cookies, on the site's registrable domain when the browser allows it.\n//\n// Why a cookie at all, next to localStorage: localStorage is per ORIGIN, so a visitor\n// who lands on `www.example.com` and signs up on `app.example.com` would be two\n// strangers. A cookie on `example.com` is shared by both \u2014 and it reaches the site's\n// own backend with the sign-up request, which is how a server reads the trackID\n// without any JavaScript.\n\n/** Every cookie the SDK writes carries this prefix \u2014 the same namespace as the URL. */\nexport const COOKIE_PREFIX = \"traq_\";\n\nfunction doc(): Document | undefined {\n return typeof document === \"undefined\" ? undefined : document;\n}\n\nexport function readCookie(name: string): string | null {\n const d = doc();\n if (!d) return null;\n for (const part of d.cookie ? d.cookie.split(\";\") : []) {\n const eq = part.indexOf(\"=\");\n if (eq < 0) continue;\n if (part.slice(0, eq).trim() === name) {\n try {\n return decodeURIComponent(part.slice(eq + 1).trim());\n } catch {\n return null;\n }\n }\n }\n return null;\n}\n\nfunction serialize(name: string, value: string, maxAgeSeconds: number, domain: string | null): string {\n const secure = typeof location !== \"undefined\" && location.protocol === \"https:\" ? \"; Secure\" : \"\";\n const scope = domain ? `; Domain=${domain}` : \"\";\n return `${name}=${encodeURIComponent(value)}; Max-Age=${Math.floor(maxAgeSeconds)}; Path=/${scope}; SameSite=Lax${secure}`;\n}\n\n/**\n * The widest domain this page may set a cookie on \u2014 `example.co.uk` for\n * `shop.example.co.uk`. There is no public-suffix list in a browser, so ask the\n * browser itself: try the shortest candidates first, and keep the first one it\n * accepts (it refuses `co.uk`, a public suffix). Null on `localhost` and IP\n * addresses, where a host-only cookie is the only kind there is.\n */\nexport function registrableDomain(hostname: string): string | null {\n const d = doc();\n if (!d || !hostname.includes(\".\") || /^[\\d.]+$/.test(hostname) || hostname.includes(\":\")) return null;\n const labels = hostname.split(\".\");\n const probe = `${COOKIE_PREFIX}probe`;\n for (let i = labels.length - 2; i >= 0; i--) {\n const candidate = labels.slice(i).join(\".\");\n d.cookie = serialize(probe, \"1\", 10, candidate);\n if (readCookie(probe) === \"1\") {\n d.cookie = serialize(probe, \"\", 0, candidate);\n return candidate;\n }\n }\n return null;\n}\n\nexport function writeCookie(name: string, value: string, maxAgeSeconds: number, domain: string | null): void {\n const d = doc();\n if (!d) return;\n try {\n d.cookie = serialize(name, value, maxAgeSeconds, domain);\n } catch {\n /* cookies disabled \u2014 localStorage still holds it on this origin */\n }\n}\n\nexport function deleteCookie(name: string, domain: string | null): void {\n writeCookie(name, \"\", 0, domain);\n}\n", "import { COOKIE_PREFIX, deleteCookie, readCookie, writeCookie } from \"./cookies\";\n\n/**\n * Keys that are mirrored into a cookie on the registrable domain, so `www.` and\n * `app.` of the same site share them. Only identifiers \u2014 the event queue stays in\n * localStorage, where it belongs (a cookie rides along on every request).\n */\nexport const DEVICE_ID_KEY = \"traq_device_id\";\n/**\n * \u00AB This browser is the team's own \u00BB (`?traqio_internal=1`, HQ cmwv9c10). Mirrored so\n * opting out on `www.` also covers `app.` \u2014 it is a flag, not an identifier, and says\n * nothing about the visitor beyond that.\n */\nexport const INTERNAL_KEY = \"traq_internal\";\nconst MIRRORED = new Set([DEVICE_ID_KEY, INTERNAL_KEY]);\nconst MIRROR_MAX_AGE_SECONDS = 395 * 24 * 60 * 60; // 13 months, the CNIL ceiling for a measurement cookie\n\nfunction local(): Storage | undefined {\n try {\n return typeof localStorage === \"undefined\" ? undefined : localStorage;\n } catch {\n return undefined; // Safari with storage blocked throws on mere access\n }\n}\n\n/**\n * @traqio/core's `KeyValueStore`, restated so the published .d.ts files never name\n * @traqio/core: it is bundled into this package, not installed next to it.\n */\ninterface KeyValueStore {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n}\n\n/**\n * The browser persistence behind @traqio/core: localStorage, plus a cookie mirror for\n * identifiers \u2014 or memory only, until the visitor agrees.\n *\n * `persistent: false` is the \"nothing on the device before consent\" mode: every\n * value lives in memory for this page, the SDK still works for this page view, and\n * `enable()` writes it all out the moment consent is given. `disable()` is the way\n * back: everything this SDK wrote is removed from the device, and the page goes on\n * in memory.\n */\nexport class BrowserStore implements KeyValueStore {\n private readonly memory = new Map<string, string>();\n\n constructor(\n private persistent: boolean,\n private readonly cookieDomain: () => string | null,\n private readonly cookies: boolean,\n ) {}\n\n get isPersistent(): boolean {\n return this.persistent;\n }\n\n async getItem(key: string): Promise<string | null> {\n return this.getSync(key);\n }\n\n async setItem(key: string, value: string): Promise<void> {\n this.setSync(key, value);\n }\n\n getSync(key: string): string | null {\n if (this.memory.has(key)) return this.memory.get(key) ?? null;\n if (!this.persistent) return null;\n let value: string | null = null;\n try {\n value = local()?.getItem(key) ?? null;\n } catch {\n /* blocked */\n }\n if (value === null && this.cookies && MIRRORED.has(key)) value = readCookie(key);\n return value;\n }\n\n setSync(key: string, value: string): void {\n if (!this.persistent) {\n this.memory.set(key, value);\n return;\n }\n let stored = false;\n try {\n const ls = local();\n if (ls) {\n ls.setItem(key, value);\n stored = true;\n }\n } catch {\n /* quota or blocked \u2014 fall through to memory */\n }\n if (!stored) this.memory.set(key, value);\n if (this.cookies && MIRRORED.has(key)) writeCookie(key, value, MIRROR_MAX_AGE_SECONDS, this.cookieDomain());\n }\n\n removeSync(key: string): void {\n this.memory.delete(key);\n try {\n local()?.removeItem(key);\n } catch {\n /* blocked */\n }\n if (this.cookies) deleteCookie(key, this.cookieDomain());\n }\n\n /** Consent given: what this page kept in memory goes to the device. */\n enable(): void {\n if (this.persistent) return;\n this.persistent = true;\n const pending = [...this.memory];\n this.memory.clear();\n for (const [key, value] of pending) this.setSync(key, value);\n }\n\n /**\n * Consent withdrawn: every `traq_*` value leaves the device (localStorage and\n * cookies) and stays in memory for the rest of this page, so nothing breaks\n * mid-visit and nothing survives it.\n */\n disable(): void {\n if (!this.persistent) return;\n const ls = local();\n const keys: string[] = [];\n try {\n for (let i = 0; ls && i < ls.length; i++) {\n const k = ls.key(i);\n if (k && k.startsWith(COOKIE_PREFIX)) keys.push(k);\n }\n } catch {\n /* blocked */\n }\n for (const k of MIRRORED) if (!keys.includes(k)) keys.push(k);\n for (const k of keys) {\n const value = this.getSync(k);\n if (value !== null) this.memory.set(k, value);\n }\n this.persistent = false;\n for (const k of keys) {\n try {\n ls?.removeItem(k);\n } catch {\n /* blocked */\n }\n if (this.cookies) deleteCookie(k, this.cookieDomain());\n }\n }\n}\n", "import { deleteCookie, readCookie, writeCookie } from \"./cookies\";\nimport type { BrowserStore } from \"./storage\";\n\n/** What localStorage holds for a kept value. The `{ id, exp }` shape predates `traq_src`: browsers already hold it for `traq_click`. */\ninterface Stored {\n id: string;\n /** Epoch ms after which the value is no longer kept. */\n exp: number;\n}\n\n/**\n * One value kept twice, on purpose:\n * - localStorage `<key>` = `{ id, exp }`: survives navigation on this origin;\n * - cookie `<key>` = the bare value, on the registrable domain: shared with the\n * other subdomains, and sent by the browser to the site's OWN backend with the\n * sign-up request \u2014 where the conversion that counts is known.\n *\n * Both writes go through the store's consent mode: before consent (with\n * `waitForConsent`) the value lives in memory and no cookie is written.\n */\nexport class KeptValue {\n constructor(\n private readonly store: BrowserStore,\n private readonly key: string,\n private readonly cookieDomain: () => string | null,\n private readonly cookies: boolean,\n /** A cookie value that fails this is ignored (another script's cookie, a tampered one). */\n private readonly valid: (value: string) => boolean,\n ) {}\n\n /** The kept value, or null once it has expired or was never there. */\n get(now = Date.now()): string | null {\n const raw = this.store.getSync(this.key);\n if (raw) {\n try {\n const parsed = JSON.parse(raw) as Stored;\n if (parsed && typeof parsed.id === \"string\" && parsed.exp > now) return parsed.id;\n } catch {\n /* corrupt \u2014 fall back to the cookie */\n }\n }\n // Another subdomain set it (localStorage is per origin, the cookie is not). The\n // cookie's own Max-Age is its expiry, so a cookie that is still there is valid.\n if (this.cookies && this.store.isPersistent) {\n const fromCookie = readCookie(this.key);\n if (fromCookie && this.valid(fromCookie)) return fromCookie;\n }\n return null;\n }\n\n set(value: string, maxAgeMs: number, now = Date.now()): void {\n const record: Stored = { id: value, exp: now + maxAgeMs };\n this.store.setSync(this.key, JSON.stringify(record));\n if (this.cookies && this.store.isPersistent) writeCookie(this.key, value, maxAgeMs / 1000, this.cookieDomain());\n }\n\n /** Removes it everywhere \u2014 `forgetMe()`. */\n clear(): void {\n this.store.removeSync(this.key);\n if (this.cookies) deleteCookie(this.key, this.cookieDomain());\n }\n\n /** Writes the cookie half once storage becomes allowed (the localStorage half moves with the store). */\n persistCookie(now = Date.now()): void {\n const raw = this.store.getSync(this.key);\n if (!raw || !this.cookies || !this.store.isPersistent) return;\n try {\n const parsed = JSON.parse(raw) as Stored;\n if (parsed.exp > now) writeCookie(this.key, parsed.id, (parsed.exp - now) / 1000, this.cookieDomain());\n } catch {\n /* corrupt \u2014 nothing to mirror */\n }\n }\n}\n", "import { KeptValue } from \"./kept\";\nimport type { BrowserStore } from \"./storage\";\n\n/**\n * Where a visitor came from when there was no Traqio link to click: the `utm_*`\n * parameters of the landing URL (an Instagram bio, a newsletter, a LinkedIn post),\n * the ad networks' own click ids (`gclid`, `fbclid`, `ttclid`), and the host of the\n * page that sent them (`document.referrer`).\n *\n * Kept like the trackID (`traq_click`) \u2014 localStorage + a first-party cookie\n * `traq_src`, same lifetime, same consent rules \u2014 so the site's backend reads it\n * with the sign-up request and sends it with the sign-up (`@traqio/node`:\n * `sourceFromRequest(req)`). Traqio then reports the sign-up under that source and\n * campaign. A Traqio link click, when there is one, wins over it.\n *\n * The cookie holds a query string \u2014 `utm_source=instagram&utm_campaign=launch&ts=\u2026`\n * \u2014 so any backend language parses it with its standard library.\n */\nexport const SOURCE_KEY = \"traq_src\";\n\n/** The landing-URL parameters kept, as written in the URL. */\nexport const SOURCE_PARAMS = [\"utm_source\", \"utm_medium\", \"utm_campaign\", \"utm_content\", \"utm_term\", \"gclid\", \"fbclid\", \"ttclid\"] as const;\n\n/** Each value is cut to this length: a cookie has ~4 KB for all of them. */\nconst MAX_VALUE_LENGTH = 200;\n\n/** Where the visitor came from \u2014 see `getSource()`. Every field is optional. */\nexport interface WebSource {\n utmSource?: string;\n utmMedium?: string;\n utmCampaign?: string;\n utmContent?: string;\n utmTerm?: string;\n /** Host of the page that linked here (`l.instagram.com`) \u2014 never its path or query. */\n referrer?: string;\n /** Google Ads click id. */\n gclid?: string;\n /** Meta click id (Facebook and Instagram links, paid or not). */\n fbclid?: string;\n /** TikTok Ads click id. */\n ttclid?: string;\n /** When the visitor landed with it, epoch ms. */\n landedAt?: number;\n}\n\nconst FIELD: Record<(typeof SOURCE_PARAMS)[number] | \"referrer\", keyof WebSource> = {\n utm_source: \"utmSource\",\n utm_medium: \"utmMedium\",\n utm_campaign: \"utmCampaign\",\n utm_content: \"utmContent\",\n utm_term: \"utmTerm\",\n gclid: \"gclid\",\n fbclid: \"fbclid\",\n ttclid: \"ttclid\",\n referrer: \"referrer\",\n};\n\nconst clean = (v: string | null): string | null => {\n const t = v?.trim();\n return t ? t.slice(0, MAX_VALUE_LENGTH) : null;\n};\n\nconst bare = (host: string): string => host.toLowerCase().replace(/^www\\./, \"\");\n\n/** Is `other` this site \u2014 the same host, a subdomain of it, or a parent of it? */\nfunction sameSite(host: string, other: string): boolean {\n const a = bare(host);\n const b = bare(other);\n return a === b || a.endsWith(`.${b}`) || b.endsWith(`.${a}`);\n}\n\n/**\n * The host of an EXTERNAL referrer, or null (none, this site, not http(s)). Only the\n * host: a referrer's path and query can carry anything, a search, an email address.\n */\nexport function referrerHost(referrer: string | null | undefined, pageHref: string): string | null {\n if (!referrer) return null;\n try {\n const ref = new URL(referrer);\n if (ref.protocol !== \"http:\" && ref.protocol !== \"https:\") return null;\n if (sameSite(new URL(pageHref).hostname, ref.hostname)) return null;\n return clean(bare(ref.hostname));\n } catch {\n return null;\n }\n}\n\n/**\n * The source a landing carries, as the query string kept in `traq_src`, or null\n * when it carries none. `fromUrl` = the landing URL itself carried a parameter (a\n * referrer-only landing does not).\n */\nexport function sourceFromLanding(href: string, referrer: string | null | undefined, now: number): { query: string; fromUrl: boolean } | null {\n const out = new URLSearchParams();\n try {\n const params = new URL(href).searchParams;\n for (const key of SOURCE_PARAMS) {\n const v = clean(params.get(key));\n if (v) out.set(key, v);\n }\n } catch {\n return null;\n }\n const fromUrl = out.toString() !== \"\";\n const ref = referrerHost(referrer, href);\n if (ref) out.set(\"referrer\", ref);\n if (out.toString() === \"\") return null;\n out.set(\"ts\", String(now));\n return { query: out.toString(), fromUrl };\n}\n\n/** The kept query string, as a `WebSource`. Null when it holds nothing we know. */\nexport function parseSource(query: string): WebSource | null {\n let params: URLSearchParams;\n try {\n params = new URLSearchParams(query);\n } catch {\n return null;\n }\n const source: WebSource = {};\n for (const [param, field] of Object.entries(FIELD)) {\n const v = clean(params.get(param));\n if (v) (source as Record<string, string>)[field] = v;\n }\n if (!Object.keys(source).length) return null;\n const ts = Number(params.get(\"ts\"));\n if (Number.isFinite(ts) && ts > 0) source.landedAt = ts;\n return source;\n}\n\nexport class SourceKeeper {\n private readonly kept: KeptValue;\n\n constructor(\n store: BrowserStore,\n private readonly maxAgeMs: number,\n cookieDomain: () => string | null,\n cookies: boolean,\n ) {\n this.kept = new KeptValue(store, SOURCE_KEY, cookieDomain, cookies, (v) => parseSource(v) !== null);\n }\n\n /**\n * Reads the landing. URL parameters (`utm_*`, a click id) REPLACE what is kept:\n * the last campaign that brought the visitor is the one that counts, as for the\n * trackID. A referrer alone only fills an empty slot \u2014 the return from a payment\n * page or a webmail must not overwrite the campaign the visitor came from. A\n * landing with neither (a typed URL, an internal navigation) changes nothing.\n */\n capture(href: string, referrer: string | null | undefined, now = Date.now()): WebSource | null {\n const landing = sourceFromLanding(href, referrer, now);\n if (!landing) return null;\n if (!landing.fromUrl && this.kept.get(now) !== null) return null;\n this.kept.set(landing.query, this.maxAgeMs, now);\n return parseSource(landing.query);\n }\n\n /** The kept source, or null (none, or expired). */\n get(now = Date.now()): WebSource | null {\n const query = this.kept.get(now);\n return query === null ? null : parseSource(query);\n }\n\n clear(): void {\n this.kept.clear();\n }\n\n persistCookie(now = Date.now()): void {\n this.kept.persistCookie(now);\n }\n}\n", "import { KeptValue } from \"./kept\";\nimport type { BrowserStore } from \"./storage\";\n\n/**\n * The trackID \u2014 the click id Traqio's tracking link appends to the landing URL as\n * `traq_click` (the same `traq_` namespace as the Play Install Referrer, so it never\n * collides with the site's own `utm_*`).\n *\n * Kept twice, on purpose:\n * - localStorage `traq_click` = `{ id, exp }`: survives navigation on this origin;\n * - cookie `traq_click` = the bare id, on the registrable domain: shared with the\n * other subdomains, and sent by the browser to the site's OWN backend with the\n * sign-up or checkout request \u2014 where the conversion that counts is known.\n */\nexport const CLICK_PARAM = \"traq_click\";\nconst STORE_KEY = \"traq_click\";\n\n/** What a click id looks like: Traqio mints UUIDs; anything else is refused, not stored. */\nconst CLICK_ID = /^[A-Za-z0-9_-]{8,64}$/;\n\n/** The click id carried by a URL, or null. Never throws on a malformed URL. */\nexport function clickIdFromUrl(href: string): string | null {\n try {\n const raw = new URL(href).searchParams.get(CLICK_PARAM);\n return raw && CLICK_ID.test(raw) ? raw : null;\n } catch {\n return null;\n }\n}\n\nexport class TrackIdKeeper {\n private readonly kept: KeptValue;\n\n constructor(\n store: BrowserStore,\n private readonly maxAgeMs: number,\n cookieDomain: () => string | null,\n cookies: boolean,\n ) {\n this.kept = new KeptValue(store, STORE_KEY, cookieDomain, cookies, (v) => CLICK_ID.test(v));\n }\n\n /**\n * Reads the landing URL. A new click REPLACES the kept one: the last ad clicked is\n * the one that brought the visitor this time. A URL without a click id changes\n * nothing \u2014 an internal navigation must not wipe the id the landing brought.\n */\n capture(href: string, now = Date.now()): string | null {\n const id = clickIdFromUrl(href);\n if (id) this.kept.set(id, this.maxAgeMs, now);\n return id;\n }\n\n /** The kept click id, or null once it has expired or was never there. */\n get(now = Date.now()): string | null {\n return this.kept.get(now);\n }\n\n /** Removes it everywhere \u2014 `forgetMe()`. */\n clear(): void {\n this.kept.clear();\n }\n\n /** Writes the cookie half once storage becomes allowed (the localStorage half moves with the store). */\n persistCookie(now = Date.now()): void {\n this.kept.persistCookie(now);\n }\n}\n", "// Core Web Vitals (HQ cmwuue1b) \u2014 LCP, INP, CLS, FCP and TTFB of the page load, measured\n// with the browser's own PerformanceObserver entries, the way Google's `web-vitals`\n// library reads them, without adding it as a dependency (a few hundred bytes here\n// against ~2 KB, and nothing to keep in step).\n//\n// One `$web_vitals` event per SAMPLED page load, sent once, when the page is first\n// hidden (tab switched, closed, navigated away) \u2014 the moment LCP is final and CLS / INP\n// have seen most of the visit. A client-side route change is not a new load: its\n// shifts and interactions count toward the load's CLS and INP, as in Chrome's own field\n// data (CrUX). Nothing personal: five numbers and the page the load started on.\n//\n// Pure where it can be: `VitalsCollector` is fed entries and answers a snapshot, so every\n// rule (CLS session windows, the INP percentile) is tested without a browser.\n\nexport interface WebVitalsOptions {\n /**\n * The share of page loads measured, 0\u20131. Default 0.5: half the loads is plenty for a\n * stable p75 on a busy page and still readable on a small site; lower it on a site\n * with millions of views, 1 to measure every load.\n */\n sampleRate?: number;\n}\n\nexport const DEFAULT_VITALS_SAMPLE_RATE = 0.5;\n\nexport interface VitalsSnapshot {\n lcp?: number;\n inp?: number;\n cls?: number;\n fcp?: number;\n ttfb?: number;\n}\n\n/** Whether this page load is measured. A rate outside 0\u20131 (or not a number) falls back to the default. */\nexport function sampled(rate: number | undefined, random: () => number = Math.random): boolean {\n const r = typeof rate === \"number\" && Number.isFinite(rate) && rate >= 0 && rate <= 1 ? rate : DEFAULT_VITALS_SAMPLE_RATE;\n if (r <= 0) return false;\n return r >= 1 || random() < r;\n}\n\n/** A CLS session window: shifts less than 1 s apart, the window at most 5 s long. */\nconst CLS_GAP_MS = 1000;\nconst CLS_WINDOW_MS = 5000;\n/** INP ignores one outlier per 50 interactions; keeping the 10 longest is enough to answer for 500. */\nconst INP_KEEP = 10;\n\nexport class VitalsCollector {\n private lcp: number | undefined;\n private fcp: number | undefined;\n private ttfb: number | undefined;\n private clsMax = 0;\n private clsSeen = false;\n private clsWindow = { value: 0, first: 0, last: 0 };\n /** The longest interactions, by interactionId: their longest entry. */\n private longest = new Map<number, number>();\n private interactions = new Set<number>();\n private inpSeen = false;\n\n /** A `largest-contentful-paint` entry: the latest one is the LCP. */\n addLcp(startTime: number): void {\n if (Number.isFinite(startTime) && startTime >= 0) this.lcp = startTime;\n }\n\n /** The `first-contentful-paint` paint entry. */\n addFcp(startTime: number): void {\n if (this.fcp === undefined && Number.isFinite(startTime) && startTime >= 0) this.fcp = startTime;\n }\n\n /** The navigation entry's `responseStart` (minus `activationStart` for a prerendered page). */\n setTtfb(ms: number): void {\n if (Number.isFinite(ms) && ms >= 0) this.ttfb = ms;\n }\n\n /**\n * A `layout-shift` entry. Shifts right after an input are expected and skipped; the\n * rest are grouped in session windows and CLS is the largest window's sum.\n */\n addShift(value: number, startTime: number, hadRecentInput: boolean): void {\n this.clsSeen = true;\n if (hadRecentInput || !Number.isFinite(value) || value < 0) return;\n const w = this.clsWindow;\n if (w.value > 0 && startTime - w.last < CLS_GAP_MS && startTime - w.first < CLS_WINDOW_MS) {\n w.value += value;\n w.last = startTime;\n } else {\n this.clsWindow = { value, first: startTime, last: startTime };\n }\n this.clsMax = Math.max(this.clsMax, this.clsWindow.value);\n }\n\n /** The browser supports layout shifts: a page that never moved has a CLS of 0, not none. */\n clsObserved(): void {\n this.clsSeen = true;\n }\n\n /** An `event` (or `first-input`) entry with an interactionId: one interaction's latency. */\n addInteraction(interactionId: number, duration: number): void {\n if (!interactionId || !Number.isFinite(duration) || duration < 0) return;\n this.inpSeen = true;\n this.interactions.add(interactionId);\n const prev = this.longest.get(interactionId);\n if (prev !== undefined && prev >= duration) return;\n this.longest.set(interactionId, duration);\n if (this.longest.size > INP_KEEP) {\n let minId = 0;\n let min = Infinity;\n for (const [id, d] of this.longest) {\n if (d < min) {\n min = d;\n minId = id;\n }\n }\n this.longest.delete(minId);\n }\n }\n\n /**\n * INP: the longest interaction, ignoring one per 50 \u2014 the 98th percentile for a busy\n * page, the worst one for an ordinary visit.\n */\n private inp(): number | undefined {\n if (!this.inpSeen || !this.longest.size) return undefined;\n const sorted = [...this.longest.values()].sort((a, b) => b - a);\n return sorted[Math.min(sorted.length - 1, Math.floor(this.interactions.size / 50))];\n }\n\n /** What was measured, rounded: ms for the timings, 4 decimals for CLS. Null when nothing was. */\n snapshot(): VitalsSnapshot | null {\n const out: VitalsSnapshot = {};\n if (this.lcp !== undefined) out.lcp = Math.round(this.lcp);\n const inp = this.inp();\n if (inp !== undefined) out.inp = Math.round(inp);\n if (this.clsSeen) out.cls = Math.round(this.clsMax * 10_000) / 10_000;\n if (this.fcp !== undefined) out.fcp = Math.round(this.fcp);\n if (this.ttfb !== undefined) out.ttfb = Math.round(this.ttfb);\n return Object.keys(out).length ? out : null;\n }\n}\n\ntype Entry = PerformanceEntry & {\n value?: number;\n hadRecentInput?: boolean;\n interactionId?: number;\n responseStart?: number;\n activationStart?: number;\n};\n\n/** Observes one entry type, buffered (what happened before the SDK loaded counts). Silent where unsupported. */\nfunction observe(type: string, onEntries: (entries: Entry[]) => void, extra: Record<string, unknown> = {}): boolean {\n try {\n const PO = (globalThis as { PerformanceObserver?: typeof PerformanceObserver }).PerformanceObserver;\n if (!PO || !PO.supportedEntryTypes?.includes(type)) return false;\n const po = new PO((list) => onEntries(list.getEntries() as Entry[]));\n po.observe({ type, buffered: true, ...extra } as PerformanceObserverInit);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Wires the observers onto a collector. A page that loaded in the background (opened in a\n * new tab) has no meaningful LCP or FCP \u2014 they would measure when the tab was looked at \u2014\n * so those two are only kept when the page started visible, as `web-vitals` does.\n */\nexport function watchVitals(c: VitalsCollector): void {\n const startedVisible = typeof document === \"undefined\" || document.visibilityState !== \"hidden\";\n let activation = 0;\n try {\n const nav = performance.getEntriesByType(\"navigation\")[0] as Entry | undefined;\n if (nav) {\n activation = Math.max(0, nav.activationStart ?? 0);\n if (typeof nav.responseStart === \"number\" && nav.responseStart > 0) c.setTtfb(Math.max(0, nav.responseStart - activation));\n }\n } catch {\n /* no Navigation Timing: no TTFB */\n }\n if (startedVisible) {\n let lcpFinal = false;\n // LCP stops at the first input: what loads after a click is the visitor's doing.\n const finalize = (): void => {\n lcpFinal = true;\n };\n for (const type of [\"keydown\", \"click\", \"pointerdown\"]) window.addEventListener(type, finalize, { once: true, capture: true });\n observe(\"largest-contentful-paint\", (es) => {\n if (lcpFinal) return;\n for (const e of es) c.addLcp(Math.max(0, e.startTime - activation));\n });\n observe(\"paint\", (es) => {\n for (const e of es) if (e.name === \"first-contentful-paint\") c.addFcp(Math.max(0, e.startTime - activation));\n });\n }\n if (observe(\"layout-shift\", (es) => es.forEach((e) => c.addShift(e.value ?? 0, e.startTime, !!e.hadRecentInput)))) c.clsObserved();\n // 40 ms is the threshold `web-vitals` uses: shorter interactions never decide an INP.\n observe(\"event\", (es) => es.forEach((e) => c.addInteraction(e.interactionId ?? 0, e.duration)), { durationThreshold: 40 });\n observe(\"first-input\", (es) => es.forEach((e) => c.addInteraction(e.interactionId ?? 0, e.duration)));\n}\n", "// Product analytics \u2014 page views, clicks, scroll depth, errors and custom analytics\n// events, posted to `POST /ingest/analytics` (HQ cmwksiam). What replaces PostHog on a\n// site: the traffic its owner reads, NOT the conversions an ad network is paid on.\n//\n// \u26A0\uFE0F An analytics event is never a conversion. `track()` stays the conversion door\n// (`/ingest`, metered, forwarded); `capture()` and everything captured here go to their\n// own route and their own table, which billing and forwarding never read. A page view\n// can therefore never be billed, whatever the site sends.\n//\n// No replay, no fingerprint, no form value: a click records the element's visible text\n// and link, never what was typed. Off unless the site turns it on (`analytics: true`).\nimport type { KeyValueStore } from \"@traqio/core\";\nimport { DEFAULT_VITALS_SAMPLE_RATE, sampled, VitalsCollector, watchVitals, type WebVitalsOptions } from \"./vitals\";\n\nexport interface AnalyticsOptions {\n /** A page view on load and on every client-side route change (history API). Default true. */\n pageviews?: boolean;\n /** Clicks on links and buttons: their text and link. Default true. */\n clicks?: boolean;\n /**\n * Rage clicks: 3 or more clicks within a second on the same spot, on ANY element \u2014\n * a dead button, a picture that looks like a link. One `$rageclick` per burst, with\n * the element's text and tag. Default true.\n */\n rageClicks?: boolean;\n /** The deepest of 25/50/75/100 % each page view reached, sent once per page view. Default true. */\n scroll?: boolean;\n /** Uncaught errors and unhandled promise rejections. Default true. */\n errors?: boolean;\n /**\n * Core Web Vitals \u2014 LCP, INP, CLS, FCP, TTFB \u2014 of a SAMPLE of page loads: one\n * `$web_vitals` per measured load, sent when the page is first hidden. Default on, at\n * `sampleRate` 0.5; `{ sampleRate: 0.1 }` on a very busy site, `false` to turn it off.\n */\n webVitals?: boolean | WebVitalsOptions;\n}\n\ntype Kind = \"pageview\" | \"custom\" | \"click\" | \"rageclick\" | \"scroll\" | \"error\" | \"vitals\";\n\n/** `identify(userId, traits)`: a user's properties, never an analytics row (the server's identify.ts). */\ninterface IdentifyEntry {\n kind: \"identify\";\n ts: number;\n userId: string;\n set?: Traits;\n setOnce?: Traits;\n}\n\n/** `group(type, key, traits)`: an account's properties, never an analytics row (the server's groups.ts). */\ninterface GroupEntry {\n kind: \"group\";\n ts: number;\n groupType: string;\n groupKey: string;\n set?: Traits;\n setOnce?: Traits;\n}\n\n/** `alias(previousId)`: two ids of one person, never an analytics row (the server's alias.ts). */\ninterface AliasEntry {\n kind: \"alias\";\n ts: number;\n userId: string;\n previousId: string;\n}\n\ntype Entry = IdentifyEntry | GroupEntry | AliasEntry;\ntype Queued = QueuedEvent | Entry;\nconst isEntry = (e: Queued): e is Entry => e.kind === \"identify\" || e.kind === \"group\" || e.kind === \"alias\";\n\n/** The accounts a visitor belongs to, by group type: `{ company: \"acme\" }`. */\nexport type Groups = Record<string, string>;\n\nconst GROUP_TYPE = /^[a-z][a-z0-9_]{0,29}$/;\n/** Group types held at once (the server's cap) \u2014 a new one past it is ignored. */\nexport const MAX_GROUP_TYPES = 5;\n\n/** A group type as the server takes it (`company`, `workspace`), or null. */\nexport function cleanGroupType(v: unknown): string | null {\n if (typeof v !== \"string\") return null;\n const t = v.trim();\n return GROUP_TYPE.test(t) ? t : null;\n}\n\n/** An account key: trimmed text (or a number) of 1\u2013256 characters, or null. */\nexport function cleanGroupKey(v: unknown): string | null {\n if (typeof v === \"number\" && Number.isFinite(v)) return String(v);\n if (typeof v !== \"string\") return null;\n const t = v.trim();\n return t && t.length <= 256 ? t : null;\n}\n\n/** Stored groups re-read through the same rules: valid pairs only, at most 5. */\nexport function cleanGroups(v: unknown): Groups {\n const out: Groups = {};\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) return out;\n for (const [t, k] of Object.entries(v as Record<string, unknown>)) {\n if (Object.keys(out).length >= MAX_GROUP_TYPES) break;\n const type = cleanGroupType(t);\n const key = cleanGroupKey(k);\n if (type && key) out[type] = key;\n }\n return out;\n}\n\n/** The groups after `group(type, key)`, or null to ignore the call (bad type/key, a 6th new type); `changed` = a new key. */\nexport function withGroup(groups: Groups, type: unknown, key: unknown): { groups: Groups; type: string; key: string; changed: boolean } | null {\n const t = cleanGroupType(type);\n const k = cleanGroupKey(key);\n if (!t || !k) return null;\n if (!(t in groups) && Object.keys(groups).length >= MAX_GROUP_TYPES) return null;\n return { groups: { ...groups, [t]: k }, type: t, key: k, changed: groups[t] !== k };\n}\n\n/** A user property or super-property value: a label to segment by. */\nexport type TraitValue = string | number | boolean;\nexport type Traits = Record<string, TraitValue>;\n\nconst TRAIT_KEY = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/;\n/** Traits one identify call carries at most, and super-properties kept at most (the server's cap). */\nexport const MAX_TRAITS = 50;\n/** An event's properties, serialised, at most this long on the server \u2014 past it they are dropped. */\nconst MAX_PROPS_BYTES = 4096;\n\n/**\n * Traits as the server keeps them: valid keys, values that are text (cut at 200), a\n * finite number or a boolean \u2014 a nested object, null or a function never travels.\n */\nexport function cleanTraits(v: unknown): Traits {\n const out: Traits = {};\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) return out;\n for (const [k, raw] of Object.entries(v as Record<string, unknown>)) {\n if (Object.keys(out).length >= MAX_TRAITS) break;\n if (!TRAIT_KEY.test(k)) continue;\n if (typeof raw === \"string\") {\n const t = raw.trim();\n if (t) out[k] = t.slice(0, 200);\n } else if ((typeof raw === \"number\" && Number.isFinite(raw)) || typeof raw === \"boolean\") {\n out[k] = raw;\n }\n }\n return out;\n}\n\n/** An event's properties over the super-properties (the event's own win); past the server's cap, its own alone. */\nexport function withSuperProps(own: Record<string, unknown> | undefined, sup: Traits): Record<string, unknown> | undefined {\n if (!Object.keys(sup).length) return own;\n const merged = { ...sup, ...(own ?? {}) };\n try {\n return JSON.stringify(merged).length <= MAX_PROPS_BYTES ? merged : own;\n } catch {\n return own;\n }\n}\n\ninterface QueuedEvent {\n /**\n * The event's own id: a batch re-sent after a request that landed but reported a\n * failure (a keepalive fetch on a hidden Chrome Android page) is stored once \u2014 the\n * server derives the row's key from it and skips a key it already holds.\n */\n id: string;\n kind: Kind;\n name?: string;\n ts: number;\n url: string;\n title?: string;\n sessionId: string;\n src?: SessionSource;\n props?: Record<string, unknown>;\n /** The accounts held when it was queued (`group()`). */\n groups?: Groups;\n /**\n * Never sent: the user id it was captured under, stamped by `reset()` on what was\n * still queued \u2014 a sign-out never re-files the last events under nobody. Absent = the current one.\n */\n asUser?: string;\n}\n\n/** Where the SESSION landed from \u2014 copied on each of its events (the server stores it per row). */\nexport interface SessionSource {\n utmSource?: string;\n utmMedium?: string;\n utmCampaign?: string;\n utmContent?: string;\n utmTerm?: string;\n referrer?: string;\n gclid?: string;\n fbclid?: string;\n ttclid?: string;\n}\n\ninterface StoredSession {\n id: string;\n /** Last activity, epoch ms. */\n last: number;\n src?: SessionSource;\n}\n\nexport interface AnalyticsDeps {\n store: KeyValueStore & { getSync(key: string): string | null; setSync(key: string, value: string): void; removeSync(key: string): void };\n endpoint: string;\n sdkKey: string;\n anonymousId: () => string | null;\n userId: () => string | undefined;\n /** `group()`'s accounts, read at each event. */\n groups?: () => Groups;\n /** `register()`'s super-properties, read at each event. */\n superProps?: () => Traits;\n isDebug: () => boolean;\n isForgotten: () => boolean;\n /** The browser opted itself out as the team's own (`?traqio_internal=1`): batches say so. */\n isInternal?: () => boolean;\n options: AnalyticsOptions;\n}\n\nexport const SESSION_KEY = \"traq_session\";\n\n/** A user id as the server takes it (alias.ts): trimmed text (or a number) of 1\u2013256 characters, or null. */\nexport function cleanUserId(v: unknown): string | null {\n if (typeof v === \"number\" && Number.isFinite(v)) return String(v);\n if (typeof v !== \"string\") return null;\n const t = v.trim();\n return t && t.length <= 256 ? t : null;\n}\n\n/** Experiment and variant as `$exposure` carries them: trimmed text of 1\u2013200 characters (a number or boolean variant as text). */\nfunction exposureText(v: unknown): string | null {\n const t = typeof v === \"string\" ? v.trim() : (typeof v === \"number\" && Number.isFinite(v)) || typeof v === \"boolean\" ? String(v) : \"\";\n return t && t.length <= 200 ? t : null;\n}\n\n/** `exposure()`'s properties \u2014 `{ ...props, experiment, variant }`, the two named ones winning \u2014 or null to ignore the call. */\nexport function exposureProps(experiment: unknown, variant: unknown, props?: Record<string, unknown>): Record<string, unknown> | null {\n const e = exposureText(experiment);\n const v = exposureText(variant);\n if (!e || !v) return null;\n return { ...(props && typeof props === \"object\" && !Array.isArray(props) ? props : {}), experiment: e, variant: v };\n}\n\n/**\n * Takes (splices) the next batch off `queue`: the leading events captured under ONE\n * user (`asUser`, else `current`) \u2014 entries ride with any batch \u2014 and that user. The\n * events keep their stamp, so a requeued batch still knows its user; the request drops it.\n */\nexport function takeBatch<T extends { kind: string; asUser?: string }>(queue: T[], current: string | undefined, max: number): { events: T[]; userId: string | undefined } {\n let n = 0;\n let userId = current;\n let fixed = false;\n for (const e of queue) {\n if (n >= max) break;\n const entry = e.kind === \"identify\" || e.kind === \"group\" || e.kind === \"alias\";\n if (!entry) {\n const who = e.asUser !== undefined ? e.asUser || undefined : current;\n if (!fixed) {\n userId = who;\n fixed = true;\n } else if (who !== userId) break;\n }\n n++;\n }\n return { events: queue.splice(0, n), userId };\n}\n/** 30 minutes without activity end a session \u2014 the convention PostHog and GA share. */\nexport const SESSION_IDLE_MS = 30 * 60 * 1000;\nconst FLUSH_EVERY_MS = 5000;\nconst FLUSH_AT = 20;\nconst MAX_QUEUE = 200;\nconst MAX_ERRORS_PER_PAGE = 10;\n/**\n * The rejection a mail link scanner's harness throws (Outlook Safe Links / Microsoft\n * Defender, HQ cmwwyam8) \u2014 the server's link-scanner.ts holds the same signature.\n */\nconst LINK_SCANNER_ERROR = /^Object Not Found Matching Id:\\d+, MethodName:\\w+, ParamCount:\\d+$/;\nconst SCROLL_STEPS = [25, 50, 75, 100] as const;\nconst UTM: Array<[string, keyof SessionSource]> = [\n [\"utm_source\", \"utmSource\"],\n [\"utm_medium\", \"utmMedium\"],\n [\"utm_campaign\", \"utmCampaign\"],\n [\"utm_content\", \"utmContent\"],\n [\"utm_term\", \"utmTerm\"],\n [\"gclid\", \"gclid\"],\n [\"fbclid\", \"fbclid\"],\n [\"ttclid\", \"ttclid\"],\n];\n\nfunction newId(): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") return crypto.randomUUID();\n } catch {\n /* fall through */\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;\n}\n\n/** The landing's source: the URL's utm_* and click ids, and the referrer when it is another site. */\nexport function landingSource(href: string, referrer: string): SessionSource | undefined {\n const src: SessionSource = {};\n try {\n const u = new URL(href);\n for (const [param, key] of UTM) {\n const v = u.searchParams.get(param)?.trim();\n if (v) src[key] = v.slice(0, 200);\n }\n if (referrer) {\n const r = new URL(referrer);\n if (r.hostname.replace(/^www\\./, \"\") !== u.hostname.replace(/^www\\./, \"\")) src.referrer = `${r.protocol}//${r.host}/`;\n }\n } catch {\n /* an unparsable URL has no source */\n }\n return Object.keys(src).length ? src : undefined;\n}\n\n/** A URL without its query string or fragment \u2014 tokens and emails live there. */\nfunction bare(href: string | null | undefined): string | undefined {\n if (!href) return undefined;\n try {\n const u = new URL(href, typeof location !== \"undefined\" ? location.href : undefined);\n if (u.protocol !== \"http:\" && u.protocol !== \"https:\") return undefined;\n return `${u.origin}${u.pathname}`;\n } catch {\n return undefined;\n }\n}\n\n/** Clicks within this long of the burst's first one, and this close to it, are one burst. */\nexport const RAGE_WINDOW_MS = 1000;\nexport const RAGE_RADIUS_PX = 30;\nexport const RAGE_THRESHOLD = 3;\n\n/**\n * Rage-click detection, pure: feed it every click's position and time, it answers\n * `true` ONCE per burst \u2014 on the click that makes the third within a second and 30 px\n * of the burst's first. The burst then has to go quiet for a second before another\n * can be reported, so ten furious clicks are one rage click, not three.\n */\nexport class RageClickDetector {\n private burst: { x: number; y: number; first: number; last: number; count: number; reported: boolean } | null = null;\n\n hit(x: number, y: number, t: number): boolean {\n const b = this.burst;\n const near = b !== null && t - b.last <= RAGE_WINDOW_MS && Math.hypot(x - b.x, y - b.y) <= RAGE_RADIUS_PX;\n // A new spot, a pause, or three clicks that took longer than a second: a new burst.\n if (!near || (!b.reported && t - b.first > RAGE_WINDOW_MS)) {\n this.burst = { x, y, first: t, last: t, count: 1, reported: false };\n return false;\n }\n // A reported burst stays open (and silent) while clicks keep coming.\n b.count++;\n b.last = t;\n if (b.reported || b.count < RAGE_THRESHOLD) return false;\n b.reported = true;\n return true;\n }\n}\n\nexport class AnalyticsTracker {\n private queue: Queued[] = [];\n private timer: ReturnType<typeof setInterval> | null = null;\n private lastPath: string | null = null;\n private maxScroll = 0;\n private scrollUrl: string | null = null;\n private errorsThisPage = 0;\n private stopped = false;\n /** This page is driven by a mail link scanner: every later batch says so (the server keeps it out of the figures). */\n private scanner = false;\n private readonly rage = new RageClickDetector();\n private vitals: VitalsCollector | null = null;\n private vitalsUrl: string | null = null;\n\n constructor(private readonly deps: AnalyticsDeps) {}\n\n /** Wires the listeners the options ask for and records the first page view. */\n start(): void {\n const o = this.deps.options;\n this.timer = setInterval(() => this.flush(false), FLUSH_EVERY_MS);\n document.addEventListener(\"visibilitychange\", () => {\n if (document.visibilityState === \"hidden\") this.leave();\n });\n window.addEventListener(\"pagehide\", () => this.leave());\n\n if (o.pageviews !== false) {\n this.pageview();\n this.watchRoutes();\n }\n if (o.clicks !== false) document.addEventListener(\"click\", (e: Event) => this.onClick(e), true);\n if (o.rageClicks !== false) document.addEventListener(\"click\", (e: Event) => this.onRageClick(e as MouseEvent), true);\n if (o.scroll !== false) window.addEventListener(\"scroll\", () => this.onScroll(), { passive: true } as AddEventListenerOptions);\n if (o.errors !== false) {\n window.addEventListener(\"error\", (e: Event) => this.onError(e as ErrorEvent));\n window.addEventListener(\"unhandledrejection\", (e: Event) => this.onRejection(e as PromiseRejectionEvent));\n }\n if (o.webVitals !== false) {\n const rate = typeof o.webVitals === \"object\" ? o.webVitals.sampleRate : DEFAULT_VITALS_SAMPLE_RATE;\n // The draw is per page LOAD: a measured load is measured whole, an unmeasured one costs nothing.\n if (sampled(rate)) {\n this.vitals = new VitalsCollector();\n this.vitalsUrl = bare(location.href) ?? null;\n watchVitals(this.vitals);\n }\n }\n }\n\n /** A custom analytics event \u2014 never a conversion (that is `track()`). */\n capture(name: string, props?: Record<string, unknown>): void {\n // `$\u2026` is reserved, but for the experiment exposure `$exposure { experiment, variant }`.\n if (typeof name !== \"string\" || !name.trim() || (name.startsWith(\"$\") && name.trim() !== \"$exposure\")) return;\n this.enqueue({ kind: \"custom\", name: name.trim(), props });\n }\n\n /**\n * The user's properties (`identify(userId, traits, traitsOnce)`): one entry in the\n * batch, under its own user id. Not activity \u2014 it neither opens nor prolongs a session.\n */\n identify(userId: string, set: Traits, setOnce: Traits): void {\n if (this.stopped || !userId) return;\n const hasSet = Object.keys(set).length > 0;\n const hasOnce = Object.keys(setOnce).length > 0;\n if (!hasSet && !hasOnce) return;\n this.queue.push({ kind: \"identify\", ts: Date.now(), userId, ...(hasSet ? { set } : {}), ...(hasOnce ? { setOnce } : {}) });\n if (this.queue.length > MAX_QUEUE) this.queue.shift();\n if (this.queue.length >= FLUSH_AT) this.flush(false);\n }\n\n /** An account's properties (`group(type, key, traits)`): one entry in the batch. Not activity either. */\n group(groupType: string, groupKey: string, set: Traits, setOnce: Traits): void {\n if (this.stopped) return;\n const hasSet = Object.keys(set).length > 0;\n const hasOnce = Object.keys(setOnce).length > 0;\n this.queue.push({ kind: \"group\", ts: Date.now(), groupType, groupKey, ...(hasSet ? { set } : {}), ...(hasOnce ? { setOnce } : {}) });\n if (this.queue.length > MAX_QUEUE) this.queue.shift();\n if (this.queue.length >= FLUSH_AT) this.flush(false);\n }\n\n /** Two ids, one person (`alias(previousId)`): one entry in the batch, under the current user. Not activity. */\n alias(userId: string, previousId: string): void {\n if (this.stopped) return;\n this.queue.push({ kind: \"alias\", ts: Date.now(), userId, previousId });\n if (this.queue.length > MAX_QUEUE) this.queue.shift();\n if (this.queue.length >= FLUSH_AT) this.flush(false);\n }\n\n /**\n * Sign-out (`reset()`): what is queued keeps `userId`, the user it was captured\n * under, and the session ends \u2014 the next event opens a new one.\n */\n reset(userId: string | undefined): void {\n if (userId) for (const e of this.queue) if (!isEntry(e) && e.asUser === undefined) e.asUser = userId;\n try {\n this.deps.store.removeSync(SESSION_KEY);\n } catch {\n /* storage refused: nothing kept anyway */\n }\n }\n\n /** Records a page view of the current URL. Called by itself on route changes; exposed for routers that need it. */\n pageview(): void {\n const url = bare(location.href);\n if (!url) return;\n if (url === this.lastPath) return;\n this.sendScroll();\n this.lastPath = url;\n this.scrollUrl = url;\n this.maxScroll = 0;\n this.errorsThisPage = 0;\n this.enqueue({ kind: \"pageview\" });\n this.onScroll();\n }\n\n /** Sends what is queued. `leaving` = the page is going away: keepalive, so the request outlives it. */\n flush(leaving: boolean): void {\n if (!this.queue.length || this.stopped) return;\n if (this.deps.isForgotten()) {\n this.stop();\n return;\n }\n const anonymousId = this.deps.anonymousId();\n if (!anonymousId) return;\n // One user per request: events queued before a reset() keep the user they were captured under.\n const taken = takeBatch(this.queue, this.deps.userId(), 100);\n const userId = taken.userId;\n // A retried batch goes back under the user it was sent for, even if a reset() came in between.\n const events = userId ? taken.events.map((e) => (isEntry(e) || e.asUser !== undefined ? e : { ...e, asUser: userId })) : taken.events;\n const body = JSON.stringify({\n sdkKey: this.deps.sdkKey,\n anonymousId,\n userId,\n debug: this.deps.isDebug() || undefined,\n internal: this.deps.isInternal?.() || undefined,\n scanner: this.scanner || undefined,\n events: events.map((e) => (isEntry(e) ? e : { ...e, asUser: undefined })),\n });\n try {\n void fetch(`${this.deps.endpoint}/ingest/analytics`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body,\n keepalive: leaving,\n })\n .then((res) => {\n // A 5xx or a 429 is worth one more try; a 4xx is the batch's own fault and is dropped.\n if (!res.ok && (res.status >= 500 || res.status === 429)) this.requeue(events);\n })\n .catch(() => this.requeue(events));\n } catch {\n this.requeue(events);\n }\n }\n\n /** Forget everything and stop: after `forgetMe()`, or on a server. */\n stop(): void {\n this.stopped = true;\n this.queue = [];\n if (this.timer) clearInterval(this.timer);\n this.timer = null;\n }\n\n // \u2500\u2500 internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private requeue(events: Queued[]): void {\n if (this.stopped) return;\n this.queue = [...events, ...this.queue].slice(-MAX_QUEUE);\n }\n\n private session(): StoredSession {\n const now = Date.now();\n let s: StoredSession | null = null;\n try {\n const raw = this.deps.store.getSync(SESSION_KEY);\n s = raw ? (JSON.parse(raw) as StoredSession) : null;\n } catch {\n s = null;\n }\n if (!s || typeof s.id !== \"string\" || typeof s.last !== \"number\" || now - s.last > SESSION_IDLE_MS) {\n s = { id: newId(), last: now, src: landingSource(location.href, document.referrer) };\n } else {\n s.last = now;\n }\n try {\n this.deps.store.setSync(SESSION_KEY, JSON.stringify(s));\n } catch {\n /* storage refused: the session lives for this page */\n }\n return s;\n }\n\n private enqueue(e: Omit<QueuedEvent, \"id\" | \"ts\" | \"url\" | \"sessionId\" | \"src\" | \"title\"> & { url?: string }): void {\n if (this.stopped) return;\n const s = this.session();\n const title = typeof document.title === \"string\" && document.title ? document.title.slice(0, 200) : undefined;\n // Super-properties ride on every event whose properties the server keeps (a scroll\n // depth and a vitals sample are rebuilt there from their own fields).\n const props = e.kind === \"scroll\" || e.kind === \"vitals\" ? e.props : withSuperProps(e.props, this.deps.superProps?.() ?? {});\n // The accounts ride on EVERY row: a scroll or a vitals sample is the account's activity too.\n const g = this.deps.groups?.() ?? {};\n const groups = Object.keys(g).length ? { ...g } : undefined;\n this.queue.push({ ...e, ...(props ? { props } : {}), ...(groups ? { groups } : {}), id: newId(), ts: Date.now(), url: e.url ?? bare(location.href) ?? \"\", title, sessionId: s.id, ...(s.src ? { src: s.src } : {}) });\n if (this.queue.length > MAX_QUEUE) this.queue.shift();\n if (this.queue.length >= FLUSH_AT) this.flush(false);\n }\n\n private leave(): void {\n this.sendScroll();\n this.sendVitals();\n this.flush(true);\n }\n\n /** Once per load, at the first hide: LCP is final then, and CLS and INP have seen the visit. */\n private sendVitals(): void {\n const c = this.vitals;\n if (!c || !this.vitalsUrl) return;\n this.vitals = null;\n const props = c.snapshot();\n if (props) this.enqueue({ kind: \"vitals\", url: this.vitalsUrl, props: { ...props } });\n }\n\n /** Single-page apps change the URL through the history API: wrap it, and listen for back/forward. */\n private watchRoutes(): void {\n if (typeof history === \"undefined\") return;\n const after = (): void => {\n // The router updates the title right after the URL: read it on the next tick.\n setTimeout(() => this.pageview(), 0);\n };\n for (const method of [\"pushState\", \"replaceState\"] as const) {\n const original = history[method];\n if (typeof original !== \"function\") continue;\n history[method] = function (this: History, ...args: Parameters<History[\"pushState\"]>) {\n const out = original.apply(this, args);\n after();\n return out;\n } as History[\"pushState\"];\n }\n window.addEventListener(\"popstate\", after);\n }\n\n private onScroll(): void {\n if (typeof document.documentElement === \"undefined\" || !document.documentElement) return;\n const doc = document.documentElement;\n const viewport = window.innerHeight || doc.clientHeight || 0;\n const height = Math.max(doc.scrollHeight || 0, document.body?.scrollHeight || 0);\n if (!height) return;\n // A page shorter than the screen has been read to the bottom by being shown.\n const seen = height <= viewport ? 1 : Math.min(1, ((window.scrollY || doc.scrollTop || 0) + viewport) / height);\n const pct = Math.round(seen * 100);\n for (const step of SCROLL_STEPS) if (pct >= step && step > this.maxScroll) this.maxScroll = step;\n }\n\n private sendScroll(): void {\n if (this.deps.options.scroll === false || !this.scrollUrl || this.maxScroll < 25) return;\n this.enqueue({ kind: \"scroll\", url: this.scrollUrl, props: { depth: this.maxScroll } });\n this.scrollUrl = null;\n this.maxScroll = 0;\n }\n\n private onClick(e: Event): void {\n const target = e.target as Element | null;\n const el = target && typeof target.closest === \"function\" ? target.closest(\"a, button, [role='button'], input[type='submit'], input[type='button']\") : null;\n if (!el || el.closest(\"[data-traqio-ignore]\")) return;\n const input = el as HTMLInputElement;\n const text = (el.tagName === \"INPUT\" ? input.value : (el as HTMLElement).innerText || el.textContent || \"\").replace(/\\s+/g, \" \").trim().slice(0, 100);\n const href = el.tagName === \"A\" ? bare((el as HTMLAnchorElement).getAttribute(\"href\")) : undefined;\n const props: Record<string, unknown> = { tag: el.tagName.toLowerCase() };\n if (text) props.text = text;\n if (href) props.href = href;\n if (el.id) props.id = el.id.slice(0, 100);\n this.enqueue({ kind: \"click\", props });\n }\n\n /** Any element: frustration is most telling where nothing was clickable. */\n private onRageClick(e: MouseEvent): void {\n const x = typeof e.clientX === \"number\" ? e.clientX : 0;\n const y = typeof e.clientY === \"number\" ? e.clientY : 0;\n if (!this.rage.hit(x, y, Date.now())) return;\n const target = e.target as Element | null;\n if (!target || typeof target.closest !== \"function\" || target.closest(\"[data-traqio-ignore]\")) return;\n const el = (target.closest(\"a, button, [role='button'], input[type='submit'], input[type='button']\") ?? target) as HTMLElement;\n const text = (el.tagName === \"INPUT\" ? (el as HTMLInputElement).value : el.innerText || el.textContent || \"\").replace(/\\s+/g, \" \").trim().slice(0, 100);\n const props: Record<string, unknown> = { tag: el.tagName.toLowerCase(), count: RAGE_THRESHOLD };\n if (text) props.text = text;\n const href = el.tagName === \"A\" ? bare((el as HTMLAnchorElement).getAttribute(\"href\")) : undefined;\n if (href) props.href = href;\n if (el.id) props.id = el.id.slice(0, 100);\n this.enqueue({ kind: \"rageclick\", props });\n }\n\n private onError(e: ErrorEvent): void {\n if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;\n const message = (e.message || (e.error instanceof Error ? e.error.message : \"\") || \"Script error\").slice(0, 300);\n if (LINK_SCANNER_ERROR.test(message.replace(/^Uncaught (?:Error: )?/, \"\"))) this.scanner = true;\n this.errorsThisPage++;\n const stack = e.error instanceof Error && typeof e.error.stack === \"string\" ? e.error.stack.slice(0, 1500) : undefined;\n this.enqueue({ kind: \"error\", props: { message, ...(stack ? { stack } : {}), ...(e.filename ? { source: bare(e.filename) } : {}), ...(e.lineno ? { line: e.lineno } : {}) } });\n }\n\n private onRejection(e: PromiseRejectionEvent): void {\n if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;\n const reason = e.reason;\n const message = (reason instanceof Error ? reason.message : typeof reason === \"string\" ? reason : \"Unhandled promise rejection\").slice(0, 300);\n if (LINK_SCANNER_ERROR.test(message)) this.scanner = true;\n this.errorsThisPage++;\n const stack = reason instanceof Error && typeof reason.stack === \"string\" ? reason.stack.slice(0, 1500) : undefined;\n this.enqueue({ kind: \"error\", props: { message, unhandledRejection: true, ...(stack ? { stack } : {}) } });\n }\n}\n", "// The <script>-tag build (build/traqio.min.js): sets `window.Traqio`, and initialises\n// itself when the tag carries a key \u2014\n//\n// <script src=\".../traqio.min.js\" data-sdk-key=\"tq_web_\u2026\" async></script>\n//\n// Optional: data-endpoint, data-wait-for-consent=\"true\", data-analytics=\"true\" (product analytics).\nimport { Traqio, TraqioWeb } from \"./index\";\n\ndeclare global {\n interface Window {\n Traqio: TraqioWeb;\n }\n}\n\nwindow.Traqio = Traqio;\n\nconst tag = document.currentScript as HTMLScriptElement | null;\nconst sdkKey = tag?.dataset.sdkKey;\nif (sdkKey) {\n void Traqio.init({\n sdkKey,\n endpoint: tag?.dataset.endpoint || undefined,\n waitForConsent: tag?.dataset.waitForConsent === \"true\",\n analytics: tag?.dataset.analytics === \"true\",\n });\n}\n"],
5
+ "mappings": "+0BAgEAA,EAAA,aAAAC,GAcAD,EAAA,iBAAAE,GAyBAF,EAAA,oBAAAG,GASAH,EAAA,mBAAAI,GAcAJ,EAAA,sBAAAK,GApFaL,EAAA,mBAA8F,CACzG,CAAE,OAAQ,EAAG,WAAY,EAAG,SAAU,EAAE,EACxC,CAAE,OAAQ,EAAG,WAAY,GAAI,SAAU,GAAG,EAC1C,CAAE,OAAQ,EAAG,W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AK,SACnB,CACF,EAGaqD,GAAS,IAAIvD,GQ7hB1B,OAAO,OAASwD,GAEhB,IAAMC,EAAM,SAAS,cACfC,GAASD,GAAA,YAAAA,EAAK,QAAQ,OACxBC,IACGF,GAAO,KAAK,CACf,OAAAE,GACA,UAAUD,GAAA,YAAAA,EAAK,QAAQ,WAAY,OACnC,gBAAgBA,GAAA,YAAAA,EAAK,QAAQ,kBAAmB,OAChD,WAAWA,GAAA,YAAAA,EAAK,QAAQ,aAAc,MACxC,CAAC",
6
+ "names": ["exports", "windowForAge", "shouldLockWindow", "fineValueForRevenue", "fineValueForEvents", "coarseValueForRevenue", "hoursSinceInstall", "found", "w", "windows", "current", "rule", "MAX_FINE_VALUE", "MAX_EVENT_BITS", "revenue", "buckets", "value", "i", "events", "bits", "reached", "name", "tiers", "best", "bestThreshold", "tier", "threshold", "EMPTY_STATE", "Skan", "opts", "amount", "m", "fine", "coarse", "_a", "_b", "since", "hours", "doFetch", "res", "body", "raw", "exports", "cleanUserId", "isEntry", "nextAnalyticsBatch", "exposureProps", "cleanGroupType", "cleanGroupKey", "cleanGroups", "withGroup", "cleanTraits", "withSuperProps", "cleanEventName", "cleanScreenName", "cleanProps", "touchSession", "parseSession", "v", "t", "kind", "queue", "current", "max", "userId", "fixed", "events", "e", "who", "_asUser", "wire", "MAX_EXPOSURE_TEXT", "exposureText", "experiment", "variant", "props", "GROUP_TYPE", "MAX_GROUP_KEY", "out", "k", "type", "key", "groups", "TRAIT_KEY", "MAX_TRAIT_TEXT", "raw", "own", "sup", "_a", "name", "n", "json", "now", "newId", "s", "exports", "reportAdServicesToken", "MAX_ATTEMPTS", "opts", "_a", "read", "token", "attempts", "write", "doFetch", "_b", "key", "value", "exports", "isTrackingUrl", "isOpenUrl", "toDeepLink", "upgradeStoredDeepLink", "TRACKING_PATH", "OPEN_PATH", "pathOf", "url", "m", "_a", "path", "answer", "deferred", "matchType", "payload", "_b", "_c", "stored", "link", "empty_exports", "init_empty", "__esmMin", "exports", "fromGoogleMobileAdsPaid", "fromGoogleMobileAdsChannel", "fromGoogleMobileAdsNativeAd", "fromMaxAdInfo", "fromCapacitorAdMob", "watchReactNativeAds", "covers", "c", "AdRevenueGate", "warn", "m", "coverage", "network", "format", "call", "raw", "key", "message", "PRECISION_BY_INDEX", "precisionOf", "_a", "text", "record", "micros", "n", "payload", "meta", "p", "currency", "valueMicros", "loaded", "channel", "event", "e", "body", "info", "i", "adFormat", "nativeModule", "rn", "name", "_d", "_b", "_c", "_e", "MAX_RN_FULLSCREEN_FORMATS", "want", "sink", "subs", "guard", "parse", "deliver", "rawOf", "v", "paidData", "sub", "nativeAds", "onNative", "emitter", "max", "names", "fromModule", "k", "s", "exports", "normalizeMetaInstallReferrers", "normalizeAdvertisingId", "fromMaxAd", "detectDebug", "isLocalPage", "skan_1", "analytics_1", "adservices_1", "deeplink_1", "adRevenue_1", "skan_2", "adservices_2", "analytics_2", "deeplink_2", "adRevenue_2", "INSTALL_SENT_KEY", "INSTALL_SENT_DEBUG_KEY", "INSTALL_ATTEMPTS_KEY", "AD_ID_SENT_KEY", "AD_ID_SENT_DEBUG_KEY", "AD_ID_PATH", "REFERRER_KEY", "QUEUE_KEY", "AD_QUEUE_KEY", "DEVICE_ID_KEY", "LAST_SESSION_KEY", "ERASED_KEY", "DEFERRED_KEY", "DEFERRED_RETRY_KEY", "DEFERRED_RETRY_WINDOW_MS", "CONSENT_KEY", "ANALYTICS_QUEUE_KEY", "ANALYTICS_SESSION_KEY", "SUPER_PROPS_KEY", "GROUPS_KEY", "ANALYTICS_PATH", "MAX_ANALYTICS_BATCH", "MAX_ANALYTICS_QUEUE", "MAX_EARLY_ANALYTICS", "MAX_BATCH", "NON_RETRYABLE_STATUS", "MAX_QUEUE", "MAX_AD_BATCH", "MAX_AD_QUEUE", "BASE_RETRY_MS", "MAX_RETRY_MS", "FLUSH_DELAY_MS", "MAX_INSTALL_ATTEMPTS", "SESSION_TIMEOUT_MS", "META_PROVIDERS", "raw", "out", "item", "r", "isCt", "ts", "TRACKING_AUTHORIZATIONS", "MAX_PRECISION", "MAX_FORMAT", "ZERO_AD_ID", "id", "ad", "_b", "_a", "_c", "uuid", "c", "safeLocale", "defaultStorage", "mod", "store", "key", "value", "reactNativeOs", "os", "Client", "adInfo", "max", "opts", "e", "freshInstall", "link", "want", "sink", "converted", "coverage", "name", "props", "transactionId", "n", "p", "userId", "traits", "traitsOnce", "set", "setOnce", "rest", "groupType", "groupKey", "next", "previousId", "prev", "experiment", "variant", "now", "sameVisit", "navigation", "report", "route", "off", "platform", "adUnitId", "adFormat", "event", "source", "origin", "listener", "pending", "url", "answer", "deferred", "code", "granted", "native", "fine", "coarse", "lockWindow", "cached", "referrer", "kept", "installReferrer", "until", "known", "Linking", "events", "AppState", "state", "screen", "groups", "schedule", "stored", "_d", "early", "_e", "parsed", "force", "last", "deviceId", "existing", "result", "read", "appId", "list", "attempts", "advertisingId", "metaInstallReferrers", "delay", "batch", "outcome", "run", "i", "_source", "impression", "body", "path", "res", "fromInit", "status", "consent", "att", "loc", "host", "import_core", "COOKIE_PREFIX", "doc", "readCookie", "name", "d", "part", "eq", "serialize", "value", "maxAgeSeconds", "domain", "secure", "scope", "registrableDomain", "hostname", "labels", "probe", "candidate", "writeCookie", "deleteCookie", "DEVICE_ID_KEY", "INTERNAL_KEY", "MIRRORED", "MIRROR_MAX_AGE_SECONDS", "local", "BrowserStore", "persistent", "cookieDomain", "cookies", "key", "value", "_a", "_b", "_c", "readCookie", "stored", "ls", "writeCookie", "deleteCookie", "pending", "keys", "i", "k", "COOKIE_PREFIX", "KeptValue", "store", "key", "cookieDomain", "cookies", "valid", "now", "raw", "parsed", "fromCookie", "readCookie", "value", "maxAgeMs", "record", "writeCookie", "deleteCookie", "SOURCE_KEY", "SOURCE_PARAMS", "MAX_VALUE_LENGTH", "FIELD", "clean", "v", "t", "bare", "host", "sameSite", "other", "a", "b", "referrerHost", "referrer", "pageHref", "ref", "sourceFromLanding", "href", "now", "out", "params", "key", "fromUrl", "parseSource", "query", "source", "param", "field", "ts", "SourceKeeper", "store", "maxAgeMs", "cookieDomain", "cookies", "KeptValue", "landing", "CLICK_PARAM", "STORE_KEY", "CLICK_ID", "clickIdFromUrl", "href", "raw", "TrackIdKeeper", "store", "maxAgeMs", "cookieDomain", "cookies", "KeptValue", "v", "now", "id", "sampled", "rate", "random", "r", "CLS_GAP_MS", "CLS_WINDOW_MS", "INP_KEEP", "VitalsCollector", "startTime", "ms", "value", "hadRecentInput", "w", "interactionId", "duration", "prev", "minId", "min", "id", "d", "sorted", "a", "b", "out", "inp", "observe", "type", "onEntries", "extra", "_a", "PO", "list", "watchVitals", "c", "startedVisible", "activation", "nav", "lcpFinal", "finalize", "es", "e", "isEntry", "e", "GROUP_TYPE", "MAX_GROUP_TYPES", "cleanGroupType", "v", "t", "cleanGroupKey", "cleanGroups", "out", "k", "type", "key", "withGroup", "groups", "TRAIT_KEY", "MAX_TRAITS", "MAX_PROPS_BYTES", "cleanTraits", "raw", "withSuperProps", "own", "sup", "merged", "SESSION_KEY", "cleanUserId", "exposureText", "exposureProps", "experiment", "variant", "props", "takeBatch", "queue", "current", "max", "n", "userId", "fixed", "who", "SESSION_IDLE_MS", "FLUSH_EVERY_MS", "FLUSH_AT", "MAX_QUEUE", "MAX_ERRORS_PER_PAGE", "LINK_SCANNER_ERROR", "SCROLL_STEPS", "UTM", "newId", "landingSource", "href", "referrer", "_a", "src", "u", "param", "bare", "RAGE_WINDOW_MS", "RAGE_RADIUS_PX", "RAGE_THRESHOLD", "RageClickDetector", "x", "y", "b", "AnalyticsTracker", "deps", "o", "rate", "sampled", "VitalsCollector", "watchVitals", "name", "set", "setOnce", "hasSet", "hasOnce", "groupType", "groupKey", "previousId", "url", "leaving", "_b", "anonymousId", "taken", "events", "body", "res", "now", "s", "_c", "_d", "_e", "_f", "_g", "_h", "title", "g", "c", "after", "method", "original", "args", "doc", "viewport", "height", "seen", "pct", "step", "target", "el", "input", "text", "message", "stack", "reason", "DEFAULT_ENDPOINT", "SUPER_PROPS_KEY", "GROUPS_KEY", "DEFAULT_TRACK_ID_DAYS", "DAY_MS", "inBrowser", "randomId", "internalParam", "href", "v", "TraqioWeb", "opts", "_a", "_b", "_c", "_d", "cookies", "domain", "cookieDomain", "registrableDomain", "consent", "persistent", "BrowserStore", "keepMs", "TrackIdKeeper", "SourceKeeper", "optOut", "DEVICE_ID_KEY", "id", "raw", "early", "cleanTraits", "cleanGroups", "endpoint", "background", "foreground", "store", "AnalyticsTracker", "set", "once", "type", "key", "user", "prev", "name", "props", "on", "INTERNAL_KEY", "userId", "traits", "traitsOnce", "rest", "groupType", "groupKey", "next", "withGroup", "previousId", "cleanUserId", "experiment", "variant", "p", "exposureProps", "fits", "granted", "ok", "Traqio", "Traqio", "tag", "sdkKey"]
7
7
  }