/** * CrispStats for React Native and Expo. * * One file with no imports: download it into the app and import it. * curl -O https://crispstats.com/sdk/react-native/crispstats.ts * * Screen views are pageviews on the same collector as the website. The install * id is random, stored only on the device, and hashed again by the collector * before it is kept. There is no advertising id. * * Calls never throw and never wait for the network. Events are kept in the * storage you pass in until the collector accepts them, and are retried with * a backoff while the device is offline. The dashboard timestamps an event * when the collector receives it, which is the same rule the website uses. * * Runs on Hermes: it uses only fetch, AbortController, setTimeout, Date and, * when present, Intl and crypto.getRandomValues. */ export const MOBILE_SDK_VERSION = "1.1.0"; /** The production collector. Mirrors `BRAND.ingestUrl`. */ export const DEFAULT_API = "https://in.crispstats.com"; // Mirrors of packages/shared/src/mobile.ts. A parity test keeps them in step. export const APP_PLATFORMS = ["ios", "android"] as const; export type AppPlatform = (typeof APP_PLATFORMS)[number]; export const APP_SDKS = ["ios", "android", "react-native", "flutter"] as const; export type AppSdk = (typeof APP_SDKS)[number]; export const APP_DEVICES = ["phone", "tablet"] as const; export type AppDevice = (typeof APP_DEVICES)[number]; /** Props the collector writes. A prop with one of these names is not sent. */ export const APP_PROP_KEYS: readonly string[] = ["app_version", "app_build", "os_version", "sdk", "sdk_version"]; export const INSTALL_ID_PATTERN = /^[a-f0-9]{32}$/; export const EVENT_TYPES = ["pageview", "event", "vitals", "error", "identify", "revenue", "ping"] as const; const QUEUE_LIMIT = 100; const INSTALL_KEY = "cs.install"; const QUEUE_KEY = "cs.queue"; const OPT_OUT_KEY = "cs.optout"; const REQUEST_TIMEOUT_MS = 10_000; const RETRY_FIRST_MS = 1_000; const RETRY_MAX_MS = 60_000; /** The collector starts a new session after 30 idle minutes. */ const SESSION_GAP_MS = 1_800_000; const MAX_URL = 2048; const MAX_REFERRER = 2000; const MAX_CAMPAIGN_PAIRS = 10; const CAMPAIGN_KEY = /^[a-z0-9_]{1,32}$/; const MAX_CAMPAIGN_VALUE = 200; const BUNDLE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; const HOST = /^[a-z0-9][a-z0-9._-]*$/; const SITE_KEY = /^cs_pk_[A-Za-z0-9_-]{1,58}$/; const SCREEN_PART = /^[A-Za-z0-9][A-Za-z0-9 ._-]*$/; export type MobileProp = string | number | boolean | null; /** App context sent on every event as `m`. */ export interface AppContext { os: AppPlatform; id: string; v: string; b?: string; ov: string; d: AppDevice; sdk: AppSdk; sv: string; sn?: string; } /** What the client posts to the collector. A subset of the collector's payload. */ export interface CrispStatsPayload { k: string; t: (typeof EVENT_TYPES)[number]; u: string; vid: string; m: AppContext; n?: string; r?: string; l?: string; z?: string; p?: Record; a?: number; c?: string; d?: number; i?: string; e?: { message: string; source?: string }; } export interface MobileStorage { get(key: string): Promise | string | null; set(key: string, value: string): Promise | void; } export type MobileTransportResult = "ok" | "retry" | "drop"; export interface MobileClientOptions { /** Site public key, `cs_pk_…`. */ site: string; /** The device's platform, `ios` or `android`. */ platform: AppPlatform; /** Bundle id or application id, for example `com.acme.app`. */ appId: string; appVersion: string; appBuild?: string; osVersion: string; /** `phone` (the default) or `tablet`. See `deviceFor`. */ device?: AppDevice; sdk: AppSdk; sdkVersion?: string; /** Collector origin, without a trailing slash. Defaults to the production collector. */ api?: string; storage: MobileStorage; /** Replaces fetch. Return `retry` to keep the event, `drop` to discard it. */ transport?: (payload: CrispStatsPayload) => Promise; /** Milliseconds since the epoch. Defaults to `Date.now`. */ now?: () => number; /** BCP-47 tag such as `en-US`. Read from `Intl` when left out. */ locale?: string; /** IANA time zone such as `Europe/Berlin`. Read from `Intl` when left out. */ timezone?: string; /** Returns a 32 character lowercase hex install id. Defaults to `randomInstallId`. */ randomId?: () => string; } export interface ScreenOptions { /** * Query parameters for this screen view, such as `utm_source`, `utm_medium`, * `utm_campaign`, `utm_term`, `utm_content`, `ref` or `gclid`. Use * `campaignFromUrl` to read them from a deep link. */ campaign?: Record | null; /** The URL that sent the user here. */ referrer?: string | null; } // --------------------------------------------------------------------------- // Helpers mirrored from the shared package export function isInstallId(value: unknown): value is string { return typeof value === "string" && INSTALL_ID_PATTERN.test(value); } /** * The path a screen is stored under. "Settings/Account" becomes * "/Settings/Account". Empty, `.` and `..` segments are rejected. */ export function screenPath(name: string): string | null { if (typeof name !== "string") return null; const parts = name .split("/") .map((part) => part.trim()) .filter((part) => part.length > 0); if (parts.length === 0 || parts.length > 8) return null; for (const part of parts) { if (part === "." || part === ".." || part.length > 80 || !SCREEN_PART.test(part)) return null; } const path = `/${parts.join("/")}`; return path.length <= 200 ? path : null; } /** `app://com.acme.app/Pricing`, plus any query string the caller supplies. */ export function appScreenUrl(bundleId: string, screen: string, query?: Record): string | null { const path = screenPath(screen); const host = typeof bundleId === "string" ? bundleId.trim().toLowerCase() : ""; if (!path || !HOST.test(host)) return null; const pairs: string[] = []; if (query) { for (const key of Object.keys(query).sort()) { const value = query[key]; if (value) pairs.push(`${formEncode(key)}=${formEncode(value)}`); } } const qs = pairs.join("&"); return `app://${host}${path}${qs ? `?${qs}` : ""}`; } /** The same bytes `URLSearchParams#toString` writes, without relying on it. */ function formEncode(text: string): string { return encodeURIComponent(wellFormed(text)) .replace(/%20/g, "+") .replace(/[!'()~]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`); } /** Replaces lone surrogates with U+FFFD, so encodeURIComponent cannot throw. */ function wellFormed(text: string): string { let out = ""; for (let i = 0; i < text.length; i++) { const code = text.charCodeAt(i); if (code >= 0xd800 && code <= 0xdbff) { const next = text.charCodeAt(i + 1); if (next >= 0xdc00 && next <= 0xdfff) { out += text[i]! + text[i + 1]!; i++; } else out += "�"; } else if (code >= 0xdc00 && code <= 0xdfff) out += "�"; else out += text[i]!; } return out; } // --------------------------------------------------------------------------- // Public helpers /** * Keeps the campaign pairs the collector can use: the key lower-cased and * matching `[a-z0-9_]{1,32}`, the value trimmed and 1 to 200 characters. * Keys are sorted and at most 10 pairs are kept. When two keys differ only in * case, the one that sorts first wins. */ export function cleanCampaign(campaign: Record | null | undefined): Record { const out: Record = {}; if (!campaign || typeof campaign !== "object") return out; const found: Record = {}; for (const rawKey of Object.keys(campaign).sort()) { const raw = campaign[rawKey]; if (typeof raw !== "string") continue; const key = rawKey.toLowerCase(); const value = raw.trim(); if (!CAMPAIGN_KEY.test(key) || value.length < 1 || value.length > MAX_CAMPAIGN_VALUE) continue; if (!(key in found)) found[key] = value; } for (const key of Object.keys(found).sort().slice(0, MAX_CAMPAIGN_PAIRS)) out[key] = found[key]!; return out; } /** * The query pairs of a deep link, under the same rules as `screen`'s * `campaign` option. `myapp://promo?utm_source=newsletter&gclid=abc` gives * `{ gclid: "abc", utm_source: "newsletter" }`. The first value of a repeated * key wins. Parses the query by hand, so it does not depend on `URL`. */ export function campaignFromUrl(url: string): Record { try { if (typeof url !== "string") return {}; const hash = url.indexOf("#"); const head = hash >= 0 ? url.slice(0, hash) : url; const mark = head.indexOf("?"); if (mark < 0) return {}; const pairs: Record = {}; for (const part of head.slice(mark + 1).split("&")) { if (!part) continue; const eq = part.indexOf("="); const key = decodePart(eq >= 0 ? part.slice(0, eq) : part); const value = decodePart(eq >= 0 ? part.slice(eq + 1) : ""); if (key === null || value === null) continue; const lower = key.toLowerCase(); if (!(lower in pairs) && CAMPAIGN_KEY.test(lower)) { const trimmed = value.trim(); if (trimmed.length >= 1 && trimmed.length <= MAX_CAMPAIGN_VALUE) pairs[lower] = trimmed; } } return cleanCampaign(pairs); } catch { return {}; } } function decodePart(text: string): string | null { try { return decodeURIComponent(text.replace(/\+/g, " ")); } catch { return null; } } /** * `tablet` on an iPad (`Platform.isPad`) or when the shorter side of the * window is at least 600 dp, otherwise `phone`. */ export function deviceFor(input: { isPad?: boolean; shortestSideDp?: number }): AppDevice { if (input?.isPad === true) return "tablet"; const side = input?.shortestSideDp; return typeof side === "number" && Number.isFinite(side) && side >= 600 ? "tablet" : "phone"; } /** * 16 random bytes as 32 lowercase hex characters. Uses `crypto.getRandomValues` * when the runtime has it (install `react-native-get-random-values` or use * `expo-crypto` on Hermes), and `Math.random` only when nothing better exists. */ export function randomInstallId(random: (size: number) => Uint8Array = cryptoBytes): string { let hex = ""; for (const byte of random(16)) hex += (byte & 0xff).toString(16).padStart(2, "0"); return hex; } function cryptoBytes(size: number): Uint8Array { const bytes = new Uint8Array(size); const cryptoObj = (globalThis as { crypto?: { getRandomValues?: (array: Uint8Array) => Uint8Array } }).crypto; try { if (typeof cryptoObj?.getRandomValues === "function") { cryptoObj.getRandomValues(bytes); return bytes; } } catch { // Fall through to Math.random. } for (let i = 0; i < size; i++) bytes[i] = Math.floor(Math.random() * 256); return bytes; } export function memoryStorage(initial: Record = {}): MobileStorage { const data = { ...initial }; return { get: (key) => data[key] ?? null, set: (key, value) => { data[key] = value; }, }; } /** Wraps AsyncStorage, or any store with `getItem` and `setItem`. */ export function asyncStorage(store: { getItem(key: string): Promise; setItem(key: string, value: string): Promise; }): MobileStorage { return { get: (key) => store.getItem(key), set: (key, value) => store.setItem(key, value), }; } /** * Calls `leave` when the app leaves the foreground and `resume` when it comes * back. Pass React Native's `AppState`. */ export function bindAppState( client: CrispStats, appState: { addEventListener(type: "change", listener: (state: string) => void): { remove(): void } }, ): { remove(): void } { return appState.addEventListener("change", (state) => { if (state === "active") client.resume(); else client.leave(); }); } // --------------------------------------------------------------------------- // Runtime access without DOM or Node types type Timer = unknown; interface Runtime { fetch?: ( url: string, init: { method: string; headers: Record; body: string; signal?: unknown }, ) => Promise<{ status: number }>; AbortController?: new () => { signal: unknown; abort(): void }; setTimeout?: (fn: () => void, ms: number) => Timer; clearTimeout?: (timer: Timer) => void; console?: { warn?: (...args: unknown[]) => void }; } const runtime = globalThis as unknown as Runtime; function intlOptions(): { locale?: string; timeZone?: string } { try { if (typeof Intl === "undefined" || typeof Intl.DateTimeFormat !== "function") return {}; return Intl.DateTimeFormat().resolvedOptions(); } catch { return {}; } } /** `en_US` becomes `en-US`. Empty or oversized tags are left out. */ function normalizeLocale(tag: string | undefined): string | undefined { if (typeof tag !== "string") return undefined; const clean = tag.trim().replace(/_/g, "-"); return clean && clean.length <= 35 ? clean : undefined; } function normalizeTimezone(zone: string | undefined): string | undefined { if (typeof zone !== "string") return undefined; const clean = zone.trim(); return clean && clean.length <= 64 ? clean : undefined; } function sanitizeProps(props?: Record | null): Record | undefined { if (!props || typeof props !== "object") return undefined; const out: Record = {}; let count = 0; for (const [rawKey, value] of Object.entries(props)) { if (count >= 30) break; const key = rawKey.trim().slice(0, 60); if (!key || APP_PROP_KEYS.includes(key)) continue; if (typeof value === "string") out[key] = value.slice(0, 500); else if (typeof value === "number" && Number.isFinite(value)) out[key] = value; else if (typeof value === "boolean" || value === null) out[key] = value; else if (value !== undefined) out[key] = String(value).slice(0, 500); else continue; count++; } return Object.keys(out).length > 0 ? out : undefined; } function shortText(value: unknown): string | null { if (typeof value !== "string") return null; const text = value.trim().slice(0, 32); return text.length > 0 ? text : null; } interface Config { site: string; host: string; context: Omit; endpoint: string; locale?: string; timezone?: string; } /** Everything that would make every event invalid, or null when the options are usable. */ function configure(options: MobileClientOptions): { config: Config } | { problems: string[] } { const problems: string[] = []; const o = (options ?? {}) as Partial; if (typeof o.site !== "string" || !SITE_KEY.test(o.site.trim())) problems.push("site must be the site's public key, cs_pk_ followed by letters and numbers"); if (!APP_PLATFORMS.includes(o.platform as AppPlatform)) problems.push(`platform must be one of ${APP_PLATFORMS.join(", ")}`); const appId = typeof o.appId === "string" ? o.appId.trim() : ""; if (!appId || appId.length > 200 || !BUNDLE_ID.test(appId)) problems.push("appId must be a bundle id such as com.acme.app"); const appVersion = shortText(o.appVersion); if (!appVersion) problems.push("appVersion must not be empty"); const osVersion = shortText(o.osVersion); if (!osVersion) problems.push("osVersion must not be empty"); const device = o.device ?? "phone"; if (!APP_DEVICES.includes(device)) problems.push(`device must be one of ${APP_DEVICES.join(", ")}`); if (!APP_SDKS.includes(o.sdk as AppSdk)) problems.push(`sdk must be one of ${APP_SDKS.join(", ")}`); const sdkVersion = o.sdkVersion === undefined ? MOBILE_SDK_VERSION : shortText(o.sdkVersion); if (!sdkVersion) problems.push("sdkVersion must not be empty"); if (o.appBuild !== undefined && o.appBuild !== null && typeof o.appBuild !== "string") problems.push("appBuild must be a string"); if (!o.storage || typeof o.storage.get !== "function" || typeof o.storage.set !== "function") problems.push("storage must have get and set"); if (o.api !== undefined && (typeof o.api !== "string" || !/^https?:\/\/[^/]/i.test(o.api))) problems.push("api must be an http or https origin"); if (problems.length > 0) return { problems }; const build = shortText(o.appBuild); const intl = o.locale === undefined || o.timezone === undefined ? intlOptions() : {}; return { config: { site: o.site!.trim(), host: appId.toLowerCase(), endpoint: `${(o.api ?? DEFAULT_API).replace(/\/+$/, "")}/e`, context: { os: o.platform!, id: appId, v: appVersion!, ...(build ? { b: build } : {}), ov: osVersion!, d: device, sdk: o.sdk!, sv: sdkVersion!, }, locale: normalizeLocale(o.locale ?? intl.locale), timezone: normalizeTimezone(o.timezone ?? intl.timeZone), }, }; } function isQueuedPayload(value: unknown): value is CrispStatsPayload { if (!value || typeof value !== "object") return false; const event = value as Partial; return ( typeof event.k === "string" && EVENT_TYPES.includes(event.t as CrispStatsPayload["t"]) && typeof event.u === "string" && event.u.length <= MAX_URL && isInstallId(event.vid) && !!event.m && typeof event.m === "object" ); } function parseQueue(raw: string | null): CrispStatsPayload[] { if (!raw) return []; try { const parsed = JSON.parse(raw) as unknown; if (!Array.isArray(parsed)) return []; return parsed.filter(isQueuedPayload).slice(-QUEUE_LIMIT); } catch { return []; } } type Draft = Omit; // --------------------------------------------------------------------------- export class CrispStats { private readonly options: MobileClientOptions; private readonly config: Config | null; private installId: string | null = null; private queue: CrispStatsPayload[] = []; private optedOut = false; private readonly loaded: Promise; /** Calls are applied in order on this chain. It never waits for the network. */ private tail: Promise = Promise.resolve(); /** The running send loop, if any. Sends are serial. */ private sending: Promise | null = null; private sendCount = 0; /** Bumped on opt out, so a send that finishes later cannot touch the new queue. */ private generation = 0; private retryTimer: Timer | null = null; private retryDelay = RETRY_FIRST_MS; private screenName: string | null = null; private screenUrl: string | null = null; private shownAt: number | null = null; private leftAt: number | null = null; private accumulated = 0; constructor(options: MobileClientOptions) { this.options = options; let configured: ReturnType; try { configured = configure(options); } catch { configured = { problems: ["options must be an object"] }; } if ("problems" in configured) { this.config = null; this.loaded = Promise.resolve(); warnOnce(configured.problems); return; } this.config = configured.config; this.loaded = this.load(); // Events saved by a previous launch go out now. this.tail = this.loaded.then(() => this.kick()); } /** Counts a screen. The previous screen's visible time is sent first. */ screen(name: string, props?: Record | null, options?: ScreenOptions): void { const at = this.now(); this.later(() => this.openScreen(at, name, props, options)); } /** A custom event on the current screen. */ track(name: string, props?: Record | null): void { this.later(() => this.sendNamed("event", name, props)); } /** Ties this install to your own user id. */ identify(userId: string, traits?: Record | null): void { this.later(() => this.sendNamed("identify", userId, traits)); } /** Revenue in minor units (cents) with an ISO currency. Refunds come from the payment provider, so a negative amount is ignored. */ revenue(amount: number, currency: string, props?: Record | null): void { this.later(() => this.sendRevenue(amount, currency, props)); } /** An app error. The message is grouped on the Errors page. */ recordError(message: string, source?: string): void { this.later(() => this.sendError(message, source)); } /** @deprecated Use `recordError`, the name the other SDKs use. */ error(message: string, source?: string): void { this.recordError(message, source); } /** The app left the foreground. Visible time so far is sent and the clock stops. */ leave(): void { const at = this.now(); this.later(() => this.pause(at)); } /** * The app came back. The same screen continues and its time keeps adding * up. After 30 minutes or more away the screen is counted again, because * the collector has started a new session. */ resume(): void { const at = this.now(); this.later(() => this.wake(at)); } /** Stops sending, drops anything still queued, and remembers the choice. */ optOut(): void { this.later(() => this.setOptOut(true)); } /** Starts sending again. A new install id is created if there is none. */ optIn(): void { this.later(() => this.setOptOut(false)); } /** Sends the queue now. Resolves when the attempt finishes, including a network failure. */ async flush(): Promise { if (!this.config) return; try { const started = this.sendCount; for (let i = 0; i < 50; i++) { const pending = this.tail; await pending; if (this.tail === pending) break; } // A send started by the calls above counts as this attempt; otherwise make one now. if (this.sendCount === started) await this.send(); for (let i = 0; i < 50 && this.sending; i++) await this.sending; } catch { // Never throws. } } // ------------------------------------------------------------------------- private later(job: () => Promise | void): void { if (!this.config) return; this.tail = this.tail.then(job).then( () => undefined, () => undefined, ); } private now(): number { try { const value = this.options.now ? this.options.now() : Date.now(); return typeof value === "number" && Number.isFinite(value) ? value : Date.now(); } catch { return Date.now(); } } private context(screen?: string): AppContext { const base = this.config!.context; return screen ? { ...base, sn: screen } : { ...base }; } private baseUrl(): string { return `app://${this.config!.host}/`; } private async load(): Promise { const { storage } = this.options; try { const [install, rawQueue, optOut] = await Promise.all([ storage.get(INSTALL_KEY), storage.get(QUEUE_KEY), storage.get(OPT_OUT_KEY), ]); this.optedOut = optOut === "1"; this.installId = isInstallId(install) ? install : null; this.queue = this.optedOut ? [] : parseQueue(rawQueue); } catch { this.queue = []; } if (!this.optedOut) await this.ensureInstallId(); } private async ensureInstallId(): Promise { if (this.installId) return; let id: string | null = null; try { id = this.options.randomId?.() ?? null; } catch { id = null; } this.installId = isInstallId(id) ? id : randomInstallId(); try { await this.options.storage.set(INSTALL_KEY, this.installId); } catch { // The id still holds for this process. } } private async openScreen(at: number, name: string, props?: Record | null, options?: ScreenOptions): Promise { if (this.optedOut) return; const path = screenPath(name); if (!path) return; await this.emitPause(at); // The name as given, or its tidy form when stray spaces make it too long. const sn = name.length <= 200 ? name : path.slice(1); const campaign = cleanCampaign(options?.campaign ?? null); const url = this.screenUrlWith(sn, campaign); if (!url) return; this.screenName = sn; this.screenUrl = appScreenUrl(this.config!.host, sn); this.accumulated = 0; this.shownAt = at; this.leftAt = null; const referrer = typeof options?.referrer === "string" ? options.referrer.trim() : ""; const extra = sanitizeProps(props); await this.enqueue({ t: "pageview", u: url, m: this.context(sn), ...(referrer.length >= 1 && referrer.length <= MAX_REFERRER ? { r: referrer } : {}), ...(extra ? { p: extra } : {}), }); } /** The screen URL with the campaign query, dropping the last pairs if it would be too long. */ private screenUrlWith(screen: string, campaign: Record): string | null { const keys = Object.keys(campaign); while (true) { const query: Record = {}; for (const key of keys) query[key] = campaign[key]!; const url = appScreenUrl(this.config!.host, screen, query); if (!url || url.length <= MAX_URL) return url; if (keys.length === 0) return null; keys.pop(); } } private async sendNamed(type: "event" | "identify", name: string, props?: Record | null): Promise { if (this.optedOut || typeof name !== "string") return; const trimmed = name.trim().slice(0, type === "identify" ? 200 : 120); if (!trimmed) return; const context = this.context(this.screenName ?? undefined); const url = this.screenUrl ?? this.baseUrl(); const extra = sanitizeProps(props); if (type === "identify") { await this.enqueue({ t: "identify", u: url, i: trimmed, m: context, ...(extra ? { p: extra } : {}) }); return; } await this.enqueue({ t: "event", n: trimmed, u: url, m: context, ...(extra ? { p: extra } : {}) }); } private async sendRevenue(amount: number, currency: string, props?: Record | null): Promise { if (this.optedOut || !Number.isSafeInteger(amount) || amount < 0 || typeof currency !== "string") return; const code = currency.trim().toUpperCase(); if (!/^[A-Z]{3}$/.test(code)) return; const extra = sanitizeProps(props); await this.enqueue({ t: "revenue", u: this.screenUrl ?? this.baseUrl(), a: amount, c: code, m: this.context(this.screenName ?? undefined), ...(extra ? { p: extra } : {}), }); } private async sendError(message: string, source?: string): Promise { if (this.optedOut || typeof message !== "string") return; const text = message.trim().slice(0, 1000); if (!text) return; const from = typeof source === "string" ? source.slice(0, 500) : ""; await this.enqueue({ t: "error", u: this.screenUrl ?? this.baseUrl(), m: this.context(this.screenName ?? undefined), e: { message: text, ...(from ? { source: from } : {}) }, }); } private async pause(at: number): Promise { if (this.optedOut || this.shownAt === null) return; await this.emitPause(at); this.leftAt = at; } private async wake(at: number): Promise { if (!this.optedOut && this.screenName && this.screenUrl && this.shownAt === null) { const away = this.leftAt === null ? 0 : at - this.leftAt; this.leftAt = null; this.shownAt = at; if (away >= SESSION_GAP_MS) { // The collector has started a new session: count the screen in it. this.accumulated = 0; await this.enqueue({ t: "pageview", u: this.screenUrl, m: this.context(this.screenName) }); } } this.kick(); } private async emitPause(at: number): Promise { if (this.optedOut || !this.screenUrl || !this.screenName || this.shownAt === null) return; const started = this.shownAt; this.shownAt = null; const delta = Math.max(0, Math.floor((at - started) / 1000)); this.accumulated = Math.min(86400, this.accumulated + delta); if (this.accumulated <= 0) return; await this.enqueue({ t: "ping", u: this.screenUrl, m: this.context(this.screenName), d: this.accumulated }); } private async enqueue(partial: Draft): Promise { if (!this.installId || this.optedOut) return; const { site, locale, timezone } = this.config!; const body: CrispStatsPayload = { k: site, vid: this.installId, ...(locale ? { l: locale } : {}), ...(timezone ? { z: timezone } : {}), ...partial, }; if (body.u.length > MAX_URL) return; this.queue.push(body); if (this.queue.length > QUEUE_LIMIT) this.queue.splice(0, this.queue.length - QUEUE_LIMIT); await this.persistQueue(); this.kick(); } /** Starts a send in the background. Never awaited by the call chain. */ private kick(): void { void this.send(); } private send(): Promise { if (this.sending) return this.sending; if (this.optedOut || this.queue.length === 0) return Promise.resolve(); this.sendCount++; this.sending = this.sendLoop().then( (waiting) => this.sent(waiting), () => this.sent(true), ); return this.sending; } private sent(waiting: boolean): void { this.sending = null; // An event queued while the loop was finishing goes out now. if (!waiting && !this.optedOut && this.queue.length > 0) this.kick(); } /** Sends the queue in order. Resolves true when it stopped to wait for a retry. */ private async sendLoop(): Promise { while (!this.optedOut) { const entry = this.queue[0]; if (!entry) return false; const generation = this.generation; const result = await this.dispatch(entry); if (this.optedOut) return false; // Opted out and back in meanwhile: the entry is gone, so start on the new queue. if (generation !== this.generation) continue; if (result === "retry") { this.scheduleRetry(); return true; } if (result === "ok") this.resetRetry(); const index = this.queue.indexOf(entry); if (index >= 0) this.queue.splice(index, 1); await this.persistQueue(); } return false; } private scheduleRetry(): void { this.clearRetryTimer(); const delay = this.retryDelay; this.retryDelay = Math.min(RETRY_MAX_MS, this.retryDelay * 2); if (typeof runtime.setTimeout !== "function") return; this.retryTimer = runtime.setTimeout(() => { this.retryTimer = null; this.kick(); }, delay); } private resetRetry(): void { this.retryDelay = RETRY_FIRST_MS; this.clearRetryTimer(); } private clearRetryTimer(): void { if (this.retryTimer !== null) { try { runtime.clearTimeout?.(this.retryTimer); } catch { // Nothing to clear. } this.retryTimer = null; } } private async dispatch(payload: CrispStatsPayload): Promise { if (this.options.transport) { try { const result = await this.options.transport(payload); return result === "ok" || result === "drop" ? result : "retry"; } catch { return "retry"; } } if (typeof runtime.fetch !== "function") return "retry"; const Controller = runtime.AbortController; const controller = typeof Controller === "function" ? new Controller() : null; let timer: Timer | null = null; try { const timeout = new Promise<"timeout">((resolve) => { timer = runtime.setTimeout?.(() => { controller?.abort(); resolve("timeout"); }, REQUEST_TIMEOUT_MS) ?? null; }); const request = runtime.fetch(this.config!.endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(payload), ...(controller ? { signal: controller.signal } : {}), }); const response = await Promise.race([request, timeout]); if (response === "timeout") { request.catch(() => undefined); return "retry"; } return resultFor(response.status); } catch { return "retry"; } finally { if (timer !== null) runtime.clearTimeout?.(timer); } } private async persistQueue(): Promise { try { await this.options.storage.set(QUEUE_KEY, JSON.stringify(this.queue)); } catch { // The events are still in memory for this process. } } private async setOptOut(out: boolean): Promise { this.optedOut = out; if (out) { this.generation++; this.clearRetryTimer(); this.retryDelay = RETRY_FIRST_MS; this.queue = []; this.screenName = null; this.screenUrl = null; this.shownAt = null; this.leftAt = null; this.accumulated = 0; await this.persistQueue(); } else { await this.ensureInstallId(); } try { await this.options.storage.set(OPT_OUT_KEY, out ? "1" : "0"); } catch { // The in-memory flag still holds for this process. } } } /** 2xx sent; 408, 429 and 5xx kept and retried; any other 4xx dropped. */ export function resultFor(status: number): MobileTransportResult { if (status >= 200 && status < 300) return "ok"; if (status === 408 || status === 429 || status >= 500) return "retry"; if (status >= 400 && status < 500) return "drop"; return "retry"; } const warned = new Set(); /** One warning per distinct mistake, so a client built on every render does not flood the log. */ function warnOnce(problems: string[]): void { const message = `CrispStats is off: ${problems.join("; ")}.`; if (warned.has(message)) return; warned.add(message); try { runtime.console?.warn?.(message); } catch { // No console. } }