@rovenue/react-native-sdk 0.28.2 → 0.28.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/version.ts","../src/events.ts","../src/errors.ts","../src/hooks/useCurrentUser.ts","../src/core/native.ts","../src/store/reactiveStore.ts","../src/hooks/useEntitlement.ts","../src/hooks/useEntitlements.ts","../src/hooks/useVirtualCurrencies.ts","../src/hooks/useRemoteConfig.ts","../src/api/remoteConfig.ts","../src/core/eventBridge.ts","../src/api/sessionTracker.ts","../src/api/configure.ts","../src/api/identity.ts","../src/api/entitlements.ts","../src/api/virtualCurrencies.ts","../src/api/purchases.ts","../src/api/placements.ts","../src/api/funnel-photos.ts","../src/api/present-funnel.ts","../src/api/events.ts","../src/api/lifecycle.ts","../src/api/accountToken.ts","../src/api/attributes.ts","../src/api/log.ts","../src/api/funnel.ts","../src/funnel-view/RovenueFunnelView.tsx","../src/funnel-view/native-view.ts"],"sourcesContent":["// @rovenue/sdk-rn — public surface.\n//\n// Imperative API: Rovenue.configure(...), Rovenue.identify(...), ...\n// React hooks: useCurrentUser, useEntitlement, useEntitlements, useVirtualCurrencies\n// Errors: RovenueError (single class with .kind: ErrorKind), ERROR_KINDS, mapNativeError\n\nexport { SDK_VERSION } from \"./version\";\n\nexport {\n EVENT_WIRE_VERSION,\n serializeEnvelope,\n stripUndefined,\n} from \"./events\";\nexport type { EventEnvelope, IdentityContext } from \"./events\";\nexport type { TrackParams } from \"./api/events\";\n\nexport type {\n User,\n AttributionProvider,\n Entitlement,\n ProductType,\n StoreProduct,\n Package,\n Offering,\n Offerings,\n VirtualCurrencyGrant,\n PurchaseResult,\n ChangeEvent,\n RemoteConfig,\n ExperimentAssignment,\n} from \"./types\";\n\nexport {\n RovenueError,\n ERROR_KINDS,\n mapNativeError,\n} from \"./errors\";\nexport type { ErrorKind, ErrorExtras } from \"./errors\";\n\nexport { useCurrentUser } from \"./hooks/useCurrentUser\";\nexport { useEntitlement } from \"./hooks/useEntitlement\";\nexport { useEntitlements } from \"./hooks/useEntitlements\";\nexport { useVirtualCurrencies, useVirtualCurrency } from \"./hooks/useVirtualCurrencies\";\nexport {\n useRemoteConfig,\n useFlag,\n useExperiment,\n} from \"./hooks/useRemoteConfig\";\n\nimport { configure } from \"./api/configure\";\nimport { currentUser, identify, logOut, setAttribution } from \"./api/identity\";\nimport { entitlement, entitlementsAll, refreshEntitlements } from \"./api/entitlements\";\nimport { virtualCurrencies, virtualCurrency, refreshVirtualCurrencies } from \"./api/virtualCurrencies\";\nimport { getOfferings, purchase, restorePurchases } from \"./api/purchases\";\nimport { preloadPlacement, setFallbackPlacements } from \"./api/placements\";\nimport { presentFunnel } from \"./api/present-funnel\";\nimport { releasePhoto } from \"./api/funnel-photos\";\nexport { releasePhoto } from \"./api/funnel-photos\";\nexport type {\n FunnelPhotoRef,\n FunnelCheckRequest,\n FunnelCheckOutcome,\n FunnelCheckHandler,\n} from \"./api/funnel-photos\";\nexport { presentFunnel } from \"./api/present-funnel\";\nexport type {\n FunnelPresentationStyle,\n FunnelPresentationEnter,\n FunnelSheetDetent,\n FunnelPresentationOverride,\n PresentFunnelOptions,\n FunnelPresentResult,\n} from \"./api/present-funnel\";\nimport { track } from \"./api/events\";\nimport {\n refreshRemoteConfig,\n getRemoteConfig,\n getFlag,\n getExperiment,\n getExperiments,\n} from \"./api/remoteConfig\";\nimport { setForeground, shutdown } from \"./api/lifecycle\";\nimport { getAppAccountToken } from \"./api/accountToken\";\nimport {\n setAttributes,\n setEmail,\n setDisplayName,\n setPhoneNumber,\n setPushToken,\n flushAttributes,\n} from \"./api/attributes\";\nimport { SDK_VERSION } from \"./version\";\nimport { getEmitter } from \"./core/native\";\nimport { setLogHandler } from \"./api/log\";\nimport { claimFunnelToken, claimInstall, claimViaEmail, installId, addFunnelClaimListener, claimFromClipboard, claimFromUrl, extractFunnelToken, resolveFunnelClaim } from \"./api/funnel\";\n\nexport const Rovenue = {\n configure,\n /** This JS package's own semantic version — a plain constant read, not\n * the native module's or Rust core's version, and not network-derived. */\n getVersion: () => SDK_VERSION,\n currentUser,\n identify,\n logOut,\n setAttribution,\n entitlement,\n entitlementsAll,\n refreshEntitlements,\n virtualCurrencies,\n virtualCurrency,\n refreshVirtualCurrencies,\n getOfferings,\n purchase,\n restorePurchases,\n setFallbackPlacements,\n preloadPlacement,\n presentFunnel,\n releasePhoto,\n track,\n refreshRemoteConfig,\n getRemoteConfig,\n getFlag,\n getExperiment,\n getExperiments,\n getAppAccountToken,\n setForeground,\n shutdown,\n setLogHandler,\n setAttributes,\n setEmail,\n setDisplayName,\n setPhoneNumber,\n setPushToken,\n flushAttributes,\n claimFunnelToken,\n claimInstall,\n claimViaEmail,\n claimFromClipboard,\n claimFromUrl,\n resolveFunnelClaim,\n installId,\n addFunnelClaimListener,\n /**\n * Subscribe to the raw native change stream — `ENTITLEMENTS_CHANGED`,\n * `IDENTITY_CHANGED`, `VIRTUAL_CURRENCIES_CHANGED`, `REMOTE_CONFIG_CHANGED`.\n * Returns an unsubscribe function; call it on unmount to avoid leaking the\n * native listener. Most apps should prefer the reactive hooks\n * (`useCurrentUser`, `useEntitlements`, `useRemoteConfig`, ...), which\n * already listen on this stream — reach for this only for imperative,\n * non-component code. Never call the matching `refreshX()` (e.g.\n * `refreshEntitlements()` on `ENTITLEMENTS_CHANGED`) from inside this\n * callback: the refresh re-emits the same event, which re-invokes the\n * callback, forever.\n */\n addChangeListener: (cb: (event: import(\"./types\").ChangeEvent) => void): (() => void) => {\n const sub = getEmitter().addListener(\"onChange\", (payload: { event: string }) => {\n cb(payload.event as import(\"./types\").ChangeEvent);\n });\n return () => sub.remove();\n },\n} as const;\n\nexport type { RovenueConfig } from \"./api/configure\";\nexport type { LogEntry } from \"./api/log\";\nexport type { FunnelClaimResult, ClaimInstallParams } from \"./api/funnel\";\nexport { extractFunnelToken } from \"./api/funnel\";\n\n\n// A funnel renders through the platform's native view too, and resolves\n// itself from a placement — there is deliberately no JS `getFunnel`, so\n// nothing about a funnel's screens ever crosses the bridge.\nexport {\n RovenueFunnelView,\n type RovenueFunnelViewProps,\n type FunnelCustomAction,\n type FunnelLoadedEvent,\n type FunnelUnavailableEvent,\n type FunnelUnavailableReason,\n type FunnelDraftIssue,\n type FunnelScreenEvent,\n} from \"./funnel-view\";\n","/** This package's version, as published — the same string `package.json` carries. */\nexport const SDK_VERSION = \"0.28.2\";\n","// =============================================================\n// events — SDK event wire types + serialiser (M7.2)\n// =============================================================\n//\n// Mirrors the Rust EventEnvelope / IdentityContext structs\n// (packages/core-rs/src/events/) in TypeScript. The serialiser\n// strips `undefined` values at both the top level and inside\n// `identityContext` so the wire payload stays compact and matches\n// the camelCase JSON the server validates.\n\n/**\n * The event envelope's wire format version, sent as `version`. The server\n * accepts exactly this value (`version: z.literal(1)`, apps/api\n * routes/v1/events.ts); a new wire shape bumps it on both sides.\n */\nexport const EVENT_WIRE_VERSION = 1 as const;\n\nexport interface IdentityContext {\n email?: string;\n externalId?: string;\n phone?: string;\n ip?: string;\n userAgent?: string;\n firstName?: string;\n lastName?: string;\n city?: string;\n countryCode?: string;\n}\n\nexport interface EventEnvelope {\n /** Wire format version (EVENT_WIRE_VERSION). Stamped by the native core. */\n version?: number;\n /**\n * Stable, client-generated id reused across retries so downstream fan-out\n * can dedupe. Generated by the native core when omitted.\n */\n eventId?: string;\n eventType: string;\n /** ISO-8601 UTC, e.g. \"2026-05-28T10:00:00Z\" */\n occurredAt: string;\n subscriberId?: string;\n productId?: string;\n /** Decimal string, e.g. \"9.99\" */\n amount?: string;\n /** ISO-4217 three-letter code, e.g. \"USD\" */\n currency?: string;\n eventSourceUrl?: string;\n identityContext?: IdentityContext;\n}\n\n// =============================================================\n// helpers\n// =============================================================\n\n/**\n * Remove keys whose value is `undefined` from a shallow object.\n * Returns a new object — never mutates the input.\n */\nexport function stripUndefined<T extends Record<string, unknown>>(\n o: T,\n): Partial<T> {\n return Object.fromEntries(\n Object.entries(o).filter(([, v]) => v !== undefined),\n ) as Partial<T>;\n}\n\n/**\n * Serialise an EventEnvelope to a compact JSON string.\n *\n * - Strips `undefined` at the top level.\n * - Strips `undefined` inside `identityContext` (if present).\n * - Omits `identityContext` entirely when all its fields are\n * `undefined` or when it was not supplied.\n */\nexport function serializeEnvelope(env: EventEnvelope): string {\n const { identityContext, ...rest } = env;\n\n const top = stripUndefined(rest as Record<string, unknown>);\n\n if (identityContext !== undefined) {\n const cleanIc = stripUndefined(\n identityContext as Record<string, unknown>,\n );\n if (Object.keys(cleanIc).length > 0) {\n (top as Record<string, unknown>).identityContext = cleanIc;\n }\n }\n\n return JSON.stringify(top);\n}\n","// Single-class error surface for the Rovenue RN SDK.\n//\n// Every failure from native (iOS/Android) is surfaced as a RovenueError with\n// a `kind: ErrorKind` discriminant. The 29 canonical PascalCase kinds match\n// the Rust UDL definitions; the JS normalizer absorbs the three casings that\n// the native bridges emit:\n//\n// iOS bridge → String(describing: error.kind) = camelCase \"networkUnavailable\"\n// Android bridge → error.kind.name = UPPER_SNAKE \"NETWORK_UNAVAILABLE\"\n// Direct JS → PascalCase \"NetworkUnavailable\"\n//\n// All three land in mapNativeError() which strips underscores and does a\n// case-insensitive compare to resolve the canonical kind.\n\nexport const ERROR_KINDS = [\n \"NetworkUnavailable\",\n \"Timeout\",\n \"RateLimited\",\n \"ServerError\",\n \"InvalidApiKey\",\n \"Forbidden\",\n \"NotFound\",\n \"InvalidRequest\",\n \"Conflict\",\n \"InvalidArgument\",\n // A Sandbox (`rov_pk_test_…`) key configured in a release build.\n \"SandboxKeyInRelease\",\n \"InsufficientCredits\",\n \"FunnelTokenNotFound\",\n \"FunnelTokenExpired\",\n \"FunnelTokenAlreadyClaimed\",\n // A funnel published under a config format this SDK build is too old to\n // read, and a funnel whose document the resolver rejected. Both are\n // resolve-time failures the native funnel view surfaces through\n // `onError`; without them here mapNativeError() would flatten them to\n // \"Internal\" and a host could not tell \"upgrade the SDK\" from a bug.\n \"FunnelConfigUnsupported\",\n \"FunnelInvalid\",\n // The server cannot resolve this device's subscriber (corrupt merge\n // chain, backend SUBSCRIBER_UNRESOLVABLE). Terminal: not retryable.\n \"SubscriberUnresolvable\",\n // The server refused the identity token identify() sent (backend\n // IDENTITY_TOKEN_INVALID, 401): expired, or minted for another user,\n // project or environment. Not retryable: identify again with a fresh token.\n \"IdentityTokenInvalid\",\n \"PurchaseCanceled\",\n \"ProductNotAvailable\",\n \"AlreadyOwned\",\n \"PaymentDeclined\",\n \"StoreServiceUnavailable\",\n \"Ineligible\",\n \"ReceiptInvalid\",\n \"StoreProblem\",\n \"Storage\",\n \"Internal\",\n] as const;\n\nexport type ErrorKind = (typeof ERROR_KINDS)[number];\n\n// Pre-compute lowercase-no-underscore lookup table once at module load.\n// Maps stripped-lowercase → canonical PascalCase kind.\nconst KIND_LOOKUP = new Map<string, ErrorKind>(\n ERROR_KINDS.map((k) => [k.toLowerCase().replace(/_/g, \"\"), k]),\n);\n\nconst RETRYABLE = new Set<ErrorKind>([\n \"NetworkUnavailable\",\n \"Timeout\",\n \"RateLimited\",\n \"ServerError\",\n \"StoreServiceUnavailable\",\n]);\n\nexport interface ErrorExtras {\n serverCode?: string;\n httpStatus?: number;\n retryable?: boolean;\n available?: number;\n retryAfter?: number;\n}\n\nexport class RovenueError extends Error {\n readonly kind: ErrorKind;\n readonly serverCode?: string;\n readonly httpStatus?: number;\n readonly isRetryable: boolean;\n /** Carries per-kind payload: `available` for InsufficientCredits, `retryAfter` for RateLimited. */\n readonly data?: { available?: number; retryAfter?: number };\n\n constructor(kind: ErrorKind, message: string, extras: ErrorExtras = {}) {\n super(message);\n this.name = \"RovenueError\";\n // Preserve prototype chain when transpiled to ES5.\n Object.setPrototypeOf(this, RovenueError.prototype);\n this.kind = kind;\n this.serverCode = extras.serverCode;\n this.httpStatus = extras.httpStatus;\n this.isRetryable = extras.retryable ?? RETRYABLE.has(kind);\n if (extras.available !== undefined || extras.retryAfter !== undefined) {\n this.data = { available: extras.available, retryAfter: extras.retryAfter };\n }\n }\n}\n\n/**\n * Normalize a native-bridge error code to a canonical `ErrorKind`.\n *\n * Accepts all three casings that the native layers emit:\n * - PascalCase \"NetworkUnavailable\" (RN canonical / direct JS)\n * - camelCase \"networkUnavailable\" (iOS — `String(describing: error.kind)`)\n * - UPPER_SNAKE \"NETWORK_UNAVAILABLE\" (Android — `error.kind.name`)\n *\n * Strategy: strip underscores, lowercase, look up in the precomputed table.\n * Unknown codes fall back to \"Internal\" while still preserving serverCode/\n * message/extras so nothing is lost.\n */\nfunction normalizeKind(code: string): ErrorKind {\n const key = code.toLowerCase().replace(/_/g, \"\");\n return KIND_LOOKUP.get(key) ?? \"Internal\";\n}\n\n/**\n * Tag that marks a native error `message` as a JSON extras-envelope.\n *\n * The Expo JSI bridge forwards ONLY `code` + `message` to JS — neither the iOS\n * `userInfo` nor the Android `CodedException` cause/extras survive the crossing\n * (iOS `makeCodedError(code, message)`; Android `PromiseImpl.reject` →\n * `callback.invoke(code, message)`). So the native bridges fold the structured\n * extras INTO the message as `PREFIX + JSON({ message, serverCode, httpStatus,\n * retryable, available, retryAfter })`, and we unpack them back out here. Kept\n * in sync verbatim with RovenueModule.swift / RovenueModule.kt.\n */\nexport const NATIVE_ERROR_ENVELOPE_PREFIX = \"@rovenue/err1:\";\n\nexport function mapNativeError(\n code: string,\n message: string,\n extras: ErrorExtras = {},\n): RovenueError {\n let kindCode = code;\n let realMessage = message;\n let realExtras = extras;\n // The envelope is found wherever it sits, not only at the start: Expo on\n // Android wraps a rejection as \"Call to function 'Rovenue.X' has been\n // rejected.\\n→ Caused by: <message>\", so the marker arrives after that\n // wrapper. iOS delivers it at index 0. Everything after the marker is the\n // JSON; the wrapper text before it is discarded.\n const markerAt = typeof message === \"string\" ? message.indexOf(NATIVE_ERROR_ENVELOPE_PREFIX) : -1;\n if (markerAt >= 0) {\n try {\n const env = JSON.parse(message.slice(markerAt + NATIVE_ERROR_ENVELOPE_PREFIX.length));\n // The bridge `code` wins; the envelope's `kind` stands in when the\n // bridge delivered none (see fromNativeError).\n if (!kindCode && typeof env.kind === \"string\") kindCode = env.kind;\n realMessage = typeof env.message === \"string\" ? env.message : \"\";\n realExtras = {\n serverCode: env.serverCode,\n httpStatus: env.httpStatus,\n retryable: env.retryable,\n available: env.available,\n retryAfter: env.retryAfter,\n };\n } catch {\n // Malformed envelope — surface the raw message rather than throwing.\n }\n }\n return new RovenueError(normalizeKind(kindCode), realMessage, realExtras);\n}\n\n/** What a native bridge rejection carries into JS. */\ninterface NativeRejection {\n code?: unknown;\n message?: unknown;\n extras?: ErrorExtras;\n}\n\nconst NATIVE_ERROR_FALLBACK_MESSAGE = \"native error\";\n\n/**\n * Turn a native-module rejection into a `RovenueError`, or return it\n * unchanged when it did not come from a Rovenue native bridge.\n *\n * A rejection is ours when it carries a `code` OR the extras envelope. The\n * envelope test is load-bearing on iOS: under Expo 56 every Swift\n * `AsyncFunction` rejection is rebuilt as a plain JS `Error` from the\n * exception's description, with NO `code` property (ExpoModulesJSI\n * `JavaScriptPromise.reject`). The envelope survives inside the message, and\n * its `kind` restores the error kind.\n */\nexport function fromNativeError(e: unknown): unknown {\n const err = (e ?? {}) as NativeRejection;\n const code = typeof err.code === \"string\" ? err.code : \"\";\n const message = typeof err.message === \"string\" ? err.message : \"\";\n if (!code && !message.includes(NATIVE_ERROR_ENVELOPE_PREFIX)) return e;\n return mapNativeError(code, message || NATIVE_ERROR_FALLBACK_MESSAGE, err.extras);\n}\n","import { useEffect, useSyncExternalStore } from \"react\";\nimport { getNative } from \"../core/native\";\nimport { store } from \"../store/reactiveStore\";\nimport type { User } from \"../types\";\n\n/**\n * Reactive current-user identity. Returns `null` until the first native\n * `currentUser()` read completes (lazily primed on mount), then re-renders\n * on every `IDENTITY_CHANGED` native event (e.g. after `identify()` or\n * `logOut()`). Reads are synchronous off the local store after that first\n * fetch — no network call on every render.\n */\nexport function useCurrentUser(): User | null {\n useEffect(() => {\n if (store.get(\"user\") === undefined) {\n getNative().currentUser().then((u) => store.set(\"user\", u)).catch(() => {});\n }\n }, []);\n return useSyncExternalStore(\n store.subscribe.bind(store),\n () => (store.get<User>(\"user\") ?? null),\n () => null,\n );\n}\n","// Lazily acquires the native Expo module the first time we touch it.\n// Tests override `_setNativeForTesting` to inject a mock instead.\n//\n// `getEmitter()` resolves an event emitter for the native module in a way\n// that works across every Expo SDK we support (51 → 56):\n//\n// - Expo SDK 51 (expo-modules-core 1.x): the module is NOT an emitter.\n// Its `addListener(eventName)` is the 1-arg NativeEventEmitter\n// bookkeeping hook (the listener is ignored), so we must subscribe\n// through the legacy `new EventEmitter(nativeModule)` JS wrapper.\n// - Expo SDK 52+ (expo-modules-core 2.x / 3.x): the EventEmitter moved\n// to C++ and every native module now *extends* it. We subscribe on\n// the module directly via its real 2-arg `addListener(name, listener)`.\n//\n// NOTE (2026-09-07), two corrections to what this comment used to claim:\n//\n// 1. It said the legacy `new EventEmitter(module)` constructor \"no longer\n// exists\" on 52+. It does. In the resolved expo-modules-core@2.5.0 it is\n// `constructor(object: EventEmitter)`, marked `@deprecated As of Expo SDK\n// 52 the given object is already an EventEmitter` and `@hidden`. It is\n// deprecated, not removed — but note its parameter type: on 2.x it expects\n// something that ALREADY is an emitter, so it cannot do the wrapping job\n// the SDK-51 branch below needs it for. That branch therefore only\n// functions on expo-modules-core 1.x.\n//\n// 2. It said this file supports \"every Expo SDK we support (51 -> 56)\".\n// `package.json` declares `expo >=52.0.0` and `expo-modules-core >=2.0.0`.\n// Under that floor the SDK-51 branch is unreachable. Manifest and comment\n// disagree, and that contradiction is UNRESOLVED: deciding it means either\n// dropping the branch or lowering the floor, and neither is safe to assert\n// until the floor is verified by a real native build. `examples/sample-rn-expo`\n// is still pinned at expo ~51 / RN 0.74.5, below the floor, and is\n// CI-verified typecheck-only.\n//\n// `__tests__/native.test.ts` exercises the SDK-51 branch against a STUB\n// EventEmitter whose constructor accepts a plain object. The real 2.x\n// constructor does not. So that test does not evidence the branch works\n// on any supported version.\n//\n// The emitter is resolved lazily so test injection is observed.\n\nimport { EventEmitter, requireNativeModule } from \"expo-modules-core\";\nimport type { RovenueModuleSpec } from \"../specs/RovenueModule.types\";\n\n// The common shape both code paths expose: a subscription-returning\n// `addListener`. This is all the callers (eventBridge, log, index) need.\ntype ListenerEmitter = {\n addListener(\n eventName: string,\n listener: (payload: any) => void,\n ): { remove(): void };\n};\n\nlet instance: RovenueModuleSpec | null = null;\nlet emitter: ListenerEmitter | null = null;\n\nexport function getNative(): RovenueModuleSpec {\n if (instance) return instance;\n instance = requireNativeModule<RovenueModuleSpec>(\"Rovenue\");\n return instance;\n}\n\nexport function getEmitter(): ListenerEmitter {\n if (emitter) return emitter;\n const native = getNative() as unknown as ListenerEmitter & {\n addListener?: (...args: unknown[]) => unknown;\n };\n // On expo-modules-core ≥ 2 the module itself is an EventEmitter; the\n // arity check is a belt-and-suspenders guard for setups where the\n // `instanceof` identity is lost (e.g. duplicated core copies under a\n // monorepo) but the real 2-arg `addListener` is still present.\n const moduleIsEmitter =\n native instanceof EventEmitter ||\n (typeof native.addListener === \"function\" && native.addListener.length >= 2);\n emitter = moduleIsEmitter\n ? native\n : (new EventEmitter(native as any) as unknown as ListenerEmitter);\n return emitter;\n}\n\n// Test seam: replaces the cached instance + forces a fresh emitter.\n// Production code MUST NOT call this.\nexport function _setNativeForTesting(mock: RovenueModuleSpec | null): void {\n instance = mock;\n emitter = null;\n}\n","// ReactiveStore — in-memory cache mirror. Hook reads come out of this\n// synchronously via useSyncExternalStore; the event bridge mutates it\n// when the native core emits a ChangeEvent.\n//\n// Slot keys are flat strings. Per-entitlement slots use the pattern\n// `entitlement:<id>` so we can look up one without scanning a list.\n\nimport type { Entitlement, RemoteConfig, User } from \"../types\";\n\ntype StoreSlot =\n | \"user\"\n | \"virtualCurrencies\"\n | \"entitlementsAll\"\n | \"remoteConfig\"\n | `entitlement:${string}`;\n\ntype StoreValue =\n | User\n | number\n | Record<string, number>\n | Entitlement\n | Entitlement[]\n | RemoteConfig\n | null;\n\nexport class ReactiveStore {\n private values = new Map<StoreSlot, StoreValue>();\n private listeners = new Set<() => void>();\n\n get<T = StoreValue>(slot: StoreSlot): T | undefined {\n return this.values.get(slot) as T | undefined;\n }\n\n set<T extends StoreValue>(slot: StoreSlot, value: T): void {\n this.values.set(slot, value);\n this.listeners.forEach((l) => l());\n }\n\n /** Every slot currently holding a value (including `null`). */\n slots(): StoreSlot[] {\n return [...this.values.keys()];\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n clear(): void {\n this.values.clear();\n this.listeners.forEach((l) => l());\n }\n}\n\n// Module singleton used by every hook + the event bridge.\nexport const store = new ReactiveStore();\n","import { useEffect, useSyncExternalStore } from \"react\";\nimport { getNative } from \"../core/native\";\nimport { store } from \"../store/reactiveStore\";\nimport type { Entitlement } from \"../types\";\n\n/**\n * Reactive read of one entitlement by id. Returns `null` until the first\n * native `entitlement(id)` read completes (lazily primed on mount and on\n * `id` change), then re-renders on `ENTITLEMENTS_CHANGED`. Also `null`\n * when the entitlement is unknown or not granted — there is no separate\n * \"loading\" state; a caller that must distinguish \"not yet loaded\" from\n * \"not entitled\" should track that itself.\n */\nexport function useEntitlement(id: string): Entitlement | null {\n useEffect(() => {\n if (store.get(`entitlement:${id}`) === undefined) {\n getNative().entitlement(id).then((e) => store.set(`entitlement:${id}`, e)).catch(() => {});\n }\n }, [id]);\n return useSyncExternalStore(\n store.subscribe.bind(store),\n () => (store.get<Entitlement | null>(`entitlement:${id}`) ?? null),\n () => null,\n );\n}\n","import { useEffect, useSyncExternalStore } from \"react\";\nimport { getNative } from \"../core/native\";\nimport { store } from \"../store/reactiveStore\";\nimport type { Entitlement } from \"../types\";\n\n// Module-level constant so React's useSyncExternalStore does not see a\n// fresh array reference on every render when the store is empty.\nconst EMPTY: Entitlement[] = [];\n\n/**\n * Reactive read of every currently-granted entitlement. Returns an empty\n * array until the first native `entitlementsAll()` read completes (lazily\n * primed on mount), then re-renders on `ENTITLEMENTS_CHANGED`. Also\n * populates the per-id store entries `useEntitlement` reads, so mounting\n * this hook once can prime individual lookups elsewhere in the tree.\n */\nexport function useEntitlements(): Entitlement[] {\n useEffect(() => {\n if (store.get(\"entitlementsAll\") === undefined) {\n getNative().entitlementsAll().then((all) => {\n store.set(\"entitlementsAll\", all);\n for (const ent of all) store.set(`entitlement:${ent.id}`, ent);\n }).catch(() => {});\n }\n }, []);\n return useSyncExternalStore(\n store.subscribe.bind(store),\n () => (store.get<Entitlement[]>(\"entitlementsAll\") ?? EMPTY),\n () => EMPTY,\n );\n}\n","import { useEffect, useSyncExternalStore } from \"react\";\nimport { getNative } from \"../core/native\";\nimport { store } from \"../store/reactiveStore\";\n\nconst EMPTY: Record<string, number> = {};\n\nfunction loadIfNeeded(): void {\n if (store.get(\"virtualCurrencies\" as any) === undefined) {\n getNative()\n .virtualCurrencies()\n .then((m) => store.set(\"virtualCurrencies\" as any, m as any))\n .catch(() => {});\n }\n}\n\n/** Reactive map of all virtual-currency balances (code → amount). */\nexport function useVirtualCurrencies(): Record<string, number> {\n useEffect(loadIfNeeded, []);\n return useSyncExternalStore(\n store.subscribe.bind(store),\n () => store.get<Record<string, number>>(\"virtualCurrencies\" as any) ?? EMPTY,\n () => EMPTY,\n );\n}\n\n/** Reactive single-currency balance; 0 when absent. */\nexport function useVirtualCurrency(code: string): number {\n const all = useVirtualCurrencies();\n return all[code] ?? 0;\n}\n","import { useEffect, useSyncExternalStore } from \"react\";\nimport { getNative } from \"../core/native\";\nimport { store } from \"../store/reactiveStore\";\nimport { EMPTY_REMOTE_CONFIG, parseRemoteConfig } from \"../api/remoteConfig\";\nimport type { ExperimentAssignment, RemoteConfig } from \"../types\";\n\nfunction loadIfNeeded(): void {\n if (store.get(\"remoteConfig\") === undefined) {\n getNative()\n .remoteConfigAllJson()\n .then((json) => store.set(\"remoteConfig\", parseRemoteConfig(json)))\n .catch(() => {});\n }\n}\n\nfunction read(): RemoteConfig {\n return store.get<RemoteConfig>(\"remoteConfig\") ?? EMPTY_REMOTE_CONFIG;\n}\n\n/**\n * Reactive Remote Config. Returns the whole `{ flags, experiments }` bundle and\n * re-renders whenever the native core emits `REMOTE_CONFIG_CHANGED`. Reads are\n * synchronous off the local cache; the first mount lazily primes it.\n */\nexport function useRemoteConfig(): RemoteConfig {\n useEffect(loadIfNeeded, []);\n return useSyncExternalStore(\n store.subscribe.bind(store),\n read,\n () => EMPTY_REMOTE_CONFIG,\n );\n}\n\n/** Reactive single-flag read with a typed fallback. */\nexport function useFlag<T>(key: string, fallback: T): T {\n const config = useRemoteConfig();\n const value = config.flags[key];\n return (value === undefined ? fallback : value) as T;\n}\n\n/** Reactive single-experiment assignment for the current subscriber. */\nexport function useExperiment(key: string): ExperimentAssignment | null {\n const config = useRemoteConfig();\n return config.experiments[key] ?? null;\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\nimport type { ExperimentAssignment, RemoteConfig } from \"../types\";\n\nexport const EMPTY_REMOTE_CONFIG: RemoteConfig = Object.freeze({\n flags: {},\n experiments: {},\n});\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/**\n * Parse the native `remoteConfigAllJson()` payload into a `RemoteConfig`.\n * Tolerant by design: a malformed/empty payload yields the empty config so a\n * read never throws.\n */\nexport function parseRemoteConfig(json: string): RemoteConfig {\n try {\n const parsed = JSON.parse(json) as Partial<RemoteConfig>;\n return {\n flags: parsed.flags ?? {},\n experiments: parsed.experiments ?? {},\n };\n } catch {\n return EMPTY_REMOTE_CONFIG;\n }\n}\n\n/** Force an immediate fetch of the latest Remote Config from the server. */\nexport async function refreshRemoteConfig(): Promise<void> {\n return call(() => getNative().refreshRemoteConfig());\n}\n\n/** The whole `{ flags, experiments }` bundle, fetched from the local cache. */\nexport async function getRemoteConfig(): Promise<RemoteConfig> {\n return call(async () => parseRemoteConfig(await getNative().remoteConfigAllJson()));\n}\n\n/**\n * Read one flag with a typed fallback. The fallback's runtime type selects the\n * native getter (boolean/number/string); anything else falls back to a parsed\n * JSON read so object/array flags resolve too.\n */\nexport async function getFlag<T>(key: string, fallback: T): Promise<T> {\n return call(async () => {\n const native = getNative();\n if (typeof fallback === \"boolean\") {\n return (await native.remoteConfigBool(key, fallback)) as unknown as T;\n }\n if (typeof fallback === \"number\") {\n return (await native.remoteConfigDouble(key, fallback)) as unknown as T;\n }\n if (typeof fallback === \"string\") {\n return (await native.remoteConfigString(key, fallback)) as unknown as T;\n }\n const raw = await native.remoteConfigJson(key);\n if (raw === null) return fallback;\n try {\n return JSON.parse(raw) as T;\n } catch {\n return fallback;\n }\n });\n}\n\n/** The current subscriber's assignment for one experiment, or `null`. */\nexport async function getExperiment(\n key: string,\n): Promise<ExperimentAssignment | null> {\n return call(async () => {\n const dto = await getNative().experiment(key);\n if (!dto) return null;\n return mapExperiment(dto);\n });\n}\n\n/** All of the current subscriber's experiment assignments. */\nexport async function getExperiments(): Promise<ExperimentAssignment[]> {\n return call(async () => (await getNative().experimentsAll()).map(mapExperiment));\n}\n\nfunction mapExperiment(dto: {\n experimentId: string;\n key: string;\n variantId: string;\n variantName: string;\n valueJson: string;\n}): ExperimentAssignment {\n let value: unknown = null;\n try {\n value = JSON.parse(dto.valueJson);\n } catch {\n value = null;\n }\n return {\n experimentId: dto.experimentId,\n key: dto.key,\n variantId: dto.variantId,\n variantName: dto.variantName,\n value,\n };\n}\n","// eventBridge — converts native `onChange` events into ReactiveStore\n// mutations. Started by configure(); stopped by shutdown().\n//\n// In M6 we subscribe via Expo's EventEmitter (\"onChange\" event) instead\n// of M5's native.addChangeListener callback. The handler is otherwise\n// identical: re-fetch from native on each hint, store the result.\n\nimport { getEmitter, getNative } from \"./native\";\nimport { store } from \"../store/reactiveStore\";\nimport { parseRemoteConfig } from \"../api/remoteConfig\";\n\nlet subscription: { remove(): void } | null = null;\n\nconst ENTITLEMENT_SLOT_PREFIX = \"entitlement:\";\n\n// Mirror the native entitlement cache into the store: the list slot, one slot\n// per cached id, and `null` for every per-id slot the cache no longer holds\n// (a revoked entitlement, or the previous user's after an identity change).\n// `entitlementsAll()` is a native CACHE read — never a network refresh.\nasync function rereadEntitlements(native: ReturnType<typeof getNative>): Promise<void> {\n const all = await native.entitlementsAll();\n store.set(\"entitlementsAll\", all);\n const cachedIds = new Set<string>();\n for (const ent of all) {\n cachedIds.add(ent.id);\n store.set(`${ENTITLEMENT_SLOT_PREFIX}${ent.id}`, ent);\n }\n for (const slot of store.slots()) {\n if (!slot.startsWith(ENTITLEMENT_SLOT_PREFIX)) continue;\n const id = slot.slice(ENTITLEMENT_SLOT_PREFIX.length);\n if (!cachedIds.has(id) && store.get(slot) !== null) store.set(slot, null);\n }\n}\n\nexport function startEventBridge(): void {\n if (subscription) return;\n const native = getNative();\n subscription = getEmitter().addListener(\"onChange\", async (payload: { event: string }) => {\n try {\n switch (payload.event) {\n case \"IDENTITY_CHANGED\": {\n // logOut emits only this event; identify() emits it after its\n // post-bind entitlements refresh (which fires ENTITLEMENTS_CHANGED\n // first when it lands), and balances follow on their own event.\n // Either way the per-user slots below may still hold the outgoing\n // identity's values. Re-READ each from the native cache (already\n // re-scoped to the new identity) — never refresh(): a refresh\n // inside this listener re-emits a change event and loops.\n const u = await native.currentUser();\n store.set(\"user\", u);\n await rereadEntitlements(native);\n store.set(\"virtualCurrencies\", await native.virtualCurrencies());\n store.set(\"remoteConfig\", parseRemoteConfig(await native.remoteConfigAllJson()));\n break;\n }\n case \"ENTITLEMENTS_CHANGED\": {\n await rereadEntitlements(native);\n break;\n }\n case \"VIRTUAL_CURRENCIES_CHANGED\": {\n const balances = await native.virtualCurrencies();\n store.set(\"virtualCurrencies\", balances);\n break;\n }\n case \"REMOTE_CONFIG_CHANGED\": {\n const json = await native.remoteConfigAllJson();\n store.set(\"remoteConfig\", parseRemoteConfig(json));\n break;\n }\n default:\n break;\n }\n } catch {\n // Best-effort: a refresh failure here cannot crash the bridge.\n }\n });\n}\n\nexport function stopEventBridge(): void {\n subscription?.remove();\n subscription = null;\n}\n","import { AppState, type AppStateStatus, type NativeEventSubscription } from \"react-native\";\nimport { getNative } from \"../core/native\";\n\nconst DEBOUNCE_MS = 1000;\nconst FLUSH_INTERVAL_MS = 30_000;\n\ntype Tracker = {\n sub: NativeEventSubscription;\n flushTimer: ReturnType<typeof setInterval>;\n foregroundStartedAt: number | null;\n pendingState: AppStateStatus | null;\n debounceTimer: ReturnType<typeof setTimeout> | null;\n};\n\nlet tracker: Tracker | null = null;\n\nfunction now(): number {\n return Date.now();\n}\nfunction isoNow(): string {\n return new Date().toISOString();\n}\n\nfunction isForeground(s: AppStateStatus): boolean {\n return s === \"active\";\n}\n\nexport function startSessionTracker(): void {\n if (tracker) return;\n const onChange = (next: AppStateStatus) => {\n if (!tracker) return;\n tracker.pendingState = next;\n if (tracker.debounceTimer) clearTimeout(tracker.debounceTimer);\n tracker.debounceTimer = setTimeout(() => {\n if (!tracker) return;\n const finalState = tracker.pendingState!;\n const wasForeground = tracker.foregroundStartedAt !== null;\n const willBeForeground = isForeground(finalState);\n if (wasForeground !== willBeForeground) {\n if (willBeForeground) {\n getNative()\n .recordSessionEvent(\"open\", isoNow(), undefined)\n .catch(() => {});\n tracker.foregroundStartedAt = now();\n } else {\n const durationMs = tracker.foregroundStartedAt\n ? Math.max(0, now() - tracker.foregroundStartedAt)\n : undefined;\n getNative()\n .recordSessionEvent(\"background\", isoNow(), durationMs)\n .catch(() => {});\n tracker.foregroundStartedAt = null;\n }\n }\n tracker.debounceTimer = null;\n }, DEBOUNCE_MS);\n };\n const sub = AppState.addEventListener(\"change\", onChange);\n const initialState = AppState.currentState as AppStateStatus;\n const startedAt = isForeground(initialState) ? now() : null;\n // The foreground state itself is NOT reported from here: `configure` runs\n // on the Swift / Kotlin façade, which observes the app lifecycle and tells\n // the core (spec 2026-11-03-sdk-automatic-foreground-design.md, Decision\n // 2 — one owner, so two sources never fight). This tracker only records\n // session events.\n tracker = {\n sub,\n flushTimer: setInterval(() => {\n getNative()\n .flushSessionEvents()\n .catch(() => {});\n }, FLUSH_INTERVAL_MS),\n foregroundStartedAt: startedAt,\n pendingState: null,\n debounceTimer: null,\n };\n // initial 'open' event — emit unconditionally on first mount so the\n // backend can join the session against a (subscriberId, app-start) pair.\n getNative()\n .recordSessionEvent(\"open\", isoNow(), undefined)\n .catch(() => {});\n}\n\nexport function stopSessionTracker(): void {\n if (!tracker) return;\n // emit a 'close' if we were foregrounded\n if (tracker.foregroundStartedAt !== null) {\n const durationMs = Math.max(0, now() - tracker.foregroundStartedAt);\n getNative()\n .recordSessionEvent(\"close\", isoNow(), durationMs)\n .catch(() => {});\n // best-effort final flush\n getNative()\n .flushSessionEvents()\n .catch(() => {});\n }\n if (tracker.debounceTimer) clearTimeout(tracker.debounceTimer);\n clearInterval(tracker.flushTimer);\n tracker.sub.remove();\n tracker = null;\n}\n","import { startEventBridge } from \"../core/eventBridge\";\nimport { getNative } from \"../core/native\";\nimport { fromNativeError, RovenueError } from \"../errors\";\nimport { startSessionTracker } from \"./sessionTracker\";\n\nexport type RovenueConfig = {\n apiKey: string;\n /**\n * API host. Optional — defaults to the hosted endpoint\n * `https://api.rovenue.io`. Self-hosters pass their own origin\n * (e.g. `https://api.acme.com`). The Rust core enforces https://\n * (http:// is accepted only for localhost during local dev).\n */\n baseUrl?: string;\n logLevel?: \"off\" | \"error\" | \"warn\" | \"info\" | \"debug\" | \"trace\";\n /**\n * Optional override for the host app's user-facing version. When\n * omitted, the native modules auto-read the value:\n * - iOS: `Bundle.main.infoDictionary[\"CFBundleShortVersionString\"]`\n * - Android: `packageManager.getPackageInfo(packageName, 0).versionName`\n * For Expo apps the auto-read value is baked from `app.json`'s\n * `expo.version` at prebuild time, so most callers should leave this\n * undefined.\n */\n appVersion?: string;\n /**\n * Remote Config environment — selects which flag/experiment set the\n * backend serves: `\"prod\"` (default), `\"staging\"`, or `\"development\"`.\n * Sent as the `X-Rovenue-Env` header on the `/v1/config` request. Omit\n * to use production.\n */\n environment?: \"prod\" | \"staging\" | \"development\";\n /**\n * Hold the first placement request after install (up to 3 s) until\n * {@link setAttribution} has been called with your MMP's callback, so the\n * first onboarding can be targeted by the MMP's campaign data. Default\n * `false`: only Rovenue's own first-launch signals are waited for.\n */\n awaitMmpAttribution?: boolean;\n /**\n * Android only: the Facebook App ID used to read Meta's install referrer.\n * Defaults to the `com.facebook.sdk.ApplicationId` manifest meta-data\n * your app already carries when it uses Meta's SDK. Ignored on iOS.\n */\n facebookAppId?: string;\n};\n\n// The host app's version as `configure()` RESOLVED it — the caller's\n// `appVersion` when given, otherwise the bundle/packageManager value the\n// native module auto-read. Stashed here so the funnel render layer can\n// evaluate `visibility.minAppVersion`/`maxAppVersion` without a native\n// round-trip per node. `undefined` until `configure()` runs, and on a JS\n// bundle running against a native binary predating `getAppVersion` (an\n// RN dev can reload JS without rebuilding native) — version bounds then\n// fail open, matching every other unknown in the visibility evaluator.\nlet configuredAppVersion: string | undefined;\n\n/** The host app version `configure()` resolved, if any. */\nexport function getConfiguredAppVersion(): string | undefined {\n return configuredAppVersion;\n}\n\n/**\n * Whether this is a release build: React Native's `__DEV__` is false. A\n * bundle with no `__DEV__` at all is not a dev bundle, so it counts as\n * release (the guard fails closed).\n */\nfunction isReleaseBuild(): boolean {\n return (globalThis as { __DEV__?: boolean }).__DEV__ !== true;\n}\n\n/**\n * Initialize the SDK. Must be called before any other `Rovenue.*` call —\n * every other method assumes a configured native module and crashes\n * (`fatalError` on iOS, `IllegalStateException` on Android) otherwise.\n * Synchronous: also starts the native-event bridge that feeds the reactive\n * hooks/`addChangeListener`, and the foreground/background session\n * tracker (both are internally guarded to start at most once).\n *\n * Throws `RovenueError` (`kind: \"InvalidApiKey\"`) synchronously — before\n * any native call — when `apiKey` is blank or `baseUrl` doesn't start with\n * `http://`/`https://`.\n *\n * Throws `RovenueError` (`kind: \"SandboxKeyInRelease\"`) when a Sandbox\n * (`rov_pk_test_…`) key is configured in a release build (`__DEV__` false):\n * a test key must never ship to the stores. Use a Production\n * (`rov_pk_live_…`) key in release builds.\n */\nexport function configure(opts: RovenueConfig): void {\n if (!opts.apiKey || opts.apiKey.trim() === \"\") {\n throw new RovenueError(\"InvalidApiKey\", \"apiKey is blank\");\n }\n if (opts.baseUrl !== undefined && !/^https?:\\/\\//.test(opts.baseUrl)) {\n throw new RovenueError(\"InvalidApiKey\", \"baseUrl must start with http:// or https://\");\n }\n const native = getNative();\n try {\n native.configure(\n opts.apiKey,\n opts.baseUrl,\n opts.logLevel ?? \"warn\",\n opts.appVersion,\n opts.environment,\n isReleaseBuild(),\n opts.awaitMmpAttribution ?? false,\n opts.facebookAppId,\n );\n } catch (e) {\n throw fromNativeError(e);\n }\n // Read back rather than reusing `opts.appVersion`: most callers omit it\n // and let native auto-read, and this getter is what drives version-based\n // node visibility. Guarded for the stale-native-binary case above.\n configuredAppVersion =\n typeof native.getAppVersion === \"function\"\n ? (native.getAppVersion() ?? undefined)\n : opts.appVersion;\n startEventBridge();\n startSessionTracker();\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\nimport type { AttributionProvider, User } from \"../types\";\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try { return await fn(); }\n catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/**\n * Current identity — the anonymous `rovenueId` plus `appUserId` once\n * {@link identify} has been called. Resolves from local state; does not\n * hit the network. Prefer the `useCurrentUser` hook in components.\n */\nexport async function currentUser(): Promise<User> {\n return call(() => getNative().currentUser());\n}\n\n/**\n * Link the anonymous device identity to `appUserId`.\n *\n * `identityToken` vouches for `appUserId`: your backend mints it with the\n * secret key (`POST /v1/identity-tokens`) for the signed-in user and hands\n * it to the app. It is valid for 15 minutes; fetch a fresh one for each\n * identify.\n *\n * The local write always succeeds; the `POST /v1/identify` to the server is\n * best-effort — if it fails (offline/5xx) the link is retried automatically\n * later with the same token, not surfaced as an error here. `IDENTITY_CHANGED` fires after the bind and\n * an entitlements refresh attempt: after a delivered bind the native core\n * fetches entitlements once (firing `ENTITLEMENTS_CHANGED` when it lands)\n * and this promise resolves after that fetch. When the bind is not\n * delivered (offline, server error, refused) it fires right after the\n * local link. Rejects on\n * validation failure (a blank id or token), with `IdentityTokenInvalid` when\n * the server refuses the token (expired, or minted for another user, project\n * or environment: the bind is dropped, so identify again with a fresh\n * token), and with `SubscriberUnresolvable` when the server cannot resolve\n * this install's subscriber (corrupt merge history) — the local link stands,\n * unsynced, until the data is repaired.\n */\nexport async function identify(appUserId: string, identityToken: string): Promise<void> {\n return call(() => getNative().identify(appUserId, identityToken));\n}\n\n/**\n * Log out the current user: mints a fresh anonymous `rovenueId` and drops\n * `appUserId`, so the next identity starts clean — including a new Apple\n * `appAccountToken`, which is derived from the `rovenueId`. Client-local\n * only — does not contact the server.\n */\nexport async function logOut(): Promise<void> {\n return call(() => getNative().logOut());\n}\n\n/**\n * Forward the attribution your MMP produced. Call it from the MMP's\n * conversion / attribution callback, passing the callback object as-is.\n * The record is write-once on the server: a call after the install is\n * already attributed changes nothing. On both platforms it rejects only\n * with `InvalidArgument` (unknown provider, or `data` not serialisable);\n * network and server failures are logged, not thrown.\n */\nexport async function setAttribution(\n provider: AttributionProvider,\n data: Record<string, unknown>,\n): Promise<void> {\n return call(() => getNative().setAttribution(provider, data));\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\nimport type { Entitlement } from \"../types\";\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try { return await fn(); }\n catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/**\n * Look up one entitlement by id from the native SDK's local cache — resolves\n * from disk/memory, not a network round trip. `null` when the id is unknown\n * or not currently granted. A stale (>60s) cache triggers a background\n * refresh on the native side; never call `refreshEntitlements()` from an\n * `ENTITLEMENTS_CHANGED` listener that refresh fires, or it loops.\n */\nexport async function entitlement(id: string): Promise<Entitlement | null> {\n return call(() => getNative().entitlement(id));\n}\n\n/**\n * All currently-granted entitlements from the native SDK's local cache — a\n * cache read, not a network call. Same background staleness-refresh\n * behaviour and `ENTITLEMENTS_CHANGED` re-entrancy footgun as\n * {@link entitlement}. Prefer the `useEntitlements` hook in components.\n */\nexport async function entitlementsAll(): Promise<Entitlement[]> {\n return call(() => getNative().entitlementsAll());\n}\n\n/**\n * Force a network refresh of entitlements, bypassing the 60s staleness\n * window that {@link entitlement}/{@link entitlementsAll} use. Never call\n * this from inside an `ENTITLEMENTS_CHANGED` listener — the refresh\n * re-emits that same event, which re-invokes the listener, forever.\n */\nexport async function refreshEntitlements(): Promise<void> {\n return call(() => getNative().refreshEntitlements());\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try { return await fn(); }\n catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/** All virtual-currency balances (code → amount). */\nexport async function virtualCurrencies(): Promise<Record<string, number>> {\n return call(() => getNative().virtualCurrencies());\n}\n\n/** One currency's balance; 0 when the code is absent. */\nexport async function virtualCurrency(code: string): Promise<number> {\n return call(() => getNative().virtualCurrency(code));\n}\n\n/** Force a refresh of virtual-currency balances from the server. */\nexport async function refreshVirtualCurrencies(): Promise<void> {\n return call(() => getNative().refreshVirtualCurrencies());\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\nimport type { Offerings, Offering, Package, PurchaseResult, StoreProduct, PackageType, SubscriptionOption } from \"../types\";\nimport type { OfferingDTO } from \"../specs/RovenueModule.types\";\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try { return await fn(); } catch (e) {\n throw fromNativeError(e);\n }\n}\n\nfunction packageTypeFromSlot(slot: string): PackageType {\n switch (slot) {\n case '$rov_weekly': return 'weekly';\n case '$rov_monthly': return 'monthly';\n case '$rov_two_month': return 'twoMonth';\n case '$rov_three_month': return 'threeMonth';\n case '$rov_six_month': return 'sixMonth';\n case '$rov_annual': return 'annual';\n case '$rov_lifetime': return 'lifetime';\n default: return 'custom';\n }\n}\n\n/** What a package or offering carries when the native side sends no metadata. */\nconst EMPTY_METADATA: Record<string, unknown> = {};\n\n/** Parses a native metadata JSON string; anything but an object reads as `{}`. */\nfunction parseMetadata(json: string | undefined): Record<string, unknown> {\n if (!json) return { ...EMPTY_METADATA };\n try {\n const v: unknown = JSON.parse(json);\n return v !== null && typeof v === \"object\" && !Array.isArray(v) ? (v as Record<string, unknown>) : { ...EMPTY_METADATA };\n } catch {\n return { ...EMPTY_METADATA };\n }\n}\n\n/** Maps a single native `OfferingDTO` to the public `Offering` domain type. */\nexport function mapOfferingDTO(o: OfferingDTO): Offering {\n return {\n identifier: o.identifier,\n isDefault: o.isDefault,\n metadata: parseMetadata(o.metadataJson),\n packages: o.packages.map((p) => ({\n identifier: p.identifier,\n packageType: packageTypeFromSlot(p.identifier),\n product: p.product as StoreProduct,\n // Optional on the DTO: an older native module sends none of the three.\n isPromoted: p.isPromoted ?? false,\n metadata: parseMetadata(p.metadataJson),\n virtualCurrencyGrants: (p.virtualCurrencyGrants ?? []).map((g) => ({\n code: g.code,\n amount: g.amount,\n grantOn: g.grantOn,\n intervalDays: g.intervalDays ?? null,\n // Optional on the DTO: an older native module sends neither.\n trialAmount: g.trialAmount ?? 0,\n expiresAtPeriodEnd: g.expiresAtPeriodEnd ?? false,\n })),\n })),\n };\n}\n\n/**\n * Fetch the project's current offerings from the backend and map them into\n * the public `Offerings` shape (`current` + `all`, keyed by identifier).\n * Always a network call from the JS side; the underlying native/Rust layer\n * falls back to its own last-cached response on a connectivity failure, but\n * an auth/server rejection still rejects this promise.\n */\nexport async function getOfferings(): Promise<Offerings> {\n const dto = await call(() => getNative().getOfferings());\n const all: Record<string, Offering> = {};\n let current: Offering | null = null;\n for (const o of dto.offerings) {\n const offering = mapOfferingDTO(o);\n all[o.identifier] = offering;\n if (o.identifier === dto.current) current = offering;\n }\n return { current, all };\n}\n\n/**\n * Buy a `Package` (from `getOfferings()`) or a raw\n * `StoreProduct` directly, driving the platform store UI (StoreKit /\n * Google Play Billing). Resolves with the resulting entitlements + VC\n * balances hydrated straight from the receipt-post response — no\n * follow-up `getOfferings`/`entitlementsAll` call needed. `isDeferred:\n * true` means the purchase is pending external approval (e.g. Ask to Buy)\n * and no entitlement has been granted yet.\n *\n * Rejects with `RovenueError` for store-level outcomes — `kind` may be\n * `PurchaseCanceled`, `AlreadyOwned`, `ProductNotAvailable`,\n * `PaymentDeclined`, `StoreServiceUnavailable`, or `ReceiptInvalid` —\n * as well as network/server failures.\n */\nexport async function purchase(\n target: Package | StoreProduct,\n options?: { promotionalOfferId?: string; subscriptionOption?: SubscriptionOption },\n): Promise<PurchaseResult> {\n const product = \"product\" in target ? target.product : target;\n const opt = options?.subscriptionOption;\n return call(() =>\n getNative().purchase(\n product.id, product.type, options?.promotionalOfferId,\n opt?.basePlanId ?? undefined, opt?.offerId ?? undefined,\n ),\n );\n}\n\n/**\n * Restore the user's previously-purchased entitlements from the store\n * (StoreKit's transaction history / Google Play's owned-purchases query),\n * re-submitting any found receipts so the server can (re-)grant\n * entitlements for this subscriber. Use for the \"Restore Purchases\" button\n * required by App Store review — not a substitute for automatic\n * entitlement sync, which already happens via `configure()`/receipt\n * posting.\n */\nexport async function restorePurchases(): Promise<PurchaseResult> {\n return call(() => getNative().restorePurchases());\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/**\n * Parse a spec D1 bundled fallback-placements file (once, replacing any\n * previously-loaded set) so `getFunnel` can serve placements offline when\n * both the network and disk cache miss. Resolves to the count of placement\n * entries actually loaded — an individual entry that fails to decode is\n * skipped natively, not fatal. Rejects with a distinct `invalidArgument`\n * error when the file doesn't parse or its `formatVersion` isn't literal\n * `1` — an integrator who bundles a stale/mismatched export must see this\n * loudly, at call time.\n */\n/**\n * Fetch a placement and warm everything its first screen draws — the\n * placement response, the first screen's images and video posters, the\n * store prices of its packages and its fonts — so even the first open of\n * `<RovenueFunnelView placementId=…>` draws complete and at once. Call it at\n * app start for the placement that shows your paywall.\n *\n * Never rejects: an unavailable placement or a network failure is logged\n * natively and the open loads as it would have without it. Nothing is\n * presented, so no funnel event is sent.\n *\n * @param placementId the placement identifier.\n * @param locale the locale the funnel will open in; the device's when omitted.\n */\nexport async function preloadPlacement(placementId: string, locale?: string): Promise<void> {\n try {\n await getNative().preloadPlacement(placementId, locale ?? null);\n } catch {\n // Native already logged it; a preload never fails the caller.\n }\n}\n\nexport async function setFallbackPlacements(json: string): Promise<number> {\n return call(() => getNative().setFallbackPlacements(json));\n}\n","import { getNative } from \"../core/native\";\nimport type { FunnelCheckRequestDTO, FunnelPhotoRefDTO } from \"../specs/RovenueModule.types\";\n\n/**\n * The photo a `photo_upload` question was answered with — normalised and\n * stored on the device (an upright JPEG with no metadata). Rovenue never\n * receives it. Call {@link releasePhoto} once you are done with the file;\n * an unreleased one is deleted 7 days after it was picked.\n */\nexport interface FunnelPhotoRef {\n /** The file, a `file://` URI. Valid until {@link releasePhoto} or for 7 days. */\n localUri: string;\n /** Pixel width, after normalisation. */\n width: number;\n /** Pixel height, after normalisation. */\n height: number;\n /** The file's size in bytes. */\n byteSize: number;\n /** Always `image/jpeg`. */\n mimeType: string;\n}\n\n/** What the SDK asks your photo checker (`onCheck`). */\nexport interface FunnelCheckRequest {\n /** The check block's answer key. */\n checkKey: string;\n /** The checker's step ids, in order. */\n steps: string[];\n /** The photo to judge, on the device. */\n photo: FunnelPhotoRef;\n /** The funnel's content locale (BCP-47), for any copy the checker returns. */\n locale: string;\n /** 1-based: completed checks for this block so far, plus one. */\n attempt: number;\n}\n\n/** Your checker's final answer for a photo check. */\nexport interface FunnelCheckOutcome {\n /** `pass` or `fail`. */\n result: \"pass\" | \"fail\";\n /** Plain text the funnel can show (`{{<checkKey>}}`). */\n label?: string;\n /** Why it failed, in plain text (`{{<checkKey>.reason}}`). */\n reason?: string;\n /** Each step id's final status (`pass` | `fail`). */\n steps?: Record<string, string>;\n}\n\n/**\n * Your photo checker. Resolve the outcome; resolving `null` / `undefined`,\n * or rejecting, applies the check's `whenUnavailable`. The native SDK bounds\n * it by the check's `timeoutMs` (then the result is `timeout` and a late\n * answer is ignored).\n *\n * On Android a presented funnel (`presentFunnel`) is its own activity, and\n * React Native pauses JS timers while the app's activity is covered: a\n * `setTimeout` inside the handler fires only after the funnel closes. Network\n * calls (`fetch`) and promises run as usual — call your checker service\n * directly rather than through a timer.\n */\nexport type FunnelCheckHandler = (\n request: FunnelCheckRequest,\n) => Promise<FunnelCheckOutcome | null | undefined> | FunnelCheckOutcome | null | undefined;\n\n/**\n * Deletes a photo a funnel stored on the device, once you are done with it:\n * the `localUri` of a {@link FunnelPhotoRef} from `onPhotoSelected` or a\n * presentation's `photos`. Anything outside the SDK's photo store is\n * ignored. Resolves whether a stored photo was deleted.\n */\nexport async function releasePhoto(localUri: string): Promise<boolean> {\n return getNative().releasePhoto(localUri);\n}\n\n/** Native numbers arrive as JS numbers; anything else is not a photo. */\nexport function photoFrom(dto: FunnelPhotoRefDTO): FunnelPhotoRef {\n return {\n localUri: dto.localUri,\n width: Number(dto.width),\n height: Number(dto.height),\n byteSize: Number(dto.byteSize),\n mimeType: dto.mimeType,\n };\n}\n\n/** The photos map of a present result; absent or null becomes `{}`. */\nexport function photosFrom(dto: Record<string, FunnelPhotoRefDTO> | null | undefined): Record<string, FunnelPhotoRef> {\n const out: Record<string, FunnelPhotoRef> = {};\n for (const [key, photo] of Object.entries(dto ?? {})) out[key] = photoFrom(photo);\n return out;\n}\n\n/**\n * The outcome as the native side decodes it, or null for \"unavailable\".\n * Anything that is not an object with a string `result` is null: a host\n * bug must not turn into a check the machine refuses.\n */\nfunction outcomeJson(outcome: unknown): string | null {\n if (typeof outcome !== \"object\" || outcome === null) return null;\n const o = outcome as Record<string, unknown>;\n if (typeof o.result !== \"string\") return null;\n const steps: Record<string, string> = {};\n if (typeof o.steps === \"object\" && o.steps !== null) {\n for (const [id, status] of Object.entries(o.steps as Record<string, unknown>)) {\n if (typeof status === \"string\") steps[id] = status;\n }\n }\n return JSON.stringify({\n result: o.result,\n ...(typeof o.label === \"string\" ? { label: o.label } : {}),\n ...(typeof o.reason === \"string\" ? { reason: o.reason } : {}),\n steps,\n });\n}\n\n/**\n * Runs the host's checker for one native check request and answers it.\n * Always answers — a missing handler, a throw or a rejection answers null —\n * so the native side never waits on JS for longer than its own timeout.\n */\nexport function answerCheckRequest(\n requestId: string,\n request: FunnelCheckRequestDTO,\n handler: FunnelCheckHandler | undefined,\n): void {\n const native = getNative();\n const run = async () => (handler ? handler({ ...request, photo: photoFrom(request.photo), attempt: Number(request.attempt) }) : null);\n run()\n .then((outcome) => native.resolveFunnelCheckRequest(requestId, outcomeJson(outcome)))\n .catch(() => native.resolveFunnelCheckRequest(requestId, null));\n}\n","import { getEmitter, getNative } from \"../core/native\";\nimport { RovenueError, fromNativeError, type ErrorKind } from \"../errors\";\nimport type { PurchaseResult } from \"../types\";\nimport type { FunnelCheckRequestDTO, FunnelPhotoRefDTO } from \"../specs/RovenueModule.types\";\nimport {\n answerCheckRequest,\n photoFrom,\n photosFrom,\n type FunnelCheckHandler,\n type FunnelPhotoRef,\n} from \"./funnel-photos\";\n\n/** How a presented funnel covers the app. */\nexport type FunnelPresentationStyle = \"fullScreen\" | \"modal\" | \"sheet\";\n/** How a full-screen funnel enters; Reduce Motion / animations off make each a fade. */\nexport type FunnelPresentationEnter = \"bottom\" | \"side\" | \"fade\" | \"none\";\n/** A sheet height: the first page's content (`fit`, capped at `large`), half the screen, or nearly all of it. */\nexport type FunnelSheetDetent = \"fit\" | \"medium\" | \"large\";\n\n/**\n * A present call's partial override of how the funnel's editor settings\n * present it. A field left out keeps the funnel's own; a style changed here\n * with no `dismissible` takes that style's default.\n */\nexport interface FunnelPresentationOverride {\n style?: FunnelPresentationStyle;\n enter?: FunnelPresentationEnter;\n detents?: FunnelSheetDetent[];\n dismissible?: boolean;\n closeOnPurchase?: boolean;\n}\n\n/** What `presentFunnel` takes. Every callback is optional. */\nexport interface PresentFunnelOptions {\n /** The placement identifier. */\n placement: string;\n /** The locale to resolve text in; the device's when omitted. */\n locale?: string;\n /** Overrides the funnel's own presentation, field by field. */\n style?: FunnelPresentationOverride;\n /**\n * Perform the purchase of this package yourself; resolve whether it went\n * through. Without it the SDK purchases. While it runs the funnel cannot\n * be swiped or backed away.\n */\n onPurchase?: (packageId: string) => Promise<{ purchased: boolean }>;\n /** Perform a restore yourself; resolve whether it restored anything. */\n onRestore?: () => Promise<{ purchased: boolean }>;\n /**\n * Observe a failed purchase or restore the SDK performed. The funnel stays\n * open; a cancelled store sheet is not reported, nor is a failure of your\n * own `onPurchase` / `onRestore`.\n */\n onPurchaseError?: (error: RovenueError) => void;\n /** A URL the funnel opens; without it, an http(s) URL opens in the browser. */\n onUrl?: (url: string) => void;\n /** A custom action the funnel runs: its id and its params as JSON. */\n onCustomAction?: (action: { actionId: string; paramsJson: string }) => void;\n /**\n * Values for the funnel's declared externals (an ad's scene, a campaign):\n * trimmed, 512 characters at most, undeclared names dropped. A fresh value\n * overrides a restored one and preselects a `defaultFrom` question. Never\n * pass personal data: values are written to the on-device session state.\n */\n values?: Record<string, string>;\n /** A `photo_upload` question was answered: its key and the photo on the device. */\n onPhotoSelected?: (questionKey: string, photo: FunnelPhotoRef) => void;\n /** Your photo checker; without it a check applies its `whenUnavailable`. */\n onCheck?: FunnelCheckHandler;\n}\n\n/** What `presentFunnel` resolves with. */\nexport interface FunnelPresentResult {\n /** How it ended: finished (or closed after a purchase), closed by the visitor, or never presented. */\n result: \"completed\" | \"dismissed\" | \"unavailable\";\n /** Whether a purchase or restore succeeded while it was presented. */\n purchased: boolean;\n /** The entitlements and balances after the purchase; set whenever `purchased` is true. */\n customerInfo?: PurchaseResult;\n /** The last purchase or restore failure the SDK saw. */\n lastError?: RovenueError;\n /** Why nothing was presented: `alreadyPresented`, `noPresenter`, or the placement's unavailable reason. */\n reason?: string;\n /**\n * The photos the visitor answered `photo_upload` questions with, by\n * question key — files on the device, kept until `releasePhoto` or 7\n * days. Empty when there were none.\n */\n photos: Record<string, FunnelPhotoRef>;\n}\n\n/** A native error as the present bridge carries it (`lastError`, `purchaseError`). */\ntype NativeErrorDTO = { kind: string; message: string; serverCode?: string | null; httpStatus?: number | null; retryable?: boolean };\n\ntype PresentEvent =\n | { presentationId: string; type: \"purchaseRequest\"; requestId: string; packageId: string }\n | { presentationId: string; type: \"restoreRequest\"; requestId: string }\n | { presentationId: string; type: \"purchaseError\"; error: NativeErrorDTO }\n | { presentationId: string; type: \"url\"; url: string }\n | { presentationId: string; type: \"customAction\"; actionId: string; paramsJson: string }\n | { presentationId: string; type: \"photoSelected\"; questionKey: string; photo: FunnelPhotoRefDTO }\n | { presentationId: string; type: \"checkRequest\"; requestId: string; request: FunnelCheckRequestDTO };\n\ntype PresentResultDTO = {\n result: FunnelPresentResult[\"result\"];\n purchased: boolean;\n customerInfo?: PurchaseResult | null;\n lastError?: NativeErrorDTO | null;\n reason?: string | null;\n photos?: Record<string, FunnelPhotoRefDTO> | null;\n};\n\n/** The native event every present callback rides on. */\nexport const FUNNEL_PRESENT_EVENT = \"onFunnelPresentEvent\";\n\nlet presentationSerial = 0;\n\nfunction toError(dto: NativeErrorDTO): RovenueError {\n const mapped = fromNativeError(Object.assign(new Error(dto.message), { code: dto.kind }));\n if (mapped instanceof RovenueError) {\n return new RovenueError(mapped.kind as ErrorKind, dto.message, {\n serverCode: dto.serverCode ?? undefined,\n httpStatus: dto.httpStatus ?? undefined,\n retryable: dto.retryable,\n });\n }\n return new RovenueError(\"Internal\", dto.message);\n}\n\n/**\n * Present the funnel a placement serves — natively, the way the funnel's\n * editor settings say (full screen, modal or sheet) — and resolve when it\n * ends. The placement is resolved first (instantly after\n * `preloadPlacement`); nothing is presented when it serves no funnel.\n *\n * The SDK performs purchases and restores itself unless you pass\n * `onPurchase` / `onRestore`, and closes after a successful one when the\n * funnel is set to \"Close after purchase\". Only one funnel is presented at\n * a time: a second call while one is up resolves `unavailable` with reason\n * `alreadyPresented`.\n *\n * A funnel with a photo check calls `onCheck` and waits for its answer, up\n * to the check's timeout; the photos the visitor gave come back in\n * `photos` — call `releasePhoto` with each once you are done with it.\n *\n * @example\n * const { result, purchased } = await presentFunnel({ placement: \"paywall\" });\n */\nexport async function presentFunnel(options: PresentFunnelOptions): Promise<FunnelPresentResult> {\n const native = getNative();\n presentationSerial += 1;\n const presentationId = `p${Date.now().toString(36)}${presentationSerial}`;\n const subscription = getEmitter().addListener(FUNNEL_PRESENT_EVENT, (event: PresentEvent) => {\n if (event.presentationId !== presentationId) return;\n switch (event.type) {\n case \"purchaseRequest\":\n case \"restoreRequest\": {\n const run = event.type === \"purchaseRequest\" ? options.onPurchase?.(event.packageId) : options.onRestore?.();\n Promise.resolve(run)\n .then((answer) => native.resolveFunnelPurchaseRequest(event.requestId, Boolean(answer?.purchased)))\n .catch(() => native.resolveFunnelPurchaseRequest(event.requestId, false));\n break;\n }\n case \"purchaseError\":\n options.onPurchaseError?.(toError(event.error));\n break;\n case \"url\":\n options.onUrl?.(event.url);\n break;\n case \"customAction\":\n options.onCustomAction?.({ actionId: event.actionId, paramsJson: event.paramsJson });\n break;\n case \"photoSelected\":\n options.onPhotoSelected?.(event.questionKey, photoFrom(event.photo));\n break;\n case \"checkRequest\":\n answerCheckRequest(event.requestId, event.request, options.onCheck);\n break;\n }\n });\n try {\n const dto: PresentResultDTO = await native.presentFunnel(\n presentationId,\n options.placement,\n options.locale ?? null,\n options.style ? JSON.stringify(options.style) : null,\n {\n onPurchase: Boolean(options.onPurchase),\n onRestore: Boolean(options.onRestore),\n onUrl: Boolean(options.onUrl),\n onCustomAction: Boolean(options.onCustomAction),\n onPhotoSelected: Boolean(options.onPhotoSelected),\n onCheck: Boolean(options.onCheck),\n },\n options.values ?? {},\n );\n return {\n result: dto.result,\n purchased: dto.purchased,\n ...(dto.customerInfo ? { customerInfo: dto.customerInfo } : {}),\n ...(dto.lastError ? { lastError: toError(dto.lastError) } : {}),\n ...(dto.reason ? { reason: dto.reason } : {}),\n photos: photosFrom(dto.photos),\n };\n } catch (e) {\n throw fromNativeError(e);\n } finally {\n subscription.remove();\n }\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\nimport {\n type EventEnvelope,\n type IdentityContext,\n serializeEnvelope,\n} from \"../events\";\n\n/** Optional fields for {@link track}. `eventType` is the first positional arg. */\nexport interface TrackParams {\n /** ISO-8601 override; defaults to the call-time timestamp. */\n occurredAt?: string;\n /** Defaults to the current scope (app user id, else anonymous id). */\n subscriberId?: string;\n productId?: string;\n /** Decimal string, e.g. \"9.99\". */\n amount?: string;\n /** ISO-4217 three-letter code, e.g. \"USD\". */\n currency?: string;\n eventSourceUrl?: string;\n identityContext?: IdentityContext;\n}\n\nfunction isoNow(): string {\n return new Date().toISOString();\n}\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/**\n * Emit a generic event to the backend (`POST /v1/events`). The SDK's HTTP\n * layer retries transient failures; the returned promise rejects if the POST\n * ultimately fails. `occurredAt` defaults to now; `subscriberId` is filled\n * from the current scope when omitted, and the native core stamps the wire\n * version and a stable `eventId`.\n */\nexport async function track(eventType: string, params: TrackParams = {}): Promise<void> {\n const envelope: EventEnvelope = {\n eventType,\n occurredAt: params.occurredAt ?? isoNow(),\n subscriberId: params.subscriberId,\n productId: params.productId,\n amount: params.amount,\n currency: params.currency,\n eventSourceUrl: params.eventSourceUrl,\n identityContext: params.identityContext,\n };\n return call(() => getNative().track(serializeEnvelope(envelope)));\n}\n","import { stopEventBridge } from \"../core/eventBridge\";\nimport { getNative } from \"../core/native\";\nimport { stopSessionTracker } from \"./sessionTracker\";\n\n/**\n * Override the SDK's foreground state. Not needed: the native SDK observes\n * the app lifecycle itself — polling and the attribute/session flush run\n * while the app is in front and pause in the background. A manual call is\n * honoured until the next lifecycle transition.\n */\nexport function setForeground(foreground: boolean): void {\n getNative().setForeground(foreground);\n}\n\n/**\n * Tear down the SDK: stops the session tracker (recording a final\n * `close` event and flushing it) and the native-event bridge before\n * stopping the native module's own background polling. The native layer\n * already calls its own equivalent of this when `configure()` is invoked\n * a second time, so most apps never need to call it directly — reach for\n * it only when the host app is shutting the SDK down without immediately\n * reconfiguring.\n */\nexport function shutdown(): void {\n // Stop the session tracker first so the final 'close' + flush happen\n // before the native module is torn down.\n stopSessionTracker();\n stopEventBridge();\n getNative().shutdown();\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/**\n * Returns the Apple `appAccountToken` (a lowercase UUID) derived from the\n * current `rovenueId`. The SDK's own `purchase` already passes it to\n * StoreKit on iOS (and attaches the matching Google Play account id on\n * Android); a host app that buys through StoreKit directly passes it as\n * `.appAccountToken(uuid)`. The server binds the same value at launch, so\n * the store notification routes to this subscriber even before the receipt.\n *\n * Stable across `identify()`; `logOut()` mints a new `rovenueId` and so a\n * new token.\n */\nexport async function getAppAccountToken(): Promise<string> {\n return call(() => getNative().getAppAccountToken());\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/**\n * Queue a batch of subscriber-attribute mutations. Written to the local\n * buffer immediately (this promise resolves once that local write\n * completes); the server sync happens in the background (30s tick, on\n * foreground, or via {@link flushAttributes}). A `null` value deletes the\n * key. Reserved keys (prefixed with `$`, e.g. `$email`) map to first-class\n * fields server-side — {@link setEmail}/{@link setDisplayName}/\n * {@link setPhoneNumber}/{@link setPushToken} are thin wrappers over this\n * for the common ones.\n */\nexport async function setAttributes(attributes: Record<string, string | null>): Promise<void> {\n return call(() => getNative().setAttributes(attributes));\n}\n/** Subscriber's email → the `$email` reserved attribute. Same buffered-write,\n * background-flush contract as {@link setAttributes}; `null` clears it. */\nexport async function setEmail(email: string | null): Promise<void> {\n return call(() => getNative().setEmail(email));\n}\n/** Subscriber's display name → the `$displayName` reserved attribute. Same\n * buffered-write, background-flush contract as {@link setAttributes};\n * `null` clears it. */\nexport async function setDisplayName(name: string | null): Promise<void> {\n return call(() => getNative().setDisplayName(name));\n}\n/** Subscriber's phone number → the `$phoneNumber` reserved attribute. Same\n * buffered-write, background-flush contract as {@link setAttributes};\n * `null` clears it. */\nexport async function setPhoneNumber(phone: string | null): Promise<void> {\n return call(() => getNative().setPhoneNumber(phone));\n}\n/** Device push token → the platform's reserved attribute (`$apnsTokens` on\n * iOS, `$fcmTokens` on Android — the native layer picks the right key).\n * Same buffered-write, background-flush contract as {@link setAttributes};\n * `null` clears it. */\nexport async function setPushToken(token: string | null): Promise<void> {\n return call(() => getNative().setPushToken(token));\n}\n/**\n * Force an immediate flush of buffered attribute mutations to the server,\n * bypassing the 30s background tick. Returns the number of mutations\n * actually sent. Most apps never need this — the background dispatcher\n * already flushes on its own tick and on foreground.\n */\nexport async function flushAttributes(): Promise<number> {\n return call(() => getNative().flushAttributes());\n}\n","// Rovenue.setLogHandler — JS-side seam for receiving bridge-level log\n// events from M3/M4. The native module emits `onLog` events; we hold a\n// single subscription and forward to the user-provided handler.\n//\n// Passing `null` removes the active subscription. Replacing a handler\n// implicitly unsubscribes the prior one — there is only ever one active\n// handler at a time, matching the M3/M4 façade contract.\n\nimport { getEmitter } from \"../core/native\";\n\nexport type LogEntry = {\n level: \"off\" | \"error\" | \"warn\" | \"info\" | \"debug\" | \"trace\";\n message: string;\n data?: Record<string, unknown>;\n};\n\nlet subscription: { remove(): void } | null = null;\n\n/**\n * Register a sink for the Rust core's structured log records, bridged\n * through the native module's `onLog` event. There is only ever one active\n * handler — calling this again replaces (implicitly unsubscribes) the\n * previous one; pass `null` to remove it entirely. The core is the sole\n * log authority (there is no separate JS-side `debug` flag) — this is the\n * only way to observe its logs from JS.\n */\nexport function setLogHandler(fn: ((entry: LogEntry) => void) | null): void {\n subscription?.remove();\n subscription = null;\n if (fn) {\n subscription = getEmitter().addListener(\n \"onLog\",\n (native: { level: LogEntry[\"level\"]; message: string; fields?: Record<string, string> }) => {\n const entry: LogEntry = {\n level: native.level,\n message: native.message,\n data:\n native.fields && Object.keys(native.fields).length > 0\n ? native.fields\n : undefined,\n };\n fn(entry);\n },\n );\n }\n}\n","import { getNative, getEmitter } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\n\nexport interface FunnelClaimResult {\n subscriberId: string;\n funnelAnswers: Record<string, unknown>;\n /**\n * The question keys an app value preselected and the visitor left\n * unchanged (the claim's `funnel_preselected`), so a default can be told\n * from a choice. Empty when nothing was preselected or the server\n * predates the field.\n */\n funnelPreselected: string[];\n}\n\nexport interface ClaimInstallParams {\n platform: \"ios\" | \"android\";\n locale: string;\n timezone: string;\n screenDims: string; // \"WIDTHxHEIGHT\"\n deviceModel?: string;\n installReferrer?: string;\n}\n\ninterface NativeClaim { subscriberId: string; funnelAnswersJson: string; funnelPreselectedJson?: string }\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try { return await fn(); }\n catch (e) {\n throw fromNativeError(e);\n }\n}\n\nfunction parse(n: NativeClaim): FunnelClaimResult {\n let funnelAnswers: Record<string, unknown> = {};\n try { funnelAnswers = JSON.parse(n.funnelAnswersJson) as Record<string, unknown>; } catch { /* keep {} */ }\n let funnelPreselected: string[] = [];\n try {\n const keys: unknown = JSON.parse(n.funnelPreselectedJson ?? \"[]\");\n if (Array.isArray(keys)) funnelPreselected = keys.filter((k): k is string => typeof k === \"string\");\n } catch { /* keep [] */ }\n return { subscriberId: n.subscriberId, funnelAnswers, funnelPreselected };\n}\n\n/** Claim a known funnel token (e.g. from a deep link). */\nexport async function claimFunnelToken(token: string): Promise<FunnelClaimResult> {\n return call(async () => parse(await getNative().claimFunnelToken(token)));\n}\n\n/** Recover + claim via install attribution. Resolves `null` when no match. */\nexport async function claimInstall(\n params: Partial<ClaimInstallParams> = {},\n): Promise<FunnelClaimResult | null> {\n return call(async () => {\n const n = (await getNative().claimInstall(params)) as NativeClaim | null;\n return n ? parse(n) : null;\n });\n}\n\n/** Kick off the email magic-link claim (resolves later via deep link). */\nexport async function claimViaEmail(email: string): Promise<void> {\n return call(() => getNative().claimViaEmail(email));\n}\n\n/** Persisted per-install id. */\nexport async function installId(): Promise<string> {\n return call(() => getNative().installId());\n}\n\n/** Subscribe to resolved funnel claims (direct calls + future auto-resolution). */\nexport function addFunnelClaimListener(cb: (result: FunnelClaimResult) => void): () => void {\n const sub = getEmitter().addListener(\"onFunnelClaimResolved\", (p: NativeClaim) => cb(parse(p)));\n return () => sub.remove();\n}\n\n/** iOS only: read a `rovenue-funnel:` clipboard marker (after a user gesture)\n * and claim it. Resolves null on Android, or when no marker is present. */\nexport async function claimFromClipboard(): Promise<FunnelClaimResult | null> {\n return call(async () => {\n const n = (await getNative().claimFromClipboard()) as NativeClaim | null;\n return n ? parse(n) : null;\n });\n}\n\nfunction safeDecode(s: string): string {\n if (!s) return \"\";\n try {\n return decodeURIComponent(s);\n } catch {\n return s;\n }\n}\n\n/**\n * Extract a funnel token from a deep link / Universal Link. Recognises:\n * - Universal Link path: `…/funnels/open/<token>`\n * - `rovenue_funnel_token=<token>` query (anywhere — Rovenue-specific key)\n * - `token=<token>` query ONLY on the funnel deep-link host\n * (`…onboarding-complete…`) so an unrelated deep link's generic `token=` is\n * not mistaken for a funnel token.\n * Returns null for any non-funnel URL. Does not use the `URL` constructor\n * (unreliable for custom schemes in RN/Hermes).\n */\nexport function extractFunnelToken(url: string): string | null {\n if (!url) return null;\n\n // 1) Universal-link path: the segment after \"funnels/open/\".\n const marker = \"funnels/open/\";\n const mi = url.indexOf(marker);\n if (mi !== -1) {\n const rest = url.slice(mi + marker.length);\n const seg = rest.split(\"/\")[0].split(\"?\")[0].split(\"#\")[0];\n if (seg) return seg;\n }\n\n // 2) Query-string extraction (manual parse — no URL constructor).\n const qi = url.indexOf(\"?\");\n if (qi !== -1) {\n const query = url.slice(qi + 1).split(\"#\")[0];\n let generic: string | null = null;\n for (const pair of query.split(\"&\")) {\n const eq = pair.indexOf(\"=\");\n if (eq === -1) continue;\n const key = pair.slice(0, eq);\n const val = safeDecode(pair.slice(eq + 1));\n if (!val) continue;\n if (key === \"rovenue_funnel_token\") return val; // Rovenue-specific → trust anywhere\n if (key === \"token\") generic = val;\n }\n // generic `token=` only on the Rovenue funnel deep-link host.\n // Check only the pre-query portion so a crafted query key like\n // `?onboarding-complete=1&token=…` cannot bypass this gate.\n const beforeQuery = url.slice(0, qi);\n if (generic && beforeQuery.includes(\"onboarding-complete\")) return generic;\n }\n\n return null;\n}\n\n/**\n * Claim a funnel token carried by a deep link / Universal Link. Forward every\n * incoming URL here from your app's Linking handler; non-funnel URLs resolve\n * `null` without a network call. A recognized-but-invalid token surfaces the\n * usual claim error via the returned promise.\n */\nexport async function claimFromUrl(url: string): Promise<FunnelClaimResult | null> {\n const token = extractFunnelToken(url);\n if (!token) return null;\n return call(async () => parse(await getNative().claimFunnelToken(token)));\n}\n\n/**\n * Run the no-gesture deterministic funnel-recovery chain once per install:\n * direct deep link (opts.url) → platform deferred match (claimInstall:\n * Android Install Referrer / iOS IP-only). Returns the claim, or null when\n * nothing resolves — then surface the gesture fallbacks yourself\n * (claimFromClipboard on iOS, then claimViaEmail). Resolved claims also fire\n * the addFunnelClaimListener callback. Safe to call on every launch; it\n * short-circuits once a claim has succeeded for this install.\n */\nexport async function resolveFunnelClaim(\n opts: { url?: string } = {},\n): Promise<FunnelClaimResult | null> {\n if (await getNative().hasResolvedFunnelClaim()) return null;\n\n if (opts.url) {\n try {\n const r = await claimFromUrl(opts.url);\n if (r) return r;\n } catch {\n // recognized-but-invalid deep-link token → fall through to the next source\n }\n }\n\n try {\n const r = await claimInstall();\n if (r) return r;\n } catch {\n // network / transient → unresolved\n }\n\n return null;\n}\n","import { StyleSheet } from \"react-native\";\nimport { mapNativeError, type RovenueError } from \"../errors\";\nimport { NativeFunnelView, type NativeFunnelViewProps } from \"./native-view\";\nimport {\n answerCheckRequest,\n photoFrom,\n type FunnelCheckHandler,\n type FunnelPhotoRef,\n} from \"../api/funnel-photos\";\n\ntype NativeLoaded = Parameters<NativeFunnelViewProps[\"onFunnelLoaded\"]>[0][\"nativeEvent\"];\ntype NativeUnavailable = Parameters<NativeFunnelViewProps[\"onFunnelUnavailable\"]>[0][\"nativeEvent\"];\n\n// The funnel fills whatever frame the host gives it; hosts size it with\n// their own flex container: the screens are laid out natively and the JS side has\n// no say in them.\nconst styles = StyleSheet.create({ fill: { flex: 1 } });\n\n/** One empty object, so a view without values never hands native a new one. */\nconst EMPTY_VALUES: Record<string, string> = {};\n\n/** What a funnel asks the app to do when it hits an app-defined action.\n * `params` is whatever the funnel's author configured, already parsed. */\nexport type FunnelCustomAction = {\n actionId: string;\n params: Record<string, unknown>;\n};\n\n/** Why a {@link RovenueFunnelView} has nothing to draw. The same spellings\n * on every Rovenue SDK. */\nexport type FunnelUnavailableReason =\n | \"empty_placement_id\"\n | \"no_placement\"\n | \"no_target\"\n | \"no_variants\"\n | \"draft_issues\";\n\n/** One problem that keeps a draft from being served, as the funnel's\n * validator reported it. */\nexport type FunnelDraftIssue = {\n path: string;\n code: string;\n message: string;\n severity: string;\n pageId?: string;\n blockId?: string;\n};\n\n/** `onLoaded`: the funnel's first screen is on screen. */\nexport type FunnelLoadedEvent = {\n /** The placement the view was asked for. */\n placementId: string;\n /** The `funnels` row id. */\n funnelId: string;\n /** The version drawn (a draft's: the version a publish would create). */\n revision: number;\n /** The experiment variant drawn, when the placement serves one. */\n variantId?: string;\n /** The experiment's key, alongside `variantId`. */\n experimentKey?: string;\n /** True when the bundled fallback file answered. */\n servedFromFallback: boolean;\n /** True when this is the funnel's latest draft (a debug build on a\n * Sandbox key). */\n isDraft: boolean;\n};\n\n/** `onUnavailable`: the view has nothing to draw, and why. */\nexport type FunnelUnavailableEvent = {\n /** The placement the view was asked for. */\n placementId: string;\n reason: FunnelUnavailableReason;\n /** What blocks the draft; set only for `draft_issues`. */\n issues?: FunnelDraftIssue[];\n};\n\n/** `onScreenChanged`: the visible screen changed, including the first. */\nexport type FunnelScreenEvent = {\n /** The screen's (page's) id in the funnel document. */\n screenId: string;\n /** Its position in the funnel's page order, from 0. */\n index: number;\n};\n\n/** Props for {@link RovenueFunnelView}. */\nexport type RovenueFunnelViewProps = {\n /** The placement to resolve. Resolution happens NATIVELY — there is no\n * JS `getFunnel`, because nothing about a funnel crosses the bridge. A\n * new value resolves again; the previous funnel is cleared first. In a\n * debug build on a Sandbox key the funnel's latest draft is shown, with\n * a \"Draft\" badge, and every builder edit arrives live. */\n placementIdentifier: string;\n locale?: string;\n /** The first screen is on screen. For a draft, fires again after every\n * live-refresh rebuild. */\n onLoaded?: (event: FunnelLoadedEvent) => void;\n /** The view has nothing to draw: an empty or unknown placement, a\n * placement with no target, or a draft that cannot be served (with its\n * issues). The previous funnel is cleared. */\n onUnavailable?: (event: FunnelUnavailableEvent) => void;\n /** Resolving failed (offline with no cache or fallback, an invalid or\n * unsupported config), or a screen did not decode\n * (`serverCode` `FUNNEL_SCREEN_UNDECODABLE`). The previous funnel is\n * cleared. A superseded resolve is never reported. */\n onError?: (error: RovenueError) => void;\n /** The visible screen changed, including the first. */\n onScreenChanged?: (event: FunnelScreenEvent) => void;\n /** The funnel reached its end. Never fires together with `onDismissed`. */\n onCompleted?: () => void;\n /** The visitor dismissed the funnel (its close action). Never fires\n * together with `onCompleted`, and not when the host unmounts the view. */\n onDismissed?: () => void;\n /** Omit to leave `open_url` actions INERT; a legal block's terms link then\n * opens only an http(s) address, in the system browser. Presence is\n * decided when the funnel resolves. */\n onUrl?: (url: string) => void;\n /** An action the funnel's author defined for this app to interpret. */\n onCustomAction?: (action: FunnelCustomAction) => void;\n /** The funnel wants this package purchased. Call `Rovenue.purchase`. */\n onPurchase?: (packageIdentifier: string) => void;\n /** The funnel asked for purchases to be restored. */\n onRestore?: () => void;\n /** Values for the funnel's declared externals (an ad's scene, a\n * campaign): trimmed, 512 characters at most, undeclared names dropped.\n * A fresh value overrides a restored one and preselects a `defaultFrom`\n * question. A changed value resolves again. Never pass personal data:\n * values are written to the on-device session state. */\n values?: Record<string, string>;\n /** A `photo_upload` question was answered: its key and the photo on the\n * device. Call `releasePhoto` once you are done with the file. */\n onPhotoSelected?: (questionKey: string, photo: FunnelPhotoRef) => void;\n /** Your photo checker; without it a check applies its `whenUnavailable`.\n * Presence is decided when the funnel resolves. */\n onCheck?: FunnelCheckHandler;\n};\n\n/** Params arrive as a JSON string: the native handler signature carries\n * `paramsJson`, because a map would have to be re-encoded per platform.\n * A malformed one yields `{}` rather than throwing inside a native event\n * callback, where the throw would surface as an unhandled JS exception\n * with no funnel context attached. */\nfunction parseParams(json: string): Record<string, unknown> {\n try {\n const parsed: unknown = JSON.parse(json);\n return typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\n/** Optional fields arrive absent or null depending on the platform; both\n * become absent here, so a host can test with `=== undefined`. */\nfunction loadedFrom(e: NativeLoaded): FunnelLoadedEvent {\n return {\n placementId: e.placementId,\n funnelId: e.funnelId,\n revision: e.revision,\n ...(e.variantId != null ? { variantId: e.variantId } : {}),\n ...(e.experimentKey != null ? { experimentKey: e.experimentKey } : {}),\n servedFromFallback: e.servedFromFallback,\n isDraft: e.isDraft,\n };\n}\n\nfunction unavailableFrom(e: NativeUnavailable): FunnelUnavailableEvent {\n const issues = e.issues?.map((i) => ({\n path: i.path,\n code: i.code,\n message: i.message,\n severity: i.severity,\n ...(i.pageId != null ? { pageId: i.pageId } : {}),\n ...(i.blockId != null ? { blockId: i.blockId } : {}),\n }));\n return {\n placementId: e.placementId,\n // The native views send only the five spellings of the union.\n reason: e.reason as FunnelUnavailableReason,\n ...(issues && issues.length > 0 ? { issues } : {}),\n };\n}\n\n/**\n * Hosts the platform's native funnel renderer for a placement.\n *\n * The funnel fills whatever frame the host gives it; size it with your own\n * flex container. Nothing about the funnel crosses the bridge — the native\n * side resolves the placement and draws the screens, so there is no JS\n * `getFunnel` and no object to pass in.\n */\nexport function RovenueFunnelView(props: RovenueFunnelViewProps) {\n const {\n placementIdentifier,\n locale,\n onLoaded,\n onUnavailable,\n onError,\n onScreenChanged,\n onCompleted,\n onDismissed,\n onUrl,\n onCustomAction,\n onPurchase,\n onRestore,\n values,\n onPhotoSelected,\n onCheck,\n } = props;\n return (\n <NativeFunnelView\n style={styles.fill}\n funnelIdentifier={placementIdentifier}\n locale={locale}\n // The native views branch on whether a handler EXISTS, so this is a\n // value, not a convenience flag.\n hasUrlHandler={onUrl !== undefined}\n // Same reason: without a checker the native side applies the check's\n // `whenUnavailable` at once instead of waiting on JS.\n hasCheckHandler={onCheck !== undefined}\n values={values ?? EMPTY_VALUES}\n onFunnelLoaded={(e) => onLoaded?.(loadedFrom(e.nativeEvent))}\n onFunnelUnavailable={(e) => onUnavailable?.(unavailableFrom(e.nativeEvent))}\n onFunnelFailed={(e) => onError?.(mapNativeError(e.nativeEvent.code, e.nativeEvent.message))}\n onFunnelScreenChanged={(e) =>\n onScreenChanged?.({ screenId: e.nativeEvent.screenId, index: e.nativeEvent.index })\n }\n onFunnelCompleted={() => onCompleted?.()}\n onFunnelDismissed={() => onDismissed?.()}\n onUrlRequested={(e) => onUrl?.(e.nativeEvent.url)}\n onCustomActionRequested={(e) =>\n onCustomAction?.({\n actionId: e.nativeEvent.actionId,\n params: parseParams(e.nativeEvent.params),\n })\n }\n onPurchaseRequested={(e) => onPurchase?.(e.nativeEvent.packageId)}\n onRestoreRequested={() => onRestore?.()}\n onPhotoSelectedEvent={(e) => onPhotoSelected?.(e.nativeEvent.questionKey, photoFrom(e.nativeEvent.photo))}\n // Always answered — a checker removed since the resolve answers null.\n onCheckRequested={(e) => answerCheckRequest(e.nativeEvent.requestId, e.nativeEvent.request, onCheck)}\n />\n );\n}\n","// `requireNativeViewManager` — NOT `requireNativeView`, which does not\n// exist in expo-modules-core 2.5.0. Events arrive wrapped in\n// `nativeEvent`.\nimport { requireNativeViewManager } from \"expo-modules-core\";\nimport type { FunnelCheckRequestDTO, FunnelPhotoRefDTO } from \"../specs/RovenueModule.types\";\n\n/** One issue that blocks a draft, as the native views send it. */\nexport type NativeDraftIssue = {\n path: string;\n code: string;\n message: string;\n severity: string;\n pageId?: string;\n blockId?: string;\n};\n\n/** Wire props for the native funnel view. Deliberately narrow: nothing\n * about the funnel crosses the bridge, only the placement identifier the\n * native side resolves it with. The screens are drawn natively. */\nexport type NativeFunnelViewProps = {\n funnelIdentifier: string;\n locale?: string;\n hasUrlHandler: boolean;\n hasCheckHandler: boolean;\n values: Record<string, string>;\n onFunnelLoaded: (event: {\n nativeEvent: {\n placementId: string;\n funnelId: string;\n revision: number;\n variantId?: string;\n experimentKey?: string;\n servedFromFallback: boolean;\n isDraft: boolean;\n };\n }) => void;\n onFunnelUnavailable: (event: {\n nativeEvent: { placementId: string; reason: string; issues?: NativeDraftIssue[] };\n }) => void;\n onFunnelFailed: (event: { nativeEvent: { code: string; message: string } }) => void;\n onFunnelScreenChanged: (event: { nativeEvent: { screenId: string; index: number } }) => void;\n onFunnelCompleted: (event: { nativeEvent: Record<string, never> }) => void;\n onFunnelDismissed: (event: { nativeEvent: Record<string, never> }) => void;\n onUrlRequested: (event: { nativeEvent: { url: string } }) => void;\n onCustomActionRequested: (event: { nativeEvent: { actionId: string; params: string } }) => void;\n onPurchaseRequested: (event: { nativeEvent: { packageId: string } }) => void;\n onRestoreRequested: (event: { nativeEvent: Record<string, never> }) => void;\n onPhotoSelectedEvent: (event: { nativeEvent: { questionKey: string; photo: FunnelPhotoRefDTO } }) => void;\n onCheckRequested: (event: { nativeEvent: { requestId: string; request: FunnelCheckRequestDTO } }) => void;\n style?: unknown;\n};\n\nconst MODULE_NAME = \"Rovenue\";\n\n/** The view name both native modules register this view under. It is the\n * module's only view since sub-project 5, but it is still asked for by\n * NAME: the native side names it, and a mismatch would resolve nothing. */\nconst VIEW_NAME = \"RovenueFunnelView\";\n\nexport const NativeFunnelView =\n requireNativeViewManager<NativeFunnelViewProps>(MODULE_NAME, VIEW_NAME);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,cAAc;;;ACcpB,IAAM,qBAAqB;AA2C3B,SAAS,eACd,GACY;AACZ,SAAO,OAAO;AAAA,IACZ,OAAO,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,CAAC,MAAM,MAAM,MAAS;AAAA,EACrD;AACF;AAUO,SAAS,kBAAkB,KAA4B;AAC5D,QAAM,EAAE,iBAAiB,GAAG,KAAK,IAAI;AAErC,QAAM,MAAM,eAAe,IAA+B;AAE1D,MAAI,oBAAoB,QAAW;AACjC,UAAM,UAAU;AAAA,MACd;AAAA,IACF;AACA,QAAI,OAAO,KAAK,OAAO,EAAE,SAAS,GAAG;AACnC,MAAC,IAAgC,kBAAkB;AAAA,IACrD;AAAA,EACF;AAEA,SAAO,KAAK,UAAU,GAAG;AAC3B;;;AC3EO,IAAM,cAAc;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA,EACA;AAAA;AAAA;AAAA,EAGA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;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A;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,mBAAmB,CAAC,OAAqE;AACvF,UAAM,MAAM,WAAW,EAAE,YAAY,YAAY,CAAC,YAA+B;AAC/E,SAAG,QAAQ,KAAsC;AAAA,IACnD,CAAC;AACD,WAAO,MAAM,IAAI,OAAO;AAAA,EAC1B;AACF;","names":["import_react","import_react","import_react","EMPTY","import_react","loadIfNeeded","call","call","call","call","call","subscription","isoNow","call","call","call","subscription","call","import_react_native","import_expo_modules_core"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/version.ts","../src/events.ts","../src/errors.ts","../src/hooks/useCurrentUser.ts","../src/core/native.ts","../src/store/reactiveStore.ts","../src/hooks/useEntitlement.ts","../src/hooks/useEntitlements.ts","../src/hooks/useVirtualCurrencies.ts","../src/hooks/useRemoteConfig.ts","../src/api/remoteConfig.ts","../src/core/eventBridge.ts","../src/api/sessionTracker.ts","../src/api/configure.ts","../src/api/identity.ts","../src/api/entitlements.ts","../src/api/virtualCurrencies.ts","../src/api/purchases.ts","../src/api/placements.ts","../src/api/funnel-photos.ts","../src/api/present-funnel.ts","../src/api/events.ts","../src/api/lifecycle.ts","../src/api/accountToken.ts","../src/api/attributes.ts","../src/api/log.ts","../src/api/funnel.ts","../src/funnel-view/RovenueFunnelView.tsx","../src/funnel-view/native-view.ts"],"sourcesContent":["// @rovenue/sdk-rn — public surface.\n//\n// Imperative API: Rovenue.configure(...), Rovenue.identify(...), ...\n// React hooks: useCurrentUser, useEntitlement, useEntitlements, useVirtualCurrencies\n// Errors: RovenueError (single class with .kind: ErrorKind), ERROR_KINDS, mapNativeError\n\nexport { SDK_VERSION } from \"./version\";\n\nexport {\n EVENT_WIRE_VERSION,\n serializeEnvelope,\n stripUndefined,\n} from \"./events\";\nexport type { EventEnvelope, IdentityContext } from \"./events\";\nexport type { TrackParams } from \"./api/events\";\n\nexport type {\n User,\n AttributionProvider,\n Entitlement,\n ProductType,\n StoreProduct,\n Package,\n Offering,\n Offerings,\n VirtualCurrencyGrant,\n PurchaseResult,\n ChangeEvent,\n RemoteConfig,\n ExperimentAssignment,\n} from \"./types\";\n\nexport {\n RovenueError,\n ERROR_KINDS,\n mapNativeError,\n} from \"./errors\";\nexport type { ErrorKind, ErrorExtras } from \"./errors\";\n\nexport { useCurrentUser } from \"./hooks/useCurrentUser\";\nexport { useEntitlement } from \"./hooks/useEntitlement\";\nexport { useEntitlements } from \"./hooks/useEntitlements\";\nexport { useVirtualCurrencies, useVirtualCurrency } from \"./hooks/useVirtualCurrencies\";\nexport {\n useRemoteConfig,\n useFlag,\n useExperiment,\n} from \"./hooks/useRemoteConfig\";\n\nimport { configure } from \"./api/configure\";\nimport { currentUser, identify, logOut, setAttribution } from \"./api/identity\";\nimport { entitlement, entitlementsAll, refreshEntitlements } from \"./api/entitlements\";\nimport { virtualCurrencies, virtualCurrency, refreshVirtualCurrencies } from \"./api/virtualCurrencies\";\nimport { getOfferings, purchase, restorePurchases } from \"./api/purchases\";\nimport { preloadPlacement, setFallbackPlacements } from \"./api/placements\";\nimport { presentFunnel } from \"./api/present-funnel\";\nimport { releasePhoto } from \"./api/funnel-photos\";\nexport { releasePhoto } from \"./api/funnel-photos\";\nexport type {\n FunnelPhotoRef,\n FunnelCheckRequest,\n FunnelCheckOutcome,\n FunnelCheckHandler,\n} from \"./api/funnel-photos\";\nexport { presentFunnel } from \"./api/present-funnel\";\nexport type {\n FunnelPresentationStyle,\n FunnelPresentationEnter,\n FunnelSheetDetent,\n FunnelPresentationOverride,\n PresentFunnelOptions,\n FunnelPresentResult,\n} from \"./api/present-funnel\";\nimport { track } from \"./api/events\";\nimport {\n refreshRemoteConfig,\n getRemoteConfig,\n getFlag,\n getExperiment,\n getExperiments,\n} from \"./api/remoteConfig\";\nimport { setForeground, shutdown } from \"./api/lifecycle\";\nimport { getAppAccountToken } from \"./api/accountToken\";\nimport {\n setAttributes,\n setEmail,\n setDisplayName,\n setPhoneNumber,\n setPushToken,\n flushAttributes,\n} from \"./api/attributes\";\nimport { SDK_VERSION } from \"./version\";\nimport { getEmitter } from \"./core/native\";\nimport { setLogHandler } from \"./api/log\";\nimport { claimFunnelToken, claimInstall, claimViaEmail, installId, addFunnelClaimListener, claimFromClipboard, claimFromUrl, extractFunnelToken, resolveFunnelClaim } from \"./api/funnel\";\n\nexport const Rovenue = {\n configure,\n /** This JS package's own semantic version — a plain constant read, not\n * the native module's or Rust core's version, and not network-derived. */\n getVersion: () => SDK_VERSION,\n currentUser,\n identify,\n logOut,\n setAttribution,\n entitlement,\n entitlementsAll,\n refreshEntitlements,\n virtualCurrencies,\n virtualCurrency,\n refreshVirtualCurrencies,\n getOfferings,\n purchase,\n restorePurchases,\n setFallbackPlacements,\n preloadPlacement,\n presentFunnel,\n releasePhoto,\n track,\n refreshRemoteConfig,\n getRemoteConfig,\n getFlag,\n getExperiment,\n getExperiments,\n getAppAccountToken,\n setForeground,\n shutdown,\n setLogHandler,\n setAttributes,\n setEmail,\n setDisplayName,\n setPhoneNumber,\n setPushToken,\n flushAttributes,\n claimFunnelToken,\n claimInstall,\n claimViaEmail,\n claimFromClipboard,\n claimFromUrl,\n resolveFunnelClaim,\n installId,\n addFunnelClaimListener,\n /**\n * Subscribe to the raw native change stream — `ENTITLEMENTS_CHANGED`,\n * `IDENTITY_CHANGED`, `VIRTUAL_CURRENCIES_CHANGED`, `REMOTE_CONFIG_CHANGED`.\n * Returns an unsubscribe function; call it on unmount to avoid leaking the\n * native listener. Most apps should prefer the reactive hooks\n * (`useCurrentUser`, `useEntitlements`, `useRemoteConfig`, ...), which\n * already listen on this stream — reach for this only for imperative,\n * non-component code. Never call the matching `refreshX()` (e.g.\n * `refreshEntitlements()` on `ENTITLEMENTS_CHANGED`) from inside this\n * callback: the refresh re-emits the same event, which re-invokes the\n * callback, forever.\n */\n addChangeListener: (cb: (event: import(\"./types\").ChangeEvent) => void): (() => void) => {\n const sub = getEmitter().addListener(\"onChange\", (payload: { event: string }) => {\n cb(payload.event as import(\"./types\").ChangeEvent);\n });\n return () => sub.remove();\n },\n} as const;\n\nexport type { RovenueConfig } from \"./api/configure\";\nexport type { LogEntry } from \"./api/log\";\nexport type { FunnelClaimResult, ClaimInstallParams } from \"./api/funnel\";\nexport { extractFunnelToken } from \"./api/funnel\";\n\n\n// A funnel renders through the platform's native view too, and resolves\n// itself from a placement — there is deliberately no JS `getFunnel`, so\n// nothing about a funnel's screens ever crosses the bridge.\nexport {\n RovenueFunnelView,\n type RovenueFunnelViewProps,\n type FunnelCustomAction,\n type FunnelLoadedEvent,\n type FunnelUnavailableEvent,\n type FunnelUnavailableReason,\n type FunnelDraftIssue,\n type FunnelScreenEvent,\n} from \"./funnel-view\";\n","/** This package's version, as published — the same string `package.json` carries. */\nexport const SDK_VERSION = \"0.28.4\";\n","// =============================================================\n// events — SDK event wire types + serialiser (M7.2)\n// =============================================================\n//\n// Mirrors the Rust EventEnvelope / IdentityContext structs\n// (packages/core-rs/src/events/) in TypeScript. The serialiser\n// strips `undefined` values at both the top level and inside\n// `identityContext` so the wire payload stays compact and matches\n// the camelCase JSON the server validates.\n\n/**\n * The event envelope's wire format version, sent as `version`. The server\n * accepts exactly this value (`version: z.literal(1)`, apps/api\n * routes/v1/events.ts); a new wire shape bumps it on both sides.\n */\nexport const EVENT_WIRE_VERSION = 1 as const;\n\nexport interface IdentityContext {\n email?: string;\n externalId?: string;\n phone?: string;\n ip?: string;\n userAgent?: string;\n firstName?: string;\n lastName?: string;\n city?: string;\n countryCode?: string;\n}\n\nexport interface EventEnvelope {\n /** Wire format version (EVENT_WIRE_VERSION). Stamped by the native core. */\n version?: number;\n /**\n * Stable, client-generated id reused across retries so downstream fan-out\n * can dedupe. Generated by the native core when omitted.\n */\n eventId?: string;\n eventType: string;\n /** ISO-8601 UTC, e.g. \"2026-05-28T10:00:00Z\" */\n occurredAt: string;\n subscriberId?: string;\n productId?: string;\n /** Decimal string, e.g. \"9.99\" */\n amount?: string;\n /** ISO-4217 three-letter code, e.g. \"USD\" */\n currency?: string;\n eventSourceUrl?: string;\n identityContext?: IdentityContext;\n}\n\n// =============================================================\n// helpers\n// =============================================================\n\n/**\n * Remove keys whose value is `undefined` from a shallow object.\n * Returns a new object — never mutates the input.\n */\nexport function stripUndefined<T extends Record<string, unknown>>(\n o: T,\n): Partial<T> {\n return Object.fromEntries(\n Object.entries(o).filter(([, v]) => v !== undefined),\n ) as Partial<T>;\n}\n\n/**\n * Serialise an EventEnvelope to a compact JSON string.\n *\n * - Strips `undefined` at the top level.\n * - Strips `undefined` inside `identityContext` (if present).\n * - Omits `identityContext` entirely when all its fields are\n * `undefined` or when it was not supplied.\n */\nexport function serializeEnvelope(env: EventEnvelope): string {\n const { identityContext, ...rest } = env;\n\n const top = stripUndefined(rest as Record<string, unknown>);\n\n if (identityContext !== undefined) {\n const cleanIc = stripUndefined(\n identityContext as Record<string, unknown>,\n );\n if (Object.keys(cleanIc).length > 0) {\n (top as Record<string, unknown>).identityContext = cleanIc;\n }\n }\n\n return JSON.stringify(top);\n}\n","// Single-class error surface for the Rovenue RN SDK.\n//\n// Every failure from native (iOS/Android) is surfaced as a RovenueError with\n// a `kind: ErrorKind` discriminant. The 29 canonical PascalCase kinds match\n// the Rust UDL definitions; the JS normalizer absorbs the three casings that\n// the native bridges emit:\n//\n// iOS bridge → String(describing: error.kind) = camelCase \"networkUnavailable\"\n// Android bridge → error.kind.name = UPPER_SNAKE \"NETWORK_UNAVAILABLE\"\n// Direct JS → PascalCase \"NetworkUnavailable\"\n//\n// All three land in mapNativeError() which strips underscores and does a\n// case-insensitive compare to resolve the canonical kind.\n\nexport const ERROR_KINDS = [\n \"NetworkUnavailable\",\n \"Timeout\",\n \"RateLimited\",\n \"ServerError\",\n \"InvalidApiKey\",\n \"Forbidden\",\n \"NotFound\",\n \"InvalidRequest\",\n \"Conflict\",\n \"InvalidArgument\",\n // A Sandbox (`rov_pk_test_…`) key configured in a release build.\n \"SandboxKeyInRelease\",\n \"InsufficientCredits\",\n \"FunnelTokenNotFound\",\n \"FunnelTokenExpired\",\n \"FunnelTokenAlreadyClaimed\",\n // A funnel published under a config format this SDK build is too old to\n // read, and a funnel whose document the resolver rejected. Both are\n // resolve-time failures the native funnel view surfaces through\n // `onError`; without them here mapNativeError() would flatten them to\n // \"Internal\" and a host could not tell \"upgrade the SDK\" from a bug.\n \"FunnelConfigUnsupported\",\n \"FunnelInvalid\",\n // The server cannot resolve this device's subscriber (corrupt merge\n // chain, backend SUBSCRIBER_UNRESOLVABLE). Terminal: not retryable.\n \"SubscriberUnresolvable\",\n // The server refused the identity token identify() sent (backend\n // IDENTITY_TOKEN_INVALID, 401): expired, or minted for another user,\n // project or environment. Not retryable: identify again with a fresh token.\n \"IdentityTokenInvalid\",\n \"PurchaseCanceled\",\n \"ProductNotAvailable\",\n \"AlreadyOwned\",\n \"PaymentDeclined\",\n \"StoreServiceUnavailable\",\n \"Ineligible\",\n \"ReceiptInvalid\",\n \"StoreProblem\",\n \"Storage\",\n \"Internal\",\n] as const;\n\nexport type ErrorKind = (typeof ERROR_KINDS)[number];\n\n// Pre-compute lowercase-no-underscore lookup table once at module load.\n// Maps stripped-lowercase → canonical PascalCase kind.\nconst KIND_LOOKUP = new Map<string, ErrorKind>(\n ERROR_KINDS.map((k) => [k.toLowerCase().replace(/_/g, \"\"), k]),\n);\n\nconst RETRYABLE = new Set<ErrorKind>([\n \"NetworkUnavailable\",\n \"Timeout\",\n \"RateLimited\",\n \"ServerError\",\n \"StoreServiceUnavailable\",\n]);\n\nexport interface ErrorExtras {\n serverCode?: string;\n httpStatus?: number;\n retryable?: boolean;\n available?: number;\n retryAfter?: number;\n}\n\nexport class RovenueError extends Error {\n readonly kind: ErrorKind;\n readonly serverCode?: string;\n readonly httpStatus?: number;\n readonly isRetryable: boolean;\n /** Carries per-kind payload: `available` for InsufficientCredits, `retryAfter` for RateLimited. */\n readonly data?: { available?: number; retryAfter?: number };\n\n constructor(kind: ErrorKind, message: string, extras: ErrorExtras = {}) {\n super(message);\n this.name = \"RovenueError\";\n // Preserve prototype chain when transpiled to ES5.\n Object.setPrototypeOf(this, RovenueError.prototype);\n this.kind = kind;\n this.serverCode = extras.serverCode;\n this.httpStatus = extras.httpStatus;\n this.isRetryable = extras.retryable ?? RETRYABLE.has(kind);\n if (extras.available !== undefined || extras.retryAfter !== undefined) {\n this.data = { available: extras.available, retryAfter: extras.retryAfter };\n }\n }\n}\n\n/**\n * Normalize a native-bridge error code to a canonical `ErrorKind`.\n *\n * Accepts all three casings that the native layers emit:\n * - PascalCase \"NetworkUnavailable\" (RN canonical / direct JS)\n * - camelCase \"networkUnavailable\" (iOS — `String(describing: error.kind)`)\n * - UPPER_SNAKE \"NETWORK_UNAVAILABLE\" (Android — `error.kind.name`)\n *\n * Strategy: strip underscores, lowercase, look up in the precomputed table.\n * Unknown codes fall back to \"Internal\" while still preserving serverCode/\n * message/extras so nothing is lost.\n */\nfunction normalizeKind(code: string): ErrorKind {\n const key = code.toLowerCase().replace(/_/g, \"\");\n return KIND_LOOKUP.get(key) ?? \"Internal\";\n}\n\n/**\n * Tag that marks a native error `message` as a JSON extras-envelope.\n *\n * The Expo JSI bridge forwards ONLY `code` + `message` to JS — neither the iOS\n * `userInfo` nor the Android `CodedException` cause/extras survive the crossing\n * (iOS `makeCodedError(code, message)`; Android `PromiseImpl.reject` →\n * `callback.invoke(code, message)`). So the native bridges fold the structured\n * extras INTO the message as `PREFIX + JSON({ message, serverCode, httpStatus,\n * retryable, available, retryAfter })`, and we unpack them back out here. Kept\n * in sync verbatim with RovenueModule.swift / RovenueModule.kt.\n */\nexport const NATIVE_ERROR_ENVELOPE_PREFIX = \"@rovenue/err1:\";\n\nexport function mapNativeError(\n code: string,\n message: string,\n extras: ErrorExtras = {},\n): RovenueError {\n let kindCode = code;\n let realMessage = message;\n let realExtras = extras;\n // The envelope is found wherever it sits, not only at the start: Expo on\n // Android wraps a rejection as \"Call to function 'Rovenue.X' has been\n // rejected.\\n→ Caused by: <message>\", so the marker arrives after that\n // wrapper. iOS delivers it at index 0. Everything after the marker is the\n // JSON; the wrapper text before it is discarded.\n const markerAt = typeof message === \"string\" ? message.indexOf(NATIVE_ERROR_ENVELOPE_PREFIX) : -1;\n if (markerAt >= 0) {\n try {\n const env = JSON.parse(message.slice(markerAt + NATIVE_ERROR_ENVELOPE_PREFIX.length));\n // The bridge `code` wins; the envelope's `kind` stands in when the\n // bridge delivered none (see fromNativeError).\n if (!kindCode && typeof env.kind === \"string\") kindCode = env.kind;\n realMessage = typeof env.message === \"string\" ? env.message : \"\";\n realExtras = {\n serverCode: env.serverCode,\n httpStatus: env.httpStatus,\n retryable: env.retryable,\n available: env.available,\n retryAfter: env.retryAfter,\n };\n } catch {\n // Malformed envelope — surface the raw message rather than throwing.\n }\n }\n return new RovenueError(normalizeKind(kindCode), realMessage, realExtras);\n}\n\n/** What a native bridge rejection carries into JS. */\ninterface NativeRejection {\n code?: unknown;\n message?: unknown;\n extras?: ErrorExtras;\n}\n\nconst NATIVE_ERROR_FALLBACK_MESSAGE = \"native error\";\n\n/**\n * Turn a native-module rejection into a `RovenueError`, or return it\n * unchanged when it did not come from a Rovenue native bridge.\n *\n * A rejection is ours when it carries a `code` OR the extras envelope. The\n * envelope test is load-bearing on iOS: under Expo 56 every Swift\n * `AsyncFunction` rejection is rebuilt as a plain JS `Error` from the\n * exception's description, with NO `code` property (ExpoModulesJSI\n * `JavaScriptPromise.reject`). The envelope survives inside the message, and\n * its `kind` restores the error kind.\n */\nexport function fromNativeError(e: unknown): unknown {\n const err = (e ?? {}) as NativeRejection;\n const code = typeof err.code === \"string\" ? err.code : \"\";\n const message = typeof err.message === \"string\" ? err.message : \"\";\n if (!code && !message.includes(NATIVE_ERROR_ENVELOPE_PREFIX)) return e;\n return mapNativeError(code, message || NATIVE_ERROR_FALLBACK_MESSAGE, err.extras);\n}\n","import { useEffect, useSyncExternalStore } from \"react\";\nimport { getNative } from \"../core/native\";\nimport { store } from \"../store/reactiveStore\";\nimport type { User } from \"../types\";\n\n/**\n * Reactive current-user identity. Returns `null` until the first native\n * `currentUser()` read completes (lazily primed on mount), then re-renders\n * on every `IDENTITY_CHANGED` native event (e.g. after `identify()` or\n * `logOut()`). Reads are synchronous off the local store after that first\n * fetch — no network call on every render.\n */\nexport function useCurrentUser(): User | null {\n useEffect(() => {\n if (store.get(\"user\") === undefined) {\n getNative().currentUser().then((u) => store.set(\"user\", u)).catch(() => {});\n }\n }, []);\n return useSyncExternalStore(\n store.subscribe.bind(store),\n () => (store.get<User>(\"user\") ?? null),\n () => null,\n );\n}\n","// Lazily acquires the native Expo module the first time we touch it.\n// Tests override `_setNativeForTesting` to inject a mock instead.\n//\n// `getEmitter()` resolves an event emitter for the native module in a way\n// that works across every Expo SDK we support (51 → 56):\n//\n// - Expo SDK 51 (expo-modules-core 1.x): the module is NOT an emitter.\n// Its `addListener(eventName)` is the 1-arg NativeEventEmitter\n// bookkeeping hook (the listener is ignored), so we must subscribe\n// through the legacy `new EventEmitter(nativeModule)` JS wrapper.\n// - Expo SDK 52+ (expo-modules-core 2.x / 3.x): the EventEmitter moved\n// to C++ and every native module now *extends* it. We subscribe on\n// the module directly via its real 2-arg `addListener(name, listener)`.\n//\n// NOTE (2026-09-07), two corrections to what this comment used to claim:\n//\n// 1. It said the legacy `new EventEmitter(module)` constructor \"no longer\n// exists\" on 52+. It does. In the resolved expo-modules-core@2.5.0 it is\n// `constructor(object: EventEmitter)`, marked `@deprecated As of Expo SDK\n// 52 the given object is already an EventEmitter` and `@hidden`. It is\n// deprecated, not removed — but note its parameter type: on 2.x it expects\n// something that ALREADY is an emitter, so it cannot do the wrapping job\n// the SDK-51 branch below needs it for. That branch therefore only\n// functions on expo-modules-core 1.x.\n//\n// 2. It said this file supports \"every Expo SDK we support (51 -> 56)\".\n// `package.json` declares `expo >=52.0.0` and `expo-modules-core >=2.0.0`.\n// Under that floor the SDK-51 branch is unreachable. Manifest and comment\n// disagree, and that contradiction is UNRESOLVED: deciding it means either\n// dropping the branch or lowering the floor, and neither is safe to assert\n// until the floor is verified by a real native build. `examples/sample-rn-expo`\n// is still pinned at expo ~51 / RN 0.74.5, below the floor, and is\n// CI-verified typecheck-only.\n//\n// `__tests__/native.test.ts` exercises the SDK-51 branch against a STUB\n// EventEmitter whose constructor accepts a plain object. The real 2.x\n// constructor does not. So that test does not evidence the branch works\n// on any supported version.\n//\n// The emitter is resolved lazily so test injection is observed.\n\nimport { EventEmitter, requireNativeModule } from \"expo-modules-core\";\nimport type { RovenueModuleSpec } from \"../specs/RovenueModule.types\";\n\n// The common shape both code paths expose: a subscription-returning\n// `addListener`. This is all the callers (eventBridge, log, index) need.\ntype ListenerEmitter = {\n addListener(\n eventName: string,\n listener: (payload: any) => void,\n ): { remove(): void };\n};\n\nlet instance: RovenueModuleSpec | null = null;\nlet emitter: ListenerEmitter | null = null;\n\nexport function getNative(): RovenueModuleSpec {\n if (instance) return instance;\n instance = requireNativeModule<RovenueModuleSpec>(\"Rovenue\");\n return instance;\n}\n\nexport function getEmitter(): ListenerEmitter {\n if (emitter) return emitter;\n const native = getNative() as unknown as ListenerEmitter & {\n addListener?: (...args: unknown[]) => unknown;\n };\n // On expo-modules-core ≥ 2 the module itself is an EventEmitter; the\n // arity check is a belt-and-suspenders guard for setups where the\n // `instanceof` identity is lost (e.g. duplicated core copies under a\n // monorepo) but the real 2-arg `addListener` is still present.\n const moduleIsEmitter =\n native instanceof EventEmitter ||\n (typeof native.addListener === \"function\" && native.addListener.length >= 2);\n emitter = moduleIsEmitter\n ? native\n : (new EventEmitter(native as any) as unknown as ListenerEmitter);\n return emitter;\n}\n\n// Test seam: replaces the cached instance + forces a fresh emitter.\n// Production code MUST NOT call this.\nexport function _setNativeForTesting(mock: RovenueModuleSpec | null): void {\n instance = mock;\n emitter = null;\n}\n","// ReactiveStore — in-memory cache mirror. Hook reads come out of this\n// synchronously via useSyncExternalStore; the event bridge mutates it\n// when the native core emits a ChangeEvent.\n//\n// Slot keys are flat strings. Per-entitlement slots use the pattern\n// `entitlement:<id>` so we can look up one without scanning a list.\n\nimport type { Entitlement, RemoteConfig, User } from \"../types\";\n\ntype StoreSlot =\n | \"user\"\n | \"virtualCurrencies\"\n | \"entitlementsAll\"\n | \"remoteConfig\"\n | `entitlement:${string}`;\n\ntype StoreValue =\n | User\n | number\n | Record<string, number>\n | Entitlement\n | Entitlement[]\n | RemoteConfig\n | null;\n\nexport class ReactiveStore {\n private values = new Map<StoreSlot, StoreValue>();\n private listeners = new Set<() => void>();\n\n get<T = StoreValue>(slot: StoreSlot): T | undefined {\n return this.values.get(slot) as T | undefined;\n }\n\n set<T extends StoreValue>(slot: StoreSlot, value: T): void {\n this.values.set(slot, value);\n this.listeners.forEach((l) => l());\n }\n\n /** Every slot currently holding a value (including `null`). */\n slots(): StoreSlot[] {\n return [...this.values.keys()];\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n clear(): void {\n this.values.clear();\n this.listeners.forEach((l) => l());\n }\n}\n\n// Module singleton used by every hook + the event bridge.\nexport const store = new ReactiveStore();\n","import { useEffect, useSyncExternalStore } from \"react\";\nimport { getNative } from \"../core/native\";\nimport { store } from \"../store/reactiveStore\";\nimport type { Entitlement } from \"../types\";\n\n/**\n * Reactive read of one entitlement by id. Returns `null` until the first\n * native `entitlement(id)` read completes (lazily primed on mount and on\n * `id` change), then re-renders on `ENTITLEMENTS_CHANGED`. Also `null`\n * when the entitlement is unknown or not granted — there is no separate\n * \"loading\" state; a caller that must distinguish \"not yet loaded\" from\n * \"not entitled\" should track that itself.\n */\nexport function useEntitlement(id: string): Entitlement | null {\n useEffect(() => {\n if (store.get(`entitlement:${id}`) === undefined) {\n getNative().entitlement(id).then((e) => store.set(`entitlement:${id}`, e)).catch(() => {});\n }\n }, [id]);\n return useSyncExternalStore(\n store.subscribe.bind(store),\n () => (store.get<Entitlement | null>(`entitlement:${id}`) ?? null),\n () => null,\n );\n}\n","import { useEffect, useSyncExternalStore } from \"react\";\nimport { getNative } from \"../core/native\";\nimport { store } from \"../store/reactiveStore\";\nimport type { Entitlement } from \"../types\";\n\n// Module-level constant so React's useSyncExternalStore does not see a\n// fresh array reference on every render when the store is empty.\nconst EMPTY: Entitlement[] = [];\n\n/**\n * Reactive read of every currently-granted entitlement. Returns an empty\n * array until the first native `entitlementsAll()` read completes (lazily\n * primed on mount), then re-renders on `ENTITLEMENTS_CHANGED`. Also\n * populates the per-id store entries `useEntitlement` reads, so mounting\n * this hook once can prime individual lookups elsewhere in the tree.\n */\nexport function useEntitlements(): Entitlement[] {\n useEffect(() => {\n if (store.get(\"entitlementsAll\") === undefined) {\n getNative().entitlementsAll().then((all) => {\n store.set(\"entitlementsAll\", all);\n for (const ent of all) store.set(`entitlement:${ent.id}`, ent);\n }).catch(() => {});\n }\n }, []);\n return useSyncExternalStore(\n store.subscribe.bind(store),\n () => (store.get<Entitlement[]>(\"entitlementsAll\") ?? EMPTY),\n () => EMPTY,\n );\n}\n","import { useEffect, useSyncExternalStore } from \"react\";\nimport { getNative } from \"../core/native\";\nimport { store } from \"../store/reactiveStore\";\n\nconst EMPTY: Record<string, number> = {};\n\nfunction loadIfNeeded(): void {\n if (store.get(\"virtualCurrencies\" as any) === undefined) {\n getNative()\n .virtualCurrencies()\n .then((m) => store.set(\"virtualCurrencies\" as any, m as any))\n .catch(() => {});\n }\n}\n\n/** Reactive map of all virtual-currency balances (code → amount). */\nexport function useVirtualCurrencies(): Record<string, number> {\n useEffect(loadIfNeeded, []);\n return useSyncExternalStore(\n store.subscribe.bind(store),\n () => store.get<Record<string, number>>(\"virtualCurrencies\" as any) ?? EMPTY,\n () => EMPTY,\n );\n}\n\n/** Reactive single-currency balance; 0 when absent. */\nexport function useVirtualCurrency(code: string): number {\n const all = useVirtualCurrencies();\n return all[code] ?? 0;\n}\n","import { useEffect, useSyncExternalStore } from \"react\";\nimport { getNative } from \"../core/native\";\nimport { store } from \"../store/reactiveStore\";\nimport { EMPTY_REMOTE_CONFIG, parseRemoteConfig } from \"../api/remoteConfig\";\nimport type { ExperimentAssignment, RemoteConfig } from \"../types\";\n\nfunction loadIfNeeded(): void {\n if (store.get(\"remoteConfig\") === undefined) {\n getNative()\n .remoteConfigAllJson()\n .then((json) => store.set(\"remoteConfig\", parseRemoteConfig(json)))\n .catch(() => {});\n }\n}\n\nfunction read(): RemoteConfig {\n return store.get<RemoteConfig>(\"remoteConfig\") ?? EMPTY_REMOTE_CONFIG;\n}\n\n/**\n * Reactive Remote Config. Returns the whole `{ flags, experiments }` bundle and\n * re-renders whenever the native core emits `REMOTE_CONFIG_CHANGED`. Reads are\n * synchronous off the local cache; the first mount lazily primes it.\n */\nexport function useRemoteConfig(): RemoteConfig {\n useEffect(loadIfNeeded, []);\n return useSyncExternalStore(\n store.subscribe.bind(store),\n read,\n () => EMPTY_REMOTE_CONFIG,\n );\n}\n\n/** Reactive single-flag read with a typed fallback. */\nexport function useFlag<T>(key: string, fallback: T): T {\n const config = useRemoteConfig();\n const value = config.flags[key];\n return (value === undefined ? fallback : value) as T;\n}\n\n/** Reactive single-experiment assignment for the current subscriber. */\nexport function useExperiment(key: string): ExperimentAssignment | null {\n const config = useRemoteConfig();\n return config.experiments[key] ?? null;\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\nimport type { ExperimentAssignment, RemoteConfig } from \"../types\";\n\nexport const EMPTY_REMOTE_CONFIG: RemoteConfig = Object.freeze({\n flags: {},\n experiments: {},\n});\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/**\n * Parse the native `remoteConfigAllJson()` payload into a `RemoteConfig`.\n * Tolerant by design: a malformed/empty payload yields the empty config so a\n * read never throws.\n */\nexport function parseRemoteConfig(json: string): RemoteConfig {\n try {\n const parsed = JSON.parse(json) as Partial<RemoteConfig>;\n return {\n flags: parsed.flags ?? {},\n experiments: parsed.experiments ?? {},\n };\n } catch {\n return EMPTY_REMOTE_CONFIG;\n }\n}\n\n/** Force an immediate fetch of the latest Remote Config from the server. */\nexport async function refreshRemoteConfig(): Promise<void> {\n return call(() => getNative().refreshRemoteConfig());\n}\n\n/** The whole `{ flags, experiments }` bundle, fetched from the local cache. */\nexport async function getRemoteConfig(): Promise<RemoteConfig> {\n return call(async () => parseRemoteConfig(await getNative().remoteConfigAllJson()));\n}\n\n/**\n * Read one flag with a typed fallback. The fallback's runtime type selects the\n * native getter (boolean/number/string); anything else falls back to a parsed\n * JSON read so object/array flags resolve too.\n */\nexport async function getFlag<T>(key: string, fallback: T): Promise<T> {\n return call(async () => {\n const native = getNative();\n if (typeof fallback === \"boolean\") {\n return (await native.remoteConfigBool(key, fallback)) as unknown as T;\n }\n if (typeof fallback === \"number\") {\n return (await native.remoteConfigDouble(key, fallback)) as unknown as T;\n }\n if (typeof fallback === \"string\") {\n return (await native.remoteConfigString(key, fallback)) as unknown as T;\n }\n const raw = await native.remoteConfigJson(key);\n if (raw === null) return fallback;\n try {\n return JSON.parse(raw) as T;\n } catch {\n return fallback;\n }\n });\n}\n\n/** The current subscriber's assignment for one experiment, or `null`. */\nexport async function getExperiment(\n key: string,\n): Promise<ExperimentAssignment | null> {\n return call(async () => {\n const dto = await getNative().experiment(key);\n if (!dto) return null;\n return mapExperiment(dto);\n });\n}\n\n/** All of the current subscriber's experiment assignments. */\nexport async function getExperiments(): Promise<ExperimentAssignment[]> {\n return call(async () => (await getNative().experimentsAll()).map(mapExperiment));\n}\n\nfunction mapExperiment(dto: {\n experimentId: string;\n key: string;\n variantId: string;\n variantName: string;\n valueJson: string;\n}): ExperimentAssignment {\n let value: unknown = null;\n try {\n value = JSON.parse(dto.valueJson);\n } catch {\n value = null;\n }\n return {\n experimentId: dto.experimentId,\n key: dto.key,\n variantId: dto.variantId,\n variantName: dto.variantName,\n value,\n };\n}\n","// eventBridge — converts native `onChange` events into ReactiveStore\n// mutations. Started by configure(); stopped by shutdown().\n//\n// In M6 we subscribe via Expo's EventEmitter (\"onChange\" event) instead\n// of M5's native.addChangeListener callback. The handler is otherwise\n// identical: re-fetch from native on each hint, store the result.\n\nimport { getEmitter, getNative } from \"./native\";\nimport { store } from \"../store/reactiveStore\";\nimport { parseRemoteConfig } from \"../api/remoteConfig\";\n\nlet subscription: { remove(): void } | null = null;\n\nconst ENTITLEMENT_SLOT_PREFIX = \"entitlement:\";\n\n// Mirror the native entitlement cache into the store: the list slot, one slot\n// per cached id, and `null` for every per-id slot the cache no longer holds\n// (a revoked entitlement, or the previous user's after an identity change).\n// `entitlementsAll()` is a native CACHE read — never a network refresh.\nasync function rereadEntitlements(native: ReturnType<typeof getNative>): Promise<void> {\n const all = await native.entitlementsAll();\n store.set(\"entitlementsAll\", all);\n const cachedIds = new Set<string>();\n for (const ent of all) {\n cachedIds.add(ent.id);\n store.set(`${ENTITLEMENT_SLOT_PREFIX}${ent.id}`, ent);\n }\n for (const slot of store.slots()) {\n if (!slot.startsWith(ENTITLEMENT_SLOT_PREFIX)) continue;\n const id = slot.slice(ENTITLEMENT_SLOT_PREFIX.length);\n if (!cachedIds.has(id) && store.get(slot) !== null) store.set(slot, null);\n }\n}\n\nexport function startEventBridge(): void {\n if (subscription) return;\n const native = getNative();\n subscription = getEmitter().addListener(\"onChange\", async (payload: { event: string }) => {\n try {\n switch (payload.event) {\n case \"IDENTITY_CHANGED\": {\n // logOut emits only this event; identify() emits it after its\n // post-bind entitlements refresh (which fires ENTITLEMENTS_CHANGED\n // first when it lands), and balances follow on their own event.\n // Either way the per-user slots below may still hold the outgoing\n // identity's values. Re-READ each from the native cache (already\n // re-scoped to the new identity) — never refresh(): a refresh\n // inside this listener re-emits a change event and loops.\n const u = await native.currentUser();\n store.set(\"user\", u);\n await rereadEntitlements(native);\n store.set(\"virtualCurrencies\", await native.virtualCurrencies());\n store.set(\"remoteConfig\", parseRemoteConfig(await native.remoteConfigAllJson()));\n break;\n }\n case \"ENTITLEMENTS_CHANGED\": {\n await rereadEntitlements(native);\n break;\n }\n case \"VIRTUAL_CURRENCIES_CHANGED\": {\n const balances = await native.virtualCurrencies();\n store.set(\"virtualCurrencies\", balances);\n break;\n }\n case \"REMOTE_CONFIG_CHANGED\": {\n const json = await native.remoteConfigAllJson();\n store.set(\"remoteConfig\", parseRemoteConfig(json));\n break;\n }\n default:\n break;\n }\n } catch {\n // Best-effort: a refresh failure here cannot crash the bridge.\n }\n });\n}\n\nexport function stopEventBridge(): void {\n subscription?.remove();\n subscription = null;\n}\n","import { AppState, type AppStateStatus, type NativeEventSubscription } from \"react-native\";\nimport { getNative } from \"../core/native\";\n\nconst DEBOUNCE_MS = 1000;\nconst FLUSH_INTERVAL_MS = 30_000;\n\ntype Tracker = {\n sub: NativeEventSubscription;\n flushTimer: ReturnType<typeof setInterval>;\n foregroundStartedAt: number | null;\n pendingState: AppStateStatus | null;\n debounceTimer: ReturnType<typeof setTimeout> | null;\n};\n\nlet tracker: Tracker | null = null;\n\nfunction now(): number {\n return Date.now();\n}\nfunction isoNow(): string {\n return new Date().toISOString();\n}\n\nfunction isForeground(s: AppStateStatus): boolean {\n return s === \"active\";\n}\n\nexport function startSessionTracker(): void {\n if (tracker) return;\n const onChange = (next: AppStateStatus) => {\n if (!tracker) return;\n tracker.pendingState = next;\n if (tracker.debounceTimer) clearTimeout(tracker.debounceTimer);\n tracker.debounceTimer = setTimeout(() => {\n if (!tracker) return;\n const finalState = tracker.pendingState!;\n const wasForeground = tracker.foregroundStartedAt !== null;\n const willBeForeground = isForeground(finalState);\n if (wasForeground !== willBeForeground) {\n if (willBeForeground) {\n getNative()\n .recordSessionEvent(\"open\", isoNow(), undefined)\n .catch(() => {});\n tracker.foregroundStartedAt = now();\n } else {\n const durationMs = tracker.foregroundStartedAt\n ? Math.max(0, now() - tracker.foregroundStartedAt)\n : undefined;\n getNative()\n .recordSessionEvent(\"background\", isoNow(), durationMs)\n .catch(() => {});\n tracker.foregroundStartedAt = null;\n }\n }\n tracker.debounceTimer = null;\n }, DEBOUNCE_MS);\n };\n const sub = AppState.addEventListener(\"change\", onChange);\n const initialState = AppState.currentState as AppStateStatus;\n const startedAt = isForeground(initialState) ? now() : null;\n // The foreground state itself is NOT reported from here: `configure` runs\n // on the Swift / Kotlin façade, which observes the app lifecycle and tells\n // the core (spec 2026-11-03-sdk-automatic-foreground-design.md, Decision\n // 2 — one owner, so two sources never fight). This tracker only records\n // session events.\n tracker = {\n sub,\n flushTimer: setInterval(() => {\n getNative()\n .flushSessionEvents()\n .catch(() => {});\n }, FLUSH_INTERVAL_MS),\n foregroundStartedAt: startedAt,\n pendingState: null,\n debounceTimer: null,\n };\n // initial 'open' event — emit unconditionally on first mount so the\n // backend can join the session against a (subscriberId, app-start) pair.\n getNative()\n .recordSessionEvent(\"open\", isoNow(), undefined)\n .catch(() => {});\n}\n\nexport function stopSessionTracker(): void {\n if (!tracker) return;\n // emit a 'close' if we were foregrounded\n if (tracker.foregroundStartedAt !== null) {\n const durationMs = Math.max(0, now() - tracker.foregroundStartedAt);\n getNative()\n .recordSessionEvent(\"close\", isoNow(), durationMs)\n .catch(() => {});\n // best-effort final flush\n getNative()\n .flushSessionEvents()\n .catch(() => {});\n }\n if (tracker.debounceTimer) clearTimeout(tracker.debounceTimer);\n clearInterval(tracker.flushTimer);\n tracker.sub.remove();\n tracker = null;\n}\n","import { startEventBridge } from \"../core/eventBridge\";\nimport { getNative } from \"../core/native\";\nimport { fromNativeError, RovenueError } from \"../errors\";\nimport { startSessionTracker } from \"./sessionTracker\";\n\nexport type RovenueConfig = {\n apiKey: string;\n /**\n * API host. Optional — defaults to the hosted endpoint\n * `https://api.rovenue.io`. Self-hosters pass their own origin\n * (e.g. `https://api.acme.com`). The Rust core enforces https://\n * (http:// is accepted only for localhost during local dev).\n */\n baseUrl?: string;\n logLevel?: \"off\" | \"error\" | \"warn\" | \"info\" | \"debug\" | \"trace\";\n /**\n * Optional override for the host app's user-facing version. When\n * omitted, the native modules auto-read the value:\n * - iOS: `Bundle.main.infoDictionary[\"CFBundleShortVersionString\"]`\n * - Android: `packageManager.getPackageInfo(packageName, 0).versionName`\n * For Expo apps the auto-read value is baked from `app.json`'s\n * `expo.version` at prebuild time, so most callers should leave this\n * undefined.\n */\n appVersion?: string;\n /**\n * Remote Config environment — selects which flag/experiment set the\n * backend serves: `\"prod\"` (default), `\"staging\"`, or `\"development\"`.\n * Sent as the `X-Rovenue-Env` header on the `/v1/config` request. Omit\n * to use production.\n */\n environment?: \"prod\" | \"staging\" | \"development\";\n /**\n * Hold the first placement request after install (up to 3 s) until\n * {@link setAttribution} has been called with your MMP's callback, so the\n * first onboarding can be targeted by the MMP's campaign data. Default\n * `false`: only Rovenue's own first-launch signals are waited for.\n */\n awaitMmpAttribution?: boolean;\n /**\n * Android only: the Facebook App ID used to read Meta's install referrer.\n * Defaults to the `com.facebook.sdk.ApplicationId` manifest meta-data\n * your app already carries when it uses Meta's SDK. Ignored on iOS.\n */\n facebookAppId?: string;\n};\n\n// The host app's version as `configure()` RESOLVED it — the caller's\n// `appVersion` when given, otherwise the bundle/packageManager value the\n// native module auto-read. Stashed here so the funnel render layer can\n// evaluate `visibility.minAppVersion`/`maxAppVersion` without a native\n// round-trip per node. `undefined` until `configure()` runs, and on a JS\n// bundle running against a native binary predating `getAppVersion` (an\n// RN dev can reload JS without rebuilding native) — version bounds then\n// fail open, matching every other unknown in the visibility evaluator.\nlet configuredAppVersion: string | undefined;\n\n/** The host app version `configure()` resolved, if any. */\nexport function getConfiguredAppVersion(): string | undefined {\n return configuredAppVersion;\n}\n\n/**\n * Whether this is a release build: React Native's `__DEV__` is false. A\n * bundle with no `__DEV__` at all is not a dev bundle, so it counts as\n * release (the guard fails closed).\n */\nfunction isReleaseBuild(): boolean {\n return (globalThis as { __DEV__?: boolean }).__DEV__ !== true;\n}\n\n/**\n * Initialize the SDK. Must be called before any other `Rovenue.*` call —\n * every other method assumes a configured native module and crashes\n * (`fatalError` on iOS, `IllegalStateException` on Android) otherwise.\n * Synchronous: also starts the native-event bridge that feeds the reactive\n * hooks/`addChangeListener`, and the foreground/background session\n * tracker (both are internally guarded to start at most once).\n *\n * Throws `RovenueError` (`kind: \"InvalidApiKey\"`) synchronously — before\n * any native call — when `apiKey` is blank or `baseUrl` doesn't start with\n * `http://`/`https://`.\n *\n * Throws `RovenueError` (`kind: \"SandboxKeyInRelease\"`) when a Sandbox\n * (`rov_pk_test_…`) key is configured in a release build (`__DEV__` false):\n * a test key must never ship to the stores. Use a Production\n * (`rov_pk_live_…`) key in release builds.\n */\nexport function configure(opts: RovenueConfig): void {\n if (!opts.apiKey || opts.apiKey.trim() === \"\") {\n throw new RovenueError(\"InvalidApiKey\", \"apiKey is blank\");\n }\n if (opts.baseUrl !== undefined && !/^https?:\\/\\//.test(opts.baseUrl)) {\n throw new RovenueError(\"InvalidApiKey\", \"baseUrl must start with http:// or https://\");\n }\n const native = getNative();\n try {\n native.configure(\n opts.apiKey,\n opts.baseUrl,\n opts.logLevel ?? \"warn\",\n opts.appVersion,\n opts.environment,\n isReleaseBuild(),\n opts.awaitMmpAttribution ?? false,\n opts.facebookAppId,\n );\n } catch (e) {\n throw fromNativeError(e);\n }\n // Read back rather than reusing `opts.appVersion`: most callers omit it\n // and let native auto-read, and this getter is what drives version-based\n // node visibility. Guarded for the stale-native-binary case above.\n configuredAppVersion =\n typeof native.getAppVersion === \"function\"\n ? (native.getAppVersion() ?? undefined)\n : opts.appVersion;\n startEventBridge();\n startSessionTracker();\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\nimport type { AttributionProvider, User } from \"../types\";\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try { return await fn(); }\n catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/**\n * Current identity — the anonymous `rovenueId` plus `appUserId` once\n * {@link identify} has been called. Resolves from local state; does not\n * hit the network. Prefer the `useCurrentUser` hook in components.\n */\nexport async function currentUser(): Promise<User> {\n return call(() => getNative().currentUser());\n}\n\n/**\n * Link the anonymous device identity to `appUserId`.\n *\n * `identityToken` vouches for `appUserId`: your backend mints it with the\n * secret key (`POST /v1/identity-tokens`) for the signed-in user and hands\n * it to the app. It is valid for 15 minutes; fetch a fresh one for each\n * identify.\n *\n * The local write always succeeds; the `POST /v1/identify` to the server is\n * best-effort — if it fails (offline/5xx) the link is retried automatically\n * later with the same token, not surfaced as an error here. `IDENTITY_CHANGED` fires after the bind and\n * an entitlements refresh attempt: after a delivered bind the native core\n * fetches entitlements once (firing `ENTITLEMENTS_CHANGED` when it lands)\n * and this promise resolves after that fetch. When the bind is not\n * delivered (offline, server error, refused) it fires right after the\n * local link. Rejects on\n * validation failure (a blank id or token), with `IdentityTokenInvalid` when\n * the server refuses the token (expired, or minted for another user, project\n * or environment: the bind is dropped, so identify again with a fresh\n * token), and with `SubscriberUnresolvable` when the server cannot resolve\n * this install's subscriber (corrupt merge history) — the local link stands,\n * unsynced, until the data is repaired.\n */\nexport async function identify(appUserId: string, identityToken: string): Promise<void> {\n return call(() => getNative().identify(appUserId, identityToken));\n}\n\n/**\n * Log out the current user: mints a fresh anonymous `rovenueId` and drops\n * `appUserId`, so the next identity starts clean — including a new Apple\n * `appAccountToken`, which is derived from the `rovenueId`. Client-local\n * only — does not contact the server.\n */\nexport async function logOut(): Promise<void> {\n return call(() => getNative().logOut());\n}\n\n/**\n * Forward the attribution your MMP produced. Call it from the MMP's\n * conversion / attribution callback, passing the callback object as-is.\n * The record is write-once on the server: a call after the install is\n * already attributed changes nothing. On both platforms it rejects only\n * with `InvalidArgument` (unknown provider, or `data` not serialisable);\n * network and server failures are logged, not thrown.\n */\nexport async function setAttribution(\n provider: AttributionProvider,\n data: Record<string, unknown>,\n): Promise<void> {\n return call(() => getNative().setAttribution(provider, data));\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\nimport type { Entitlement } from \"../types\";\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try { return await fn(); }\n catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/**\n * Look up one entitlement by id from the native SDK's local cache — resolves\n * from disk/memory, not a network round trip. `null` when the id is unknown\n * or not currently granted. A stale (>60s) cache triggers a background\n * refresh on the native side; never call `refreshEntitlements()` from an\n * `ENTITLEMENTS_CHANGED` listener that refresh fires, or it loops.\n */\nexport async function entitlement(id: string): Promise<Entitlement | null> {\n return call(() => getNative().entitlement(id));\n}\n\n/**\n * All currently-granted entitlements from the native SDK's local cache — a\n * cache read, not a network call. Same background staleness-refresh\n * behaviour and `ENTITLEMENTS_CHANGED` re-entrancy footgun as\n * {@link entitlement}. Prefer the `useEntitlements` hook in components.\n */\nexport async function entitlementsAll(): Promise<Entitlement[]> {\n return call(() => getNative().entitlementsAll());\n}\n\n/**\n * Force a network refresh of entitlements, bypassing the 60s staleness\n * window that {@link entitlement}/{@link entitlementsAll} use. Never call\n * this from inside an `ENTITLEMENTS_CHANGED` listener — the refresh\n * re-emits that same event, which re-invokes the listener, forever.\n */\nexport async function refreshEntitlements(): Promise<void> {\n return call(() => getNative().refreshEntitlements());\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try { return await fn(); }\n catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/** All virtual-currency balances (code → amount). */\nexport async function virtualCurrencies(): Promise<Record<string, number>> {\n return call(() => getNative().virtualCurrencies());\n}\n\n/** One currency's balance; 0 when the code is absent. */\nexport async function virtualCurrency(code: string): Promise<number> {\n return call(() => getNative().virtualCurrency(code));\n}\n\n/** Force a refresh of virtual-currency balances from the server. */\nexport async function refreshVirtualCurrencies(): Promise<void> {\n return call(() => getNative().refreshVirtualCurrencies());\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\nimport type { Offerings, Offering, Package, PurchaseResult, StoreProduct, PackageType, SubscriptionOption } from \"../types\";\nimport type { OfferingDTO } from \"../specs/RovenueModule.types\";\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try { return await fn(); } catch (e) {\n throw fromNativeError(e);\n }\n}\n\nfunction packageTypeFromSlot(slot: string): PackageType {\n switch (slot) {\n case '$rov_weekly': return 'weekly';\n case '$rov_monthly': return 'monthly';\n case '$rov_two_month': return 'twoMonth';\n case '$rov_three_month': return 'threeMonth';\n case '$rov_six_month': return 'sixMonth';\n case '$rov_annual': return 'annual';\n case '$rov_lifetime': return 'lifetime';\n default: return 'custom';\n }\n}\n\n/** What a package or offering carries when the native side sends no metadata. */\nconst EMPTY_METADATA: Record<string, unknown> = {};\n\n/** Parses a native metadata JSON string; anything but an object reads as `{}`. */\nfunction parseMetadata(json: string | undefined): Record<string, unknown> {\n if (!json) return { ...EMPTY_METADATA };\n try {\n const v: unknown = JSON.parse(json);\n return v !== null && typeof v === \"object\" && !Array.isArray(v) ? (v as Record<string, unknown>) : { ...EMPTY_METADATA };\n } catch {\n return { ...EMPTY_METADATA };\n }\n}\n\n/** Maps a single native `OfferingDTO` to the public `Offering` domain type. */\nexport function mapOfferingDTO(o: OfferingDTO): Offering {\n return {\n identifier: o.identifier,\n isDefault: o.isDefault,\n metadata: parseMetadata(o.metadataJson),\n packages: o.packages.map((p) => ({\n identifier: p.identifier,\n packageType: packageTypeFromSlot(p.identifier),\n product: p.product as StoreProduct,\n // Optional on the DTO: an older native module sends none of the three.\n isPromoted: p.isPromoted ?? false,\n metadata: parseMetadata(p.metadataJson),\n virtualCurrencyGrants: (p.virtualCurrencyGrants ?? []).map((g) => ({\n code: g.code,\n amount: g.amount,\n grantOn: g.grantOn,\n intervalDays: g.intervalDays ?? null,\n // Optional on the DTO: an older native module sends neither.\n trialAmount: g.trialAmount ?? 0,\n expiresAtPeriodEnd: g.expiresAtPeriodEnd ?? false,\n })),\n })),\n };\n}\n\n/**\n * Fetch the project's current offerings from the backend and map them into\n * the public `Offerings` shape (`current` + `all`, keyed by identifier).\n * Always a network call from the JS side; the underlying native/Rust layer\n * falls back to its own last-cached response on a connectivity failure, but\n * an auth/server rejection still rejects this promise.\n */\nexport async function getOfferings(): Promise<Offerings> {\n const dto = await call(() => getNative().getOfferings());\n const all: Record<string, Offering> = {};\n let current: Offering | null = null;\n for (const o of dto.offerings) {\n const offering = mapOfferingDTO(o);\n all[o.identifier] = offering;\n if (o.identifier === dto.current) current = offering;\n }\n return { current, all };\n}\n\n/**\n * Buy a `Package` (from `getOfferings()`) or a raw\n * `StoreProduct` directly, driving the platform store UI (StoreKit /\n * Google Play Billing). Resolves with the resulting entitlements + VC\n * balances hydrated straight from the receipt-post response — no\n * follow-up `getOfferings`/`entitlementsAll` call needed. `isDeferred:\n * true` means the purchase is pending external approval (e.g. Ask to Buy)\n * and no entitlement has been granted yet.\n *\n * Rejects with `RovenueError` for store-level outcomes — `kind` may be\n * `PurchaseCanceled`, `AlreadyOwned`, `ProductNotAvailable`,\n * `PaymentDeclined`, `StoreServiceUnavailable`, or `ReceiptInvalid` —\n * as well as network/server failures.\n */\nexport async function purchase(\n target: Package | StoreProduct,\n options?: { promotionalOfferId?: string; subscriptionOption?: SubscriptionOption },\n): Promise<PurchaseResult> {\n const product = \"product\" in target ? target.product : target;\n const opt = options?.subscriptionOption;\n return call(() =>\n getNative().purchase(\n product.id, product.type, options?.promotionalOfferId,\n opt?.basePlanId ?? undefined, opt?.offerId ?? undefined,\n ),\n );\n}\n\n/**\n * Restore the user's previously-purchased entitlements from the store\n * (StoreKit's transaction history / Google Play's owned-purchases query),\n * re-submitting any found receipts so the server can (re-)grant\n * entitlements for this subscriber. Use for the \"Restore Purchases\" button\n * required by App Store review — not a substitute for automatic\n * entitlement sync, which already happens via `configure()`/receipt\n * posting.\n */\nexport async function restorePurchases(): Promise<PurchaseResult> {\n return call(() => getNative().restorePurchases());\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/**\n * Parse a spec D1 bundled fallback-placements file (once, replacing any\n * previously-loaded set) so `getFunnel` can serve placements offline when\n * both the network and disk cache miss. Resolves to the count of placement\n * entries actually loaded — an individual entry that fails to decode is\n * skipped natively, not fatal. Rejects with a distinct `invalidArgument`\n * error when the file doesn't parse or its `formatVersion` isn't literal\n * `1` — an integrator who bundles a stale/mismatched export must see this\n * loudly, at call time.\n */\n/**\n * Fetch a placement and warm everything its first screen draws — the\n * placement response, the first screen's images and video posters, the\n * store prices of its packages and its fonts — so even the first open of\n * `<RovenueFunnelView placementId=…>` draws complete and at once. Call it at\n * app start for the placement that shows your paywall.\n *\n * Never rejects: an unavailable placement or a network failure is logged\n * natively and the open loads as it would have without it. Nothing is\n * presented, so no funnel event is sent.\n *\n * @param placementId the placement identifier.\n * @param locale the locale the funnel will open in; the device's when omitted.\n */\nexport async function preloadPlacement(placementId: string, locale?: string): Promise<void> {\n try {\n await getNative().preloadPlacement(placementId, locale ?? null);\n } catch {\n // Native already logged it; a preload never fails the caller.\n }\n}\n\nexport async function setFallbackPlacements(json: string): Promise<number> {\n return call(() => getNative().setFallbackPlacements(json));\n}\n","import { getNative } from \"../core/native\";\nimport type { FunnelCheckRequestDTO, FunnelPhotoRefDTO } from \"../specs/RovenueModule.types\";\n\n/**\n * The photo a `photo_upload` question was answered with — normalised and\n * stored on the device (an upright JPEG with no metadata). Rovenue never\n * receives it. Call {@link releasePhoto} once you are done with the file;\n * an unreleased one is deleted 7 days after it was picked.\n */\nexport interface FunnelPhotoRef {\n /** The file, a `file://` URI. Valid until {@link releasePhoto} or for 7 days. */\n localUri: string;\n /** Pixel width, after normalisation. */\n width: number;\n /** Pixel height, after normalisation. */\n height: number;\n /** The file's size in bytes. */\n byteSize: number;\n /** Always `image/jpeg`. */\n mimeType: string;\n}\n\n/** What the SDK asks your photo checker (`onCheck`). */\nexport interface FunnelCheckRequest {\n /** The check block's answer key. */\n checkKey: string;\n /** The checker's step ids, in order. */\n steps: string[];\n /** The photo to judge, on the device. */\n photo: FunnelPhotoRef;\n /** The funnel's content locale (BCP-47), for any copy the checker returns. */\n locale: string;\n /** 1-based: completed checks for this block so far, plus one. */\n attempt: number;\n}\n\n/** Your checker's final answer for a photo check. */\nexport interface FunnelCheckOutcome {\n /** `pass` or `fail`. */\n result: \"pass\" | \"fail\";\n /** Plain text the funnel can show (`{{<checkKey>}}`). */\n label?: string;\n /** Why it failed, in plain text (`{{<checkKey>.reason}}`). */\n reason?: string;\n /** Each step id's final status (`pass` | `fail`). */\n steps?: Record<string, string>;\n}\n\n/**\n * Your photo checker. Resolve the outcome; resolving `null` / `undefined`,\n * or rejecting, applies the check's `whenUnavailable`. The native SDK bounds\n * it by the check's `timeoutMs` (then the result is `timeout` and a late\n * answer is ignored).\n *\n * On Android a presented funnel (`presentFunnel`) is its own activity, and\n * React Native pauses JS timers while the app's activity is covered: a\n * `setTimeout` inside the handler fires only after the funnel closes. Network\n * calls (`fetch`) and promises run as usual — call your checker service\n * directly rather than through a timer.\n */\nexport type FunnelCheckHandler = (\n request: FunnelCheckRequest,\n) => Promise<FunnelCheckOutcome | null | undefined> | FunnelCheckOutcome | null | undefined;\n\n/**\n * Deletes a photo a funnel stored on the device, once you are done with it:\n * the `localUri` of a {@link FunnelPhotoRef} from `onPhotoSelected` or a\n * presentation's `photos`. Anything outside the SDK's photo store is\n * ignored. Resolves whether a stored photo was deleted.\n */\nexport async function releasePhoto(localUri: string): Promise<boolean> {\n return getNative().releasePhoto(localUri);\n}\n\n/** Native numbers arrive as JS numbers; anything else is not a photo. */\nexport function photoFrom(dto: FunnelPhotoRefDTO): FunnelPhotoRef {\n return {\n localUri: dto.localUri,\n width: Number(dto.width),\n height: Number(dto.height),\n byteSize: Number(dto.byteSize),\n mimeType: dto.mimeType,\n };\n}\n\n/** The photos map of a present result; absent or null becomes `{}`. */\nexport function photosFrom(dto: Record<string, FunnelPhotoRefDTO> | null | undefined): Record<string, FunnelPhotoRef> {\n const out: Record<string, FunnelPhotoRef> = {};\n for (const [key, photo] of Object.entries(dto ?? {})) out[key] = photoFrom(photo);\n return out;\n}\n\n/**\n * The outcome as the native side decodes it, or null for \"unavailable\".\n * Anything that is not an object with a string `result` is null: a host\n * bug must not turn into a check the machine refuses.\n */\nfunction outcomeJson(outcome: unknown): string | null {\n if (typeof outcome !== \"object\" || outcome === null) return null;\n const o = outcome as Record<string, unknown>;\n if (typeof o.result !== \"string\") return null;\n const steps: Record<string, string> = {};\n if (typeof o.steps === \"object\" && o.steps !== null) {\n for (const [id, status] of Object.entries(o.steps as Record<string, unknown>)) {\n if (typeof status === \"string\") steps[id] = status;\n }\n }\n return JSON.stringify({\n result: o.result,\n ...(typeof o.label === \"string\" ? { label: o.label } : {}),\n ...(typeof o.reason === \"string\" ? { reason: o.reason } : {}),\n steps,\n });\n}\n\n/**\n * Runs the host's checker for one native check request and answers it.\n * Always answers — a missing handler, a throw or a rejection answers null —\n * so the native side never waits on JS for longer than its own timeout.\n */\nexport function answerCheckRequest(\n requestId: string,\n request: FunnelCheckRequestDTO,\n handler: FunnelCheckHandler | undefined,\n): void {\n const native = getNative();\n const run = async () => (handler ? handler({ ...request, photo: photoFrom(request.photo), attempt: Number(request.attempt) }) : null);\n run()\n .then((outcome) => native.resolveFunnelCheckRequest(requestId, outcomeJson(outcome)))\n .catch(() => native.resolveFunnelCheckRequest(requestId, null));\n}\n","import { getEmitter, getNative } from \"../core/native\";\nimport { RovenueError, fromNativeError, type ErrorKind } from \"../errors\";\nimport type { PurchaseResult } from \"../types\";\nimport type { FunnelCheckRequestDTO, FunnelPhotoRefDTO } from \"../specs/RovenueModule.types\";\nimport {\n answerCheckRequest,\n photoFrom,\n photosFrom,\n type FunnelCheckHandler,\n type FunnelPhotoRef,\n} from \"./funnel-photos\";\n\n/** How a presented funnel covers the app. */\nexport type FunnelPresentationStyle = \"fullScreen\" | \"modal\" | \"sheet\";\n/** How a full-screen funnel enters; Reduce Motion / animations off make each a fade. */\nexport type FunnelPresentationEnter = \"bottom\" | \"side\" | \"fade\" | \"none\";\n/** A sheet height: the first page's content (`fit`, capped at `large`), half the screen, or nearly all of it. */\nexport type FunnelSheetDetent = \"fit\" | \"medium\" | \"large\";\n\n/**\n * A present call's partial override of how the funnel's editor settings\n * present it. A field left out keeps the funnel's own; a style changed here\n * with no `dismissible` takes that style's default.\n */\nexport interface FunnelPresentationOverride {\n style?: FunnelPresentationStyle;\n enter?: FunnelPresentationEnter;\n detents?: FunnelSheetDetent[];\n dismissible?: boolean;\n closeOnPurchase?: boolean;\n}\n\n/** What `presentFunnel` takes. Every callback is optional. */\nexport interface PresentFunnelOptions {\n /** The placement identifier. */\n placement: string;\n /** The locale to resolve text in; the device's when omitted. */\n locale?: string;\n /** Overrides the funnel's own presentation, field by field. */\n style?: FunnelPresentationOverride;\n /**\n * Perform the purchase of this package yourself; resolve whether it went\n * through. Without it the SDK purchases. While it runs the funnel cannot\n * be swiped or backed away.\n */\n onPurchase?: (packageId: string) => Promise<{ purchased: boolean }>;\n /** Perform a restore yourself; resolve whether it restored anything. */\n onRestore?: () => Promise<{ purchased: boolean }>;\n /**\n * Observe a failed purchase or restore the SDK performed. The funnel stays\n * open; a cancelled store sheet is not reported, nor is a failure of your\n * own `onPurchase` / `onRestore`.\n */\n onPurchaseError?: (error: RovenueError) => void;\n /** A URL the funnel opens; without it, an http(s) URL opens in the browser. */\n onUrl?: (url: string) => void;\n /** A custom action the funnel runs: its id and its params as JSON. */\n onCustomAction?: (action: { actionId: string; paramsJson: string }) => void;\n /**\n * Values for the funnel's declared externals (an ad's scene, a campaign):\n * trimmed, 512 characters at most, undeclared names dropped. A fresh value\n * overrides a restored one and preselects a `defaultFrom` question. Never\n * pass personal data: values are written to the on-device session state.\n */\n values?: Record<string, string>;\n /** A `photo_upload` question was answered: its key and the photo on the device. */\n onPhotoSelected?: (questionKey: string, photo: FunnelPhotoRef) => void;\n /** Your photo checker; without it a check applies its `whenUnavailable`. */\n onCheck?: FunnelCheckHandler;\n}\n\n/** What `presentFunnel` resolves with. */\nexport interface FunnelPresentResult {\n /** How it ended: finished (or closed after a purchase), closed by the visitor, or never presented. */\n result: \"completed\" | \"dismissed\" | \"unavailable\";\n /** Whether a purchase or restore succeeded while it was presented. */\n purchased: boolean;\n /** The entitlements and balances after the purchase; set whenever `purchased` is true. */\n customerInfo?: PurchaseResult;\n /** The last purchase or restore failure the SDK saw. */\n lastError?: RovenueError;\n /** Why nothing was presented: `alreadyPresented`, `noPresenter`, or the placement's unavailable reason. */\n reason?: string;\n /**\n * The photos the visitor answered `photo_upload` questions with, by\n * question key — files on the device, kept until `releasePhoto` or 7\n * days. Empty when there were none.\n */\n photos: Record<string, FunnelPhotoRef>;\n /**\n * The visitor's answers by question key: every key the funnel wrote —\n * answers, `set_variable` results and app values — exactly as a web\n * funnel's claim carries them (`FunnelClaimResult.funnelAnswers`). Empty\n * when nothing was presented or nothing was answered.\n */\n answers: Record<string, unknown>;\n /**\n * The question keys an app value preselected and the visitor left\n * unchanged, so a default can be told from a choice (the claim's\n * `funnelPreselected`). Empty when none.\n */\n preselected: string[];\n}\n\n/** A native error as the present bridge carries it (`lastError`, `purchaseError`). */\ntype NativeErrorDTO = { kind: string; message: string; serverCode?: string | null; httpStatus?: number | null; retryable?: boolean };\n\ntype PresentEvent =\n | { presentationId: string; type: \"purchaseRequest\"; requestId: string; packageId: string }\n | { presentationId: string; type: \"restoreRequest\"; requestId: string }\n | { presentationId: string; type: \"purchaseError\"; error: NativeErrorDTO }\n | { presentationId: string; type: \"url\"; url: string }\n | { presentationId: string; type: \"customAction\"; actionId: string; paramsJson: string }\n | { presentationId: string; type: \"photoSelected\"; questionKey: string; photo: FunnelPhotoRefDTO }\n | { presentationId: string; type: \"checkRequest\"; requestId: string; request: FunnelCheckRequestDTO };\n\ntype PresentResultDTO = {\n result: FunnelPresentResult[\"result\"];\n purchased: boolean;\n customerInfo?: PurchaseResult | null;\n lastError?: NativeErrorDTO | null;\n reason?: string | null;\n photos?: Record<string, FunnelPhotoRefDTO> | null;\n answersJson?: string | null;\n preselected?: unknown;\n};\n\n/**\n * The answers half of a present result: the native side's JSON object string\n * parsed, and its preselected keys. Anything unreadable (an older native\n * module, a malformed string) is no answers rather than a throw.\n */\nfunction answersFrom(dto: Pick<PresentResultDTO, \"answersJson\" | \"preselected\">): {\n answers: Record<string, unknown>;\n preselected: string[];\n} {\n let answers: Record<string, unknown> = {};\n try {\n const parsed: unknown = JSON.parse(dto.answersJson ?? \"{}\");\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n answers = parsed as Record<string, unknown>;\n }\n } catch {\n // keep {}\n }\n const preselected = Array.isArray(dto.preselected)\n ? dto.preselected.filter((k): k is string => typeof k === \"string\")\n : [];\n return { answers, preselected };\n}\n\n/** The native event every present callback rides on. */\nexport const FUNNEL_PRESENT_EVENT = \"onFunnelPresentEvent\";\n\nlet presentationSerial = 0;\n\nfunction toError(dto: NativeErrorDTO): RovenueError {\n const mapped = fromNativeError(Object.assign(new Error(dto.message), { code: dto.kind }));\n if (mapped instanceof RovenueError) {\n return new RovenueError(mapped.kind as ErrorKind, dto.message, {\n serverCode: dto.serverCode ?? undefined,\n httpStatus: dto.httpStatus ?? undefined,\n retryable: dto.retryable,\n });\n }\n return new RovenueError(\"Internal\", dto.message);\n}\n\n/**\n * Present the funnel a placement serves — natively, the way the funnel's\n * editor settings say (full screen, modal or sheet) — and resolve when it\n * ends. The placement is resolved first (instantly after\n * `preloadPlacement`); nothing is presented when it serves no funnel.\n *\n * The SDK performs purchases and restores itself unless you pass\n * `onPurchase` / `onRestore`, and closes after a successful one when the\n * funnel is set to \"Close after purchase\". Only one funnel is presented at\n * a time: a second call while one is up resolves `unavailable` with reason\n * `alreadyPresented`.\n *\n * A funnel with a photo check calls `onCheck` and waits for its answer, up\n * to the check's timeout; the photos the visitor gave come back in\n * `photos` — call `releasePhoto` with each once you are done with it.\n *\n * @example\n * const { result, purchased } = await presentFunnel({ placement: \"paywall\" });\n */\nexport async function presentFunnel(options: PresentFunnelOptions): Promise<FunnelPresentResult> {\n const native = getNative();\n presentationSerial += 1;\n const presentationId = `p${Date.now().toString(36)}${presentationSerial}`;\n const subscription = getEmitter().addListener(FUNNEL_PRESENT_EVENT, (event: PresentEvent) => {\n if (event.presentationId !== presentationId) return;\n switch (event.type) {\n case \"purchaseRequest\":\n case \"restoreRequest\": {\n const run = event.type === \"purchaseRequest\" ? options.onPurchase?.(event.packageId) : options.onRestore?.();\n Promise.resolve(run)\n .then((answer) => native.resolveFunnelPurchaseRequest(event.requestId, Boolean(answer?.purchased)))\n .catch(() => native.resolveFunnelPurchaseRequest(event.requestId, false));\n break;\n }\n case \"purchaseError\":\n options.onPurchaseError?.(toError(event.error));\n break;\n case \"url\":\n options.onUrl?.(event.url);\n break;\n case \"customAction\":\n options.onCustomAction?.({ actionId: event.actionId, paramsJson: event.paramsJson });\n break;\n case \"photoSelected\":\n options.onPhotoSelected?.(event.questionKey, photoFrom(event.photo));\n break;\n case \"checkRequest\":\n answerCheckRequest(event.requestId, event.request, options.onCheck);\n break;\n }\n });\n try {\n const dto: PresentResultDTO = await native.presentFunnel(\n presentationId,\n options.placement,\n options.locale ?? null,\n options.style ? JSON.stringify(options.style) : null,\n {\n onPurchase: Boolean(options.onPurchase),\n onRestore: Boolean(options.onRestore),\n onUrl: Boolean(options.onUrl),\n onCustomAction: Boolean(options.onCustomAction),\n onPhotoSelected: Boolean(options.onPhotoSelected),\n onCheck: Boolean(options.onCheck),\n },\n options.values ?? {},\n );\n return {\n result: dto.result,\n purchased: dto.purchased,\n ...(dto.customerInfo ? { customerInfo: dto.customerInfo } : {}),\n ...(dto.lastError ? { lastError: toError(dto.lastError) } : {}),\n ...(dto.reason ? { reason: dto.reason } : {}),\n photos: photosFrom(dto.photos),\n ...answersFrom(dto),\n };\n } catch (e) {\n throw fromNativeError(e);\n } finally {\n subscription.remove();\n }\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\nimport {\n type EventEnvelope,\n type IdentityContext,\n serializeEnvelope,\n} from \"../events\";\n\n/** Optional fields for {@link track}. `eventType` is the first positional arg. */\nexport interface TrackParams {\n /** ISO-8601 override; defaults to the call-time timestamp. */\n occurredAt?: string;\n /** Defaults to the current scope (app user id, else anonymous id). */\n subscriberId?: string;\n productId?: string;\n /** Decimal string, e.g. \"9.99\". */\n amount?: string;\n /** ISO-4217 three-letter code, e.g. \"USD\". */\n currency?: string;\n eventSourceUrl?: string;\n identityContext?: IdentityContext;\n}\n\nfunction isoNow(): string {\n return new Date().toISOString();\n}\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/**\n * Emit a generic event to the backend (`POST /v1/events`). The SDK's HTTP\n * layer retries transient failures; the returned promise rejects if the POST\n * ultimately fails. `occurredAt` defaults to now; `subscriberId` is filled\n * from the current scope when omitted, and the native core stamps the wire\n * version and a stable `eventId`.\n */\nexport async function track(eventType: string, params: TrackParams = {}): Promise<void> {\n const envelope: EventEnvelope = {\n eventType,\n occurredAt: params.occurredAt ?? isoNow(),\n subscriberId: params.subscriberId,\n productId: params.productId,\n amount: params.amount,\n currency: params.currency,\n eventSourceUrl: params.eventSourceUrl,\n identityContext: params.identityContext,\n };\n return call(() => getNative().track(serializeEnvelope(envelope)));\n}\n","import { stopEventBridge } from \"../core/eventBridge\";\nimport { getNative } from \"../core/native\";\nimport { stopSessionTracker } from \"./sessionTracker\";\n\n/**\n * Override the SDK's foreground state. Not needed: the native SDK observes\n * the app lifecycle itself — polling and the attribute/session flush run\n * while the app is in front and pause in the background. A manual call is\n * honoured until the next lifecycle transition.\n */\nexport function setForeground(foreground: boolean): void {\n getNative().setForeground(foreground);\n}\n\n/**\n * Tear down the SDK: stops the session tracker (recording a final\n * `close` event and flushing it) and the native-event bridge before\n * stopping the native module's own background polling. The native layer\n * already calls its own equivalent of this when `configure()` is invoked\n * a second time, so most apps never need to call it directly — reach for\n * it only when the host app is shutting the SDK down without immediately\n * reconfiguring.\n */\nexport function shutdown(): void {\n // Stop the session tracker first so the final 'close' + flush happen\n // before the native module is torn down.\n stopSessionTracker();\n stopEventBridge();\n getNative().shutdown();\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/**\n * Returns the Apple `appAccountToken` (a lowercase UUID) derived from the\n * current `rovenueId`. The SDK's own `purchase` already passes it to\n * StoreKit on iOS (and attaches the matching Google Play account id on\n * Android); a host app that buys through StoreKit directly passes it as\n * `.appAccountToken(uuid)`. The server binds the same value at launch, so\n * the store notification routes to this subscriber even before the receipt.\n *\n * Stable across `identify()`; `logOut()` mints a new `rovenueId` and so a\n * new token.\n */\nexport async function getAppAccountToken(): Promise<string> {\n return call(() => getNative().getAppAccountToken());\n}\n","import { getNative } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (e) {\n throw fromNativeError(e);\n }\n}\n\n/**\n * Queue a batch of subscriber-attribute mutations. Written to the local\n * buffer immediately (this promise resolves once that local write\n * completes); the server sync happens in the background (30s tick, on\n * foreground, or via {@link flushAttributes}). A `null` value deletes the\n * key. Reserved keys (prefixed with `$`, e.g. `$email`) map to first-class\n * fields server-side — {@link setEmail}/{@link setDisplayName}/\n * {@link setPhoneNumber}/{@link setPushToken} are thin wrappers over this\n * for the common ones.\n */\nexport async function setAttributes(attributes: Record<string, string | null>): Promise<void> {\n return call(() => getNative().setAttributes(attributes));\n}\n/** Subscriber's email → the `$email` reserved attribute. Same buffered-write,\n * background-flush contract as {@link setAttributes}; `null` clears it. */\nexport async function setEmail(email: string | null): Promise<void> {\n return call(() => getNative().setEmail(email));\n}\n/** Subscriber's display name → the `$displayName` reserved attribute. Same\n * buffered-write, background-flush contract as {@link setAttributes};\n * `null` clears it. */\nexport async function setDisplayName(name: string | null): Promise<void> {\n return call(() => getNative().setDisplayName(name));\n}\n/** Subscriber's phone number → the `$phoneNumber` reserved attribute. Same\n * buffered-write, background-flush contract as {@link setAttributes};\n * `null` clears it. */\nexport async function setPhoneNumber(phone: string | null): Promise<void> {\n return call(() => getNative().setPhoneNumber(phone));\n}\n/** Device push token → the platform's reserved attribute (`$apnsTokens` on\n * iOS, `$fcmTokens` on Android — the native layer picks the right key).\n * Same buffered-write, background-flush contract as {@link setAttributes};\n * `null` clears it. */\nexport async function setPushToken(token: string | null): Promise<void> {\n return call(() => getNative().setPushToken(token));\n}\n/**\n * Force an immediate flush of buffered attribute mutations to the server,\n * bypassing the 30s background tick. Returns the number of mutations\n * actually sent. Most apps never need this — the background dispatcher\n * already flushes on its own tick and on foreground.\n */\nexport async function flushAttributes(): Promise<number> {\n return call(() => getNative().flushAttributes());\n}\n","// Rovenue.setLogHandler — JS-side seam for receiving bridge-level log\n// events from M3/M4. The native module emits `onLog` events; we hold a\n// single subscription and forward to the user-provided handler.\n//\n// Passing `null` removes the active subscription. Replacing a handler\n// implicitly unsubscribes the prior one — there is only ever one active\n// handler at a time, matching the M3/M4 façade contract.\n\nimport { getEmitter } from \"../core/native\";\n\nexport type LogEntry = {\n level: \"off\" | \"error\" | \"warn\" | \"info\" | \"debug\" | \"trace\";\n message: string;\n data?: Record<string, unknown>;\n};\n\nlet subscription: { remove(): void } | null = null;\n\n/**\n * Register a sink for the Rust core's structured log records, bridged\n * through the native module's `onLog` event. There is only ever one active\n * handler — calling this again replaces (implicitly unsubscribes) the\n * previous one; pass `null` to remove it entirely. The core is the sole\n * log authority (there is no separate JS-side `debug` flag) — this is the\n * only way to observe its logs from JS.\n */\nexport function setLogHandler(fn: ((entry: LogEntry) => void) | null): void {\n subscription?.remove();\n subscription = null;\n if (fn) {\n subscription = getEmitter().addListener(\n \"onLog\",\n (native: { level: LogEntry[\"level\"]; message: string; fields?: Record<string, string> }) => {\n const entry: LogEntry = {\n level: native.level,\n message: native.message,\n data:\n native.fields && Object.keys(native.fields).length > 0\n ? native.fields\n : undefined,\n };\n fn(entry);\n },\n );\n }\n}\n","import { getNative, getEmitter } from \"../core/native\";\nimport { fromNativeError } from \"../errors\";\n\nexport interface FunnelClaimResult {\n subscriberId: string;\n funnelAnswers: Record<string, unknown>;\n /**\n * The question keys an app value preselected and the visitor left\n * unchanged (the claim's `funnel_preselected`), so a default can be told\n * from a choice. Empty when nothing was preselected or the server\n * predates the field.\n */\n funnelPreselected: string[];\n}\n\nexport interface ClaimInstallParams {\n platform: \"ios\" | \"android\";\n locale: string;\n timezone: string;\n screenDims: string; // \"WIDTHxHEIGHT\"\n deviceModel?: string;\n installReferrer?: string;\n}\n\ninterface NativeClaim { subscriberId: string; funnelAnswersJson: string; funnelPreselectedJson?: string }\n\nasync function call<T>(fn: () => Promise<T>): Promise<T> {\n try { return await fn(); }\n catch (e) {\n throw fromNativeError(e);\n }\n}\n\nfunction parse(n: NativeClaim): FunnelClaimResult {\n let funnelAnswers: Record<string, unknown> = {};\n try { funnelAnswers = JSON.parse(n.funnelAnswersJson) as Record<string, unknown>; } catch { /* keep {} */ }\n let funnelPreselected: string[] = [];\n try {\n const keys: unknown = JSON.parse(n.funnelPreselectedJson ?? \"[]\");\n if (Array.isArray(keys)) funnelPreselected = keys.filter((k): k is string => typeof k === \"string\");\n } catch { /* keep [] */ }\n return { subscriberId: n.subscriberId, funnelAnswers, funnelPreselected };\n}\n\n/** Claim a known funnel token (e.g. from a deep link). */\nexport async function claimFunnelToken(token: string): Promise<FunnelClaimResult> {\n return call(async () => parse(await getNative().claimFunnelToken(token)));\n}\n\n/** Recover + claim via install attribution. Resolves `null` when no match. */\nexport async function claimInstall(\n params: Partial<ClaimInstallParams> = {},\n): Promise<FunnelClaimResult | null> {\n return call(async () => {\n const n = (await getNative().claimInstall(params)) as NativeClaim | null;\n return n ? parse(n) : null;\n });\n}\n\n/** Kick off the email magic-link claim (resolves later via deep link). */\nexport async function claimViaEmail(email: string): Promise<void> {\n return call(() => getNative().claimViaEmail(email));\n}\n\n/** Persisted per-install id. */\nexport async function installId(): Promise<string> {\n return call(() => getNative().installId());\n}\n\n/** Subscribe to resolved funnel claims (direct calls + future auto-resolution). */\nexport function addFunnelClaimListener(cb: (result: FunnelClaimResult) => void): () => void {\n const sub = getEmitter().addListener(\"onFunnelClaimResolved\", (p: NativeClaim) => cb(parse(p)));\n return () => sub.remove();\n}\n\n/** iOS only: read a `rovenue-funnel:` clipboard marker (after a user gesture)\n * and claim it. Resolves null on Android, or when no marker is present. */\nexport async function claimFromClipboard(): Promise<FunnelClaimResult | null> {\n return call(async () => {\n const n = (await getNative().claimFromClipboard()) as NativeClaim | null;\n return n ? parse(n) : null;\n });\n}\n\nfunction safeDecode(s: string): string {\n if (!s) return \"\";\n try {\n return decodeURIComponent(s);\n } catch {\n return s;\n }\n}\n\n/**\n * Extract a funnel token from a deep link / Universal Link. Recognises:\n * - Universal Link path: `…/funnels/open/<token>`\n * - `rovenue_funnel_token=<token>` query (anywhere — Rovenue-specific key)\n * - `token=<token>` query ONLY on the funnel deep-link host\n * (`…onboarding-complete…`) so an unrelated deep link's generic `token=` is\n * not mistaken for a funnel token.\n * Returns null for any non-funnel URL. Does not use the `URL` constructor\n * (unreliable for custom schemes in RN/Hermes).\n */\nexport function extractFunnelToken(url: string): string | null {\n if (!url) return null;\n\n // 1) Universal-link path: the segment after \"funnels/open/\".\n const marker = \"funnels/open/\";\n const mi = url.indexOf(marker);\n if (mi !== -1) {\n const rest = url.slice(mi + marker.length);\n const seg = rest.split(\"/\")[0].split(\"?\")[0].split(\"#\")[0];\n if (seg) return seg;\n }\n\n // 2) Query-string extraction (manual parse — no URL constructor).\n const qi = url.indexOf(\"?\");\n if (qi !== -1) {\n const query = url.slice(qi + 1).split(\"#\")[0];\n let generic: string | null = null;\n for (const pair of query.split(\"&\")) {\n const eq = pair.indexOf(\"=\");\n if (eq === -1) continue;\n const key = pair.slice(0, eq);\n const val = safeDecode(pair.slice(eq + 1));\n if (!val) continue;\n if (key === \"rovenue_funnel_token\") return val; // Rovenue-specific → trust anywhere\n if (key === \"token\") generic = val;\n }\n // generic `token=` only on the Rovenue funnel deep-link host.\n // Check only the pre-query portion so a crafted query key like\n // `?onboarding-complete=1&token=…` cannot bypass this gate.\n const beforeQuery = url.slice(0, qi);\n if (generic && beforeQuery.includes(\"onboarding-complete\")) return generic;\n }\n\n return null;\n}\n\n/**\n * Claim a funnel token carried by a deep link / Universal Link. Forward every\n * incoming URL here from your app's Linking handler; non-funnel URLs resolve\n * `null` without a network call. A recognized-but-invalid token surfaces the\n * usual claim error via the returned promise.\n */\nexport async function claimFromUrl(url: string): Promise<FunnelClaimResult | null> {\n const token = extractFunnelToken(url);\n if (!token) return null;\n return call(async () => parse(await getNative().claimFunnelToken(token)));\n}\n\n/**\n * Run the no-gesture deterministic funnel-recovery chain once per install:\n * direct deep link (opts.url) → platform deferred match (claimInstall:\n * Android Install Referrer / iOS IP-only). Returns the claim, or null when\n * nothing resolves — then surface the gesture fallbacks yourself\n * (claimFromClipboard on iOS, then claimViaEmail). Resolved claims also fire\n * the addFunnelClaimListener callback. Safe to call on every launch; it\n * short-circuits once a claim has succeeded for this install.\n */\nexport async function resolveFunnelClaim(\n opts: { url?: string } = {},\n): Promise<FunnelClaimResult | null> {\n if (await getNative().hasResolvedFunnelClaim()) return null;\n\n if (opts.url) {\n try {\n const r = await claimFromUrl(opts.url);\n if (r) return r;\n } catch {\n // recognized-but-invalid deep-link token → fall through to the next source\n }\n }\n\n try {\n const r = await claimInstall();\n if (r) return r;\n } catch {\n // network / transient → unresolved\n }\n\n return null;\n}\n","import { StyleSheet } from \"react-native\";\nimport { mapNativeError, type RovenueError } from \"../errors\";\nimport { NativeFunnelView, type NativeFunnelViewProps } from \"./native-view\";\nimport {\n answerCheckRequest,\n photoFrom,\n type FunnelCheckHandler,\n type FunnelPhotoRef,\n} from \"../api/funnel-photos\";\n\ntype NativeLoaded = Parameters<NativeFunnelViewProps[\"onFunnelLoaded\"]>[0][\"nativeEvent\"];\ntype NativeUnavailable = Parameters<NativeFunnelViewProps[\"onFunnelUnavailable\"]>[0][\"nativeEvent\"];\n\n// The funnel fills whatever frame the host gives it; hosts size it with\n// their own flex container: the screens are laid out natively and the JS side has\n// no say in them.\nconst styles = StyleSheet.create({ fill: { flex: 1 } });\n\n/** One empty object, so a view without values never hands native a new one. */\nconst EMPTY_VALUES: Record<string, string> = {};\n\n/** What a funnel asks the app to do when it hits an app-defined action.\n * `params` is whatever the funnel's author configured, already parsed. */\nexport type FunnelCustomAction = {\n actionId: string;\n params: Record<string, unknown>;\n};\n\n/** Why a {@link RovenueFunnelView} has nothing to draw. The same spellings\n * on every Rovenue SDK. */\nexport type FunnelUnavailableReason =\n | \"empty_placement_id\"\n | \"no_placement\"\n | \"no_target\"\n | \"no_variants\"\n | \"draft_issues\";\n\n/** One problem that keeps a draft from being served, as the funnel's\n * validator reported it. */\nexport type FunnelDraftIssue = {\n path: string;\n code: string;\n message: string;\n severity: string;\n pageId?: string;\n blockId?: string;\n};\n\n/** `onLoaded`: the funnel's first screen is on screen. */\nexport type FunnelLoadedEvent = {\n /** The placement the view was asked for. */\n placementId: string;\n /** The `funnels` row id. */\n funnelId: string;\n /** The version drawn (a draft's: the version a publish would create). */\n revision: number;\n /** The experiment variant drawn, when the placement serves one. */\n variantId?: string;\n /** The experiment's key, alongside `variantId`. */\n experimentKey?: string;\n /** True when the bundled fallback file answered. */\n servedFromFallback: boolean;\n /** True when this is the funnel's latest draft (a debug build on a\n * Sandbox key). */\n isDraft: boolean;\n};\n\n/** `onUnavailable`: the view has nothing to draw, and why. */\nexport type FunnelUnavailableEvent = {\n /** The placement the view was asked for. */\n placementId: string;\n reason: FunnelUnavailableReason;\n /** What blocks the draft; set only for `draft_issues`. */\n issues?: FunnelDraftIssue[];\n};\n\n/** `onScreenChanged`: the visible screen changed, including the first. */\nexport type FunnelScreenEvent = {\n /** The screen's (page's) id in the funnel document. */\n screenId: string;\n /** Its position in the funnel's page order, from 0. */\n index: number;\n};\n\n/** Props for {@link RovenueFunnelView}. */\nexport type RovenueFunnelViewProps = {\n /** The placement to resolve. Resolution happens NATIVELY — there is no\n * JS `getFunnel`, because nothing about a funnel crosses the bridge. A\n * new value resolves again; the previous funnel is cleared first. In a\n * debug build on a Sandbox key the funnel's latest draft is shown, with\n * a \"Draft\" badge, and every builder edit arrives live. */\n placementIdentifier: string;\n locale?: string;\n /** The first screen is on screen. For a draft, fires again after every\n * live-refresh rebuild. */\n onLoaded?: (event: FunnelLoadedEvent) => void;\n /** The view has nothing to draw: an empty or unknown placement, a\n * placement with no target, or a draft that cannot be served (with its\n * issues). The previous funnel is cleared. */\n onUnavailable?: (event: FunnelUnavailableEvent) => void;\n /** Resolving failed (offline with no cache or fallback, an invalid or\n * unsupported config), or a screen did not decode\n * (`serverCode` `FUNNEL_SCREEN_UNDECODABLE`). The previous funnel is\n * cleared. A superseded resolve is never reported. */\n onError?: (error: RovenueError) => void;\n /** The visible screen changed, including the first. */\n onScreenChanged?: (event: FunnelScreenEvent) => void;\n /** The funnel reached its end. Never fires together with `onDismissed`. */\n onCompleted?: () => void;\n /** The visitor dismissed the funnel (its close action). Never fires\n * together with `onCompleted`, and not when the host unmounts the view. */\n onDismissed?: () => void;\n /** Omit to leave `open_url` actions INERT; a legal block's terms link then\n * opens only an http(s) address, in the system browser. Presence is\n * decided when the funnel resolves. */\n onUrl?: (url: string) => void;\n /** An action the funnel's author defined for this app to interpret. */\n onCustomAction?: (action: FunnelCustomAction) => void;\n /** The funnel wants this package purchased. Call `Rovenue.purchase`. */\n onPurchase?: (packageIdentifier: string) => void;\n /** The funnel asked for purchases to be restored. */\n onRestore?: () => void;\n /** Values for the funnel's declared externals (an ad's scene, a\n * campaign): trimmed, 512 characters at most, undeclared names dropped.\n * A fresh value overrides a restored one and preselects a `defaultFrom`\n * question. A changed value resolves again. Never pass personal data:\n * values are written to the on-device session state. */\n values?: Record<string, string>;\n /** A `photo_upload` question was answered: its key and the photo on the\n * device. Call `releasePhoto` once you are done with the file. */\n onPhotoSelected?: (questionKey: string, photo: FunnelPhotoRef) => void;\n /** Your photo checker; without it a check applies its `whenUnavailable`.\n * Presence is decided when the funnel resolves. */\n onCheck?: FunnelCheckHandler;\n};\n\n/** Params arrive as a JSON string: the native handler signature carries\n * `paramsJson`, because a map would have to be re-encoded per platform.\n * A malformed one yields `{}` rather than throwing inside a native event\n * callback, where the throw would surface as an unhandled JS exception\n * with no funnel context attached. */\nfunction parseParams(json: string): Record<string, unknown> {\n try {\n const parsed: unknown = JSON.parse(json);\n return typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\n/** Optional fields arrive absent or null depending on the platform; both\n * become absent here, so a host can test with `=== undefined`. */\nfunction loadedFrom(e: NativeLoaded): FunnelLoadedEvent {\n return {\n placementId: e.placementId,\n funnelId: e.funnelId,\n revision: e.revision,\n ...(e.variantId != null ? { variantId: e.variantId } : {}),\n ...(e.experimentKey != null ? { experimentKey: e.experimentKey } : {}),\n servedFromFallback: e.servedFromFallback,\n isDraft: e.isDraft,\n };\n}\n\nfunction unavailableFrom(e: NativeUnavailable): FunnelUnavailableEvent {\n const issues = e.issues?.map((i) => ({\n path: i.path,\n code: i.code,\n message: i.message,\n severity: i.severity,\n ...(i.pageId != null ? { pageId: i.pageId } : {}),\n ...(i.blockId != null ? { blockId: i.blockId } : {}),\n }));\n return {\n placementId: e.placementId,\n // The native views send only the five spellings of the union.\n reason: e.reason as FunnelUnavailableReason,\n ...(issues && issues.length > 0 ? { issues } : {}),\n };\n}\n\n/**\n * Hosts the platform's native funnel renderer for a placement.\n *\n * The funnel fills whatever frame the host gives it; size it with your own\n * flex container. Nothing about the funnel crosses the bridge — the native\n * side resolves the placement and draws the screens, so there is no JS\n * `getFunnel` and no object to pass in.\n */\nexport function RovenueFunnelView(props: RovenueFunnelViewProps) {\n const {\n placementIdentifier,\n locale,\n onLoaded,\n onUnavailable,\n onError,\n onScreenChanged,\n onCompleted,\n onDismissed,\n onUrl,\n onCustomAction,\n onPurchase,\n onRestore,\n values,\n onPhotoSelected,\n onCheck,\n } = props;\n return (\n <NativeFunnelView\n style={styles.fill}\n funnelIdentifier={placementIdentifier}\n locale={locale}\n // The native views branch on whether a handler EXISTS, so this is a\n // value, not a convenience flag.\n hasUrlHandler={onUrl !== undefined}\n // Same reason: without a checker the native side applies the check's\n // `whenUnavailable` at once instead of waiting on JS.\n hasCheckHandler={onCheck !== undefined}\n values={values ?? EMPTY_VALUES}\n onFunnelLoaded={(e) => onLoaded?.(loadedFrom(e.nativeEvent))}\n onFunnelUnavailable={(e) => onUnavailable?.(unavailableFrom(e.nativeEvent))}\n onFunnelFailed={(e) => onError?.(mapNativeError(e.nativeEvent.code, e.nativeEvent.message))}\n onFunnelScreenChanged={(e) =>\n onScreenChanged?.({ screenId: e.nativeEvent.screenId, index: e.nativeEvent.index })\n }\n onFunnelCompleted={() => onCompleted?.()}\n onFunnelDismissed={() => onDismissed?.()}\n onUrlRequested={(e) => onUrl?.(e.nativeEvent.url)}\n onCustomActionRequested={(e) =>\n onCustomAction?.({\n actionId: e.nativeEvent.actionId,\n params: parseParams(e.nativeEvent.params),\n })\n }\n onPurchaseRequested={(e) => onPurchase?.(e.nativeEvent.packageId)}\n onRestoreRequested={() => onRestore?.()}\n onPhotoSelectedEvent={(e) => onPhotoSelected?.(e.nativeEvent.questionKey, photoFrom(e.nativeEvent.photo))}\n // Always answered — a checker removed since the resolve answers null.\n onCheckRequested={(e) => answerCheckRequest(e.nativeEvent.requestId, e.nativeEvent.request, onCheck)}\n />\n );\n}\n","// `requireNativeViewManager` — NOT `requireNativeView`, which does not\n// exist in expo-modules-core 2.5.0. Events arrive wrapped in\n// `nativeEvent`.\nimport { requireNativeViewManager } from \"expo-modules-core\";\nimport type { FunnelCheckRequestDTO, FunnelPhotoRefDTO } from \"../specs/RovenueModule.types\";\n\n/** One issue that blocks a draft, as the native views send it. */\nexport type NativeDraftIssue = {\n path: string;\n code: string;\n message: string;\n severity: string;\n pageId?: string;\n blockId?: string;\n};\n\n/** Wire props for the native funnel view. Deliberately narrow: nothing\n * about the funnel crosses the bridge, only the placement identifier the\n * native side resolves it with. The screens are drawn natively. */\nexport type NativeFunnelViewProps = {\n funnelIdentifier: string;\n locale?: string;\n hasUrlHandler: boolean;\n hasCheckHandler: boolean;\n values: Record<string, string>;\n onFunnelLoaded: (event: {\n nativeEvent: {\n placementId: string;\n funnelId: string;\n revision: number;\n variantId?: string;\n experimentKey?: string;\n servedFromFallback: boolean;\n isDraft: boolean;\n };\n }) => void;\n onFunnelUnavailable: (event: {\n nativeEvent: { placementId: string; reason: string; issues?: NativeDraftIssue[] };\n }) => void;\n onFunnelFailed: (event: { nativeEvent: { code: string; message: string } }) => void;\n onFunnelScreenChanged: (event: { nativeEvent: { screenId: string; index: number } }) => void;\n onFunnelCompleted: (event: { nativeEvent: Record<string, never> }) => void;\n onFunnelDismissed: (event: { nativeEvent: Record<string, never> }) => void;\n onUrlRequested: (event: { nativeEvent: { url: string } }) => void;\n onCustomActionRequested: (event: { nativeEvent: { actionId: string; params: string } }) => void;\n onPurchaseRequested: (event: { nativeEvent: { packageId: string } }) => void;\n onRestoreRequested: (event: { nativeEvent: Record<string, never> }) => void;\n onPhotoSelectedEvent: (event: { nativeEvent: { questionKey: string; photo: FunnelPhotoRefDTO } }) => void;\n onCheckRequested: (event: { nativeEvent: { requestId: string; request: FunnelCheckRequestDTO } }) => void;\n style?: unknown;\n};\n\nconst MODULE_NAME = \"Rovenue\";\n\n/** The view name both native modules register this view under. It is the\n * module's only view since sub-project 5, but it is still asked for by\n * NAME: the native side names it, and a mismatch would resolve nothing. */\nconst VIEW_NAME = \"RovenueFunnelView\";\n\nexport const NativeFunnelView =\n requireNativeViewManager<NativeFunnelViewProps>(MODULE_NAME, VIEW_NAME);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,cAAc;;;ACcpB,IAAM,qBAAqB;AA2C3B,SAAS,eACd,GACY;AACZ,SAAO,OAAO;AAAA,IACZ,OAAO,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,CAAC,MAAM,MAAM,MAAS;AAAA,EACrD;AACF;AAUO,SAAS,kBAAkB,KAA4B;AAC5D,QAAM,EAAE,iBAAiB,GAAG,KAAK,IAAI;AAErC,QAAM,MAAM,eAAe,IAA+B;AAE1D,MAAI,oBAAoB,QAAW;AACjC,UAAM,UAAU;AAAA,MACd;AAAA,IACF;AACA,QAAI,OAAO,KAAK,OAAO,EAAE,SAAS,GAAG;AACnC,MAAC,IAAgC,kBAAkB;AAAA,IACrD;AAAA,EACF;AAEA,SAAO,KAAK,UAAU,GAAG;AAC3B;;;AC3EO,IAAM,cAAc;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA,EACA;AAAA;AAAA;AAAA,EAGA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,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,EAAE,YAAY,aAAa,UAAU,EAAE,YAAY,KAAK,CAAC;AAAA,MAExG,kBAAkB,CAAC,MAAM,mBAAmB,EAAE,YAAY,WAAW,EAAE,YAAY,SAAS,OAAO;AAAA;AAAA,EACrG;AAEJ;;;A5BnJO,IAAM,UAAU;AAAA,EACrB;AAAA;AAAA;AAAA,EAGA,YAAY,MAAM;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,mBAAmB,CAAC,OAAqE;AACvF,UAAM,MAAM,WAAW,EAAE,YAAY,YAAY,CAAC,YAA+B;AAC/E,SAAG,QAAQ,KAAsC;AAAA,IACnD,CAAC;AACD,WAAO,MAAM,IAAI,OAAO;AAAA,EAC1B;AACF;","names":["import_react","import_react","import_react","EMPTY","import_react","loadIfNeeded","call","call","call","call","call","subscription","isoNow","call","call","call","subscription","call","import_react_native","import_expo_modules_core"]}