@voidhash/nitro-ui 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Package.swift +1 -1
- package/README.md +5 -5
- package/build/{chunk-Z6TDMZMZ.js → chunk-5LFKYB24.js} +6 -1
- package/build/chunk-5LFKYB24.js.map +1 -0
- package/build/index.d.ts +5 -1
- package/build/index.js +3 -2
- package/build/index.js.map +1 -1
- package/build/navigation.js +1 -1
- package/ios/Shared/VoidhashNativeClientCore.swift +1 -0
- package/package.json +6 -6
- package/src/specs/VoidhashNativeClient.nitro.ts +2 -2
- package/build/chunk-Z6TDMZMZ.js.map +0 -1
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../react-native/src/client.tsx","../../react-native/src/core/analytics/constants.ts","../../react-native/src/core/caching/namespace.ts","../../react-native/package.json","../../react-native/src/core/constants.ts","../../react-native/src/core/diagnostics/diagnostics.ts","../../react-native/src/core/entities/reported-transaction.ts","../../react-native/src/core/flows/flows.ts","../../react-native/src/core/native/native-client.ts","../../react-native/src/core/analytics/json-safe.ts","../../react-native/src/core/entitlements/find-grant.ts","../../react-native/src/core/entities/app-store.ts","../../react-native/src/core/entities/decoding.ts","../../react-native/src/core/entities/person.ts","../../react-native/src/core/reactivity/client-state.ts","../../react-native/src/core/schema/decode.ts","../../react-native/src/core/schema/runtime.ts","../../react-native/src/core/sdk-configuration.ts","../../react-native/src/core/utils/native-error.ts","../../react-native/src/core/native/billing.ts","../../react-native/src/core/entities/google-play.ts","../../react-native/src/core/person-attributes.ts","../../react-native/src/core/screens/screen-tracker.ts","../../react-native/src/constants.ts","../../react-native/src/core/entities/perk.ts","../src/client-nitro-ui.ts","../../react-native/src/client-host.ts","../../react-native/src/react/hooks/use-person.ts","../../react-native/src/react/hooks/use-async-function.ts","../../react-native/src/react/hooks/use-atom-value.ts","../../react-native/src/react/hooks/use-feature-flags.ts","../../react-native/src/react/hooks/use-has-perk.ts","../../react-native/src/react/hooks/use-present-flow.ts","../../react-native/src/react/hooks/use-products.ts","../../react-native/src/react/hooks/use-purchase.ts","../../react-native/src/react/internal/host-callback.ts","../../react-native/src/react/hooks/use-restore-purchases.ts","../../react-native/src/react/hooks/use-subscriptions.ts","../src/specs/VoidhashNativeClient.nitro.ts"],"sourcesContent":["import { Result } from \"better-result\";\nimport * as Arr from \"effect/Array\";\nimport * as MutableHashMap from \"effect/MutableHashMap\";\nimport * as MutableHashSet from \"effect/MutableHashSet\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\nimport * as R from \"effect/Record\";\nimport * as EffectResult from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport type { AtomRegistry } from \"effect/reactivity\";\n\nimport {\n AUTOMATIC_EVENTS,\n PUSH_SEND_ID_DATA_KEY,\n PUSH_SEND_ID_PROPERTY,\n SCREEN_PROPERTIES,\n} from \"./core/analytics/constants\";\nimport { buildCacheNamespace } from \"./core/caching/namespace\";\nimport { SDK_VERSION } from \"./core/constants\";\nimport {\n makeDiagnosticEmitter,\n type VoidhashDiagnostic,\n type VoidhashDiagnosticHandler,\n} from \"./core/diagnostics/diagnostics\";\nimport type {\n AppStorePurchaseIntent,\n AppStoreSubscriptionStatus,\n AppTransaction,\n RefundRequestStatus,\n} from \"./core/entities/app-store\";\nimport type {\n GooglePlayBillingFeature,\n GooglePlayInAppMessageResult,\n} from \"./core/entities/google-play\";\nimport type { EntitlementGrant, Person } from \"./core/entities/person\";\nimport type {\n Offer,\n OfferKind,\n Product,\n ProductsForSlugs,\n SubscriptionReplacement,\n SubscriptionReplacementMode,\n} from \"./core/entities/product\";\nimport {\n fromReportedTransaction,\n type StoreReport,\n type StoreTransaction,\n} from \"./core/entities/reported-transaction\";\nimport type { Transaction, TransactionUpdate } from \"./core/entities/transaction\";\nimport type {\n FeatureFlagsResult,\n Group,\n GroupProperties,\n GroupPropertyValue,\n Groups,\n PersonAttributes,\n ResolvedPaywall,\n} from \"./core/facade-types\";\nimport {\n type FlowCapability,\n flowError,\n type FlowResult,\n type FlowLoading,\n type FlowRuntime,\n type PresentFlowArguments,\n type PresentFlowOptions,\n} from \"./core/flows/flows\";\nimport {\n makeNativeClientAdapter,\n type NativeClientAdapter,\n type NativeClientPort,\n} from \"./core/native/native-client\";\nimport { invalidPersonAttributes } from \"./core/person-attributes\";\nimport { clientRunAtom, schemaAtom } from \"./core/reactivity/client-state\";\nimport type {\n FeatureFlagKey,\n FeatureFlagValue,\n FlowInput,\n FlowValues,\n LocationSlug,\n PerkSlug,\n ProductSlug,\n} from \"./core/schema/registry\";\nimport { RuntimeSchemaValue, type RuntimeSchema } from \"./core/schema/runtime\";\nimport {\n createScreenTracker,\n type ScreenTracker,\n type ScreenView,\n} from \"./core/screens/screen-tracker\";\nimport {\n type AnalyticsConsent,\n type AnalyticsWhilePending,\n isAnalyticsConsent,\n} from \"./core/sdk-configuration\";\nimport {\n InvalidArgumentError,\n NotInitializedError,\n PurchaseInProgressError,\n ReadOnlyModePurchaseNotAllowedError,\n UnsupportedPlatformError,\n VoidhashError,\n} from \"./errors\";\nimport type {\n NativeClientConfiguration,\n NativePurchaseOptions,\n NativeReportedTransaction,\n NativeSubscriptionReplacement,\n} from \"./specs/VoidhashNativeClient.nitro\";\n\nexport type {\n FeatureFlagsResult,\n Group,\n GroupProperties,\n GroupPropertyValue,\n Groups,\n PersonAttributes,\n ResolvedPaywall,\n};\n\n/**\n * The native flow module as earlier releases drove it from JavaScript.\n * @deprecated No longer used: the native client presents flows itself. Kept\n * so code that imports the type still compiles; removed in a future release.\n */\nexport interface VoidhashFlowsPort {\n readonly isRendererAvailable: boolean;\n engineCapabilities?(): string;\n present(\n requestJson: string,\n purchase: (productId: string, offerId: string) => Promise<void>,\n restore: () => Promise<void>,\n setAttribute: (name: string, valueJson: string) => Promise<void>,\n loadState: (key: string) => Promise<string>,\n saveState: (key: string, variablesJson: string) => Promise<void>,\n clearState: (key: string) => Promise<void>,\n track: (name: string, propertiesJson: string) => void,\n screen: (name: string, propertiesJson: string) => void,\n ): Promise<string>;\n preload(requestJson: string): Promise<void>;\n dismiss(): Promise<void>;\n}\n\n/**\n * A reachability source as the `connectivity` option took it: a subscribe\n * function returning an unsubscribe callback.\n */\nexport interface ConnectivityPort {\n readonly subscribe: (listener: (online: boolean) => void) => () => void;\n}\n\n/** Controls the built-in `$screen` event. */\nexport interface ScreenTrackingOptions {\n /** Default `true`. `false` makes every integration and `screen()` a no-op. */\n enabled?: boolean;\n /** Default `false`. Adds `$screen_params` (route params, string-coerced, max 20 keys). */\n includeParams?: boolean;\n /**\n * Rewrites or drops a screen before capture. Return `null` to skip it. A\n * throw, or a result whose `identity`, `name` or `path` is not a string,\n * tracks the screen unmapped and is reported as `HOST_CALLBACK_FAILED`.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK option consumed by non-Effect app code; `null` is the documented \"drop this screen\" answer and mirrors the iOS and Android SDKs.\n mapScreen?: (view: ScreenView) => ScreenView | null;\n}\n\n/** How feature flag reads behave before Voidhash has answered them. */\nexport interface FeatureFlagsOptions {\n /**\n * What a flag reads as while it has no evaluated value: before its first\n * evaluation arrives, and when Voidhash cannot be reached and nothing is\n * cached. `useFeatureFlags().isEnabled()` answers it, on a disabled client\n * too, and `getFeatureFlags()` answers each requested key that has one as\n * a flag without a variant. Flags without a default read as `false`. Use\n * `true` for a flag whose feature must stay on when Voidhash is unreachable.\n */\n readonly defaults?: Readonly<Record<string, boolean>>;\n /**\n * How long a flag read with nothing cached waits for Voidhash before it\n * answers with no flags, in milliseconds (default 2000). The evaluation\n * carries on in the background, and the hooks update when it lands. A\n * cached value never waits more than 500 ms. A request gives up after 10\n * seconds, so a longer wait ends there.\n */\n readonly maxWaitMs?: number;\n}\n\nexport interface VoidhashClientOptions {\n /**\n * The end user's consent to usage analytics (default `\"granted\"`). While it\n * is `\"denied\"` or `\"pending\"` the SDK captures, stores and sends no\n * analytics: no custom events, screens, lifecycle or install events or\n * paywall impressions. What the app says about the end user is not\n * analytics: `identify()`, person attributes and groups are sent whatever\n * the consent, and purchases, restores, entitlements, feature flags and\n * paywalls work as usual.\n * A consent set later with `client.setAnalyticsConsent()` is stored on the\n * device and takes precedence over this option on the next launch.\n */\n analyticsConsent?: AnalyticsConsent;\n /**\n * What happens to analytics captured while consent is `\"pending\"` (default\n * `\"drop\"`). `\"buffer\"` holds up to 100 events in memory, with the time\n * each happened, and records them once consent is granted; a denial\n * discards them. Nothing is sent or stored while they are held. Person\n * attributes and groups are never held: they are sent whatever the consent.\n */\n analyticsWhilePending?: AnalyticsWhilePending;\n /**\n * `true` makes `identify()` grant a `\"pending\"` consent, for apps whose\n * sign-in accepts their terms (default `false`). A `\"denied\"` consent is\n * never overridden. `signOut()` and `reset()` send what was recorded and\n * return that consent to `\"pending\"`; a consent set with\n * `setAnalyticsConsent()` is the app's own decision and stays.\n */\n grantConsentOnIdentify?: boolean;\n /**\n * Captures `$app_installed`, `$app_updated`, `$app_opened`,\n * `$app_backgrounded`, `$app_became_active`, `$app_crashed` and `$sign_out`\n * automatically (default `true`). Turn it off when the app reports these\n * events itself.\n */\n automaticLifecycleEvents?: boolean;\n baseUrl?: string;\n debug?: boolean;\n /** Enables isolated test purchases in debug builds. Release builds always ignore this option. */\n dev?: boolean;\n distinctId?: string;\n /**\n * Reads which ad brought this install and records it on the person as a\n * touch (default `true`): Apple Ads on iOS, the Google Play install referrer\n * and, with `metaAppId`, Meta's apps on Android. Runs once per install, in\n * the background, only with analytics consent. An install that predates this\n * option is not read.\n */\n installAttribution?: boolean;\n /**\n * The app's Meta (Facebook) app id. On Android, `installAttribution` then also\n * asks the Facebook, Instagram and Facebook Lite apps on the device for the ad\n * behind the install, which is preferred over the Play referrer. iOS ignores it.\n */\n metaAppId?: string;\n /**\n * When StoreKit shows its own messages, such as a price increase to agree\n * to or a billing issue (default `\"deferWhileFlowPresented\"`): at once\n * (`\"automatic\"`), or held while a Voidhash flow is on screen and shown once\n * it closes. Google Play ignores it.\n */\n appStoreMessages?: \"automatic\" | \"deferWhileFlowPresented\";\n /**\n * What happens to a purchase the end user starts on the App Store, such as\n * a promoted in-app purchase or a win-back offer (default\n * `\"purchaseWhenReady\"`). `\"purchaseWhenReady\"` buys it once `init()` has\n * finished, never before. `\"manual\"` hands it to the listeners of\n * `client.appStore.addPurchaseIntentListener()`, to complete with\n * `purchase()` when the app is ready; one that arrives before a listener\n * is added waits for the first. Google Play ignores it.\n */\n purchaseIntents?: \"purchaseWhenReady\" | \"manual\";\n /**\n * Ships the SDK fully disabled (default `true`). A disabled client never\n * connects to the native store, never talks to the network and never\n * registers listeners: `init()` and every side-effect method resolve as\n * no-ops, and reads answer with their empty shape. Intended for\n * feature-flagged rollouts, where mounting the provider unconditionally\n * avoids hook-order violations.\n *\n * Fixed at construction. Enabling the SDK later means creating a new client\n * — cheap, because a disabled client never builds its Effect runtime and so\n * holds no store connection, timers or listeners.\n */\n enabled?: boolean;\n /**\n * What flows may do in this app (default `[\"links\"]`). Purchases, restores,\n * closing and analytics need no grant. `notifications` and `tracking` let a\n * flow ask for those system permissions, `attributes` lets it set person\n * attributes and `links` lets it open links outside the app. A flow action\n * needing a capability that is not granted is ignored.\n */\n flowCapabilities?: ReadonlyArray<FlowCapability>;\n /**\n * Which flow runtime draws flows (default `linked`, the one built into the\n * SDK). `module` draws them with the flow runtime module each flow names,\n * downloaded once, verified and cached. It applies to the whole app process\n * from the first `init()`, on iOS and Android, and needs the native flow\n * renderer; `linked` leaves the renderer as native code set it.\n */\n flowRuntime?: FlowRuntime;\n /**\n * What a paywall shows while it waits for the network (default `standard`):\n * the native SDK's loading screen, shown 0.4 seconds after `presentFlow` until\n * the paywall takes its place, which the end user can close (`presentFlow`\n * then resolves with the outcome `dismissed` and `wasShown: false`). `none`\n * keeps the app's screen as it is until the paywall is shown. A paywall\n * already on the device appears before then either way.\n */\n flowLoading?: FlowLoading;\n /** How feature flag reads behave before Voidhash has answered them; see {@link FeatureFlagsOptions}. */\n featureFlags?: FeatureFlagsOptions;\n ingestUrl?: string;\n /**\n * @deprecated No longer needed: the SDK observes reachability and the app\n * lifecycle natively and recovers on its own when the device comes back\n * online or to the foreground. Still accepted, and ignored.\n */\n connectivity?: ConnectivityPort;\n /**\n * Called for every non-fatal event the SDK handled itself — a request that\n * failed and will be retried, an event evicted from a full queue, a rejected\n * publishable key. Purely informational; exceptions thrown here are\n * swallowed. Prefer this over `unstable_swallowErrors`.\n */\n onDiagnostic?: VoidhashDiagnosticHandler;\n /**\n * Locations whose flows are downloaded at boot, so their first\n * `presentFlow()` shows without a round trip. Locations the device has\n * presented before are preloaded anyway. Nothing is preloaded when the app\n * does not include the flow renderer.\n */\n preloadLocations?: string[];\n /**\n * The interface revision the app was built against, by location slug. Pass\n * the `flowRevisions` constant of the generated declarations: a location's\n * revision is then used to preload its flow and by every `presentFlow()`\n * that names none. A location that is not listed counts as revision 0.\n */\n flowRevisions?: Readonly<Record<string, number>>;\n /**\n * Starts the SDK in observer mode: transactions are reported to Voidhash but\n * never finished/acknowledged with the store, and purchases are blocked, so\n * another billing integration can own them. Off by default. Can be flipped\n * later with `client.setReadOnly()`.\n */\n readOnly?: boolean;\n scheme?: string;\n /**\n * Automatic screen tracking (`$screen`). On by default; the Expo Router and\n * React Navigation integrations under `@voidhash/react-native/expo-router`\n * and `@voidhash/react-native/react-navigation` feed it, as does\n * `client.screen()`.\n */\n screenTracking?: ScreenTrackingOptions;\n /**\n * @deprecated Transport failures no longer surface as errors, so there is\n * nothing left for this to swallow. Use `onDiagnostic` to observe recovered\n * failures instead. Removed in a future release.\n */\n unstable_swallowErrors?: boolean;\n /**\n * Test/internal escape hatch — inject a known runtime schema instead of\n * letting the SDK fetch from the server on init. Not part of the public\n * API; production code should rely on the server-side schema endpoint.\n */\n unstable_internalSchema?: RuntimeSchema;\n /**\n * @deprecated No longer has an effect: the SDK always runs on its native client.\n * Still accepted; development builds log a one-time notice when it is set.\n */\n unstable_nativeEngine?: boolean;\n}\n\n/**\n * How a {@link VoidhashClient.purchase} call ended. Every failure is the\n * `Err` of the returned `Result`.\n *\n * - `purchased`: the store charged. `synced` is `true` once Voidhash\n * accepted the receipt; `false` while it waits on the device, sent again\n * at launch, in the foreground and when the device is back online, and\n * access arrives once it lands. Either way the purchase is done: do not\n * offer it again.\n * - `pending`: the store needs outside action first, such as Ask to Buy\n * approval or a pending payment. It completes later, as a transaction\n * update (`addTransactionListener()`), and access arrives with it.\n * - `cancelled`: the end user dismissed the store sheet.\n * - `disabled`: the client was created with `enabled: false`; nothing was bought.\n */\nexport type PurchaseResult =\n | { readonly status: \"purchased\"; readonly transaction: Transaction; readonly synced: boolean }\n | { readonly status: \"pending\" }\n | { readonly status: \"cancelled\" }\n | { readonly status: \"disabled\" };\n\n/**\n * Which offer a purchase buys:\n *\n * - `\"automatic\"` (default): a subscription's `introOffer` when the end user\n * is eligible for one, otherwise the regular price.\n * - `\"none\"`: the regular price. The App Store may still apply an\n * introductory offer the end user is eligible for.\n * - an `Offer` from `product.offers` or `product.subscription.introOffer`.\n * - an offer's `id`, looked up in the same offers.\n *\n * An offer that cannot be bought fails the purchase with `OFFER_UNAVAILABLE`;\n * the product is never bought at its regular price instead.\n */\n// `string & Record<never, never>` keeps the two words above suggested next to any offer id.\nexport type OfferSelection = \"automatic\" | \"none\" | Offer | (string & Record<never, never>);\n\n/** What a {@link VoidhashClient.purchase} call may ask for beyond the product. */\nexport interface PurchaseOptions {\n /** The offer to buy; see {@link OfferSelection}. Default `\"automatic\"`. */\n readonly offer?: OfferSelection;\n /**\n * How many to buy, default 1. Only App Store consumables can be bought\n * several at once; on Google Play the end user picks the quantity in the\n * store's sheet. Anything but 1 elsewhere is an `INVALID_ARGUMENT` error.\n * The transaction reports the quantity the store charged.\n */\n readonly quantity?: number;\n /**\n * The subscription the user has now, which this purchase replaces: an\n * upgrade, a downgrade or a change of plan. Google Play only. Without it,\n * buying another subscription product there adds a second subscription\n * next to the first, and Google Play bills both.\n *\n * Nothing is bought when the replacement cannot be made. The purchase\n * fails with `REPLACED_SUBSCRIPTION_NOT_OWNED` when the signed-in Google\n * Play account does not own the named subscription, with\n * `INVALID_ARGUMENT` when either product is not a subscription, both are\n * the same product, or the option names no product or an unknown mode, and\n * with `SUBSCRIPTION_REPLACEMENT_REFUSED` when Google Play rejects the\n * replacement before its sheet opens.\n *\n * Ignored on iOS, where the App Store moves a subscriber between the\n * products of one subscription group by itself.\n */\n readonly replacing?: SubscriptionReplacement;\n /** App Store options; Google Play ignores them. */\n readonly appStore?: {\n /** Simulates Ask to Buy in the sandbox, so the purchase ends `pending`. */\n readonly simulatesAskToBuyInSandbox?: boolean;\n };\n /** Google Play options; the App Store ignores them. */\n readonly googlePlay?: {\n /** Tells Google Play the price was personalized for the end user (an EU disclosure). */\n readonly isOfferPersonalized?: boolean;\n /** Google Play's obfuscated profile id, for apps with several profiles per account. */\n readonly obfuscatedProfileId?: string;\n /**\n * Buys exactly this Google Play offer token, from\n * `product.googlePlay.subscriptionOffers` or `oneTimeOffers`, instead of\n * what `offer` selects.\n */\n readonly offerToken?: string;\n };\n}\n\n/** The storefront the end user buys from. */\nexport interface Storefront {\n /** ISO 3166-1 alpha-2 country code, such as `US`. */\n readonly countryCode: string;\n /** ISO 4217 currency code, when the store says. */\n readonly currencyCode?: string;\n}\n\n/** Outcome of an identity switch reported by {@link VoidhashClient.identifySync}. */\nexport type IdentifyResult =\n | {\n /** The server confirmed the identity and returned the person. */\n status: \"confirmed\";\n person: Person;\n }\n | {\n /**\n * The server has not confirmed the switch yet (it was unreachable, or\n * the key was rejected). The device already runs under the new distinct\n * id, and the link from the previous identity is queued on the device\n * and delivered once the server can be reached.\n */\n status: \"deferred\";\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n person: Person | null;\n }\n | {\n /** The client was created with `enabled: false`, so nothing was recorded. */\n status: \"disabled\";\n person: null;\n };\n\n/** Answer to an entitlement check for one perk. */\nexport interface HasPerkResult {\n /** The active grant behind `hasAccess`, when one exists. */\n grant?: EntitlementGrant;\n hasAccess: boolean;\n /**\n * The answer came from a cached snapshot that is past its refresh window,\n * either because a refresh is still running or because the server could not\n * be reached.\n */\n isStale: boolean;\n /**\n * The cached snapshot is past its two-day TTL. Access is still reported as\n * the snapshot recorded it; apps gating high-value content can decide to\n * treat this as untrusted.\n */\n isExpired: boolean;\n /**\n * Why the answer has the freshness it has.\n *\n * - `fresh`: confirmed by the server just now.\n * - `refresh-in-flight`: served from cache while a refresh is still running;\n * its result lands for the next read.\n * - `refresh-failed`: served from cache because the refresh could not\n * complete.\n * - `no-cache`: the SDK has never seen a snapshot for this identity, so\n * `hasAccess` is `false` for lack of evidence rather than because access\n * was denied.\n */\n reason: \"fresh\" | \"refresh-in-flight\" | \"refresh-failed\" | \"no-cache\";\n}\n\n/** Person snapshot together with how much to trust it. */\nexport interface CurrentPersonResult {\n /** The snapshot, or `null` before the SDK has ever seen one. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n person: Person | null;\n /** Served from cache past its refresh window. */\n isStale: boolean;\n /** Served from cache past its TTL. */\n isExpired: boolean;\n /** Why the snapshot has the freshness it has; see {@link HasPerkResult.reason}. */\n reason: \"fresh\" | \"refresh-in-flight\" | \"refresh-failed\" | \"no-cache\";\n}\n\n/** Outcome of a synchronous person-attribute update. */\nexport type SetPersonAttributesResult =\n | {\n /** The server accepted and returned the updated snapshot. */\n status: \"confirmed\";\n person: Person;\n }\n | {\n /** The server was unreachable; the update is queued and will be retried. */\n status: \"deferred\";\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n person: Person | null;\n }\n | {\n /** The client was created with `enabled: false`, so nothing was recorded. */\n status: \"disabled\";\n person: null;\n }\n | {\n /**\n * Nothing was left to write: the only attribute was an agreement to ad\n * data sharing, which waits for analytics consent.\n */\n status: \"skipped\";\n person: null;\n };\n\n/** Outcome of an analytics flush. */\nexport interface FlushResult {\n /** Events the server accepted during this flush. */\n flushed: number;\n /** Events still queued, waiting for their next attempt. */\n pending: number;\n /** The failure that stopped the flush, when one did. */\n lastError?: VoidhashError;\n}\n\n/** Feature flag answer of a disabled client: no flags were ever evaluated. */\nconst DISABLED_FEATURE_FLAGS: FeatureFlagsResult = { flags: [], isStale: false };\n\n/** Where the JavaScript runtime holds {@link liveClients}. */\nconst LIVE_CLIENTS = Symbol.for(\"@voidhash/react-native/live-clients\");\n\n/**\n * The client that owns each storage namespace (publishable key and base URL)\n * right now. A client that initializes ends the one it replaces first, so two\n * native clients never write the same queues. Where the platform runs one\n * native client per process, every client shares {@link PROCESS_SLOT} instead,\n * so a client of another project is ended as well: its native client stops\n * when the next one starts.\n *\n * Kept on the JavaScript runtime rather than in this module: a module\n * evaluated again in the same runtime (Fast Refresh of linked package sources,\n * or a second copy of the SDK in one bundle) must still find, and end, the\n * client the earlier evaluation started. A new runtime (a full reload) starts\n * empty; the native SDK then retires the client the old runtime left over the\n * same storage.\n */\nconst runtimeState: typeof globalThis & {\n [LIVE_CLIENTS]?: MutableHashMap.MutableHashMap<string, VoidhashClient>;\n} = globalThis;\nconst liveClients = (runtimeState[LIVE_CLIENTS] ??= MutableHashMap.empty());\n\n/** The key in {@link liveClients} of the one client a process can run. */\nconst PROCESS_SLOT = \"process\";\n\n/** How many purchase intents a client holds while no listener is registered; older ones are dropped. */\nconst MAX_HELD_PURCHASE_INTENTS = 10;\n\n/**\n * How many events and screens a client holds while an identity change called\n * before them has not switched the identity yet; older ones are dropped. The\n * same number the native client holds before it starts.\n */\nconst MAX_EVENTS_HELD_FOR_IDENTITY = 100;\n\n/**\n * Whether a value is a string with something besides whitespace. A blank\n * distinct id cannot identify anyone (HTTP trims header values, so it would\n * reach the server as a missing one).\n */\nconst isNonBlankString = (value: unknown): value is string =>\n P.isString(value) && value.trim() !== \"\";\n\nconst encodeProjectSchemaJson = Schema.encodeSync(Schema.fromJsonString(RuntimeSchemaValue));\nconst encodeJson = Schema.encodeUnknownOption(Schema.fromJsonString(Schema.Unknown));\n\n/**\n * Whether a screen, as an integration, `screen()` or `mapScreen` handed it\n * over, has the strings it is tracked by. Types do not guarantee it: a\n * `mapScreen` that looks a title up yields `undefined` for a missing key.\n */\nconst isTrackableScreen = (view: unknown): view is ScreenView =>\n P.hasProperty(view, \"identity\") &&\n P.isString(view.identity) &&\n P.hasProperty(view, \"name\") &&\n P.isString(view.name) &&\n P.hasProperty(view, \"path\") &&\n P.isString(view.path);\n\nconst REPLACEMENT_MODES: ReadonlyArray<SubscriptionReplacementMode> = [\n \"withTimeProration\",\n \"chargeProratedPrice\",\n \"chargeFullPrice\",\n \"withoutProration\",\n \"deferred\",\n];\n\nconst isReplacementMode = (value: unknown): value is SubscriptionReplacementMode =>\n REPLACEMENT_MODES.some((mode) => mode === value);\n\n/**\n * The subscription `purchase()` was asked to replace, as the native client\n * takes it, or an argument error when it names no product or a mode the SDK\n * does not have. Types do not guarantee either.\n */\nconst toNativeReplacement = (\n replacing: SubscriptionReplacement,\n): EffectResult.Result<NativeSubscriptionReplacement, InvalidArgumentError> => {\n const product: unknown = P.hasProperty(replacing, \"product\") ? replacing.product : undefined;\n const productSlug: unknown = P.hasProperty(product, \"slug\") ? product.slug : undefined;\n if (!isNonBlankString(productSlug)) {\n return EffectResult.fail(\n new InvalidArgumentError(\n \"purchase() needs `replacing.product` to be the product being replaced, from getProducts()\",\n ),\n );\n }\n const mode: unknown =\n (P.hasProperty(replacing, \"mode\") ? replacing.mode : undefined) ?? \"withTimeProration\";\n return isReplacementMode(mode)\n ? EffectResult.succeed({ mode, productSlug })\n : EffectResult.fail(\n new InvalidArgumentError(\n `purchase() needs \\`replacing.mode\\` to be one of ${REPLACEMENT_MODES.join(\", \")}${P.isString(mode) ? `, got \"${mode}\"` : \"\"}`,\n ),\n );\n};\n\n/** The offer `purchase()` was asked for, as the native client takes it. */\nconst toNativeOfferSelection = (\n offer: unknown,\n): EffectResult.Result<\n Pick<NativePurchaseOptions, \"offerSelection\" | \"offerId\" | \"offerKind\">,\n InvalidArgumentError\n> => {\n if (offer === undefined || offer === \"automatic\") {\n return EffectResult.succeed({ offerSelection: \"automatic\" });\n }\n if (offer === \"none\") return EffectResult.succeed({ offerSelection: \"regularPrice\" });\n if (isNonBlankString(offer))\n return EffectResult.succeed({ offerId: offer, offerSelection: \"offer\" });\n // An offer from the product names itself by its kind as well: the App Store's introductory\n // offer has no id of its own, so its `id` may be empty.\n const kind: unknown = P.hasProperty(offer, \"kind\") ? offer.kind : undefined;\n const offerKind = Option.filter(\n Option.some(kind),\n (value): value is Exclude<OfferKind, \"unknown\"> =>\n value === \"introductory\" ||\n value === \"promotional\" ||\n value === \"winBack\" ||\n value === \"oneTime\",\n );\n const id: unknown = P.hasProperty(offer, \"id\") ? offer.id : undefined;\n if (P.isString(id) && (Option.isSome(offerKind) || isNonBlankString(id))) {\n return EffectResult.succeed({\n offerId: id,\n offerSelection: \"offer\",\n ...Option.match(offerKind, { onNone: () => ({}), onSome: (value) => ({ offerKind: value }) }),\n });\n }\n return EffectResult.fail(\n new InvalidArgumentError(\n 'purchase() needs `offer` to be \"automatic\", \"none\", an offer of the product or its id',\n ),\n );\n};\n\n/**\n * A purchase's options as the native client takes them, or an argument error\n * for options no store could honour: a quantity that is not a whole number of\n * at least 1, several of anything but an App Store consumable, an offer or a\n * replacement that names nothing. They come from app code, so types guarantee\n * none of it.\n */\nconst toNativePurchaseOptions = (\n product: Product,\n options: PurchaseOptions,\n): EffectResult.Result<NativePurchaseOptions, InvalidArgumentError> => {\n const quantity: unknown = options.quantity ?? 1;\n if (!P.isNumber(quantity) || !Number.isInteger(quantity) || quantity < 1) {\n return EffectResult.fail(\n new InvalidArgumentError(\"purchase() needs `quantity` to be a whole number of at least 1\"),\n );\n }\n if (quantity !== 1 && !(product.store === \"appStore\" && product.type === \"consumable\")) {\n return EffectResult.fail(\n new InvalidArgumentError(\n `purchase() can buy several only of an App Store consumable; \"${product.slug}\" is bought one at a time`,\n ),\n );\n }\n const offer = toNativeOfferSelection(options.offer);\n if (EffectResult.isFailure(offer)) return EffectResult.fail(offer.failure);\n const replacing = Option.map(Option.fromNullishOr(options.replacing), toNativeReplacement);\n if (Option.isSome(replacing) && EffectResult.isFailure(replacing.value)) {\n return EffectResult.fail(replacing.value.failure);\n }\n const { appStore, googlePlay } = options;\n return EffectResult.succeed({\n ...offer.success,\n quantity,\n ...(Option.isSome(replacing) && EffectResult.isSuccess(replacing.value)\n ? { replacing: replacing.value.success }\n : {}),\n ...(appStore?.simulatesAskToBuyInSandbox === undefined\n ? {}\n : { appStore: { simulatesAskToBuyInSandbox: appStore.simulatesAskToBuyInSandbox } }),\n ...(googlePlay === undefined\n ? {}\n : {\n googlePlay: {\n ...(googlePlay.isOfferPersonalized === undefined\n ? {}\n : { isOfferPersonalized: googlePlay.isOfferPersonalized }),\n ...(googlePlay.obfuscatedProfileId === undefined\n ? {}\n : { obfuscatedProfileId: googlePlay.obfuscatedProfileId }),\n ...(googlePlay.offerToken === undefined ? {} : { offerToken: googlePlay.offerToken }),\n },\n }),\n });\n};\n\n/**\n * Why `groups` cannot be set, or `None` when they can: a group's id is a\n * string or a finite number, as the web SDK takes it. Types do not guarantee\n * it, and an id read as text would put the end user in a group named\n * `\"undefined\"`. A type given as `null` or `undefined` is not in the set.\n */\nconst invalidGroups = (groups: Groups): Option.Option<InvalidArgumentError> => {\n const invalidTypes = R.keys(\n R.filter(groups, (group: unknown) => {\n if (P.isNullish(group)) return false;\n const id: unknown = P.hasProperty(group, \"id\") ? group.id : group;\n return !(P.isString(id) || (P.isNumber(id) && Number.isFinite(id)));\n }),\n );\n return Arr.match(invalidTypes, {\n onEmpty: () => Option.none(),\n onNonEmpty: (types) =>\n Option.some(\n new InvalidArgumentError(\n `setGroups() needs each group's id to be a string or a finite number (${types.join(\", \")})`,\n ),\n ),\n });\n};\n\n/** A host report as the native client takes it: the store identifier and, on iOS, its JWS. */\nconst toNativeReport = (report: StoreReport): NativeReportedTransaction =>\n report.platform === \"ios\"\n ? {\n platform: \"appStore\",\n transactionId: report.transactionId,\n ...(report.signedTransaction === undefined\n ? {}\n : { signedTransaction: report.signedTransaction }),\n }\n : {\n platform: \"googlePlay\",\n purchaseToken: report.purchaseToken,\n ...(report.purchaseState === undefined ? {} : { purchaseState: report.purchaseState }),\n };\n\n/**\n * What {@link VoidhashClient} is built from: the options `createVoidhashClient`\n * validated, and where the native client comes from.\n * @internal\n */\nexport interface VoidhashClientSetup {\n readonly publishableKey: string;\n readonly baseUrl: string;\n readonly ingestUrl: Option.Option<string>;\n readonly distinctId: Option.Option<string>;\n readonly scheme: string;\n readonly readOnly: boolean;\n readonly debug: boolean;\n /** `dev: true` in a debug build. */\n readonly developmentMode: boolean;\n readonly enabled: boolean;\n readonly analyticsConsent: AnalyticsConsent;\n readonly analyticsWhilePending: AnalyticsWhilePending;\n readonly grantConsentOnIdentify: boolean;\n readonly automaticLifecycleEvents: boolean;\n readonly installAttribution: boolean;\n readonly metaAppId: Option.Option<string>;\n readonly flowCapabilities: ReadonlyArray<FlowCapability>;\n /** The validated `featureFlags.maxWaitMs`; `None` keeps the native client's default. */\n readonly featureFlagMaxWaitMs: Option.Option<number>;\n /** The validated `featureFlags.defaults`. */\n readonly featureFlagDefaults: Readonly<Record<string, boolean>>;\n readonly flowRuntime: FlowRuntime;\n readonly flowLoading: FlowLoading;\n readonly preloadLocations: ReadonlyArray<string>;\n readonly flowRevisions: Readonly<Record<string, number>>;\n readonly screenTracking: ScreenTrackingOptions;\n readonly internalSchema: Option.Option<RuntimeSchema>;\n readonly unstableSwallowErrors: boolean;\n readonly onDiagnostic: Option.Option<VoidhashDiagnosticHandler>;\n readonly atomRegistry: AtomRegistry.AtomRegistry;\n /** A new native client for this facade, or `None` where the binary has none. */\n readonly createNativeClient: () => Option.Option<NativeClientPort>;\n /**\n * Whether the platform runs one native client per process (Android): starting\n * a client there stops the one running, whatever project it belongs to.\n */\n readonly oneNativeClientPerProcess: boolean;\n /** `Platform.OS`: the `appStore` actions run on `ios` only, the `googlePlay` ones on `android`. */\n readonly platform: string;\n /** The npm package the app installs, which a failure that needs a new native build names. */\n readonly packageName: string;\n readonly appStoreMessages: \"automatic\" | \"deferWhileFlowPresented\";\n readonly purchaseIntents: \"purchaseWhenReady\" | \"manual\";\n}\n\n/**\n * App Store actions, on `client.appStore`. On any other platform each one\n * answers `UNSUPPORTED_PLATFORM`. While the client is disabled the reads\n * answer empty and `beginRefundRequest()` and `appTransaction()`, which have\n * no empty answer, `VOIDHASH_CLIENT_NOT_INITIALIZED`.\n */\nexport interface AppStoreActions {\n /**\n * Shows Apple's refund request sheet for a transaction, by its App Store\n * transaction id (`transaction.id`). `success` means Apple received the\n * request, not that it refunded anything: a refund arrives later and\n * reaches the person's subscriptions and entitlements.\n */\n readonly beginRefundRequest: (\n transactionId: string,\n ) => Promise<Result<RefundRequestStatus, VoidhashError>>;\n /**\n * Every status the Apple account has in an App Store subscription group\n * (`subscription.groupId`), as StoreKit reports them on this device: state,\n * latest transaction and renewal info. The current person's comes first (the\n * one bought for them), then the account's others, ones shared through\n * Family Sharing included. For what the person can use, read their\n * entitlements; the server knows subscriptions across devices and stores,\n * see `useSubscriptions()`.\n */\n readonly subscriptionStatus: (\n groupId: string,\n ) => Promise<Result<ReadonlyArray<AppStoreSubscriptionStatus>, VoidhashError>>;\n /** StoreKit's verified current entitlements on this device. */\n readonly currentEntitlements: () => Promise<Result<ReadonlyArray<Transaction>, VoidhashError>>;\n /** How the end user got the app: StoreKit's verified `AppTransaction`. */\n readonly appTransaction: () => Promise<Result<AppTransaction, VoidhashError>>;\n /**\n * Calls `listener` with each purchase the end user starts on the App Store\n * (a promoted in-app purchase, a win-back offer) while the\n * `purchaseIntents` option is `\"manual\"`; complete it with `purchase()`.\n * Intents that arrived while no listener was registered (they can arrive\n * as soon as `init()` starts) are held, the 10 latest, and handed to the\n * first listener added, at once. Returns the function that removes the\n * listener. Never called on another platform.\n */\n readonly addPurchaseIntentListener: (\n listener: (intent: AppStorePurchaseIntent) => void,\n ) => () => void;\n}\n\n/**\n * Google Play actions, on `client.googlePlay`. On any other platform each one\n * answers `UNSUPPORTED_PLATFORM`. While the client is disabled each answers\n * empty: `noActionNeeded`, no purchases, `false`.\n */\nexport interface GooglePlayActions {\n /**\n * Shows Google Play's in-app messages for the end user's subscriptions,\n * such as a prompt to fix a declined payment. When they fixed it, the\n * answer names the purchase token, and the SDK has synced purchases and\n * refreshed the person.\n */\n readonly showInAppMessages: () => Promise<Result<GooglePlayInAppMessageResult, VoidhashError>>;\n /**\n * The Google Play account's purchases on this device, suspended\n * subscriptions included unless `includeSuspended` is `false`\n * (`transaction.googlePlay.isSuspended`). For what the person can use, read\n * their entitlements.\n */\n readonly queryPurchases: (options?: {\n readonly includeSuspended?: boolean;\n }) => Promise<Result<ReadonlyArray<Transaction>, VoidhashError>>;\n /** Whether Google Play supports a billing feature on this device. */\n readonly isFeatureSupported: (\n feature: GooglePlayBillingFeature,\n ) => Promise<Result<boolean, VoidhashError>>;\n}\n\n/**\n * The Voidhash client: the public facade over the native Voidhash client.\n * Every method answers with a `Result` carrying a coded `VoidhashError`\n * instead of throwing, and a client created with `enabled: false` never\n * touches the native client and answers every read with its empty shape.\n */\nexport class VoidhashClient {\n private readonly setup: VoidhashClientSetup;\n private readonly atomRegistry: AtomRegistry.AtomRegistry;\n private readonly namespace: string;\n /** What this client holds in `liveClients` while it runs: its namespace, or the process. */\n private readonly slot: string;\n private readonly emitDiagnostic: (diagnostic: VoidhashDiagnostic) => void;\n private readonly screenTracker: ScreenTracker;\n private manualScreenCounter = 0;\n /** The send id `trackPushOpened()` reported last. */\n private lastPushOpenedSendId = Option.none<string>();\n /** The native client and its adapter, made on first use. */\n private native = Option.none<NativeClientAdapter>();\n /** Seeds the first `init()` of the process; cleared once applied or by an identity change. */\n private initialDistinctId: Option.Option<string>;\n /** The consent in effect, mirrored from the native client once it runs. */\n private analyticsConsent: AnalyticsConsent;\n /** A consent `setAnalyticsConsent()` chose before `init()`; it wins over the stored one. */\n private chosenAnalyticsConsent = Option.none<AnalyticsConsent>();\n private analyticsConsentDeniedReported = false;\n private readOnly: boolean;\n private _isInitialized = false;\n /** Set by `end()` until the next `init()`. */\n private ended = false;\n /**\n * The `init()` or `end()` called last, until it settles. A call for the\n * same transition joins it and a call for the other one runs after it, so\n * the client ends up in the state asked for last.\n */\n private transition = Option.none<{\n readonly to: \"initialized\" | \"ended\";\n readonly settled: Promise<Result<void, VoidhashError>>;\n }>();\n private flushInFlight = Option.none<Promise<Result<FlushResult, VoidhashError>>>();\n /** The purchase this client runs, until it settles; a second one fails `PURCHASE_IN_PROGRESS`. */\n private purchaseInFlight = Option.none<Promise<Result<PurchaseResult, VoidhashError>>>();\n private identityChangeTail: Promise<void> = Promise.resolve();\n /**\n * The `identify()`, `reset()` and `signOut()` calls made, and how many of\n * them, in call order, have switched the identity or settled without doing\n * so. An event, a screen or a purchase report waits for the ones called\n * before it, so it is recorded for the person the app switched to; see\n * {@link identityChangeSwitched}.\n */\n private identityChangesCalled = 0;\n private identityChangesSwitched = 0;\n /** The identity change the native client is running now, by its number among those called. */\n private identityChangeRunning = Option.none<number>();\n private readonly eventsHeldForIdentity: Array<{\n readonly after: number;\n readonly name: string;\n readonly operation: \"capture\" | \"screen\";\n readonly send: () => void;\n }> = [];\n private readonly reportsHeldForIdentity: Array<{\n readonly after: number;\n readonly proceed: () => void;\n }> = [];\n /**\n * One entry per `addTransactionListener()` call, each its own function, so\n * adding a listener twice calls it twice.\n */\n private readonly transactionListeners =\n MutableHashSet.empty<(update: TransactionUpdate) => void>();\n private readonly purchaseIntentListeners =\n MutableHashSet.empty<(intent: AppStorePurchaseIntent) => void>();\n /**\n * Purchase intents that arrived while no listener was registered (they\n * arrive from `init()` on, before the app may have added one), oldest\n * first, for the first listener the app adds.\n */\n private heldPurchaseIntents: Array<AppStorePurchaseIntent> = [];\n\n /**\n * @internal Not part of the public API: create clients with\n * `createVoidhashClient()`, which validates the options and builds the\n * provider and hooks. The parameters change between releases.\n */\n constructor(setup: VoidhashClientSetup) {\n this.setup = setup;\n this.atomRegistry = setup.atomRegistry;\n this.namespace = buildCacheNamespace(setup.publishableKey, setup.baseUrl);\n this.slot = setup.oneNativeClientPerProcess ? PROCESS_SLOT : this.namespace;\n this.emitDiagnostic = makeDiagnosticEmitter(setup.onDiagnostic);\n this.initialDistinctId = setup.distinctId;\n this.analyticsConsent = setup.analyticsConsent;\n this.readOnly = setup.readOnly;\n const mapScreen = setup.screenTracking.mapScreen;\n this.screenTracker = createScreenTracker({\n enabled: setup.enabled && (setup.screenTracking.enabled ?? true),\n includeParams: setup.screenTracking.includeParams ?? false,\n mapScreen: mapScreen\n ? (view) => {\n // oxlint-disable-next-line effect/avoid-try-catch -- boundary with host application code: `mapScreen` is a plain function the app supplies and may throw anything; the throw must not escape into the navigation listener that reported the screen.\n try {\n const mapped: unknown = mapScreen(view);\n if (P.isNullish(mapped)) return Option.none();\n if (isTrackableScreen(mapped)) return Option.some(mapped);\n this.emitDiagnostic({\n code: \"HOST_CALLBACK_FAILED\",\n kind: \"configuration\",\n message:\n \"screenTracking.mapScreen returned a screen whose identity, name or path is not a string; the screen was tracked unmapped\",\n operation: \"screenTracking.mapScreen\",\n retryable: false,\n });\n return Option.some(view);\n } catch (error) {\n this.reportHostCallbackFailure(\"screenTracking.mapScreen\", error);\n return Option.some(view);\n }\n }\n : undefined,\n });\n }\n\n /** The adapter over this client's native client, created on first use. */\n private nativeClient(): Option.Option<NativeClientAdapter> {\n if (Option.isSome(this.native)) return this.native;\n this.native = Option.map(this.setup.createNativeClient(), (native) =>\n makeNativeClientAdapter({\n atomRegistry: this.atomRegistry,\n native,\n packageName: this.setup.packageName,\n onAnalyticsConsentChanged: (consent) => {\n this.analyticsConsent = consent;\n if (consent === \"granted\") this.analyticsConsentDeniedReported = false;\n },\n // The switch a running identity change made: what waited for it goes on\n // now, not once Voidhash answered the call.\n onIdentitySwitched: () => {\n Option.map(this.identityChangeRunning, (change) => this.identityChangeSwitched(change));\n },\n onDiagnostic: this.emitDiagnostic,\n onPurchaseIntent: (intent) => this.receivePurchaseIntent(intent),\n onTransaction: (update) =>\n this.notify(\"addTransactionListener\", this.transactionListeners, update),\n }),\n );\n return this.native;\n }\n\n /** The configuration the next `start()` runs with. */\n private configuration(): NativeClientConfiguration {\n const setup = this.setup;\n return {\n analyticsConsent: setup.analyticsConsent,\n analyticsWhilePending: setup.analyticsWhilePending,\n appStoreMessages: setup.appStoreMessages,\n automaticLifecycleEvents: setup.automaticLifecycleEvents,\n baseUrl: setup.baseUrl,\n grantConsentOnIdentify: setup.grantConsentOnIdentify,\n debug: setup.debug,\n developmentMode: setup.developmentMode,\n featureFlagDefaults: { ...setup.featureFlagDefaults },\n flowCapabilities: [...setup.flowCapabilities],\n flowRuntime: setup.flowRuntime,\n flowLoading: setup.flowLoading,\n installAttribution: setup.installAttribution,\n flowRevisions: R.collect(setup.flowRevisions, (location, revision) => ({\n location,\n revision,\n })),\n preloadLocations: [...setup.preloadLocations],\n publishableKey: setup.publishableKey,\n purchaseIntents: setup.purchaseIntents,\n readOnly: this.readOnly,\n screenTrackingEnabled: setup.screenTracking.enabled ?? true,\n sdkVersion: SDK_VERSION,\n ...Option.match(this.initialDistinctId, {\n onNone: () => ({}),\n onSome: (distinctId) => ({ distinctId }),\n }),\n ...Option.match(setup.metaAppId, {\n onNone: () => ({}),\n onSome: (metaAppId) => ({ metaAppId }),\n }),\n ...Option.match(this.chosenAnalyticsConsent, {\n onNone: () => ({}),\n onSome: (chosenAnalyticsConsent) => ({ chosenAnalyticsConsent }),\n }),\n ...Option.match(setup.ingestUrl, {\n onNone: () => ({}),\n onSome: (ingestUrl) => ({ ingestUrl }),\n }),\n ...Option.match(setup.featureFlagMaxWaitMs, {\n onNone: () => ({}),\n onSome: (featureFlagMaxWaitMs) => ({ featureFlagMaxWaitMs }),\n }),\n ...Option.match(setup.internalSchema, {\n onNone: () => ({}),\n onSome: (schema) => ({ internalSchemaJson: encodeProjectSchemaJson(schema) }),\n }),\n };\n }\n\n /**\n * The answer of a side-effect call, unless `unstable_swallowErrors` asks for\n * failures to be logged and answered as success.\n */\n private swallowed(\n operation: string,\n result: Result<void, VoidhashError>,\n ): Result<void, VoidhashError> {\n if (result.isErr() && this.setup.unstableSwallowErrors) {\n // oxlint-disable-next-line effect/use-console-service -- the deprecated escape hatch logs what it swallows, outside any runtime.\n console.warn(`[voidhash] swallowed error in ${operation}`, result.error);\n return Result.ok(undefined);\n }\n return result;\n }\n\n /** The started adapter, or `NOT_INITIALIZED`. */\n private started(): Result<NativeClientAdapter, VoidhashError> {\n return this._isInitialized && Option.isSome(this.native)\n ? Result.ok(this.native.value)\n : Result.err(new NotInitializedError());\n }\n\n /**\n * Joins an `init()` in progress or starts one — after `end()` and behind an\n * `end()` still running too — the way identity calls do, so a purchase\n * reported during launch or teardown is not refused.\n */\n private async whenInitialized(): Promise<Result<NativeClientAdapter, VoidhashError>> {\n await this.init();\n return this.started();\n }\n\n /** Runs an `init()` or `end()` as the transition called last. */\n private runTransition(\n to: \"initialized\" | \"ended\",\n run: () => Promise<Result<void, VoidhashError>>,\n ): Promise<Result<void, VoidhashError>> {\n const settled = run().finally(() => {\n if (Option.exists(this.transition, (current) => current.settled === settled)) {\n this.transition = Option.none();\n }\n });\n this.transition = Option.some({ settled, to });\n return settled;\n }\n\n /**\n * The client that took over this client's storage namespace while this one\n * is not running. Identity and purchase calls on a replaced instance go to\n * it: starting this instance again would end the live one. A live client of\n * another project is never a replacement: nothing made for one project is\n * handed to another.\n */\n private replacement(): Option.Option<VoidhashClient> {\n const starting = Option.exists(this.transition, (current) => current.to === \"initialized\");\n if (this._isInitialized || starting) return Option.none();\n return Option.filter(\n MutableHashMap.get(liveClients, this.slot),\n (owner) => owner !== this && owner.namespace === this.namespace,\n );\n }\n\n /**\n * Runs an identity change in call order. Events, screens and purchase\n * reports made after it wait until it switched the identity, which the\n * native client announces at once, before it waits for Voidhash. A change\n * that switches nothing lets them go on when it starts (an `identify()` of\n * `target`, already the identity) or when it settles.\n */\n private enqueueIdentityChange<T>(\n operation: () => Promise<Result<T, VoidhashError>>,\n target: Option.Option<string> = Option.none(),\n ): Promise<Result<T, VoidhashError>> {\n this.initialDistinctId = Option.none();\n this.identityChangesCalled += 1;\n const change = this.identityChangesCalled;\n const settled = this.enqueueInIdentityOrder(() => {\n this.identityChangeRunning = Option.some(change);\n const current = Option.flatMap(this.native, (native) => native.currentDistinctId());\n // With a consent the identify() may still grant, events wait for it to settle.\n if (\n Option.isSome(target) &&\n Option.contains(current, target.value) &&\n this.analyticsConsent === \"granted\"\n ) {\n this.identityChangeSwitched(change);\n }\n return operation();\n });\n const switched = () => {\n // An identity announced from here on is not this change's switch.\n if (Option.contains(this.identityChangeRunning, change)) {\n this.identityChangeRunning = Option.none();\n }\n this.identityChangeSwitched(change);\n };\n void settled.then(switched, switched);\n return settled;\n }\n\n /**\n * Identity change number `change` switched the identity, or will not: sends\n * the events and screens held for it and lets the purchase reports go on.\n * Changes run one at a time, so the ones before it have switched too.\n */\n private identityChangeSwitched(change: number) {\n if (change <= this.identityChangesSwitched) return;\n this.identityChangesSwitched = change;\n const isDue = (held: { readonly after: number }) => held.after <= change;\n const events = this.eventsHeldForIdentity.splice(\n 0,\n this.eventsHeldForIdentity.filter(isDue).length,\n );\n events.forEach((event) => event.send());\n const reports = this.reportsHeldForIdentity.splice(\n 0,\n this.reportsHeldForIdentity.filter(isDue).length,\n );\n reports.forEach((report) => report.proceed());\n }\n\n /** Whether an identity change called before now has not switched the identity yet. */\n private awaitsIdentityChange() {\n return this.identityChangesSwitched < this.identityChangesCalled;\n }\n\n /**\n * Keeps an event or a screen until the identity changes called before it\n * switched the identity, then calls `send` with the time it was captured\n * at. In memory, as the native client holds events before it starts: past\n * {@link MAX_EVENTS_HELD_FOR_IDENTITY} the oldest is dropped and reported.\n */\n private holdEventForIdentity(\n operation: \"capture\" | \"screen\",\n name: string,\n send: (capturedAt: number) => void,\n ) {\n // oxlint-disable-next-line effect/use-clock-service -- the time of the app's call, outside any Effect, as the native client stamps an event it is handed.\n const capturedAt = Date.now();\n this.eventsHeldForIdentity.push({\n after: this.identityChangesCalled,\n name,\n operation,\n // Whether it may be recorded is settled as it is sent: the consent may\n // have changed since, and an `identify()` can grant a pending one.\n send: () => {\n if (Option.isSome(this.analyticsIntake(operation, name))) send(capturedAt);\n },\n });\n if (this.eventsHeldForIdentity.length <= MAX_EVENTS_HELD_FOR_IDENTITY) return;\n Option.map(Option.fromUndefinedOr(this.eventsHeldForIdentity.shift()), (dropped) =>\n this.emitDiagnostic({\n code: \"ANALYTICS_EVENT_DROPPED\",\n kind: \"eviction\",\n message: `Dropped \"${dropped.name}\": more than ${MAX_EVENTS_HELD_FOR_IDENTITY} events were captured while identify(), reset() or signOut() was switching the identity`,\n operation: dropped.operation,\n retryable: false,\n }),\n );\n }\n\n /** Resolves once the identity changes called before now switched the identity. */\n private afterIdentityChanges(): Promise<void> {\n if (!this.awaitsIdentityChange()) return Promise.resolve();\n return new Promise((proceed) => {\n this.reportsHeldForIdentity.push({ after: this.identityChangesCalled, proceed });\n });\n }\n\n /**\n * Runs `operation` once `init()` has settled, after every identity change\n * and group call made before it.\n */\n private enqueueInIdentityOrder<T>(\n operation: () => Promise<Result<T, VoidhashError>>,\n ): Promise<Result<T, VoidhashError>> {\n const next = this.identityChangeTail.then(async () => {\n const initialized = await this.init();\n if (initialized.isErr()) return Result.err(initialized.error);\n return operation();\n });\n this.identityChangeTail = next.then(\n () => undefined,\n () => undefined,\n );\n return next;\n }\n\n /**\n * Starts the native client from local state: identity, caches and queues\n * are loaded without waiting for the network, and the refreshes, store\n * observation and delivery continue in the background. Resolves\n * immediately without touching the native client when the client was\n * created with `enabled: false`.\n *\n * An app launched in the background before the device has been unlocked\n * since it started (on Android, only an app with a `directBootAware`\n * component) cannot read anything the SDK stored, so this waits for that\n * first unlock; events captured meanwhile are kept.\n *\n * Idempotent: a call that overlaps a running `init()` joins it, and a call\n * on an initialized client resolves at once. A call made while `end()` is\n * still running waits for it and then starts the client again, unless\n * another client took over its storage meanwhile: then this one stays ended\n * and the call answers `VOIDHASH_CLIENT_NOT_INITIALIZED`.\n */\n async init(): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const pending = this.transition;\n if (Option.isSome(pending) && pending.value.to === \"initialized\") {\n return pending.value.settled;\n }\n if (Option.isNone(pending) && this._isInitialized) return Result.ok(undefined);\n return this.runTransition(\"initialized\", async () => {\n if (Option.isSome(pending)) {\n await pending.value.settled;\n // A client that took the namespace over meanwhile has asked this one\n // to end, and waits for that. Starting here would in turn wait for\n // that client to end, so neither would ever finish.\n const takenOver = Option.exists(\n MutableHashMap.get(liveClients, this.slot),\n (owner) => owner !== this,\n );\n if (takenOver && Option.exists(this.transition, (current) => current.to === \"ended\")) {\n return Result.err(new NotInitializedError());\n }\n }\n return this.runInit();\n });\n }\n\n private async runInit(): Promise<Result<void, VoidhashError>> {\n await this.claimNamespace();\n const native = this.nativeClient();\n if (Option.isNone(native)) {\n this.releaseNamespace();\n return this.swallowed(\n \"init\",\n Result.err(\n new VoidhashError(\n \"FAILED_TO_INITIALIZE_VOIDHASH_CLIENT\",\n `FAILED_TO_INITIALIZE_VOIDHASH_CLIENT: the Voidhash native module is missing. Rebuild the app after installing ${this.setup.packageName}.`,\n ),\n ),\n );\n }\n const started = await native.value.start(this.configuration());\n if (started.isErr()) {\n this.releaseNamespace();\n return this.swallowed(\"init\", started);\n }\n this.initialDistinctId = Option.none();\n this.chosenAnalyticsConsent = Option.none();\n // A native client that cannot say leaves the consent this facade configured.\n this.analyticsConsent = Option.getOrElse(\n native.value.getAnalyticsConsent(),\n () => this.analyticsConsent,\n );\n this.ended = false;\n this._isInitialized = true;\n // Hooks that loaded for the previous run (an `end()` dropped what it loaded) load again.\n this.atomRegistry.update(clientRunAtom, (runs) => runs + 1);\n return Result.ok(undefined);\n }\n\n /**\n * Makes this client the owner of its storage namespace (of the process,\n * where it runs one native client), ending the client that owned it until\n * now. It is the owner before that client has ended, so identity and\n * purchase calls made on a replaced client of the same namespace meanwhile\n * already go to this one instead of starting the replaced one again.\n */\n private async claimNamespace(): Promise<void> {\n const owner = MutableHashMap.get(liveClients, this.slot);\n MutableHashMap.set(liveClients, this.slot, this);\n if (Option.isNone(owner) || owner.value === this) return;\n if (__DEV__) {\n // oxlint-disable-next-line effect/use-console-service -- development-only guidance for a misconfigured integration, outside any SDK runtime.\n console.warn(\n owner.value.namespace === this.namespace\n ? \"[voidhash] A second client for the same publishable key and base URL replaced the first one. Create the client once, at module scope.\"\n : \"[voidhash] A client for another publishable key or base URL ended the one that was running: Android runs one Voidhash client at a time.\",\n );\n }\n await owner.value.end();\n }\n\n /** Gives up this client's storage namespace, if it still owns it. */\n private releaseNamespace() {\n if (Option.exists(MutableHashMap.get(liveClients, this.slot), (owner) => owner === this)) {\n MutableHashMap.remove(liveClients, this.slot);\n }\n }\n\n /**\n * Ends the client: flushes for at most about two seconds, persists what is\n * still queued and stops every observer, timer and listener. Whatever was\n * not delivered goes out after the next `init()`. An `init()` still running\n * is waited for first. The client stops being initialized as soon as the\n * teardown begins: reads answer `VOIDHASH_CLIENT_NOT_INITIALIZED` from then\n * on. Afterwards `capture()` drops events with a diagnostic and `init()`\n * starts the client again. Overlapping calls share one teardown. No-ops on\n * a disabled client.\n */\n async end(): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const pending = this.transition;\n if (Option.isSome(pending) && pending.value.to === \"ended\") return pending.value.settled;\n return this.runTransition(\"ended\", async () => {\n if (Option.isSome(pending)) await pending.value.settled;\n const started = this.started();\n if (started.isErr()) {\n this.releaseNamespace();\n return Result.err(started.error);\n }\n // Events still waiting for an identity change were captured before this\n // call: the native client takes them now, under the identity in effect,\n // and its shutdown stores them with the rest.\n this.eventsHeldForIdentity.splice(0).forEach((event) => event.send());\n // Not initialized while the native client shuts down: it refuses calls\n // from here on, and an `init()` made meanwhile has to start it again.\n this._isInitialized = false;\n const shutdown = await started.value.shutdown().finally(() => {\n // Torn down whatever the native client answered: a client left\n // half-running would keep owning its storage namespace.\n this.ended = true;\n this.releaseNamespace();\n });\n return shutdown.map(() => undefined);\n });\n }\n\n /** Whether the client is initialized. Always false while the client is disabled. */\n get isInitialized() {\n return this._isInitialized;\n }\n\n /** Whether this client does anything at all, fixed at construction by the `enabled` option. */\n get isEnabled() {\n return this.setup.enabled;\n }\n\n /** Whether the SDK currently runs in observer (\"read-only\") mode. */\n get isReadOnly() {\n return this.readOnly;\n }\n\n /**\n * Switches observer mode at runtime, so an app migrating onto Voidhash can\n * flip from watching another SDK's purchases to owning them without\n * recreating the client. A purchase that already started keeps the mode it\n * started with. No-ops in effect on a disabled client.\n */\n setReadOnly(readOnly: boolean) {\n this.readOnly = readOnly;\n Option.map(this.native, (native) => native.setReadOnly(readOnly));\n }\n\n /**\n * The end user's analytics consent in effect: the last\n * {@link setAnalyticsConsent} value, else (once `init()` has read it) the\n * stored one, else the `analyticsConsent` option.\n */\n getAnalyticsConsent(): AnalyticsConsent {\n return this.analyticsConsent;\n }\n\n /**\n * Records whether the end user consents to usage analytics. Takes effect\n * immediately and is stored on the device, where it takes precedence over\n * the `analyticsConsent` option on later launches; `reset()` and\n * `signOut()` keep it.\n *\n * `\"denied\"` and `\"pending\"` stop all analytics: events, screens, lifecycle\n * and install events and paywall impressions are dropped, and every event\n * still queued on the device is discarded together with the analytics\n * session. Purchases, restores, entitlements, `identify()`, person\n * attributes, groups, feature flags and paywalls are unaffected. `\"granted\"`\n * resumes analytics for what is captured from then on.\n *\n * Called before `init()` the consent applies at once and is stored when\n * `init()` runs. An `Err` with `FAILED_TO_SET_ANALYTICS_CONSENT` means the\n * consent applies to this process but could not be stored; an invalid value\n * is an `INVALID_ARGUMENT` error and changes nothing.\n */\n async setAnalyticsConsent(consent: AnalyticsConsent): Promise<Result<void, VoidhashError>> {\n if (!isAnalyticsConsent(consent)) {\n return Result.err(\n new InvalidArgumentError(\n `setAnalyticsConsent() needs \"granted\", \"denied\" or \"pending\", got ${String(consent)}`,\n ),\n );\n }\n this.analyticsConsent = consent;\n if (consent === \"granted\") this.analyticsConsentDeniedReported = false;\n if (!this.setup.enabled) return Result.ok(undefined);\n if (Option.isSome(this.transition)) await this.transition.value.settled;\n const started = this.started();\n if (started.isErr()) {\n // Stored by the next start, and told to a native client that already\n // holds events captured before it, so a consent other than granted\n // discards them.\n this.chosenAnalyticsConsent = Option.some(consent);\n await Option.match(this.native, {\n onNone: () => Promise.resolve(),\n onSome: (native) => native.setAnalyticsConsent(consent),\n });\n return Result.ok(undefined);\n }\n const stored = await started.value.setAnalyticsConsent(consent);\n if (stored.isErr()) return Result.err(stored.error);\n return stored.value\n ? Result.ok(undefined)\n : Result.err(\n new VoidhashError(\n \"FAILED_TO_SET_ANALYTICS_CONSENT\",\n \"FAILED_TO_SET_ANALYTICS_CONSENT: the consent applies now but could not be stored on the device\",\n ),\n );\n }\n\n /**\n * Returns the current person snapshot together with how much to trust it.\n * The answer comes from cache whenever one exists — a stale entry is served\n * while a refresh runs behind the read — so this never waits long on the\n * network and never fails because the server is unreachable. Pass\n * `{ forceFetch: true }` to prefer the server. Answers an empty snapshot\n * while disabled.\n */\n async getCurrentPerson(\n options: { forceFetch?: boolean } = {},\n ): Promise<Result<CurrentPersonResult, VoidhashError>> {\n if (!this.setup.enabled) {\n return Result.ok({ isExpired: false, isStale: false, person: null, reason: \"no-cache\" });\n }\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.getCurrentPerson(options);\n }\n\n /**\n * Checks whether the current person holds an active grant for a perk.\n *\n * Cache-first: a fresh snapshot answers immediately, a stale one is served\n * while a refresh runs behind the read, and an entitlement granted before\n * the device went offline keeps answering `true`. The result always says how\n * fresh it is (`isStale`, `isExpired`, `reason`) — it never fails because\n * the server is unreachable. Pass `{ forceFetch: true }` to prefer the\n * server.\n */\n async hasPerk(\n perkSlug: PerkSlug,\n options: {\n /**\n * @deprecated No longer read. A stale answer beats no answer, so the\n * cached grant is always served. Branch on `isStale`/`isExpired` in the\n * result instead. Removed in a future release.\n */\n allowStale?: boolean;\n /** Prefer the server, waiting for it before answering. */\n forceFetch?: boolean;\n } = {},\n ): Promise<Result<HasPerkResult, VoidhashError>> {\n if (!this.setup.enabled) {\n return Result.ok({\n hasAccess: false,\n isExpired: false,\n isStale: false,\n reason: \"no-cache\",\n });\n }\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.hasPerk(perkSlug, { forceFetch: options.forceFetch });\n }\n\n /**\n * Sets person attributes without waiting on the network. Reserved\n * `email`/`name` keys map to the dedicated server fields (strings); any\n * other key is a custom trait whose value must be a string, a number, a\n * boolean or `null`. Anything else is an `INVALID_ARGUMENT` error and\n * nothing is written. The update is stored on the device and sent right\n * away, then retried until the server applies it; `flush()` waits for it.\n * Attributes are written whatever the analytics consent, except that the\n * native SDK leaves `$ad_data_sharing` set to anything but `false` out until\n * it is granted: see {@link setAdDataSharing}.\n *\n * Like identity calls, it waits for initialization and runs in call order\n * with `identify()`, `reset()` and `signOut()`, so the attributes belong to\n * the person identified when this was called. Called right after an\n * `identify()` that wasn't awaited, it resolves once that identify settles.\n */\n async setPersonAttributes(attributes: PersonAttributes): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const invalid = invalidPersonAttributes(attributes);\n if (Option.isSome(invalid)) return Result.err(invalid.value);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.setPersonAttributes(attributes);\n return this.enqueueInIdentityOrder(async () => {\n const started = this.started();\n if (started.isErr()) return this.swallowed(\"setPersonAttributes\", Result.err(started.error));\n return this.swallowed(\n \"setPersonAttributes\",\n await started.value.setPersonAttributes(attributes),\n );\n });\n }\n\n /**\n * Records whether the end user agreed to you sharing their purchases with ad\n * platforms, as the person trait `$ad_data_sharing`. Voidhash sends a\n * person's purchases to a Conversions API you turned on only when it is\n * `true`.\n *\n * `true` needs analytics consent: it does nothing while that is not\n * granted. Once written, it also drops a revocation\n * still queued for the person. `false` is a revocation, which analytics\n * consent neither blocks nor discards: the native SDK stores it on the device\n * and retries it until Voidhash has written it, or for 48 hours while Voidhash\n * has no such person, and it records no analytics. When someone rejects\n * everything, call it next to `setAnalyticsConsent(\"denied\")`. Withdrawing\n * analytics consent does not take this back by itself.\n *\n * Waits for initialization and runs in call order with identity changes, as\n * {@link setPersonAttributes} does.\n */\n async setAdDataSharing(granted: boolean): Promise<Result<void, VoidhashError>> {\n return this.setPersonAttributes({ $ad_data_sharing: granted === true });\n }\n\n /**\n * Sets person attributes and reports whether the server confirmed them.\n * When the server cannot confirm the update now (it is unreachable, the key\n * was rejected, or an earlier write for this person is still queued) the\n * update is queued and the result is `deferred` with the last known\n * snapshot, rather than an error. Values, ordering and observer mode follow\n * {@link setPersonAttributes}: attributes are written whatever the analytics\n * consent and whether or not the client is read-only. The result is\n * `skipped` only when the one attribute was an agreement to ad data sharing\n * made without analytics consent: see {@link setAdDataSharing}.\n */\n async setPersonAttributesSync(\n attributes: PersonAttributes,\n ): Promise<Result<SetPersonAttributesResult, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok({ person: null, status: \"disabled\" });\n const invalid = invalidPersonAttributes(attributes);\n if (Option.isSome(invalid)) return Result.err(invalid.value);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.setPersonAttributesSync(attributes);\n return this.enqueueInIdentityOrder(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.setPersonAttributesSync(attributes);\n });\n }\n\n /**\n * Returns the active analytics session id, or `undefined` before `init()`,\n * while disabled, or once the session has been idle past the inactivity\n * timeout. Reading does not extend the session.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK method consumed by non-Effect app code; `undefined` is the documented \"no active session\" answer and mirrors the iOS and Android SDKs.\n getSessionId(): string | undefined {\n const started = this.started();\n return this.setup.enabled && started.isOk() ? started.value.getSessionId() : undefined;\n }\n\n /** Returns the current distinct id, or `Ok(null)` while disabled. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK method consumed by non-Effect app code; `null` is the documented answer of a disabled client.\n async getDistinctId(): Promise<Result<string | null, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(null);\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.getDistinctId();\n }\n\n /**\n * Identifies the user by switching the current distinct id. The switch\n * happens locally first, and the link from the previous (anonymous)\n * identity is stored on the device before it is sent; when the server\n * cannot confirm it now, the link is retried until it lands rather than\n * failing, and an anonymous purchaser keeps their cached access meanwhile.\n * Use {@link identifySync} to learn which of the two happened. Identity\n * calls wait for initialization and run in invocation order. Repeating the\n * same ID without profile changes preserves the session and cached state.\n * A blank ID is an `INVALID_ARGUMENT` error and leaves the identity alone.\n */\n async identify(\n externalUserId: string,\n options: { email?: string; name?: string } = {},\n ): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n if (!isNonBlankString(externalUserId)) {\n return Result.err(new InvalidArgumentError(\"identify() needs a non-blank distinct id\"));\n }\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.identify(externalUserId, options);\n return this.enqueueIdentityChange(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\"identify\", await started.value.identify(externalUserId, options));\n }, Option.some(externalUserId));\n }\n\n /**\n * Identifies the user and reports whether the server confirmed the switch\n * (`confirmed`, with the person) or the device switched locally and queued\n * the link for later delivery (`deferred`, with the last known snapshot\n * for that identity, if any). Only a verdict the Voidhash API will not\n * change — which also restores the previous identity — or a blank ID\n * (`INVALID_ARGUMENT`) is an `Err`.\n */\n async identifySync(\n externalUserId: string,\n options: { email?: string; name?: string } = {},\n ): Promise<Result<IdentifyResult, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok({ person: null, status: \"disabled\" });\n if (!isNonBlankString(externalUserId)) {\n return Result.err(new InvalidArgumentError(\"identifySync() needs a non-blank distinct id\"));\n }\n const replacement = this.replacement();\n if (Option.isSome(replacement)) {\n return replacement.value.identifySync(externalUserId, options);\n }\n return this.enqueueIdentityChange(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.identifySync(externalUserId, options);\n }, Option.some(externalUserId));\n }\n\n /**\n * Starts a fresh visitor: a new anonymous distinct id and analytics session,\n * with no groups. When someone is signed in this is exactly `signOut()`;\n * when nobody is, `signOut()` does nothing and this still starts over, with\n * no event recorded. Use it for a shared device, or a guest starting over.\n */\n async reset(): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.reset();\n return this.enqueueIdentityChange(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\"reset\", await started.value.reset());\n });\n }\n\n /**\n * Signs the current user out: captures the built-in `$sign_out` event\n * (unless automatic lifecycle events are off or analytics consent is not\n * granted), flushes it under the signing-out identity, then resets to a\n * fresh anonymous distinct id and starts a new analytics session. Does\n * nothing when nobody is signed in, so it is safe to call whenever the app\n * finds no session; `reset()` is the call for a fresh anonymous visitor.\n */\n async signOut(): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.signOut();\n return this.enqueueIdentityChange(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\"signOut\", await started.value.signOut());\n });\n }\n\n /**\n * Puts the end user in a group, such as the company or workspace they use\n * your app as part of. Every event captured after the returned promise\n * resolves carries it in `$groups`, until `resetGroups()`, `reset()` or\n * `signOut()`; the native SDK stores it on the device with the distinct id,\n * one group per type.\n *\n * `properties` set the group's own properties, such as its `name` and\n * `plan`: strings, numbers or booleans. They are sent as a `$groupidentify`\n * event when given, or when the end user's group of that type changed.\n * Groups and their properties are sent whatever the analytics consent;\n * without it the `$groupidentify` goes out at once, on its own, and is not\n * retried if it fails.\n *\n * A group type is a lower-case letter followed by up to 63 lower-case\n * letters, digits or underscores, such as `company`, and a key has 1 to 256\n * characters; a number is kept as text. Any other is an `INVALID_ARGUMENT`\n * error. `null` properties count as none. Like identity calls, it waits for initialization and runs in call\n * order with `identify()`, `reset()` and `signOut()`.\n */\n async group(\n groupType: string,\n groupKey: string | number,\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK input from non-Effect app code, where a group without properties is naturally passed as null.\n properties?: GroupProperties | null,\n ): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const key = String(groupKey);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.group(groupType, key, properties);\n return this.enqueueInIdentityOrder(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\n \"group\",\n await started.value.group(groupType, key, Option.fromNullishOr(properties)),\n );\n });\n }\n\n /**\n * Replaces every group the end user is in, in one call: the groups to be in\n * by type, each an id or `{ id, ...properties }`. A type left out, or given\n * as `null` or `undefined`, is dropped. Safe to call whenever the groups\n * might have changed: a `$groupidentify` is sent only for a group whose id\n * or properties differ from what was last sent, so repeating a call sends\n * nothing. An empty object behaves like `resetGroups()`.\n *\n * An id is a string or a finite number. A group given with any other id, or\n * with none, is an `INVALID_ARGUMENT` error for the whole call, and nothing\n * changes. Types and ids otherwise follow the rules of `group()`: a group\n * whose type or id those refuse is left out. Runs in call order with `identify()`, `reset()` and `signOut()`.\n */\n async setGroups(groups: Groups): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.setGroups(groups);\n const invalid = invalidGroups(groups);\n if (Option.isSome(invalid)) return Result.err(invalid.value);\n return this.enqueueInIdentityOrder(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\"setGroups\", await started.value.setGroups(groups));\n });\n }\n\n /** Takes the end user out of every group; later events carry no `$groups`. */\n async resetGroups(): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.resetGroups();\n return this.enqueueInIdentityOrder(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\"resetGroups\", await started.value.resetGroups());\n });\n }\n\n /**\n * The groups the end user belongs to, by group type, as `group()` set them:\n * `{}` before `init()` resolves, while disabled, and when they belong to none.\n */\n getGroups(): Readonly<Record<string, string>> {\n const started = this.started();\n return this.setup.enabled && started.isOk() ? started.value.getGroups() : {};\n }\n\n /**\n * Evaluates feature flags for the current person, cache-first: `flagKeys`\n * (every flag when omitted), each with its enabled state, variant key\n * (`null` without a variant) and payload. Returns no flags while disabled.\n */\n async getFeatureFlags(\n flagKeys?: ReadonlyArray<FeatureFlagKey>,\n ): Promise<Result<FeatureFlagsResult, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(DISABLED_FEATURE_FLAGS);\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.getFeatureFlags(flagKeys);\n }\n\n /**\n * The value of the variant flag `key` selected for the current person: the\n * variant's value when the flag is enabled and evaluated, `null` when it is\n * off, has no variant (or one whose value is not text), is unknown, or was\n * not evaluated within `featureFlags.maxWaitMs`. Evaluates `key`\n * cache-first, as `getFeatureFlags([key])` does. Answers `Ok(null)` while\n * disabled. Typed by the variant values `voidhash.gen.d.ts` lists for the\n * flag; a variant added since generation is not in that union.\n */\n async getVariantValue<K extends FeatureFlagKey>(\n key: K,\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK method consumed by non-Effect app code; `null` is the documented \"no variant\" answer.\n ): Promise<Result<FeatureFlagValue<K> | null, VoidhashError>> {\n const evaluation = await this.getFeatureFlags([key]);\n return evaluation.map(({ flags }) => {\n const flag = flags.find((candidate) => candidate.key === key);\n return flag?.enabled === true && P.isString(flag.payload) ? flag.payload : null;\n });\n }\n\n /**\n * Resolves the currently assigned paywall showing for a location slug.\n * Answers `Ok(null)` while disabled.\n */\n async getPaywallForLocation(\n locationSlug: LocationSlug,\n ): Promise<Result<ResolvedPaywall, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(null);\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.getPaywallForLocation(String(locationSlug));\n }\n\n /**\n * The products the store sells this end user, sorted by slug, with the\n * offers they can buy them with. With `slugs`, the products those slugs\n * name, in that order: `undefined` where the store has none, which the\n * `onDiagnostic` handler hears about as `PRODUCT_NOT_FOUND`. With the types\n * `voidhash-cli types generate` writes, each is typed by its slug, so a\n * subscription's slug is a `SubscriptionProduct`.\n *\n * One load serves every caller and every `useProducts()`; it runs again\n * after an identity change, a completed purchase or new product\n * definitions. Answers no products while disabled.\n */\n getProducts(): Promise<Result<ReadonlyArray<Product>, VoidhashError>>;\n getProducts<const Slugs extends ReadonlyArray<ProductSlug>>(\n slugs: Slugs,\n ): Promise<Result<ProductsForSlugs<Slugs>, VoidhashError>>;\n async getProducts(\n slugs?: ReadonlyArray<ProductSlug>,\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n ): Promise<Result<ReadonlyArray<Product | undefined>, VoidhashError>> {\n if (!this.setup.enabled) {\n return Result.ok(slugs === undefined ? [] : slugs.map(() => undefined));\n }\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return (await started.value.loadProducts()).map((products) =>\n slugs === undefined\n ? products\n : slugs.map((slug) => products.find((product) => product.slug === slug)),\n );\n }\n\n /**\n * Buys a product from `getProducts()` or `useProducts()`. By default a\n * subscription comes with the free trial or introductory price the end\n * user is eligible for; `options.offer` picks another offer or the regular\n * price. Resolves to a `Result`: `purchased`, `pending` and `cancelled` are\n * outcomes, every failure is an `Err` carrying a coded\n * {@link VoidhashError}. Answers `Ok({ status: \"disabled\" })` while\n * disabled.\n *\n * Waits for `init()`. One purchase runs at a time: another started while\n * it runs fails with `PURCHASE_IN_PROGRESS` and buys nothing. Blocked in\n * observer mode; the mode in effect when the purchase starts decides, so a\n * `setReadOnly()` landing later doesn't abandon it. Options no store could\n * honour are an `INVALID_ARGUMENT` error, and nothing is bought.\n */\n async purchase(\n product: Product,\n options: PurchaseOptions = {},\n ): Promise<Result<PurchaseResult, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok({ status: \"disabled\" });\n const slug: unknown = P.hasProperty(product, \"slug\") ? product.slug : undefined;\n if (!isNonBlankString(slug)) {\n return Result.err(\n new InvalidArgumentError(\"purchase() needs a product from getProducts() or useProducts()\"),\n );\n }\n const nativeOptions = toNativePurchaseOptions(product, options);\n if (EffectResult.isFailure(nativeOptions)) return Result.err(nativeOptions.failure);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.purchase(product, options);\n if (Option.isSome(this.purchaseInFlight)) return Result.err(new PurchaseInProgressError());\n const purchased = (async (): Promise<Result<PurchaseResult, VoidhashError>> => {\n const initialized = await this.whenInitialized();\n if (initialized.isErr()) return Result.err(initialized.error);\n if (this.readOnly) return Result.err(new ReadOnlyModePurchaseNotAllowedError());\n return initialized.value.purchase(slug, nativeOptions.success);\n })().finally(() => {\n this.purchaseInFlight = Option.none();\n });\n this.purchaseInFlight = Option.some(purchased);\n return purchased;\n }\n\n /**\n * Revalidates restorable purchases for the user who requested the restore,\n * and answers the refreshed person, `null` when there is none, so a\n * \"nothing to restore\" needs no second read: check the person's\n * entitlements. Call from a user action: iOS may prompt for App Store\n * authentication. Known consumables are excluded. Waits for `init()`;\n * answers `Ok(null)` while disabled.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n async restorePurchases(): Promise<Result<Person | null, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(null);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.restorePurchases();\n const initialized = await this.whenInitialized();\n if (initialized.isErr()) return Result.err(initialized.error);\n const restored = await initialized.value.restorePurchases();\n return restored.isOk()\n ? restored\n : this.swallowed(\"restorePurchases\", Result.err(restored.error)).map(() => null);\n }\n\n /**\n * Calls `listener` with each purchase that completes outside `purchase()`:\n * an approved Ask to Buy, a pending payment that went through, a redeemed\n * offer code, a promoted purchase, and on iOS a renewal seen on the device\n * (`transaction.isRenewal`; Google Play does not report renewals to the\n * device). A purchase or restore made in a flow is not one: `presentFlow()`\n * answers it. It is called once the SDK handled the purchase; `synced`\n * says whether Voidhash already accepted it. A signal for the UI, not a\n * delivery guarantee: access always comes from the person's entitlements,\n * which hooks re-render with. Returns the function that removes the\n * listener. Never called while disabled.\n */\n addTransactionListener(listener: (update: TransactionUpdate) => void): () => void {\n const entry = (update: TransactionUpdate) => listener(update);\n MutableHashSet.add(this.transactionListeners, entry);\n return () => {\n MutableHashSet.remove(this.transactionListeners, entry);\n };\n }\n\n /**\n * Opens the store's subscription management: the App Store's sheet (for\n * `product`'s subscription group, on iOS 17 and later) or Google Play's\n * subscriptions page (for `product`, when given). No-op while disabled.\n */\n async showManageSubscriptions(product?: Product): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\n \"showManageSubscriptions\",\n await started.value.showManageSubscriptions(product?.slug),\n );\n }\n\n /**\n * Lets the end user redeem an offer code: Apple's redemption sheet (where\n * they type the code; `code` is ignored), or Google Play's redeem page\n * filled in with `code`. A redeemed code arrives as a transaction update.\n * No-op while disabled.\n */\n async presentCodeRedemption(code?: string): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\"presentCodeRedemption\", await started.value.presentCodeRedemption(code));\n }\n\n /**\n * The storefront the end user buys from: its ISO 3166-1 alpha-2 country,\n * and currency where the store says. `undefined` when the store has none to\n * give, and while disabled.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n async getStorefront(): Promise<Result<Storefront | undefined, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.getStorefront();\n }\n\n /**\n * Whether this device can make purchases: payments are not restricted (App\n * Store) and billing is available (Google Play). `false` while disabled.\n */\n async canMakePayments(): Promise<Result<boolean, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(false);\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.canMakePayments();\n }\n\n /**\n * Hands a purchase intent to the listeners, or holds it for the first one\n * while there is none: the native client sends intents from `init()` on,\n * possibly before the app added its listener.\n */\n private receivePurchaseIntent(intent: AppStorePurchaseIntent) {\n if (MutableHashSet.size(this.purchaseIntentListeners) > 0) {\n this.notify(\"appStore.addPurchaseIntentListener\", this.purchaseIntentListeners, intent);\n return;\n }\n this.heldPurchaseIntents.push(intent);\n if (this.heldPurchaseIntents.length <= MAX_HELD_PURCHASE_INTENTS) return;\n const dropped = this.heldPurchaseIntents.shift();\n this.emitDiagnostic({\n code: \"PURCHASE_INTENT_DROPPED\",\n kind: \"eviction\",\n message: `Dropped the purchase intent for \"${dropped?.productSlug}\": ${MAX_HELD_PURCHASE_INTENTS} are held until a listener is added`,\n operation: \"appStore.addPurchaseIntentListener\",\n retryable: false,\n });\n }\n\n /** App Store actions; see {@link AppStoreActions}. */\n readonly appStore: AppStoreActions = {\n addPurchaseIntentListener: (listener) => {\n const entry = (intent: AppStorePurchaseIntent) => listener(intent);\n MutableHashSet.add(this.purchaseIntentListeners, entry);\n const held = this.heldPurchaseIntents.splice(0);\n held.forEach((intent) => this.notify(\"appStore.addPurchaseIntentListener\", [entry], intent));\n return () => {\n MutableHashSet.remove(this.purchaseIntentListeners, entry);\n };\n },\n appTransaction: () =>\n this.storeAction(\n \"appStore\",\n \"appTransaction\",\n () => Result.err(new NotInitializedError()),\n (native) => native.appStoreAppTransaction(),\n ),\n beginRefundRequest: (transactionId) =>\n this.storeAction(\n \"appStore\",\n \"beginRefundRequest\",\n () => Result.err(new NotInitializedError()),\n (native) => native.appStoreBeginRefundRequest(transactionId),\n ),\n currentEntitlements: () =>\n this.storeAction(\n \"appStore\",\n \"currentEntitlements\",\n () => Result.ok([]),\n (native) => native.appStoreCurrentEntitlements(),\n ),\n subscriptionStatus: (groupId) =>\n this.storeAction(\n \"appStore\",\n \"subscriptionStatus\",\n () => Result.ok([]),\n (native) => native.appStoreSubscriptionStatus(groupId),\n ),\n };\n\n /** Google Play actions; see {@link GooglePlayActions}. */\n readonly googlePlay: GooglePlayActions = {\n isFeatureSupported: (feature) =>\n this.storeAction(\n \"googlePlay\",\n \"isFeatureSupported\",\n () => Result.ok(false),\n (native) => native.googlePlayIsFeatureSupported(feature),\n ),\n queryPurchases: (options = {}) =>\n this.storeAction(\n \"googlePlay\",\n \"queryPurchases\",\n () => Result.ok([]),\n (native) => native.googlePlayQueryPurchases(options.includeSuspended ?? true),\n ),\n showInAppMessages: () =>\n this.storeAction(\n \"googlePlay\",\n \"showInAppMessages\",\n () => Result.ok({ status: \"noActionNeeded\" }),\n (native) => native.googlePlayShowInAppMessages(),\n ),\n };\n\n /**\n * Runs an action of one store: `UNSUPPORTED_PLATFORM` on the other\n * platform, `whileDisabled` on a disabled client, and\n * `VOIDHASH_CLIENT_NOT_INITIALIZED` before `init()`.\n */\n private async storeAction<A>(\n store: \"appStore\" | \"googlePlay\",\n operation: string,\n whileDisabled: () => Result<A, VoidhashError>,\n run: (native: NativeClientAdapter) => Promise<Result<A, VoidhashError>>,\n ): Promise<Result<A, VoidhashError>> {\n const platform = store === \"appStore\" ? \"ios\" : \"android\";\n if (this.setup.platform !== platform) {\n return Result.err(\n new UnsupportedPlatformError(\n this.setup.platform,\n `${store}.${operation}() is available on ${store === \"appStore\" ? \"iOS\" : \"Android\"} only`,\n ),\n );\n }\n if (!this.setup.enabled) return whileDisabled();\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return run(started.value);\n }\n\n /** Calls every listener with `value`; one that throws is reported and the others still run. */\n private notify<A>(operation: string, listeners: Iterable<(value: A) => void>, value: A) {\n Array.from(listeners).forEach((listener) => {\n // oxlint-disable-next-line effect/avoid-try-catch -- boundary with host application code: the listener is a plain function the app supplies and may throw anything.\n try {\n listener(value);\n } catch (error) {\n this.reportHostCallbackFailure(operation, error);\n }\n });\n }\n\n /**\n * Presents the flow assigned to a location and resolves once it ends, with\n * its `outcome` (`purchased`, `restored`, `dismissed`, or the outcome the\n * flow finished with), its `output` and the `productId` of a purchase.\n *\n * `options.input` are the flow's inputs and `options.actions` a handler per\n * app action the flow can call; a handler that throws or rejects makes the\n * flow run that action's failure path. `options.revision` is the interface\n * revision the app was built against, by default the one the\n * `flowRevisions` option sets for the location.\n *\n * Rejects with a {@link VoidhashError} when the flow cannot be shown; its\n * `code` says why (`FLOW_NOT_ASSIGNED`, `FLOW_UNAVAILABLE`,\n * `FLOW_RENDERER_MISSING`, …).\n *\n * The location's assignment is served from cache when the server cannot be\n * reached. Purchases started from the flow go through the SDK's purchase\n * path, so observer mode blocks them and the flow shows the failure. A flow\n * already on screen is closed first and resolves as `dismissed`.\n */\n presentFlow<const L extends LocationSlug>(\n location: L,\n ...args: PresentFlowArguments<L>\n ): Promise<FlowResult<L>>;\n async presentFlow(location: string, options?: PresentFlowOptions): Promise<FlowResult> {\n if (!this.setup.enabled) throw flowError(\"FLOW_DISABLED\", \"Voidhash is disabled\");\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.presentFlow(location, options);\n const initialized = await this.whenInitialized();\n if (initialized.isErr()) throw flowError(\"FLOW_UNAVAILABLE\", initialized.error.message);\n return initialized.value.presentFlow(location, options);\n }\n\n /**\n * Changes inputs of the flow on screen; inputs that are not named keep\n * their values. No-op when no flow is shown and while disabled.\n */\n updateFlowInput<L extends string = string>(values: Partial<FlowInput<L>>): Promise<void>;\n async updateFlowInput(values: FlowValues): Promise<void> {\n const started = this.started();\n if (!this.setup.enabled || started.isErr()) return;\n await started.value.updateFlowInput(values);\n }\n\n /**\n * Closes the flow on screen, if any; its `presentFlow()` resolves as\n * `dismissed`. No-op while disabled.\n */\n async dismissFlow(): Promise<void> {\n const started = this.started();\n if (!this.setup.enabled || started.isErr()) return;\n await started.value.dismissFlow();\n }\n\n /**\n * Reports a purchase your own billing integration completed: its Apple\n * transaction (ID or JWS) or its Google Play token. Other purchase metadata\n * is optional and discarded. On iOS, a JWS is sent as the device's proof of\n * the purchase; with an ID only, the native SDK reads the JWS from the\n * device's purchase history.\n *\n * The report is a purchase the user just made: it goes to the current\n * user, even when an earlier purchase of the Apple Account or Google account\n * belongs to another user. Voidhash moves a purchase only when the store\n * shows it was made in the last 24 hours, and on iOS only with the JWS;\n * otherwise it is recorded for its current owner. A purchase is claimed\n * once from a device: reporting it again, also after another user signed\n * in, cannot move it.\n *\n * A report made after an `identify()`, `reset()` or `signOut()` that was\n * not awaited goes to the user that call switches to: it waits until the\n * device has switched, not for Voidhash to answer.\n *\n * Does not query, finish, acknowledge or consume the purchase. Pending\n * Android purchases are ignored; report them again when purchased.\n * Delivery failures remain queued for retry, so success does not imply\n * server acceptance.\n */\n async reportTransaction(\n transaction: StoreTransaction,\n options?: {\n /**\n * Reports a transaction your own restore flow returned after the user\n * asked to restore purchases. It is sent as an explicit restore, like\n * `restorePurchases()`, even when Voidhash accepted it before, and\n * keeps that intent across retries and relaunches: the project's paid\n * access sharing setting then decides whether a purchase another user\n * has is shared, moved or kept.\n */\n readonly isRestore?: boolean;\n },\n ): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) {\n return replacement.value.reportTransaction(transaction, options);\n }\n const report = EffectResult.try({\n catch: (error) =>\n new VoidhashError(\n \"FAILED_TO_REPORT_TRANSACTION\",\n `FAILED_TO_REPORT_TRANSACTION: ${P.isError(error) ? error.message : String(error)}`,\n { cause: error },\n ),\n try: () => toNativeReport(fromReportedTransaction(transaction)),\n });\n if (EffectResult.isFailure(report)) {\n return this.swallowed(\"reportTransaction\", Result.err(report.failure));\n }\n await this.afterIdentityChanges();\n const initialized = await this.whenInitialized();\n if (initialized.isErr()) return Result.err(initialized.error);\n return this.swallowed(\n \"reportTransaction\",\n await initialized.value.reportTransaction(report.success, options?.isRestore === true),\n );\n }\n\n /**\n * Reports pending purchases and current store entitlements to Voidhash.\n * Recovery fallback when a host callback exposes no transaction values. Prefer\n * reportTransaction for purchase results, especially consumables already finalized.\n * In observer mode transactions are never finished. Delivery failures stay\n * queued and emit diagnostics; success does not imply server acceptance.\n */\n async syncPurchases(): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.syncPurchases();\n await this.afterIdentityChanges();\n const initialized = await this.whenInitialized();\n if (initialized.isErr()) return Result.err(initialized.error);\n return this.swallowed(\"syncPurchases\", await initialized.value.syncPurchases());\n }\n\n /**\n * Captures a product analytics event.\n * Events are batched and delivered on size/time thresholds. Dropped — not\n * buffered — while disabled or while analytics consent is not granted\n * (unless `analyticsWhilePending` holds them for a pending one).\n * Events captured before `init()` resolves are kept and sent once it has,\n * provided the analytics consent `init()` settles on (the one chosen with\n * `setAnalyticsConsent()`, else the stored one, else the option) is\n * `\"granted\"`; a consent other than `\"granted\"` chosen meanwhile discards them.\n *\n * An event captured after an `identify()`, `reset()` or `signOut()` that\n * was not awaited is recorded for the person that call switches to: it\n * waits, in memory, until the device has switched, not for Voidhash to\n * answer, and keeps the time it was captured at. That is a moment after\n * `identify()`, and up to about two seconds after a `signOut()` or\n * `reset()` of a signed-in user, whose last events are sent first. An\n * identity call runs after the identity, group and person calls made\n * before it have settled, so behind several of those the wait is as long\n * as they take, which on a slow network is seconds each. Past 100 events\n * waiting, the oldest is dropped and reported as `ANALYTICS_EVENT_DROPPED`;\n * `end()` hands the waiting ones over as they are.\n *\n * Property values are copied as the event is captured, into what JSON can\n * hold: a `bigint` is sent as its decimal string, a `Date` as its ISO\n * string, a non-finite number as `null`, and functions, symbols,\n * `undefined` and circular references are left out. An event whose\n * properties cannot be copied at all (more than 10,000 values, or a getter\n * that throws) is dropped and reported as `ANALYTICS_EVENT_DROPPED`. Never\n * throws.\n */\n capture(eventName: string, properties: Record<string, unknown> = {}) {\n if (!this.setup.enabled) return;\n const normalized = P.isString(eventName) ? eventName.trim() : \"\";\n if (!normalized) return;\n if (!this.awaitsIdentityChange()) {\n Option.map(this.analyticsIntake(\"capture\", normalized), (native) =>\n native.capture(normalized, properties),\n );\n return;\n }\n // Copied now and queued once the identity switched.\n const native = this.ended ? Option.none<NativeClientAdapter>() : this.nativeClient();\n if (Option.isNone(native)) {\n this.analyticsIntake(\"capture\", normalized);\n return;\n }\n Option.map(native.value.holdEvent(\"capture\", normalized, properties), (send) =>\n this.holdEventForIdentity(\"capture\", normalized, send),\n );\n }\n\n /**\n * Reports that the end user opened a notification, as `$push_opened` naming\n * its send. Call it from your notification library's opened-notification\n * handler, with the notification's data: the SDK has no notification handling\n * of its own. A notification not sent through Voidhash is ignored, and so is\n * one reported again right after its first report, as a handler that reads\n * the last opened notification on every mount does. Dropped while disabled or\n * while analytics consent is not granted. Never throws.\n */\n trackPushOpened(data?: Readonly<Record<string, unknown>>) {\n const sendId = data?.[PUSH_SEND_ID_DATA_KEY];\n if (!P.isString(sendId) || sendId.trim() === \"\") return;\n if (Option.contains(this.lastPushOpenedSendId, sendId)) return;\n this.lastPushOpenedSendId = Option.some(sendId);\n this.capture(AUTOMATIC_EVENTS.PUSH_OPENED, { [PUSH_SEND_ID_PROPERTY]: sendId });\n }\n\n /**\n * The native client an event for `name` can be handed to, or `None` when it\n * is dropped: without consent (reported once) unless the native client\n * holds it for a pending one, after `end()`, or without\n * the native module (each reported).\n *\n * Before the client has started only the native client can know the consent\n * stored on the device, so the event is handed over for it to keep or\n * discard at start, whatever the `analyticsConsent` option says. A consent\n * `setAnalyticsConsent()` chose in this process is the exception: it wins\n * over the stored one, so it decides here already.\n */\n private analyticsIntake(\n operation: \"capture\" | \"screen\",\n name: string,\n ): Option.Option<NativeClientAdapter> {\n const known = this._isInitialized\n ? Option.some(this.analyticsConsent)\n : this.chosenAnalyticsConsent;\n const isRefused = Option.exists(\n known,\n (consent) =>\n consent !== \"granted\" &&\n !(consent === \"pending\" && this.setup.analyticsWhilePending === \"buffer\"),\n );\n if (isRefused) {\n this.reportAnalyticsConsentDenied(operation);\n return Option.none();\n }\n const native = this.ended ? Option.none<NativeClientAdapter>() : this.nativeClient();\n if (Option.isNone(native)) {\n this.emitDiagnostic({\n code: \"ANALYTICS_EVENT_DROPPED\",\n kind: \"eviction\",\n message: this.ended\n ? `Dropped \"${name}\" — captured after end()`\n : `Dropped \"${name}\" — the Voidhash native module is missing`,\n operation,\n retryable: false,\n });\n }\n return native;\n }\n\n /**\n * Captures a `$screen` event for a screen the SDK cannot observe itself\n * (custom navigation, onboarding steps, pager pages). Every call is a new\n * screen instance, so calling it twice with the same name emits twice.\n * No-op while disabled or when `screenTracking.enabled` is `false`. Never\n * throws: a screen whose name is not a string, or that cannot be read, is\n * dropped and reported as `ANALYTICS_EVENT_DROPPED`.\n */\n screen(name: string, properties: Record<string, unknown> = {}) {\n this.manualScreenCounter += 1;\n // A name that is not a string is dropped below; it is kept out of the\n // identity because not every value has a text form.\n const identity = `${P.isString(name) ? name : \"\"}#${this.manualScreenCounter}`;\n this.trackScreenView({ identity, name, path: name, source: \"manual\" }, properties);\n }\n\n /**\n * Feeds a screen arrival observed by an integration through the screen\n * tracker and captures `$screen` when it is a new screen instance. Whether\n * the event may be recorded is settled first: a screen seen without consent\n * neither runs `mapScreen` nor becomes the previous screen of a later one.\n * Never throws: it runs inside the host's navigation listeners and effects, so a\n * screen that cannot be tracked is dropped and reported instead.\n * @internal\n */\n trackScreenView(view: ScreenView, properties: Record<string, unknown> = {}) {\n if (!this.setup.enabled || this.setup.screenTracking.enabled === false) return;\n const failure = isTrackableScreen(view)\n ? Option.map(\n EffectResult.getFailure(\n EffectResult.try(() => {\n const native = this.analyticsIntake(\"screen\", view.name);\n if (Option.isNone(native)) return;\n const screenProperties = this.screenTracker.transition(view);\n if (Option.isNone(screenProperties)) return;\n // The tracker applied `mapScreen` and the include-params rule; the native\n // client records `$screen` with these properties as they are.\n const mappedName = screenProperties.value[SCREEN_PROPERTIES.NAME];\n const screenName = P.isString(mappedName) ? mappedName : view.name;\n const recorded = { ...properties, ...screenProperties.value };\n if (!this.awaitsIdentityChange()) {\n native.value.screen(screenName, recorded);\n return;\n }\n Option.map(native.value.holdEvent(\"screen\", screenName, recorded), (send) =>\n this.holdEventForIdentity(\"screen\", screenName, send),\n );\n }),\n ),\n (error) => (P.isError(error) ? error.message : \"it could not be read\"),\n )\n : Option.some(\"its identity, name or path is not a string\");\n if (Option.isSome(failure)) {\n this.emitDiagnostic({\n code: \"ANALYTICS_EVENT_DROPPED\",\n kind: \"eviction\",\n message: `Dropped a screen: ${failure.value}`,\n operation: \"screen\",\n retryable: false,\n });\n }\n }\n\n /**\n * Sends everything queued now: person writes (`identify()` links and\n * attributes) first, then store receipts and analytics events, and reports\n * the analytics outcome. Waits at most about two seconds; delivery goes on\n * past that. Events still waiting for an identity change to switch the\n * person are sent too: the flush starts once it has. Nothing is ever queued\n * while disabled, so this no-ops.\n */\n async flush(): Promise<Result<FlushResult, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok({ flushed: 0, pending: 0 });\n if (this.awaitsIdentityChange()) await this.afterIdentityChanges();\n if (Option.isSome(this.flushInFlight)) return this.flushInFlight.value;\n const started = this.started();\n if (started.isErr()) return Result.ok({ flushed: 0, pending: 0 });\n const inFlight = started.value.flush().finally(() => {\n this.flushInFlight = Option.none();\n });\n this.flushInFlight = Option.some(inFlight);\n return inFlight;\n }\n\n /** Clears the cached person snapshot. The next read refetches from the server. */\n async resetCache(): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const started = this.started();\n if (started.isErr()) return this.swallowed(\"resetCache\", Result.err(started.error));\n return this.swallowed(\"resetCache\", await started.value.resetCache());\n }\n\n /**\n * Internal surface used by the SDK's React bindings.\n * Not part of the public API — may change or disappear at any time.\n */\n readonly internal = {\n getAtomRegistry: () => this.atomRegistry,\n /** What flag `key` reads as while it has no evaluated value: its `featureFlags.defaults` entry, or `false`. */\n isFeatureEnabledByDefault: (key: string): boolean =>\n Option.getOrElse(R.get(this.setup.featureFlagDefaults, key), () => false),\n /**\n * What a purchase of `product` with `options` buys, as text: two\n * purchases with the same key buy the same product the same way. `None`\n * for options `purchase()` refuses.\n */\n purchaseKey: (product: Product, options: PurchaseOptions): Option.Option<string> =>\n Option.flatMap(EffectResult.getSuccess(toNativePurchaseOptions(product, options)), (native) =>\n encodeJson({ ...native, productSlug: product.slug }),\n ),\n getSchema: (): Option.Option<RuntimeSchema> =>\n this._isInitialized ? this.atomRegistry.get(schemaAtom) : Option.none(),\n getSuccessCallbackBaseUrl: () => `${this.setup.scheme}://voidhash/callback/success`,\n getErrorCallbackBaseUrl: () => `${this.setup.scheme}://voidhash/callback/error`,\n reportHostCallbackFailure: (operation: string, error: unknown) =>\n this.reportHostCallbackFailure(operation, error),\n };\n\n /** Reports an exception a callback the app supplied threw; the SDK carried on without it. */\n private reportHostCallbackFailure(operation: string, error: unknown) {\n this.emitDiagnostic({\n code: \"HOST_CALLBACK_FAILED\",\n kind: \"configuration\",\n message: `${operation} threw: ${P.isError(error) ? error.message : String(error)}`,\n operation,\n retryable: false,\n });\n }\n\n /**\n * Reports, once until consent is granted again, that analytics work was\n * skipped for lack of consent.\n */\n private reportAnalyticsConsentDenied(operation: string) {\n if (this.analyticsConsentDeniedReported) return;\n this.analyticsConsentDeniedReported = true;\n this.emitDiagnostic({\n code: \"ANALYTICS_CONSENT_DENIED\",\n kind: \"consent\",\n message: `Skipped ${operation}: analytics consent is \"${this.analyticsConsent}\", so no analytics are captured or sent until it is granted`,\n operation,\n retryable: false,\n });\n }\n}\n\n/** Convenience re-export to keep `ProductSlug` reachable from this module. */\nexport type { ProductSlug };\nexport type { AnalyticsConsent };\n","/**\n * Names of analytics events the SDK captures automatically on the user's\n * behalf. The leading `$` marks them as built-in/reserved — mirroring the\n * convention used for standardized properties (`$app_version`, `$platform`,\n * …) — so they can be told apart from custom product events captured via\n * `capture(...)`.\n */\nexport const AUTOMATIC_EVENTS = {\n /** First launch the SDK has seen on this install (no cached release). */\n APP_INSTALLED: \"$app_installed\",\n /** Launch where the app build/version differs from the last seen one. */\n APP_UPDATED: \"$app_updated\",\n /** Every SDK startup, after install/update has been resolved. */\n APP_OPENED: \"$app_opened\",\n /** App moved to the background. */\n APP_BACKGROUNDED: \"$app_backgrounded\",\n /** App returned to the foreground from a non-active state. */\n APP_BECAME_ACTIVE: \"$app_became_active\",\n /** The app ended in a crash the system recorded, reported natively at a later launch. */\n APP_CRASHED: \"$app_crashed\",\n /** User signed out (identity reset triggered via `signOut`). */\n SIGN_OUT: \"$sign_out\",\n /** The user arrived on a screen (route, view controller, activity, …). */\n SCREEN: \"$screen\",\n /** The user opened a notification sent through Voidhash; see `client.trackPushOpened()`. */\n PUSH_OPENED: \"$push_opened\",\n} as const;\n\n/** The custom data key Voidhash adds to every notification it sends, holding its send's id. */\nexport const PUSH_SEND_ID_DATA_KEY = \"voidhash_send_id\";\n\n/** The `$push_opened` property naming the send. */\nexport const PUSH_SEND_ID_PROPERTY = \"push_notification_send_id\";\n\n/**\n * Property names stamped on the built-in `$screen` event. The `$` prefix\n * marks them as reserved, next to the standardized `$app_version`-style\n * properties every event carries.\n */\nexport const SCREEN_PROPERTIES = {\n /** Stable, low-cardinality identity of the screen (route pattern, route or class name). */\n NAME: \"$screen_name\",\n /** Concrete location, including dynamic segment values where the router has them. */\n PATH: \"$screen_path\",\n /** Human title when the platform exposes one. */\n TITLE: \"$screen_title\",\n /** `$screen_name` of the screen the user came from; `null` for the first screen. */\n PREVIOUS_NAME: \"$previous_screen_name\",\n /** `$screen_path` of the screen the user came from; `null` for the first screen. */\n PREVIOUS_PATH: \"$previous_screen_path\",\n /** Wall-clock milliseconds spent on the previous screen; `null` for the first screen. */\n PREVIOUS_DURATION_MS: \"$previous_screen_duration_ms\",\n /** Integration that produced the event (`expo-router`, `react-navigation`, `manual`, …). */\n SOURCE: \"$screen_source\",\n /** Route params, string-coerced and capped at 20 keys. Only with `includeParams`. */\n PARAMS: \"$screen_params\",\n} as const;\n","import * as Arr from \"effect/Array\";\n\n/**\n * Version of the on-device cache layout. Bumping it moves every entry to a new\n * namespace, so a future SDK release can change the envelope or key scheme\n * without having to recognise and migrate old entries one by one.\n */\nexport const CACHE_SCHEMA_VERSION = 1;\n\n/**\n * FNV-1a, 32-bit, over the UTF-8 bytes of `value`. Small, dependency-free and\n * stable across JS engines; the same digest the native SDKs derive, so the\n * embedded native client and this SDK land in one namespace on a device.\n */\nexport const hashCacheNamespace = (value: string) =>\n (\n Arr.reduce(Array.from(new TextEncoder().encode(value)), 0x811c9dc5, (hash, byte) =>\n Math.imul(hash ^ byte, 0x01000193),\n ) >>> 0\n )\n .toString(16)\n .padStart(8, \"0\");\n\n/**\n * Builds the storage-key prefix for one project on one host:\n * `vh:<cacheSchemaVersion>:<hash(publishableKey + baseUrl)>:`.\n *\n * Namespacing matters because on iOS the SDK's cache entries live in\n * `UserDefaults.standard`, which the host app also uses: unprefixed keys can\n * collide with the app's own. Keying by publishable key and base URL\n * additionally keeps a staging build's cache from being read by a production\n * one, on both platforms. The queues' record files are named after the same\n * namespace.\n */\nexport const buildCacheNamespace = (publishableKey: string, baseUrl: string) =>\n `vh:${CACHE_SCHEMA_VERSION}:${hashCacheNamespace(`${publishableKey}|${baseUrl}`)}:`;\n","{\n \"name\": \"@voidhash/react-native\",\n \"version\": \"0.4.0\",\n \"private\": false,\n \"description\": \"Voidhash React Native SDK for in-app purchases.\",\n \"keywords\": [\n \"expo\",\n \"nitro\",\n \"payments\",\n \"react-native\",\n \"sdk\",\n \"voidhash\"\n ],\n \"homepage\": \"https://voidhash.com/docs\",\n \"bugs\": {\n \"url\": \"https://github.com/voidhashcom/voidhash/issues\"\n },\n \"license\": \"MIT\",\n \"author\": \"Voidhash (https://voidhash.com)\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/voidhashcom/voidhash\",\n \"directory\": \"libraries/react-native\"\n },\n \"source\": \"src/index\",\n \"files\": [\n \"*.podspec\",\n \"app.plugin.js\",\n \"build\",\n \"nitrogen\",\n \"plugin/build\",\n \"react-native.config.js\",\n \"README.md\",\n \"src\",\n \"android/build.gradle\",\n \"android/CMakeLists.txt\",\n \"android/consumer-rules.pro\",\n \"android/gradle.properties\",\n \"android/src\",\n \"ios/**/*.cpp\",\n \"ios/**/*.h\",\n \"ios/**/*.m\",\n \"ios/**/*.mm\",\n \"ios/**/*.swift\"\n ],\n \"main\": \"build/index\",\n \"module\": \"build/index\",\n \"types\": \"build/index.d.ts\",\n \"react-native\": \"src/index\",\n \"exports\": {\n \"./app.plugin.js\": \"./app.plugin.js\",\n \"./package.json\": \"./package.json\",\n \"./expo-router\": {\n \"types\": \"./build/expo-router.d.ts\",\n \"react-native\": \"./src/expo-router.tsx\",\n \"default\": \"./build/expo-router.js\"\n },\n \"./metro\": {\n \"types\": \"./build/metro/index.d.ts\",\n \"node\": \"./build/metro/index.js\"\n },\n \"./react-navigation\": {\n \"types\": \"./build/react-navigation.d.ts\",\n \"react-native\": \"./src/react-navigation.tsx\",\n \"default\": \"./build/react-navigation.js\"\n },\n \".\": {\n \"types\": \"./build/index.d.ts\",\n \"react-native\": \"./src/index.ts\",\n \"default\": \"./build/index.js\"\n }\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n },\n \"scripts\": {\n \"typecheck\": \"tsrs --noEmit -p tsconfig.json\",\n \"test:types\": \"tsrs -p tests/types/tsconfig.sdk.json && tsrs --noEmit -p tests/types/tsconfig.json && tsrs --noEmit -p tests/types/untyped/tsconfig.json\",\n \"build\": \"expo-module build && tsrs -p tsconfig.metro.json && tsrs -p plugin/tsconfig.json && vp fmt plugin/build\",\n \"test\": \"vp test run -c vitest.unit.mts && pnpm run test:types\",\n \"test:artifact\": \"node ../../scripts/smoke-react-native-artifact.mjs\",\n \"test:android-engine\": \"ANDROID_HOME=\\\"${ANDROID_HOME:-$HOME/Library/Android/sdk}\\\" \\\"$(node -p \\\"require('node:path').dirname(require.resolve('@react-native/gradle-plugin/package.json'))\\\")/gradlew\\\" -p ../android :react-native-engine-tests:testDebugUnitTest --no-daemon\",\n \"test:android-purchase-coordinator\": \"\\\"$(node -p \\\"require('node:path').dirname(require.resolve('@react-native/gradle-plugin/package.json'))\\\")/gradlew\\\" -p android/coordinator-tests test --no-daemon\",\n \"test:storekit-purchase-coordinator\": \"swift test --package-path .\",\n \"test:storekit-simulator\": \"bash ios-storekit-tests/run-tests.sh\",\n \"clean\": \"rm -rf android/build node_modules/**/android/build lib\",\n \"lint\": \"vp check\",\n \"lint-ci\": \"vp check\",\n \"format\": \"vp check --fix\",\n \"typescript\": \"tsrs -p tsconfig.test.json --noEmit\",\n \"specs\": \"pnpm run typescript && nitrogen --logLevel=\\\"debug\\\"\"\n },\n \"dependencies\": {\n \"better-result\": \"3.0.1\",\n \"pathe\": \"^2.0.3\"\n },\n \"devDependencies\": {\n \"@effect/platform-node\": \"catalog:\",\n \"@effect/vitest\": \"catalog:\",\n \"@react-navigation/native\": \"^7.3.17\",\n \"@srsholmes/vitest-react-native\": \"^0.1.5\",\n \"@types/node\": \"^24.0.12\",\n \"@types/react\": \"~19.1.10\",\n \"@vitejs/plugin-react\": \"catalog:\",\n \"@voidhash/generated-clients\": \"workspace:*\",\n \"@voidhash/shared\": \"workspace:*\",\n \"expo\": \"54.0.33\",\n \"expo-module-scripts\": \"^5.0.8\",\n \"expo-router\": \"~55.0.18\",\n \"nitrogen\": \"0.37.1\",\n \"react\": \"19.1.0\",\n \"react-native\": \"0.81.5\",\n \"react-native-nitro-modules\": \"0.37.1\",\n \"typescript\": \"5.9.3\",\n \"vite-tsconfig-paths\": \"catalog:\",\n \"vitest\": \"catalog:\"\n },\n \"peerDependencies\": {\n \"@react-navigation/native\": \"*\",\n \"effect\": \"^4.0.7\",\n \"expo\": \"*\",\n \"expo-router\": \"*\",\n \"react\": \"*\",\n \"react-native\": \"*\",\n \"react-native-nitro-modules\": \"^0.37.1\"\n },\n \"peerDependenciesMeta\": {\n \"@react-navigation/native\": {\n \"optional\": true\n },\n \"expo\": {\n \"optional\": true\n },\n \"expo-router\": {\n \"optional\": true\n }\n },\n \"packageManager\": \"pnpm@10.19.0\"\n}\n","// A named import, so a bundler keeps just the version, not the whole manifest.\nimport { version } from \"../../package.json\";\n\n/** The published package version, reported as `x-sdk-version` and `$sdk_version`. */\nexport const SDK_VERSION: string = version;\n","import * as Option from \"effect/Option\";\n\n/**\n * Coarse category of a diagnostic, so hosts can route to logging versus\n * alerting without matching on individual codes.\n */\nexport type VoidhashDiagnosticKind =\n | \"transport\"\n | \"eviction\"\n | \"breaker\"\n | \"auth\"\n | \"cache\"\n | \"configuration\"\n | \"consent\";\n\n/**\n * A non-fatal event the SDK handled on its own. Diagnostics are informational:\n * every one of them describes a situation the SDK already recovered from\n * (retry scheduled, cache served, event evicted). They never require the host\n * app to act.\n */\nexport interface VoidhashDiagnostic {\n /** Category used for routing (logging vs. alerting). */\n readonly kind: VoidhashDiagnosticKind;\n /** Stable, machine-matchable identifier — see {@link DIAGNOSTIC_CODES}. */\n readonly code: string;\n /** SDK operation that produced the diagnostic (`capture`, `getPerson`, …). */\n readonly operation: string;\n /** Whether the SDK will try the same work again on its own. */\n readonly retryable: boolean;\n /** HTTP status behind the diagnostic, when there was a response. */\n readonly httpStatus?: number;\n /** Human-readable detail. Not stable; do not parse. */\n readonly message?: string;\n}\n\n/** Stable diagnostic codes emitted by the SDK. */\nexport const DIAGNOSTIC_CODES = {\n /**\n * An analytics event was dropped: evicted because the queue hit its cap,\n * refused by the ingest API with a verdict re-sending cannot change, or\n * captured with properties that could not be copied into JSON.\n */\n ANALYTICS_EVENT_DROPPED: \"ANALYTICS_EVENT_DROPPED\",\n /**\n * Analytics work (an event, a screen, an opened notification) was skipped\n * because analytics consent is not granted. Reported once until consent is\n * granted again.\n */\n ANALYTICS_CONSENT_DENIED: \"ANALYTICS_CONSENT_DENIED\",\n /** The publishable key was rejected; outbound traffic is paused. */\n AUTHENTICATION_FAILED: \"AUTHENTICATION_FAILED\",\n /** The store could not say which ad brought the install yet; a later launch asks again. */\n INSTALL_ATTRIBUTION_DEFERRED: \"INSTALL_ATTRIBUTION_DEFERRED\",\n /** The SDK stopped asking the store which ad brought the install, without an answer. */\n INSTALL_ATTRIBUTION_ABANDONED: \"INSTALL_ATTRIBUTION_ABANDONED\",\n /**\n * Device storage could not be read, or a stored entry could not be decoded.\n * An unreadable value counts as unknown, never as absent: the SDK does not\n * overwrite it. A corrupt entry is discarded and treated as a miss.\n */\n CACHE_READ_FAILED: \"CACHE_READ_FAILED\",\n /** A write to device storage failed; the value is still held in memory. */\n CACHE_WRITE_FAILED: \"CACHE_WRITE_FAILED\",\n /**\n * @deprecated No longer emitted: the SDK has no pre-namespace entries to\n * migrate. Kept so handlers that match on it still compile.\n */\n CACHE_MIGRATION_FAILED: \"CACHE_MIGRATION_FAILED\",\n /** The breaker for a host is open, so the request was skipped. */\n CIRCUIT_OPEN: \"CIRCUIT_OPEN\",\n /**\n * A callback the app handed the SDK threw (a `usePurchase` callback,\n * `screenTracking.mapScreen`, the `connectivity` source). The SDK carried on\n * without it: the purchase kept its result, the screen was tracked unmapped.\n */\n HOST_CALLBACK_FAILED: \"HOST_CALLBACK_FAILED\",\n /** A client option was invalid and the SDK fell back to its default (release builds only). */\n INVALID_CONFIGURATION: \"INVALID_CONFIGURATION\",\n /** A request failed and the SDK fell back to cache or a retry. */\n REQUEST_FAILED: \"REQUEST_FAILED\",\n /** A request exceeded the per-attempt timeout. */\n REQUEST_TIMEOUT: \"REQUEST_TIMEOUT\",\n /** A background task the SDK owns failed outright. */\n BACKGROUND_TASK_FAILED: \"BACKGROUND_TASK_FAILED\",\n /**\n * A product, perk or paywall location in the project schema could not be\n * read by this SDK version and was left out. Every other entry is still\n * served; updating the SDK makes the entry available.\n */\n SCHEMA_ENTRY_SKIPPED: \"SCHEMA_ENTRY_SKIPPED\",\n /**\n * A queued `identify` or person-attribute write was dropped because the\n * Voidhash API refused it with a verdict re-sending cannot change.\n */\n PERSON_WRITE_REJECTED: \"PERSON_WRITE_REJECTED\",\n /**\n * A product the project defines was not returned by the store, so\n * `getProducts()` and `useProducts()` leave it out. Reported once per\n * product per load; the message names its slug and the store's reason.\n * Check the store product id in Studio and the product's state in App Store\n * Connect or the Play Console.\n */\n PRODUCT_NOT_FOUND: \"PRODUCT_NOT_FOUND\",\n /**\n * The store sells a product as another type than Studio, such as a Studio\n * subscription the App Store sells as a non-renewing one or Google Play as\n * an in-app product, so `getProducts()` and `useProducts()` leave it out.\n * The message names its slug and both types.\n */\n PRODUCT_TYPE_MISMATCH: \"PRODUCT_TYPE_MISMATCH\",\n /**\n * iOS, with `purchaseIntents: \"manual\"`: more App Store purchase intents\n * arrived before any `appStore.addPurchaseIntentListener()` than the SDK\n * holds for it (10), so the oldest was dropped. The end user can start that\n * purchase again on the App Store.\n */\n PURCHASE_INTENT_DROPPED: \"PURCHASE_INTENT_DROPPED\",\n /** A queued transaction receipt was discarded as unsendable. */\n TRANSACTION_RECEIPT_DROPPED: \"TRANSACTION_RECEIPT_DROPPED\",\n /**\n * The Voidhash API refused a store receipt with a verdict re-sending cannot\n * change on its own: the store is not configured for this app, or the\n * transaction is unknown or belongs to another environment. The receipt\n * stays queued and is sent again at the next launch or after six hours.\n * Reported once per receipt.\n */\n TRANSACTION_REJECTED: \"TRANSACTION_REJECTED\",\n /**\n * Android: a purchase the SDK started was still not recorded by Voidhash 48\n * hours after its payment went through, so the background check acknowledged\n * it on the device before Google Play refunds it. The SDK still holds the\n * receipt and delivers it.\n */\n PURCHASE_FINISHED_BEFORE_SYNC: \"PURCHASE_FINISHED_BEFORE_SYNC\",\n /** A transaction receipt is waiting in the outbox for a successful sync. */\n TRANSACTION_SYNC_DEFERRED: \"TRANSACTION_SYNC_DEFERRED\",\n /**\n * iOS: what an earlier release of this package stored on the device was not\n * carried over, because the storage it was kept under doesn't match the\n * configured base URL. Reported once per start.\n */\n LEGACY_IMPORT_SKIPPED: \"LEGACY_IMPORT_SKIPPED\",\n} as const;\n\n/** Handler supplied through the `onDiagnostic` client option. */\n// oxlint-disable-next-line effect/prefer-option-over-null -- public SDK option consumed by non-Effect app code.\nexport type VoidhashDiagnosticHandler = (diagnostic: VoidhashDiagnostic) => void;\n\n/** Delivers diagnostics to an optional host handler, swallowing whatever it throws. */\nexport const makeDiagnosticEmitter =\n (handler: Option.Option<VoidhashDiagnosticHandler>) => (diagnostic: VoidhashDiagnostic) => {\n if (Option.isNone(handler)) return;\n // oxlint-disable-next-line effect/avoid-try-catch -- boundary with host application code: the handler is a plain callback the app supplies and may throw anything.\n try {\n handler.value(diagnostic);\n } catch {\n // A throwing host handler is never allowed to fail the SDK operation\n // that emitted the diagnostic.\n }\n };\n","import { Base64Url } from \"effect/encoding\";\nimport * as Result from \"effect/Result\";\nimport * as P from \"effect/Predicate\";\nimport * as Schema from \"effect/Schema\";\n\n/** Only the store identifier is required. Legacy metadata is accepted but discarded. */\nexport type ReportedTransaction = {\n productId?: string;\n purchaseDate?: number;\n quantity?: number;\n receipt?: string;\n appAccountToken?: string;\n} & (\n | { platform: \"ios\"; transactionId: string }\n | {\n platform: \"android\";\n purchaseToken: string;\n transactionId?: string;\n /** If supplied, pending/unspecified purchases are ignored until reported as purchased. */\n purchaseState?: \"purchased\" | \"pending\" | \"unspecified\";\n }\n);\n\n/** Original bridge data accepted as a convenience; only the token and state are read. */\nexport interface GooglePlayPurchaseData {\n readonly originalJson: string;\n readonly signature?: string;\n}\n\n/** Minimal store identifiers, or original store data from which the SDK extracts them. */\nexport type StoreTransaction = ReportedTransaction | string | GooglePlayPurchaseData;\n\n/** What Voidhash needs of a reported purchase: its store identifier and, on Google Play, its state. */\nexport type StoreReport =\n | {\n readonly platform: \"ios\";\n readonly transactionId: string;\n /** The JWS the report was made from, the proof a purchase or restore claim needs. */\n readonly signedTransaction?: string;\n }\n | {\n readonly platform: \"android\";\n readonly purchaseToken: string;\n readonly purchaseState?: \"purchased\" | \"pending\" | \"unspecified\";\n };\n\nconst identifier = Schema.String.check(Schema.isPattern(/\\S/));\nconst decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));\nconst decodeReport = Schema.decodeUnknownSync(\n Schema.Union([\n Schema.Struct({\n platform: Schema.Literal(\"ios\"),\n transactionId: identifier,\n signedTransaction: Schema.optional(identifier),\n }),\n Schema.Struct({\n platform: Schema.Literal(\"android\"),\n purchaseToken: identifier,\n purchaseState: Schema.optional(Schema.Literals([\"purchased\", \"pending\", \"unspecified\"])),\n }),\n ]),\n);\n\n// The server fetches the transaction with Apple by its ID; the JWS goes along as the device's\n// proof of a purchase or restore claim, so the native SDK need not look it up in the history.\nconst fromStoreKitJws = (jws: string): StoreReport => {\n const parts = jws.split(\".\");\n if (parts.length !== 3 || !parts[1]) throw new TypeError(\"Expected a StoreKit transaction JWS\");\n const payload = Schema.decodeUnknownSync(Schema.Struct({ transactionId: identifier }))(\n Result.match(Base64Url.decodeString(parts[1]), {\n onFailure: () => {\n throw new TypeError(\"Invalid StoreKit transaction encoding\");\n },\n onSuccess: decodeJson,\n }),\n );\n return { platform: \"ios\", signedTransaction: jws, transactionId: payload.transactionId };\n};\n\nconst fromPlayPurchase = (input: GooglePlayPurchaseData): ReportedTransaction => {\n const payload = Schema.decodeUnknownSync(\n Schema.Struct({\n token: Schema.optional(identifier),\n purchaseToken: Schema.optional(identifier),\n purchaseState: Schema.optional(Schema.Literals([0, 1, 4])),\n productIds: Schema.optional(Schema.Array(Schema.Unknown)),\n }),\n )(decodeJson(input.originalJson));\n if (payload.productIds && payload.productIds.length > 1) {\n throw new TypeError(\"Multi-product purchases are not supported\");\n }\n const token = payload.token ?? payload.purchaseToken;\n if (!token) throw new TypeError(\"A Google Play purchase token is required\");\n return {\n platform: \"android\",\n purchaseToken: token,\n purchaseState: payload.purchaseState === 4 ? \"pending\" : \"purchased\",\n };\n};\n\n/**\n * Extracts only the store identifiers of a purchase another billing\n * integration reported, leaving its finalization with that integration.\n * Throws for input that names no purchase.\n */\nexport const fromReportedTransaction = (input: StoreTransaction): StoreReport =>\n decodeReport(\n P.isString(input)\n ? fromStoreKitJws(input)\n : input && \"originalJson\" in input\n ? fromPlayPurchase(input)\n : input,\n );\n","import * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\n\nimport { VoidhashError, type VoidhashErrorCode } from \"../../errors\";\nimport type { FlowActions, FlowInput, FlowOutcome, FlowOutput } from \"../schema/registry\";\n\n/**\n * What an app lets its flows do, granted at SDK setup. Purchases, restores,\n * closing and analytics need no grant; an action needing a capability the\n * app did not grant is dropped with a warning.\n *\n * - `notifications`: ask the user to allow notifications.\n * - `tracking`: ask the user to allow tracking (App Tracking Transparency on iOS).\n * - `attributes`: set attributes on the current person.\n * - `links`: open links outside the app.\n */\nexport type FlowCapability = \"notifications\" | \"tracking\" | \"attributes\" | \"links\";\n\n/**\n * Which flow runtime draws flows, for the whole app process.\n *\n * - `linked`: the runtime built into the SDK (the default).\n * - `module`: the flow runtime module each flow names, which the SDK\n * downloads once, verifies and caches, so flows can use flow editor\n * features newer than the SDK. Not yet recommended for production.\n */\nexport type FlowRuntime = \"linked\" | \"module\";\n\n/**\n * What a paywall shows while it waits for the network: `standard` (the default),\n * the native SDK's loading screen 0.4 seconds after `presentFlow`, which the end\n * user can close; `none`, the app's screen as it is until the paywall is shown.\n */\nexport type FlowLoading = \"standard\" | \"none\";\n\n/** Capabilities granted when `flowCapabilities` is not set. */\nexport const DEFAULT_FLOW_CAPABILITIES: ReadonlyArray<FlowCapability> = [\"links\"];\n\n/** Codes of the errors a failed flow presentation carries. */\nexport type FlowErrorCode = Extract<VoidhashErrorCode, `FLOW_${string}`>;\n\n/**\n * How a presented flow ended.\n *\n * - `outcome`: `purchased` when a purchase ended the flow, `restored` when a\n * restore did, `dismissed` when the user or the app closed it or another\n * flow replaced it; otherwise the outcome the flow finished with.\n * - `output`: the flow's outputs by name; empty when it declares none.\n * - `productId`: the store product bought, when the outcome is `purchased`.\n *\n * A flow that could not be presented is not a result: `presentFlow()` rejects.\n */\nexport interface FlowResult<L extends string = string> {\n readonly outcome: FlowOutcome<L>;\n readonly output: FlowOutput<L>;\n readonly productId?: string;\n /**\n * `false` when the presentation ended before the paywall reached the screen,\n * with the outcome `dismissed`: the end user closed the loading screen, or the\n * app dismissed it or presented another paywall while it loaded. Absent from\n * native SDKs that do not report it; read absent as `true`.\n */\n readonly wasShown?: boolean;\n}\n\ntype RequiredWhenNotEmpty<Key extends string, Value> =\n Record<never, never> extends Value\n ? { readonly [K in Key]?: Value }\n : { readonly [K in Key]: Value };\n\n/**\n * What an app passes to one presentation of the flow at location `L`.\n *\n * - `input`: the flow's inputs by name.\n * - `actions`: a handler per app action the flow can call.\n * - `revision`: the interface revision the app was built against. Leave it\n * out to use the one set for the location in the `flowRevisions` option.\n */\nexport type PresentFlowOptions<L extends string = string> = {\n readonly revision?: number;\n} & RequiredWhenNotEmpty<\"input\", FlowInput<L>> &\n RequiredWhenNotEmpty<\"actions\", FlowActions<L>>;\n\n/**\n * The arguments of a presentation after its location: the options are\n * required when the location's flow has required inputs or app actions.\n */\nexport type PresentFlowArguments<L extends string = string> =\n Record<never, never> extends PresentFlowOptions<L>\n ? [options?: PresentFlowOptions<L>]\n : [options: PresentFlowOptions<L>];\n\n/** The error a presentation that could not be shown rejects with. */\nexport const flowError = (code: FlowErrorCode, message: string): VoidhashError =>\n new VoidhashError(code, `${code}: ${message}`);\n\nconst NativeFlowValue = Schema.Union([\n Schema.String,\n Schema.Number,\n Schema.Boolean,\n Schema.Array(Schema.String),\n]);\n\nconst NativeFlowResult = Schema.Union([\n Schema.Struct({\n outcome: Schema.String,\n output: Schema.Record(Schema.String, NativeFlowValue),\n productId: Schema.optional(Schema.String),\n wasShown: Schema.optional(Schema.Boolean),\n }),\n Schema.Struct({\n failure: Schema.Struct({\n code: Schema.Literals([\n \"FLOW_DISABLED\",\n \"FLOW_NOT_ASSIGNED\",\n \"FLOW_UNAVAILABLE\",\n \"FLOW_RENDERER_MISSING\",\n \"FLOW_UNSUPPORTED_PACKAGE\",\n \"FLOW_PRESENTATION_FAILED\",\n ]),\n message: Schema.String,\n }),\n }),\n]);\n\nconst decodeNativeFlowResult = Schema.decodeUnknownResult(Schema.fromJsonString(NativeFlowResult));\n\n/**\n * Reads the answer of the native coordinator: how the flow ended, or the\n * error of a flow that could not be presented. An answer this SDK does not\n * understand (a native module from another SDK version) is such an error too.\n */\nexport const parseFlowResult = (json: string): Result.Result<FlowResult, VoidhashError> => {\n const decoded = decodeNativeFlowResult(json);\n if (Result.isFailure(decoded)) {\n return Result.fail(flowError(\"FLOW_PRESENTATION_FAILED\", `unreadable flow result ${json}`));\n }\n const native = decoded.success;\n // The native message already starts with its code.\n if (\"failure\" in native) {\n return Result.fail(new VoidhashError(native.failure.code, native.failure.message));\n }\n return Result.succeed({\n outcome: native.outcome,\n output: native.output,\n ...(native.productId === undefined ? {} : { productId: native.productId }),\n ...(native.wasShown === undefined ? {} : { wasShown: native.wasShown }),\n });\n};\n","import { Result } from \"better-result\";\nimport * as Arr from \"effect/Array\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Match from \"effect/Match\";\nimport * as MutableRef from \"effect/MutableRef\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\nimport * as R from \"effect/Record\";\nimport * as EffectResult from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { Atom, type AtomRegistry } from \"effect/reactivity\";\n\nimport type {\n CurrentPersonResult,\n FlushResult,\n HasPerkResult,\n IdentifyResult,\n SetPersonAttributesResult,\n} from \"../../client\";\nimport {\n NotInitializedError,\n VOIDHASH_ERROR_CODES,\n VoidhashError,\n type VoidhashErrorCode,\n type VoidhashErrorReason,\n} from \"../../errors\";\nimport type {\n NativeAnalyticsConsent,\n NativeClientConfiguration,\n NativeClientEvent,\n NativeDiagnostic,\n NativeFeatureFlag,\n NativeFeatureFlagsResult,\n NativeFlushStatus,\n NativeFreshnessReason,\n NativeIdentityChange,\n NativePersonState,\n NativePersonWriteResult,\n NativePurchaseOptions,\n NativeReportedTransaction,\n NativeStorefront,\n VoidhashNativeClient,\n} from \"../../specs/VoidhashNativeClient.nitro\";\nimport { toJsonSafeProperties } from \"../analytics/json-safe\";\nimport type { VoidhashDiagnostic } from \"../diagnostics/diagnostics\";\nimport { findActiveGrant } from \"../entitlements/find-grant\";\nimport {\n type AppStorePurchaseIntent,\n type AppStoreSubscriptionStatus,\n type AppTransaction,\n decodeAppStoreRenewalInfo,\n decodeAppTransaction,\n type RefundRequestStatus,\n} from \"../entities/app-store\";\nimport type { GooglePlayInAppMessageResult } from \"../entities/google-play\";\nimport { decodePerson, type Person } from \"../entities/person\";\nimport type { Product } from \"../entities/product\";\nimport type { TransactionUpdate } from \"../entities/transaction\";\nimport {\n flowError,\n type FlowErrorCode,\n type FlowResult,\n parseFlowResult,\n type PresentFlowOptions,\n} from \"../flows/flows\";\nimport type {\n FeatureFlagsResult,\n GroupProperties,\n Groups,\n PersonAttributes,\n ResolvedPaywall,\n SdkFeatureFlag,\n} from \"../facade-types\";\nimport {\n currentPersonAtom,\n currentPersonFreshnessAtom,\n featureFlagsByKeyAtom,\n identityEpochAtom,\n NO_PRODUCTS,\n normalizeFeatureFlagKeys,\n productsAtom,\n publishCurrentPerson,\n schemaAtom,\n UNCONFIRMED_PERSON,\n} from \"../reactivity/client-state\";\nimport type { FlowValues, PerkSlug } from \"../schema/registry\";\nimport { decodeRuntimeSchema } from \"../schema/decode\";\nimport { type AnalyticsConsent, isAnalyticsConsent } from \"../sdk-configuration\";\nimport { readNativeError } from \"../utils/native-error\";\nimport { type StorePurchaseResult, toProduct, toPurchaseResult, toTransaction } from \"./billing\";\n\n/**\n * The members every Nitro hybrid object has (`HybridObject` in both Nitro\n * generations), which the adapter never calls. Named here rather than taken\n * from a Nitro package, so the facade's types do not depend on which Nitro\n * the host app runs.\n */\ntype HybridObjectMember = \"__type\" | \"name\" | \"toString\" | \"equals\" | \"dispose\";\n\n/**\n * The hybrid as the adapter uses it: its members without Nitro's own object\n * plumbing, so tests can hand in an in-memory implementation.\n */\nexport type NativeClientPort = Omit<VoidhashNativeClient, HybridObjectMember>;\n\n/** What the adapter reports to and through, besides the hybrid itself. */\nexport interface NativeClientAdapterOptions {\n readonly native: NativeClientPort;\n /** The npm package the app installs, which a failure that needs a new native build names. */\n readonly packageName: string;\n /** The client's registry; the hooks read the atoms the adapter writes into it. */\n readonly atomRegistry: AtomRegistry.AtomRegistry;\n /** Receives every native diagnostic; the facade's `onDiagnostic` dispatch. */\n readonly onDiagnostic: (diagnostic: VoidhashDiagnostic) => void;\n /**\n * Called when the native client switched to another identity, as soon as it\n * says so: the events it is handed from here on are recorded under it.\n */\n readonly onIdentitySwitched?: () => void;\n /** Called when the analytics consent in effect changes natively, including at start. */\n readonly onAnalyticsConsentChanged?: (consent: AnalyticsConsent) => void;\n /** Receives each purchase the native client completed outside `purchase()`. */\n readonly onTransaction?: (update: TransactionUpdate) => void;\n /** Receives each App Store purchase intent, with `purchaseIntents: \"manual\"`. */\n readonly onPurchaseIntent?: (intent: AppStorePurchaseIntent) => void;\n}\n\n/**\n * The version of the contract in `VoidhashNativeClient.nitro.ts` this facade\n * speaks; the native client's `contractVersion()` must answer the same.\n */\nexport const NATIVE_CONTRACT_VERSION = 1;\n\n/**\n * The contract version `native` implements: 0 for a binary built before\n * `contractVersion()` existed, whose hybrid has no such member, and for one\n * that answers no number.\n */\nconst contractVersionOf = (native: NativeClientPort): number => {\n const version = EffectResult.try(() =>\n P.isFunction(Reflect.get(native, \"contractVersion\")) ? native.contractVersion() : 0,\n );\n return EffectResult.isSuccess(version) && P.isNumber(version.success) ? version.success : 0;\n};\n\n/** Native codes for a client that is not started, the facade's `VOIDHASH_CLIENT_NOT_INITIALIZED`. */\nconst NOT_STARTED_CODES: ReadonlyArray<string> = [\"NOT_INITIALIZED\", \"NOT_CONFIGURED\"];\n\n/**\n * How one facade method reports a native failure: under its own code, except\n * for the codes it reports today, which pass through.\n */\ninterface FailureCodes {\n readonly fallback: VoidhashErrorCode;\n /** Codes the facade method reports today besides `fallback`. */\n readonly passThrough?: ReadonlyArray<VoidhashErrorCode>;\n /**\n * Whether a client that is not started is reported as\n * `VOIDHASH_CLIENT_NOT_INITIALIZED`, as every facade method but `init()`\n * does. Default `true`.\n */\n readonly notStarted?: boolean;\n}\n\n/**\n * Maps a native rejection to the error the facade method reports. The code\n * is read through the bridge's wrapping (`readNativeError`): a code the method\n * reports today keeps it, a client that is not started is the facade's\n * `NotInitializedError`, and anything else is reported as the method's own\n * code with the native message's first line kept, so no stack trace reaches\n * the app.\n */\nexport const toVoidhashError = (error: unknown, codes: FailureCodes): VoidhashError => {\n if (error instanceof VoidhashError) return error;\n const native = readNativeError(error);\n const code = Option.getOrElse(native.code, () => \"\");\n if ((codes.notStarted ?? true) && NOT_STARTED_CODES.includes(code)) {\n return new NotInitializedError();\n }\n const passing = Arr.findFirst(codes.passThrough ?? [], (known) => known === code);\n return Option.match(passing, {\n onNone: () =>\n new VoidhashError(codes.fallback, `${codes.fallback}: ${native.message}`, { cause: error }),\n onSome: (known) => new VoidhashError(known, native.message, { cause: error }),\n });\n};\n\n/** What every facade method below reports, keyed by the method. */\nconst FAILURES = {\n appStoreAppTransaction: {\n fallback: \"FAILED_TO_GET_APP_TRANSACTION\",\n passThrough: [\"UNSUPPORTED_PLATFORM\"],\n },\n appStoreBeginRefundRequest: {\n fallback: \"FAILED_TO_BEGIN_REFUND_REQUEST\",\n passThrough: [\"INVALID_ARGUMENT\", \"UNSUPPORTED_PLATFORM\"],\n },\n appStoreCurrentEntitlements: {\n fallback: \"FAILED_TO_GET_CURRENT_ENTITLEMENTS\",\n passThrough: [\"UNSUPPORTED_PLATFORM\"],\n },\n appStoreSubscriptionStatus: {\n fallback: \"FAILED_TO_GET_SUBSCRIPTION_STATUS\",\n passThrough: [\"UNSUPPORTED_PLATFORM\"],\n },\n canMakePayments: { fallback: \"FAILED_TO_CHECK_CAN_MAKE_PAYMENTS\" },\n dismissFlow: { fallback: \"FLOW_PRESENTATION_FAILED\" },\n updateFlowInput: { fallback: \"FLOW_PRESENTATION_FAILED\" },\n flush: { fallback: \"FAILED_TO_FLUSH_ANALYTICS\" },\n getCurrentPerson: {\n fallback: \"FAILED_TO_GET_CURRENT_PERSON\",\n passThrough: [\"AUTHENTICATION_FAILED\"],\n },\n getDistinctId: { fallback: \"FAILED_TO_GET_DISTINCT_ID\" },\n getFeatureFlags: {\n fallback: \"FAILED_TO_GET_FEATURE_FLAGS\",\n passThrough: [\"AUTHENTICATION_FAILED\"],\n },\n getPaywallForLocation: {\n fallback: \"FAILED_TO_GET_PAYWALL_FOR_LOCATION\",\n passThrough: [\"AUTHENTICATION_FAILED\", \"PAYWALL_UNAVAILABLE\"],\n },\n getProducts: { fallback: \"FAILED_TO_GET_PRODUCTS\" },\n getStorefront: { fallback: \"FAILED_TO_GET_STOREFRONT\" },\n googlePlayIsFeatureSupported: {\n fallback: \"FAILED_TO_CHECK_FEATURE_SUPPORT\",\n passThrough: [\"INVALID_ARGUMENT\", \"UNSUPPORTED_PLATFORM\"],\n },\n googlePlayQueryPurchases: {\n fallback: \"FAILED_TO_QUERY_PURCHASES\",\n passThrough: [\"UNSUPPORTED_PLATFORM\"],\n },\n googlePlayShowInAppMessages: {\n fallback: \"FAILED_TO_SHOW_IN_APP_MESSAGES\",\n passThrough: [\"UNSUPPORTED_PLATFORM\"],\n },\n group: { fallback: \"FAILED_TO_SET_GROUP\", passThrough: [\"INVALID_ARGUMENT\"] },\n setGroups: { fallback: \"FAILED_TO_SET_GROUP\", passThrough: [\"INVALID_ARGUMENT\"] },\n identify: { fallback: \"FAILED_TO_IDENTIFY\", passThrough: [\"INVALID_ARGUMENT\"] },\n presentCodeRedemption: { fallback: \"FAILED_TO_PRESENT_CODE_REDEMPTION\" },\n purchase: {\n fallback: \"FAILED_TO_PURCHASE\",\n passThrough: [\n \"INVALID_ARGUMENT\",\n \"OFFER_UNAVAILABLE\",\n \"PURCHASE_IN_PROGRESS\",\n \"READ_ONLY_PURCHASE_NOT_ALLOWED\",\n \"REPLACED_SUBSCRIPTION_NOT_OWNED\",\n \"SUBSCRIPTION_REPLACEMENT_REFUSED\",\n ],\n },\n reportTransaction: { fallback: \"FAILED_TO_REPORT_TRANSACTION\" },\n reset: { fallback: \"FAILED_TO_RESET\" },\n resetCache: { fallback: \"FAILED_TO_RESET_PERSON_CACHE\" },\n resetGroups: { fallback: \"FAILED_TO_RESET_GROUPS\" },\n restorePurchases: { fallback: \"FAILED_TO_RESTORE_PURCHASES\" },\n setAnalyticsConsent: { fallback: \"FAILED_TO_SET_ANALYTICS_CONSENT\" },\n setPersonAttributes: {\n fallback: \"FAILED_TO_SET_PERSON_ATTRIBUTES\",\n passThrough: [\"INVALID_ARGUMENT\"],\n },\n setPersonAttributesSync: {\n fallback: \"FAILED_TO_SET_PERSON_ATTRIBUTES_SYNC\",\n passThrough: [\"INVALID_ARGUMENT\", \"READ_ONLY_PURCHASE_NOT_ALLOWED\"],\n },\n showManageSubscriptions: { fallback: \"FAILED_TO_SHOW_MANAGE_SUBSCRIPTIONS\" },\n shutdown: { fallback: \"FAILED_TO_END_VOIDHASH_CLIENT\" },\n signOut: { fallback: \"FAILED_TO_SIGN_OUT\" },\n start: { fallback: \"FAILED_TO_INITIALIZE_VOIDHASH_CLIENT\", notStarted: false },\n syncPurchases: { fallback: \"FAILED_TO_SYNC_PURCHASES\" },\n} as const satisfies Record<string, FailureCodes>;\n\n/**\n * Runs one native call and answers it as the facade does: `Ok` with the\n * mapped value, or `Err` with the mapped error. A native call that throws\n * synchronously is a rejection like any other.\n */\nconst call = async <A>(\n codes: FailureCodes,\n run: () => Promise<A>,\n): Promise<Result<A, VoidhashError>> => {\n const exit = await Effect.runPromiseExit(\n Effect.tryPromise({ catch: (error) => error, try: () => run() }),\n );\n return Exit.isSuccess(exit)\n ? Result.ok(exit.value)\n : Result.err(toVoidhashError(Cause.squash(exit.cause), codes));\n};\n\n/** The native codes of a purchase the store refused for a reason, and the reason each is. */\nconst PURCHASE_FAILURE_REASONS: Readonly<Record<string, VoidhashErrorReason>> = {\n INELIGIBLE_FOR_OFFER: \"ineligibleForOffer\",\n PAYMENT_DECLINED: \"paymentDeclined\",\n};\n\nconst decodeJson = Schema.decodeUnknownResult(Schema.fromJsonString(Schema.Unknown));\nconst encodeJson = Schema.encodeUnknownResult(Schema.fromJsonString(Schema.Unknown));\n\nconst PaywallValue = Schema.declare(\n (value: unknown): value is ResolvedPaywall => value === null || P.isObject(value),\n);\nconst decodePaywall = Schema.decodeUnknownResult(PaywallValue);\n\n/** A person snapshot crossing as JSON; one that is absent or unreadable counts as none. */\nconst personOf = (payload: { readonly personJson?: string }): Option.Option<Person> =>\n Option.flatMap(Option.fromUndefinedOr(payload.personJson), decodePerson);\n\nconst REASONS: Readonly<Record<NativeFreshnessReason, CurrentPersonResult[\"reason\"]>> = {\n fresh: \"fresh\",\n noCache: \"no-cache\",\n refreshFailed: \"refresh-failed\",\n refreshInFlight: \"refresh-in-flight\",\n};\n\nconst toCurrentPerson = (state: NativePersonState): CurrentPersonResult => ({\n isExpired: state.isExpired,\n isStale: state.isStale,\n person: Option.getOrNull(personOf(state)),\n reason: REASONS[state.reason],\n});\n\nconst toFlag = (flag: NativeFeatureFlag): SdkFeatureFlag => ({\n enabled: flag.enabled,\n key: flag.key,\n payload: Option.getOrNull(\n Option.flatMap(Option.fromUndefinedOr(flag.payloadJson), (json) =>\n EffectResult.getSuccess(decodeJson(json)),\n ),\n ),\n variantKey: flag.variantKey ?? null,\n});\n\nconst toFlags = (result: NativeFeatureFlagsResult): FeatureFlagsResult => ({\n flags: result.flags.map(toFlag),\n isStale: result.isStale,\n});\n\nconst toDiagnostic = (diagnostic: NativeDiagnostic): VoidhashDiagnostic => ({\n code: diagnostic.code,\n kind: diagnostic.kind,\n operation: diagnostic.operation,\n retryable: diagnostic.retryable,\n ...(diagnostic.httpStatus === undefined ? {} : { httpStatus: diagnostic.httpStatus }),\n ...(diagnostic.message === undefined ? {} : { message: diagnostic.message }),\n});\n\nconst toFlushResult = (status: NativeFlushStatus): FlushResult => ({\n flushed: status.flushed,\n pending: status.pending,\n ...(status.lastErrorMessage === undefined\n ? {}\n : {\n lastError: new VoidhashError(\n \"FAILED_TO_FLUSH_ANALYTICS\",\n `FAILED_TO_FLUSH_ANALYTICS: ${status.lastErrorMessage}`,\n ),\n }),\n});\n\n/** Inputs, action arguments and action replies as the native side carries them. */\nconst FlowValuesFromJson = Schema.fromJsonString(\n Schema.Record(\n Schema.String,\n Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Array(Schema.String)]),\n ),\n);\nconst decodeFlowValues = Schema.decodeUnknownSync(FlowValuesFromJson);\nconst encodeFlowValues = Schema.encodeSync(FlowValuesFromJson);\n\n/** Whether a native code is one of the `FLOW_*` codes a presentation rejects with. */\nconst isFlowErrorCode = (code: string): code is FlowErrorCode =>\n code.startsWith(\"FLOW_\") && VOIDHASH_ERROR_CODES.some((known) => known === code);\n\n/**\n * The facade's view of the native Voidhash client: every method answers in\n * the facade's types (`Result` with a coded `VoidhashError`), and every native\n * state change lands in the reactive atoms the hooks read, so the hooks work\n * unchanged whichever side produced the state.\n *\n * The adapter follows the identity generation the native client last\n * announced, by event or in the answer of the call that switched it. A person\n * or flag answer, read or event, from any other generation is not published:\n * it belongs to a switch that has already been superseded, or to an earlier\n * run of the client (generations grow for the life of the process), even when\n * the identity has since switched back to the same distinct id. A read still\n * answers its caller with what it read.\n */\nexport const makeNativeClientAdapter = (options: NativeClientAdapterOptions) => {\n const { atomRegistry, native } = options;\n const currentIdentity = MutableRef.make(Option.none<NativeIdentityChange>());\n /** The generation person or flags were last published for; `-1` before any. */\n const publishedGeneration = MutableRef.make(-1);\n const listening = MutableRef.make(false);\n /**\n * Counts what made the products this client holds outdated: identity\n * switches, product definition changes, purchases and restores. A load\n * publishes only when nothing outdated it while it ran.\n */\n const productsRevision = MutableRef.make(0);\n const productsLoad = MutableRef.make(\n Option.none<{\n readonly revision: number;\n readonly settled: Promise<Result<ReadonlyArray<Product>, VoidhashError>>;\n }>(),\n );\n /** The reload `invalidateProducts()` scheduled for the next tick, until it starts. */\n const scheduledReload = MutableRef.make(Option.none<ReturnType<typeof setTimeout>>());\n /** The product definitions of the schema published last, encoded; empty before any. */\n const productDefinitions = MutableRef.make(\"\");\n\n /** The host's diagnostic handler, which must not take the adapter down with it. */\n const report = (diagnostic: VoidhashDiagnostic) => {\n EffectResult.try(() => options.onDiagnostic(diagnostic));\n };\n\n const cancelScheduledReload = () => {\n Option.map(MutableRef.get(scheduledReload), clearTimeout);\n MutableRef.set(scheduledReload, Option.none());\n };\n\n /**\n * Loads the products, one native call for every caller of the same\n * revision, and publishes them for the hooks. A load that an identity\n * switch, a schema change or a purchase outdated while it ran answers its\n * caller but publishes nothing: the load started for the new revision does.\n *\n * Never rejects: a product this SDK cannot read fails the load as\n * `FAILED_TO_GET_PRODUCTS`, like a native failure, and a settled load\n * never leaves the products loading.\n */\n const loadProducts = (): Promise<Result<ReadonlyArray<Product>, VoidhashError>> => {\n const revision = MutableRef.get(productsRevision);\n const running = MutableRef.get(productsLoad);\n if (Option.isSome(running) && running.value.revision === revision) {\n return running.value.settled;\n }\n // This load serves every change so far; a reload scheduled for them is not needed.\n cancelScheduledReload();\n atomRegistry.update(productsAtom, (state) => ({ ...state, isLoading: true }));\n const settled: Promise<Result<ReadonlyArray<Product>, VoidhashError>> = call(\n FAILURES.getProducts,\n async () =>\n Arr.getSomes(\n (await native.getProducts()).map((product) =>\n toProduct(product, (message) => reportContractViolation(\"getProducts\", message)),\n ),\n ),\n ).then((products) => {\n const isCurrent = MutableRef.get(productsRevision) === revision;\n if (Option.exists(MutableRef.get(productsLoad), (load) => load.settled === settled)) {\n MutableRef.set(productsLoad, Option.none());\n }\n if (isCurrent) {\n atomRegistry.update(productsAtom, (state) =>\n products.isOk()\n ? { error: Option.none(), isLoading: false, products: Option.some(products.value) }\n : { ...state, error: Option.some(products.error), isLoading: false },\n );\n } else if (\n Option.isNone(MutableRef.get(productsLoad)) &&\n Option.isNone(MutableRef.get(scheduledReload))\n ) {\n // Outdated, and no load for the new revision runs or is due.\n atomRegistry.update(productsAtom, (state) => ({ ...state, isLoading: false }));\n }\n return products;\n });\n MutableRef.set(productsLoad, Option.some({ revision, settled }));\n return settled;\n };\n\n /**\n * The products held are outdated. They load again when anything asked for\n * them before (otherwise the first `useProducts()` or `getProducts()` loads\n * them), on the next tick: changes that land together, such as an identity\n * switch and a schema, or several transactions, load once.\n */\n const invalidateProducts = () => {\n MutableRef.update(productsRevision, (revision) => revision + 1);\n if (Option.isSome(MutableRef.get(scheduledReload))) return;\n const state = atomRegistry.get(productsAtom);\n if (Option.isNone(state.products) && Option.isNone(state.error) && !state.isLoading) return;\n MutableRef.set(\n scheduledReload,\n Option.some(\n setTimeout(() => {\n MutableRef.set(scheduledReload, Option.none());\n void loadProducts();\n }, 0),\n ),\n );\n };\n\n const isCurrent = (generation: number) =>\n Option.exists(\n MutableRef.get(currentIdentity),\n (identity) => identity.generation === generation,\n );\n\n const publishPerson = (state: NativePersonState) => {\n if (!isCurrent(state.generation)) return;\n MutableRef.set(publishedGeneration, state.generation);\n publishCurrentPerson(atomRegistry, personOf(state), {\n isExpired: state.isExpired,\n isStale: state.isStale,\n });\n };\n\n /** Stores an evaluation under `signature`, the key set it is published for. */\n const publishFlags = (result: NativeFeatureFlagsResult, signature: string) => {\n if (!isCurrent(result.generation)) return;\n MutableRef.set(publishedGeneration, result.generation);\n atomRegistry.update(featureFlagsByKeyAtom, (current) => ({\n ...current,\n [signature]: toFlags(result),\n }));\n };\n\n /**\n * Adopts the identity the native client switched to. A switch clears the\n * person and every flag evaluation and counts in `identityEpochAtom`, so\n * mounted hooks read again for the new identity, as `IdentityManager` does\n * for the TypeScript core. A generation no newer than the current one (the\n * event of a switch whose answer was already adopted, say) changes nothing.\n */\n const adoptIdentity = (change: NativeIdentityChange) => {\n if (\n Option.exists(\n MutableRef.get(currentIdentity),\n (current) => current.generation >= change.generation,\n )\n ) {\n return;\n }\n MutableRef.set(currentIdentity, Option.some(change));\n options.onIdentitySwitched?.();\n Atom.batch(() => {\n atomRegistry.set(featureFlagsByKeyAtom, {});\n publishCurrentPerson(atomRegistry, Option.none(), UNCONFIRMED_PERSON);\n atomRegistry.update(identityEpochAtom, (switches) => switches + 1);\n });\n // Offers and intro eligibility are the end user's.\n invalidateProducts();\n };\n\n const reportContractViolation = (operation: string, message: string) =>\n report({\n code: \"BACKGROUND_TASK_FAILED\",\n kind: \"configuration\",\n message,\n operation,\n retryable: false,\n });\n\n /**\n * Publishes a schema event. Decoded entry by entry like a fetched schema:\n * an entry this SDK version cannot read is left out (the native client\n * reports it); a document that is no schema at all is reported and dropped.\n */\n const publishSchema = (schemaJson: string) => {\n const decoded = EffectResult.flatMap(decodeJson(schemaJson), (document) => {\n const exit = Effect.runSyncExit(decodeRuntimeSchema(document));\n return Exit.isSuccess(exit)\n ? EffectResult.succeed(exit.value.schema)\n : EffectResult.fail(Cause.squash(exit.cause));\n });\n if (EffectResult.isSuccess(decoded)) {\n atomRegistry.set(schemaAtom, Option.some(decoded.success));\n // Every refresh publishes a new schema; only changed product definitions outdate the products.\n const definitions = EffectResult.getOrElse(encodeJson(decoded.success.products), () => \"\");\n if (definitions !== MutableRef.get(productDefinitions)) {\n MutableRef.set(productDefinitions, definitions);\n invalidateProducts();\n }\n return;\n }\n reportContractViolation(\"getSchema\", \"The native client sent a schema this SDK cannot read\");\n };\n\n /** Routes one event; the event's `type` names the payload it carries. */\n const routeEvent = (event: NativeClientEvent) =>\n Match.value(event.type).pipe(\n Match.when(\"identity\", () =>\n Option.map(Option.fromUndefinedOr(event.identity), adoptIdentity),\n ),\n Match.when(\"person\", () => Option.map(Option.fromUndefinedOr(event.person), publishPerson)),\n Match.when(\"flags\", () =>\n Option.map(Option.fromUndefinedOr(event.flags), (flags) =>\n publishFlags(flags, normalizeFeatureFlagKeys(flags.flagKeys)),\n ),\n ),\n Match.when(\"schema\", () =>\n Option.map(Option.fromUndefinedOr(event.schemaJson), publishSchema),\n ),\n Match.when(\"consent\", () =>\n Option.map(Option.fromUndefinedOr(event.consent), (consent) =>\n options.onAnalyticsConsentChanged?.(consent),\n ),\n ),\n Match.when(\"diagnostic\", () =>\n Option.map(Option.fromUndefinedOr(event.diagnostic), (diagnostic) =>\n report(toDiagnostic(diagnostic)),\n ),\n ),\n Match.when(\"transaction\", () =>\n Option.map(Option.fromUndefinedOr(event.transaction), (update) => {\n // A completed purchase can change which offers the end user is eligible for; a\n // renewal of a subscription they already have cannot.\n if (update.transaction.isRenewal !== true) invalidateProducts();\n options.onTransaction?.({\n synced: update.synced,\n transaction: toTransaction(update.transaction, (message) =>\n reportContractViolation(\"transactionUpdates\", message),\n ),\n });\n }),\n ),\n Match.when(\"purchaseIntent\", () =>\n Option.map(Option.fromUndefinedOr(event.purchaseIntent), (intent) =>\n options.onPurchaseIntent?.({\n productSlug: intent.productSlug,\n ...(intent.offer === undefined ? {} : { offer: intent.offer }),\n }),\n ),\n ),\n Match.exhaustive,\n );\n\n /**\n * The listener handed to the native client. Whatever goes wrong while an\n * event is handled (a host callback or a hook's render throwing) is\n * reported as a diagnostic instead of escaping into the native bridge.\n */\n const handleEvent = (event: NativeClientEvent) => {\n if (!MutableRef.get(listening)) return;\n const handled = EffectResult.try(() => routeEvent(event));\n if (EffectResult.isFailure(handled)) {\n report({\n code: \"BACKGROUND_TASK_FAILED\",\n kind: \"configuration\",\n message: `Handling a native ${event.type} event failed: ${String(handled.failure)}`,\n operation: \"nativeEvent\",\n retryable: false,\n });\n }\n };\n\n /**\n * Reports a synchronous native call that threw. These calls answer no\n * `Result`, so the failure is a diagnostic rather than an exception that\n * would escape the facade.\n */\n const reportThrow = (operation: string, error: unknown) =>\n report({\n code: \"BACKGROUND_TASK_FAILED\",\n kind: \"configuration\",\n message: `${operation} failed: ${readNativeError(error).message}`,\n operation,\n retryable: false,\n });\n\n /** Runs a synchronous native call, reporting a throw; `None` when it threw. */\n const trySync = <A>(operation: string, run: () => A): Option.Option<A> => {\n const ran = EffectResult.try(run);\n if (EffectResult.isSuccess(ran)) return Option.some(ran.success);\n reportThrow(operation, ran.failure);\n return Option.none();\n };\n\n const stopListening = () => {\n MutableRef.set(listening, false);\n trySync(\"removeEventListener\", () => native.removeEventListener());\n };\n\n /** Reads the person and publishes it, unless the identity changed meanwhile. */\n const readPerson = (forceFetch: boolean) =>\n call(FAILURES.getCurrentPerson, async () => {\n const state = await native.getPersonState(forceFetch);\n publishPerson(state);\n return state;\n });\n\n /**\n * Switches the identity through the native client. The switch is adopted\n * from the answer as well as from the event, so the atoms follow it however\n * the two arrive. A switch the server refused leaves the native client back\n * on the previous identity; the person and flag evaluations held before the\n * call are then put back, as `IdentityManager` does for the TypeScript core,\n * unless something was already published for the generations since. An\n * identify of the current identity adopts nothing and leaves both alone.\n */\n const switchIdentity = async (\n externalUserId: string,\n profile: { email?: string; name?: string },\n ) => {\n const before = MutableRef.get(currentIdentity);\n const held = {\n flags: atomRegistry.get(featureFlagsByKeyAtom),\n freshness: atomRegistry.get(currentPersonFreshnessAtom),\n person: atomRegistry.get(currentPersonAtom),\n };\n const result = await call(FAILURES.identify, () =>\n native.identify(externalUserId, profile.email, profile.name),\n );\n if (result.isOk()) {\n adoptIdentity(result.value.identity);\n return result;\n }\n const after = MutableRef.get(currentIdentity);\n const restored =\n Option.isSome(before) &&\n Option.isSome(after) &&\n after.value.distinctId === before.value.distinctId &&\n after.value.generation > before.value.generation &&\n MutableRef.get(publishedGeneration) <= before.value.generation;\n if (restored) {\n Atom.batch(() => {\n atomRegistry.set(featureFlagsByKeyAtom, held.flags);\n publishCurrentPerson(atomRegistry, held.person, held.freshness);\n });\n }\n return result;\n };\n\n /** Resets or signs out, adopting the fresh identity from the answer too. */\n const switchToAnonymous = async (codes: FailureCodes, run: () => Promise<NativeIdentityChange>) =>\n (await call(codes, run)).map((identity) => {\n adoptIdentity(identity);\n return undefined;\n });\n\n const toAttributesResult = (result: NativePersonWriteResult): SetPersonAttributesResult => {\n const person = personOf(result);\n if (result.status === \"skipped\") return { person: null, status: \"skipped\" };\n return result.status === \"confirmed\" && Option.isSome(person)\n ? { person: person.value, status: \"confirmed\" }\n : { person: Option.getOrNull(person), status: \"deferred\" };\n };\n\n /**\n * Encodes person attributes for the bridge. Attributes JSON cannot hold\n * are an `INVALID_ARGUMENT`, never sent as something else.\n */\n const encodeAttributes = (attributes: PersonAttributes) =>\n Option.match(EffectResult.getSuccess(encodeJson(attributes)), {\n onNone: () =>\n Result.err(\n new VoidhashError(\n \"INVALID_ARGUMENT\",\n \"INVALID_ARGUMENT: person attributes must be values JSON can hold\",\n ),\n ),\n onSome: (json) => Result.ok(json),\n });\n\n /**\n * An event's (or a screen's) properties, copied into what JSON can hold as\n * the TypeScript core does. `None` for an event they cannot be copied for,\n * which is dropped and reported.\n */\n const encodeEvent = (\n operation: \"capture\" | \"screen\",\n name: string,\n properties: Record<string, unknown>,\n ): Option.Option<string> => {\n const json = EffectResult.flatMap(toJsonSafeProperties(properties), (copied) =>\n Option.match(EffectResult.getSuccess(encodeJson(copied)), {\n onNone: () => EffectResult.fail(\"cannot be encoded as JSON\"),\n onSome: (encoded) => EffectResult.succeed(encoded),\n }),\n );\n if (EffectResult.isFailure(json)) {\n report({\n code: \"ANALYTICS_EVENT_DROPPED\",\n kind: \"eviction\",\n message: `Dropped \"${name}\": its properties ${json.failure}`,\n operation,\n retryable: false,\n });\n return Option.none();\n }\n return Option.some(json.success);\n };\n\n // A binary built before `captureAt` and `screenAt` has neither; an event the\n // facade held back then takes the time it is handed over at.\n const takesCaptureTime =\n P.isFunction(Reflect.get(native, \"captureAt\")) && P.isFunction(Reflect.get(native, \"screenAt\"));\n\n /**\n * Queues an encoded event (or screen) through a synchronous native call,\n * at `capturedAt` for one the facade held back. A native call that throws\n * is reported: capturing never throws.\n */\n const sendEvent = (\n operation: \"capture\" | \"screen\",\n name: string,\n propertiesJson: string,\n capturedAt: Option.Option<number>,\n ) => {\n const sent = EffectResult.try(() => {\n if (Option.isSome(capturedAt) && takesCaptureTime) {\n if (operation === \"capture\") native.captureAt(name, propertiesJson, capturedAt.value);\n else native.screenAt(name, propertiesJson, capturedAt.value);\n return;\n }\n if (operation === \"capture\") native.capture(name, propertiesJson);\n else native.screen(name, propertiesJson);\n });\n if (EffectResult.isFailure(sent)) {\n report({\n code: \"ANALYTICS_EVENT_DROPPED\",\n kind: \"eviction\",\n message: `Dropped \"${name}\": ${readNativeError(sent.failure).message}`,\n operation,\n retryable: false,\n });\n }\n };\n\n return {\n /**\n * Configures and starts the native client, also again after `shutdown()`\n * (a re-init). The listener is attached first, so what `start()`\n * announces reaches the atoms. The identity a new run loads has a newer\n * generation than anything of the previous run, so a read the previous\n * run left pending is never published. A failed start detaches the\n * listener again.\n */\n start: async (\n configuration: NativeClientConfiguration,\n ): Promise<Result<void, VoidhashError>> => {\n // An over-the-air bundle onto a build made for another contract would misread every\n // answer: nothing of it is started.\n const version = contractVersionOf(native);\n if (version !== NATIVE_CONTRACT_VERSION) {\n return Result.err(\n new VoidhashError(\n \"FAILED_TO_INITIALIZE_VOIDHASH_CLIENT\",\n `FAILED_TO_INITIALIZE_VOIDHASH_CLIENT: the app's native Voidhash module implements version ${version} of its contract, and this JavaScript bundle needs version ${NATIVE_CONTRACT_VERSION}. Make a new native build of the app with this version of ${options.packageName}; an over-the-air update cannot change the native module.`,\n ),\n );\n }\n MutableRef.set(listening, true);\n const started = await call(FAILURES.start, async () => {\n native.setEventListener(handleEvent);\n native.configure(configuration);\n await native.start();\n });\n if (started.isErr()) stopListening();\n return started;\n },\n\n /**\n * Shuts the native client down; events it emits from then on are ignored.\n * The products go with it: a later run loads them for its own identity.\n */\n shutdown: async () => {\n const result = await call(FAILURES.shutdown, () => native.shutdown());\n stopListening();\n MutableRef.update(productsRevision, (revision) => revision + 1);\n cancelScheduledReload();\n MutableRef.set(productsLoad, Option.none());\n atomRegistry.set(productsAtom, NO_PRODUCTS);\n return result.map(toFlushResult);\n },\n\n getDistinctId: () => call(FAILURES.getDistinctId, () => native.getDistinctId()),\n\n /** Backs `identify()`: the switch, without the confirmation. */\n identify: async (externalUserId: string, profile: { email?: string; name?: string } = {}) =>\n (await switchIdentity(externalUserId, profile)).map(() => undefined),\n\n /** Backs `identifySync()`: the switch and whether the server confirmed it. */\n identifySync: async (externalUserId: string, profile: { email?: string; name?: string } = {}) =>\n (await switchIdentity(externalUserId, profile)).map((result): IdentifyResult => {\n const person = personOf(result);\n return result.status === \"confirmed\" && Option.isSome(person)\n ? { person: person.value, status: \"confirmed\" }\n : { person: Option.getOrNull(person), status: \"deferred\" };\n }),\n\n reset: () => switchToAnonymous(FAILURES.reset, () => native.reset()),\n signOut: () => switchToAnonymous(FAILURES.signOut, () => native.signOut()),\n\n /**\n * Backs `group()`. The native SDK checks the type and key (an invalid one\n * rejects `INVALID_ARGUMENT`), keeps the group with the identity and sends\n * the `$groupidentify`.\n */\n group: async (\n groupType: string,\n groupKey: string,\n properties: Option.Option<GroupProperties>,\n ): Promise<Result<void, VoidhashError>> => {\n if (Option.isNone(properties)) {\n return call(FAILURES.group, () => native.group(groupType, groupKey, undefined));\n }\n return Option.match(EffectResult.getSuccess(encodeJson(properties.value)), {\n onNone: () =>\n Promise.resolve(\n Result.err(\n new VoidhashError(\n \"INVALID_ARGUMENT\",\n \"INVALID_ARGUMENT: group properties must be values JSON can hold\",\n ),\n ),\n ),\n onSome: (json) => call(FAILURES.group, () => native.group(groupType, groupKey, json)),\n });\n },\n /**\n * Backs `setGroups()`. The native SDK replaces the held groups, checks\n * each type and id, and sends a `$groupidentify` only for what changed.\n */\n setGroups: async (groups: Groups): Promise<Result<void, VoidhashError>> => {\n const entries = R.filterMap(groups, (group) => {\n if (P.isNullish(group)) return EffectResult.failVoid;\n if (!P.isObject(group)) return EffectResult.succeed({ id: String(group), properties: {} });\n const { id, ...properties } = group;\n return EffectResult.succeed({ id: String(id), properties });\n });\n return Option.match(EffectResult.getSuccess(encodeJson(entries)), {\n onNone: () =>\n Promise.resolve(\n Result.err(\n new VoidhashError(\n \"INVALID_ARGUMENT\",\n \"INVALID_ARGUMENT: group properties must be values JSON can hold\",\n ),\n ),\n ),\n onSome: (json) => call(FAILURES.setGroups, () => native.setGroups(json)),\n });\n },\n resetGroups: () => call(FAILURES.resetGroups, () => native.resetGroups()),\n /** The groups the native client holds; none when it could not say. */\n getGroups: (): Readonly<Record<string, string>> =>\n Option.getOrElse(\n trySync(\"getGroups\", () => native.getGroups()),\n () => ({}),\n ),\n\n setPersonAttributes: async (\n attributes: PersonAttributes,\n ): Promise<Result<void, VoidhashError>> => {\n const encoded = encodeAttributes(attributes);\n if (encoded.isErr()) return Result.err(encoded.error);\n return call(FAILURES.setPersonAttributes, () => native.setPersonAttributes(encoded.value));\n },\n\n setPersonAttributesSync: async (\n attributes: PersonAttributes,\n ): Promise<Result<SetPersonAttributesResult, VoidhashError>> => {\n const encoded = encodeAttributes(attributes);\n if (encoded.isErr()) return Result.err(encoded.error);\n return (\n await call(FAILURES.setPersonAttributesSync, () =>\n native.setPersonAttributesState(encoded.value),\n )\n ).map(toAttributesResult);\n },\n\n getCurrentPerson: async (options: { forceFetch?: boolean } = {}) =>\n (await readPerson(options.forceFetch ?? false)).map(toCurrentPerson),\n\n /** Answers an entitlement check from the person read, as the TypeScript core does. */\n hasPerk: async (perkSlug: PerkSlug, options: { forceFetch?: boolean } = {}) =>\n (await readPerson(options.forceFetch ?? false)).map((state): HasPerkResult => {\n const snapshot = toCurrentPerson(state);\n const grant = findActiveGrant(Option.fromNullOr(snapshot.person), perkSlug);\n return {\n ...Option.match(grant, { onNone: () => ({}), onSome: (found) => ({ grant: found }) }),\n hasAccess: Option.isSome(grant),\n isExpired: snapshot.isExpired,\n isStale: snapshot.isStale,\n reason: snapshot.reason,\n };\n }),\n\n resetCache: () => call(FAILURES.resetCache, () => native.resetPersonCache()),\n\n /**\n * Evaluates flags and stores the answer under the keys asked for, which\n * is where the hook that asked reads it, whatever the native side echoes.\n */\n getFeatureFlags: (flagKeys?: ReadonlyArray<string>) =>\n call(FAILURES.getFeatureFlags, async () => {\n const result = await native.getFeatureFlags(\n flagKeys === undefined ? undefined : [...flagKeys],\n );\n publishFlags(result, normalizeFeatureFlagKeys(flagKeys));\n return toFlags(result);\n }),\n\n getPaywallForLocation: async (location: string) => {\n const json = await call(FAILURES.getPaywallForLocation, () => native.getPaywall(location));\n return json.andThen((value) =>\n EffectResult.match(EffectResult.flatMap(decodeJson(value), decodePaywall), {\n onFailure: () =>\n Result.err(\n new VoidhashError(\n \"FAILED_TO_GET_PAYWALL_FOR_LOCATION\",\n `FAILED_TO_GET_PAYWALL_FOR_LOCATION: unreadable paywall for \"${location}\"`,\n ),\n ),\n onSuccess: (paywall) => Result.ok(paywall),\n }),\n );\n },\n\n /** Loads the products, sharing a load already running; see `loadProducts`. */\n loadProducts,\n\n /**\n * Buys a product. A cancelled sheet and a pending payment are results; a\n * native client that rejects them with `USER_CANCELLED` or\n * `PURCHASE_PENDING` is read the same way. A store refusal with a reason\n * is `FAILED_TO_PURCHASE` with that reason. A completed purchase, and an\n * offer the end user could not get (`INELIGIBLE_FOR_OFFER` or\n * `OFFER_UNAVAILABLE`), outdate the products: the offers they list may\n * have changed.\n */\n purchase: async (\n productSlug: string,\n purchaseOptions: NativePurchaseOptions,\n ): Promise<Result<StorePurchaseResult, VoidhashError>> => {\n const exit = await Effect.runPromiseExit(\n Effect.tryPromise({\n catch: (error) => error,\n try: () => native.purchase(productSlug, purchaseOptions),\n }),\n );\n if (Exit.isSuccess(exit)) {\n const result = toPurchaseResult(exit.value, (message) =>\n reportContractViolation(\"purchase\", message),\n );\n if (Option.isNone(result)) {\n return Result.err(\n new VoidhashError(\n \"FAILED_TO_PURCHASE\",\n \"FAILED_TO_PURCHASE: the native client reported a purchase without its transaction\",\n ),\n );\n }\n if (result.value.status === \"purchased\") invalidateProducts();\n return Result.ok(result.value);\n }\n const error = Cause.squash(exit.cause);\n const failure = readNativeError(error);\n const code = Option.getOrElse(failure.code, () => \"\");\n if (code === \"USER_CANCELLED\") return Result.ok({ status: \"cancelled\" });\n if (code === \"PURCHASE_PENDING\") return Result.ok({ status: \"pending\" });\n if (code === \"INELIGIBLE_FOR_OFFER\" || code === \"OFFER_UNAVAILABLE\") invalidateProducts();\n const reason = R.get(PURCHASE_FAILURE_REASONS, code);\n if (Option.isSome(reason)) {\n return Result.err(\n new VoidhashError(\"FAILED_TO_PURCHASE\", `FAILED_TO_PURCHASE: ${failure.message}`, {\n cause: error,\n reason: reason.value,\n }),\n );\n }\n return Result.err(toVoidhashError(error, FAILURES.purchase));\n },\n\n /**\n * Revalidates the store's purchase history and answers the refreshed\n * person (`null` when there is none), publishing it as a read does. A\n * restore outdates the products: what was restored can change the\n * offers the end user is eligible for.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n restorePurchases: async (): Promise<Result<Person | null, VoidhashError>> => {\n const restored = await call(FAILURES.restorePurchases, async () => {\n const state = await native.restorePurchases();\n publishPerson(state);\n return state;\n });\n if (restored.isOk()) invalidateProducts();\n return restored.map((state) => Option.getOrNull(personOf(state)));\n },\n\n syncPurchases: () => call(FAILURES.syncPurchases, () => native.syncPurchases()),\n reportTransaction: (transaction: NativeReportedTransaction, isRestore: boolean) =>\n call(FAILURES.reportTransaction, () => native.reportTransaction(transaction, isRestore)),\n\n /** Answers whether the consent was also stored for later launches. */\n setAnalyticsConsent: (consent: NativeAnalyticsConsent) =>\n call(FAILURES.setAnalyticsConsent, () => native.setAnalyticsConsent(consent)),\n /** The consent the native client has in effect; `None` when it could not say. */\n getAnalyticsConsent: (): Option.Option<AnalyticsConsent> =>\n Option.filter(\n trySync(\"getAnalyticsConsent\", () => native.getAnalyticsConsent()),\n isAnalyticsConsent,\n ),\n /** Switches observer mode natively; a throw is reported, the facade's mode still switches. */\n setReadOnly: (readOnly: boolean) => {\n trySync(\"setReadOnly\", () => native.setReadOnly(readOnly));\n },\n\n flush: async () => (await call(FAILURES.flush, () => native.flush())).map(toFlushResult),\n\n /** The active session id, or `undefined` when there is none. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the facade's `getSessionId()` answer.\n getSessionId: (): string | undefined =>\n Option.getOrUndefined(\n Option.filter(\n trySync(\"getSessionId\", () => native.getSessionId()),\n (sessionId) => sessionId !== \"\",\n ),\n ),\n\n capture: (eventName: string, properties: Record<string, unknown> = {}) =>\n Option.map(encodeEvent(\"capture\", eventName, properties), (json) =>\n sendEvent(\"capture\", eventName, json, Option.none()),\n ),\n screen: (name: string, properties: Record<string, unknown> = {}) =>\n Option.map(encodeEvent(\"screen\", name, properties), (json) =>\n sendEvent(\"screen\", name, json, Option.none()),\n ),\n /**\n * Copies an event's (or a screen's) properties now and answers what\n * queues it later, given the time it was captured at: for an event the\n * facade holds back until an identity change switched the identity.\n * `None` for an event whose properties cannot be copied, already reported.\n */\n holdEvent: (\n operation: \"capture\" | \"screen\",\n name: string,\n properties: Record<string, unknown>,\n ): Option.Option<(capturedAt: number) => void> =>\n Option.map(\n encodeEvent(operation, name, properties),\n (json) => (capturedAt: number) => sendEvent(operation, name, json, Option.some(capturedAt)),\n ),\n /** The distinct id in effect, as last announced; `None` before the first `start()`. */\n currentDistinctId: (): Option.Option<string> =>\n Option.map(MutableRef.get(currentIdentity), (identity) => identity.distinctId),\n\n // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the Nitro contract, where an optional is `undefined`.\n showManageSubscriptions: (productSlug: string | undefined) =>\n call(FAILURES.showManageSubscriptions, () => native.showManageSubscriptions(productSlug)),\n // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the Nitro contract, where an optional is `undefined`.\n presentCodeRedemption: (code: string | undefined) =>\n call(FAILURES.presentCodeRedemption, () => native.presentCodeRedemption(code)),\n getStorefront: async () =>\n (await call(FAILURES.getStorefront, () => native.getStorefront())).map(\n // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the Nitro contract, where an optional is `undefined`.\n (storefront: NativeStorefront | undefined) =>\n storefront === undefined\n ? undefined\n : {\n countryCode: storefront.countryCode,\n ...(storefront.currencyCode === undefined\n ? {}\n : { currencyCode: storefront.currencyCode }),\n },\n ),\n canMakePayments: () => call(FAILURES.canMakePayments, () => native.canMakePayments()),\n\n appStoreBeginRefundRequest: (transactionId: string) =>\n call(FAILURES.appStoreBeginRefundRequest, (): Promise<RefundRequestStatus> =>\n native.appStoreBeginRefundRequest(transactionId),\n ),\n /**\n * The group's statuses. One whose renewal info cannot be read breaks the\n * contract: it is left out and reported.\n */\n appStoreSubscriptionStatus: async (groupId: string) =>\n (\n await call(FAILURES.appStoreSubscriptionStatus, () =>\n native.appStoreSubscriptionStatus(groupId),\n )\n ).map((statuses): ReadonlyArray<AppStoreSubscriptionStatus> =>\n Arr.filterMap(statuses, (status) => {\n const renewalInfo = decodeAppStoreRenewalInfo(status.renewalInfoJson);\n if (Option.isNone(renewalInfo)) {\n reportContractViolation(\n \"appStore.subscriptionStatus\",\n `The renewal info of transaction ${status.transaction.id} could not be read`,\n );\n return EffectResult.failVoid;\n }\n return EffectResult.succeed({\n renewalInfo: renewalInfo.value,\n state: status.state,\n transaction: toTransaction(status.transaction, (message) =>\n reportContractViolation(\"appStore.subscriptionStatus\", message),\n ),\n });\n }),\n ),\n appStoreCurrentEntitlements: async () =>\n (\n await call(FAILURES.appStoreCurrentEntitlements, () => native.appStoreCurrentEntitlements())\n ).map((transactions) =>\n transactions.map((transaction) =>\n toTransaction(transaction, (message) =>\n reportContractViolation(\"appStore.currentEntitlements\", message),\n ),\n ),\n ),\n appStoreAppTransaction: async () =>\n (await call(FAILURES.appStoreAppTransaction, () => native.appStoreAppTransaction())).andThen(\n (json): Result<AppTransaction, VoidhashError> =>\n Option.match(decodeAppTransaction(json), {\n onNone: () =>\n Result.err(\n new VoidhashError(\n \"FAILED_TO_GET_APP_TRANSACTION\",\n \"FAILED_TO_GET_APP_TRANSACTION: the native client sent an app transaction this SDK cannot read\",\n ),\n ),\n onSome: (appTransaction) => Result.ok(appTransaction),\n }),\n ),\n\n googlePlayShowInAppMessages: async () =>\n (\n await call(FAILURES.googlePlayShowInAppMessages, () => native.googlePlayShowInAppMessages())\n ).map((result): GooglePlayInAppMessageResult =>\n result.status === \"subscriptionStatusUpdated\" && result.purchaseToken !== undefined\n ? { purchaseToken: result.purchaseToken, status: \"subscriptionStatusUpdated\" }\n : { status: \"noActionNeeded\" },\n ),\n googlePlayQueryPurchases: async (includeSuspended: boolean) =>\n (\n await call(FAILURES.googlePlayQueryPurchases, () =>\n native.googlePlayQueryPurchases(includeSuspended),\n )\n ).map((transactions) =>\n transactions.map((transaction) =>\n toTransaction(transaction, (message) =>\n reportContractViolation(\"googlePlay.queryPurchases\", message),\n ),\n ),\n ),\n googlePlayIsFeatureSupported: (feature: string) =>\n call(FAILURES.googlePlayIsFeatureSupported, () =>\n native.googlePlayIsFeatureSupported(feature),\n ),\n\n /**\n * Resolves with how the flow ended and rejects with a `VoidhashError` when\n * it could not be presented. A `FLOW_*` code the native side gives is\n * kept; a client that is not started is `FLOW_UNAVAILABLE`.\n *\n * The native coordinator runs the flow: it calls back only for the\n * actions named here, and answers a rejected call, a slow one and one\n * whose flow has ended itself.\n * A flow that ended in a purchase or a restore outdates the products, as\n * `purchase()` and `restorePurchases()` do: the native client reports\n * neither as a transaction update.\n */\n presentFlow: async (\n location: string,\n options: PresentFlowOptions = {},\n ): Promise<FlowResult> => {\n const handlers = options.actions ?? {};\n const onAction = async (name: string, argsJson: string) => {\n const handler = handlers[name];\n if (handler === undefined) {\n throw new VoidhashError(\"INVALID_ARGUMENT\", `no handler for app action \"${name}\"`);\n }\n const reply = await handler(decodeFlowValues(argsJson));\n return encodeFlowValues(reply ?? {});\n };\n const exit = await Effect.runPromiseExit(\n Effect.tryPromise({\n catch: (error) => error,\n try: () =>\n native.presentFlow(\n location,\n {\n actions: R.keys(handlers),\n inputJson: encodeFlowValues(options.input ?? {}),\n ...(options.revision === undefined ? {} : { revision: options.revision }),\n },\n onAction,\n ),\n }),\n );\n if (Exit.isSuccess(exit)) {\n const parsed = parseFlowResult(exit.value);\n if (EffectResult.isFailure(parsed)) throw parsed.failure;\n if (parsed.success.outcome === \"purchased\" || parsed.success.outcome === \"restored\") {\n invalidateProducts();\n }\n return parsed.success;\n }\n const failure = readNativeError(Cause.squash(exit.cause));\n const code = Option.getOrElse(failure.code, () => \"\");\n if (NOT_STARTED_CODES.includes(code)) {\n throw flowError(\"FLOW_UNAVAILABLE\", new NotInitializedError().message);\n }\n throw isFlowErrorCode(code)\n ? new VoidhashError(code, failure.message)\n : flowError(\"FLOW_PRESENTATION_FAILED\", failure.message);\n },\n updateFlowInput: (values: FlowValues) =>\n call(FAILURES.updateFlowInput, () => native.updateFlowInput(encodeFlowValues(values))),\n dismissFlow: () => call(FAILURES.dismissFlow, () => native.dismissFlow()),\n } as const;\n};\n\n/** The facade-facing client over one native hybrid. */\nexport type NativeClientAdapter = ReturnType<typeof makeNativeClientAdapter>;\n","import * as Arr from \"effect/Array\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\nimport * as R from \"effect/Record\";\nimport * as Result from \"effect/Result\";\n\n/**\n * Values, nested ones included, that one event's properties may hold. No\n * product event comes close; an object graph passed by mistake (a press\n * event, a navigation or error object) runs to many thousands, and copying it\n * would hold up the thread that captured it.\n */\nexport const EVENT_PROPERTY_VALUE_LIMIT = 10_000;\n\nclass EventPropertyValueLimitExceeded extends Error {\n constructor() {\n super(`holds more than ${EVENT_PROPERTY_VALUE_LIMIT} values`);\n }\n}\n\n/**\n * Copies an event's properties into values JSON can always hold, the way\n * `JSON.stringify` would write them except where it would throw or write\n * nothing useful: a `bigint` becomes its decimal string, a non-finite number\n * `null`, and a reference back to an object that contains it is left out.\n * `undefined`, functions and symbols are left out (`null` inside an array),\n * and `toJSON` is honoured, so a `Date` becomes its ISO string.\n *\n * The copy is taken as the event is captured, so a host that mutates the\n * object afterwards does not change the queued event. Fails with the reason\n * when the properties cannot be copied at all: more than\n * {@link EVENT_PROPERTY_VALUE_LIMIT} values, or a getter or `toJSON` that\n * throws.\n */\nexport const toJsonSafeProperties = (\n properties: Record<string, unknown>,\n): Result.Result<Record<string, unknown>, string> => {\n let remaining = EVENT_PROPERTY_VALUE_LIMIT;\n // By identity: a structural set would hash, and so read, the host's whole\n // object graph.\n const ancestors = new WeakSet<object>();\n\n const copy = (value: unknown): Option.Option<unknown> => {\n remaining -= 1;\n if (remaining < 0) throw new EventPropertyValueLimitExceeded();\n if (P.isString(value) || P.isBoolean(value)) return Option.some(value);\n // oxlint-disable-next-line effect/prefer-option-over-null -- JSON `null` is the value written for a number JSON cannot hold.\n if (P.isNumber(value)) return Option.some(Number.isFinite(value) ? value : null);\n if (P.isBigInt(value)) return Option.some(value.toString());\n // oxlint-disable-next-line effect/prefer-option-over-null -- JSON `null` is a property value like any other.\n if (P.isNull(value)) return Option.some(null);\n // Functions, symbols and `undefined` have no JSON form.\n return P.isObjectOrArray(value) ? copyObject(value) : Option.none();\n };\n\n const copyEntries = (value: object): Option.Option<unknown> => {\n if (Array.isArray(value)) {\n // oxlint-disable-next-line effect/prefer-option-over-null -- JSON writes `null` for an array item it cannot hold.\n return Option.some(value.map((item: unknown) => Option.getOrNull(copy(item))));\n }\n if (!P.isObject(value)) return Option.none();\n return Option.some(\n R.fromEntries(\n R.keys(value).flatMap((key) =>\n Arr.fromOption(Option.map(copy(value[key]), (item) => [key, item] as const)),\n ),\n ),\n );\n };\n\n const copyObject = (value: object): Option.Option<unknown> => {\n if (ancestors.has(value)) return Option.none();\n ancestors.add(value);\n const toJson = Reflect.get(value, \"toJSON\");\n const json: unknown = P.isFunction(toJson) ? Reflect.apply(toJson, value, []) : value;\n const copied = json === value ? copyEntries(value) : copy(json);\n ancestors.delete(value);\n return copied;\n };\n\n return Result.try({\n catch: (error) =>\n error instanceof EventPropertyValueLimitExceeded\n ? error.message\n : `could not be read${P.isError(error) ? ` (${error.message})` : \"\"}`,\n try: () => Option.getOrElse(Option.filter(copy(properties), P.isObject), () => ({})),\n });\n};\n","import * as Arr from \"effect/Array\";\nimport * as Option from \"effect/Option\";\n\nimport type { EntitlementGrant, Person } from \"../entities/person\";\n\nexport type { EntitlementGrant };\n\n/**\n * Finds the active grant for a perk in a person snapshot. `None` when the\n * person has no snapshot or no active grant for the perk — both mean \"no\n * access\".\n *\n * `perkSlug` is the slug configured in Studio, matched against the grant's\n * `perkSlug`. A grant's `perkId` (the perk's internal id) matches too, so a\n * snapshot cached before grants carried a slug, or a check by id, still\n * answers.\n */\nexport const findActiveGrant = (\n person: Option.Option<Person>,\n perkSlug: string,\n): Option.Option<EntitlementGrant> =>\n Option.flatMap(person, (snapshot) =>\n Arr.findFirst(\n snapshot.entitlements.grants,\n (grant) =>\n grant.status === \"active\" && (grant.perkSlug === perkSlug || grant.perkId === perkSlug),\n ),\n );\n","import * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport type { ProductSlug } from \"../schema/registry\";\nimport {\n EnvironmentValue,\n enumOrUnknown,\n listOrEmpty,\n optionalNullable,\n PaymentModeValue,\n PeriodValue,\n PriceValue,\n} from \"./decoding\";\nimport type { Offer, PaymentMode, Period, Price } from \"./product\";\nimport type { Environment, Transaction } from \"./transaction\";\n\n/*\n * The App Store's own view of products and transactions, with StoreKit's\n * field names. The native client sends each as JSON (dates as milliseconds\n * since the epoch); the decoders here read it forward-compatibly.\n */\n\n/** StoreKit's `Product.ProductType`. */\nexport type AppStoreProductType =\n | \"consumable\"\n | \"nonConsumable\"\n | \"autoRenewable\"\n | \"nonRenewable\"\n | \"unknown\";\n\n/** StoreKit's `Product.SubscriptionOffer.OfferType`. */\nexport type AppStoreOfferType = \"introductory\" | \"promotional\" | \"winBack\" | \"unknown\";\n\n/** A StoreKit `Product.SubscriptionOffer`, whether or not this end user can buy it. */\nexport interface AppStoreOffer {\n /** The offer's id in App Store Connect; absent for the introductory offer. */\n readonly id?: string;\n readonly type: AppStoreOfferType;\n readonly paymentMode: PaymentMode;\n /** The length of one period of the offer. */\n readonly period: Period;\n /** How many periods the offer lasts. */\n readonly periodCount: number;\n /** What one period costs; zero for a free trial. */\n readonly price: Price;\n}\n\n/** A StoreKit `Product` as the App Store reports it. */\nexport interface AppStoreProductInfo {\n readonly subscriptionGroupId?: string;\n /** The product's level in its subscription group (iOS 16.4 and later). */\n readonly subscriptionGroupLevel?: number;\n /** The subscription group's name (iOS 16.4 and later). */\n readonly subscriptionGroupDisplayName?: string;\n readonly isFamilyShareable: boolean;\n readonly productType: AppStoreProductType;\n /** The introductory offer, whether or not this end user is eligible for it. */\n readonly introductoryOffer?: AppStoreOffer;\n readonly promotionalOffers: ReadonlyArray<AppStoreOffer>;\n /** Win-back offers (iOS 18 and later). */\n readonly winBackOffers: ReadonlyArray<AppStoreOffer>;\n /** Whether this end user can get the group's introductory offer; absent when unknown. */\n readonly isEligibleForIntroOffer?: boolean;\n}\n\n/** StoreKit's `Transaction.OwnershipType`. */\nexport type AppStoreOwnershipType = \"purchased\" | \"familyShared\" | \"unknown\";\n\n/** StoreKit's `Transaction.RevocationReason`. */\nexport type AppStoreRevocationReason = \"developerIssue\" | \"other\" | \"unknown\";\n\n/** A StoreKit `Transaction` as the App Store reports it. */\nexport interface AppStoreTransactionInfo {\n readonly ownershipType: AppStoreOwnershipType;\n /** The ISO 3166-1 alpha-2 country of the storefront it was bought in. */\n readonly storefrontCountryCode?: string;\n /** Whether the end user upgraded to another subscription in the group. */\n readonly isUpgraded: boolean;\n /** When the App Store refunded or revoked it, in milliseconds since the epoch. */\n readonly revocationDate?: number;\n readonly revocationReason?: AppStoreRevocationReason;\n readonly appTransactionId?: string;\n /** The transaction's signed JWS, for your own server to verify. */\n readonly jwsRepresentation: string;\n}\n\n/** StoreKit's `Product.SubscriptionInfo.RenewalState`. */\nexport type AppStoreSubscriptionState =\n | \"subscribed\"\n | \"expired\"\n | \"inBillingRetryPeriod\"\n | \"inGracePeriod\"\n | \"revoked\"\n | \"unknown\";\n\n/** StoreKit's `RenewalInfo.ExpirationReason`. */\nexport type AppStoreExpirationReason =\n | \"autoRenewDisabled\"\n | \"billingError\"\n | \"didNotConsentToPriceIncrease\"\n | \"productUnavailable\"\n | \"unknown\";\n\n/** StoreKit's `RenewalInfo.PriceIncreaseStatus`. */\nexport type AppStorePriceIncreaseStatus = \"noIncreasePending\" | \"pending\" | \"agreed\" | \"unknown\";\n\n/** A StoreKit `Product.SubscriptionInfo.RenewalInfo`. */\nexport interface AppStoreRenewalInfo {\n readonly willAutoRenew: boolean;\n /** The product the subscription renews into. */\n readonly autoRenewProductId?: string;\n readonly expirationReason?: AppStoreExpirationReason;\n /** When the billing grace period ends, in milliseconds since the epoch. */\n readonly gracePeriodExpiresAt?: number;\n readonly isInBillingRetry: boolean;\n readonly priceIncreaseStatus?: AppStorePriceIncreaseStatus;\n /** What the next renewal costs. */\n readonly renewalPrice?: Price;\n readonly eligibleWinBackOfferIds: ReadonlyArray<string>;\n}\n\n/** One of a subscription group's statuses on this device: the end user's own. */\nexport interface AppStoreSubscriptionStatus {\n readonly state: AppStoreSubscriptionState;\n /** The subscription's latest transaction. */\n readonly transaction: Transaction;\n readonly renewalInfo: AppStoreRenewalInfo;\n}\n\n/** StoreKit's `AppStore.Platform`. */\nexport type AppStorePlatform = \"iOS\" | \"macOS\" | \"tvOS\" | \"visionOS\" | \"unknown\";\n\n/** StoreKit's `AppTransaction`: how the end user got the app. */\nexport interface AppTransaction {\n /** The app version the end user first got. */\n readonly originalAppVersion: string;\n /** When the end user first got the app, in milliseconds since the epoch. */\n readonly originalPurchaseDate: number;\n readonly environment: Environment;\n readonly appTransactionId?: string;\n readonly originalPlatform?: AppStorePlatform;\n /** The app transaction's signed JWS, for your own server to verify. */\n readonly jwsRepresentation: string;\n}\n\n/** How `beginRefundRequest()` ended: Apple received the request, or the end user closed the sheet. */\nexport type RefundRequestStatus = \"success\" | \"userCancelled\";\n\n/**\n * A purchase the end user started outside the app, such as a promoted\n * in-app purchase or a win-back offer on the App Store. Complete it with\n * `purchase()`.\n */\nexport interface AppStorePurchaseIntent {\n readonly productSlug: ProductSlug;\n /** The offer the end user chose, when they chose one. */\n readonly offer?: Offer;\n}\n\nconst AppStoreOfferValue = Schema.Struct({\n id: optionalNullable(Schema.String),\n type: enumOrUnknown([\"introductory\", \"promotional\", \"winBack\"]),\n paymentMode: PaymentModeValue,\n period: PeriodValue,\n periodCount: Schema.Number,\n price: PriceValue,\n});\n\nconst AppStoreProductJson = Schema.fromJsonString(\n Schema.Struct({\n subscriptionGroupId: optionalNullable(Schema.String),\n subscriptionGroupLevel: optionalNullable(Schema.Number),\n subscriptionGroupDisplayName: optionalNullable(Schema.String),\n isFamilyShareable: Schema.Boolean,\n productType: enumOrUnknown([\"consumable\", \"nonConsumable\", \"autoRenewable\", \"nonRenewable\"]),\n introductoryOffer: optionalNullable(AppStoreOfferValue),\n promotionalOffers: listOrEmpty(AppStoreOfferValue),\n winBackOffers: listOrEmpty(AppStoreOfferValue),\n isEligibleForIntroOffer: optionalNullable(Schema.Boolean),\n }),\n);\n\nconst AppStoreTransactionJson = Schema.fromJsonString(\n Schema.Struct({\n ownershipType: enumOrUnknown([\"purchased\", \"familyShared\"]),\n storefrontCountryCode: optionalNullable(Schema.String),\n isUpgraded: Schema.Boolean,\n revocationDate: optionalNullable(Schema.Number),\n revocationReason: optionalNullable(enumOrUnknown([\"developerIssue\", \"other\"])),\n appTransactionId: optionalNullable(Schema.String),\n jwsRepresentation: Schema.String,\n }),\n);\n\nconst AppStoreRenewalInfoJson = Schema.fromJsonString(\n Schema.Struct({\n willAutoRenew: Schema.Boolean,\n autoRenewProductId: optionalNullable(Schema.String),\n expirationReason: optionalNullable(\n enumOrUnknown([\n \"autoRenewDisabled\",\n \"billingError\",\n \"didNotConsentToPriceIncrease\",\n \"productUnavailable\",\n ]),\n ),\n gracePeriodExpiresAt: optionalNullable(Schema.Number),\n isInBillingRetry: Schema.Boolean,\n priceIncreaseStatus: optionalNullable(\n enumOrUnknown([\"noIncreasePending\", \"pending\", \"agreed\"]),\n ),\n renewalPrice: optionalNullable(PriceValue),\n eligibleWinBackOfferIds: listOrEmpty(Schema.String),\n }),\n);\n\nconst AppTransactionJson = Schema.fromJsonString(\n Schema.Struct({\n originalAppVersion: Schema.String,\n originalPurchaseDate: Schema.Number,\n environment: EnvironmentValue,\n appTransactionId: optionalNullable(Schema.String),\n originalPlatform: optionalNullable(enumOrUnknown([\"iOS\", \"macOS\", \"tvOS\", \"visionOS\"])),\n jwsRepresentation: Schema.String,\n }),\n);\n\n/** Reads a product's App Store part; `None` when it is not one. */\nexport const decodeAppStoreProduct = (json: string): Option.Option<AppStoreProductInfo> =>\n Schema.decodeUnknownOption(AppStoreProductJson)(json);\n\n/** Reads a transaction's App Store part; `None` when it is not one. */\nexport const decodeAppStoreTransaction = (json: string): Option.Option<AppStoreTransactionInfo> =>\n Schema.decodeUnknownOption(AppStoreTransactionJson)(json);\n\n/** Reads a subscription status's renewal info; `None` when it is not one. */\nexport const decodeAppStoreRenewalInfo = (json: string): Option.Option<AppStoreRenewalInfo> =>\n Schema.decodeUnknownOption(AppStoreRenewalInfoJson)(json);\n\n/** Reads the app transaction; `None` when it is not one. */\nexport const decodeAppTransaction = (json: string): Option.Option<AppTransaction> =>\n Schema.decodeUnknownOption(AppTransactionJson)(json);\n","import * as Arr from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\nimport * as R from \"effect/Record\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\n\n/*\n * Schema building blocks for the payloads the SDK reads but does not define:\n * the server's person snapshot and the store parts the native client sends as\n * JSON. They read forward-compatibly: a value a newer server or store adds\n * never fails decoding.\n */\n\n/**\n * A string from a closed set the SDK knows. A value outside `values` decodes\n * as `\"unknown\"`, so a newer server or store never breaks decoding.\n */\nexport const enumOrUnknown = <const Value extends string>(values: ReadonlyArray<Value>) => {\n const isKnown = (value: string): value is Value => values.some((known) => known === value);\n return Schema.String.pipe(\n Schema.decodeTo(\n Schema.Literals([...values, \"unknown\"]),\n SchemaTransformation.transform<Value | \"unknown\", string>({\n decode: (value) => (isKnown(value) ? value : \"unknown\"),\n encode: (value) => value,\n }),\n ),\n );\n};\n\n/**\n * A string from a closed set the server names its own way (`app_store`),\n * decoded to the SDK's name for it (`appStore`). A value missing from `names`\n * decodes as `\"unknown\"`.\n */\nexport const renamedEnumOrUnknown = <const Value extends string>(\n names: Readonly<Record<string, Value>>,\n) =>\n Schema.String.pipe(\n Schema.decodeTo(\n Schema.Literals([...R.values(names), \"unknown\"]),\n SchemaTransformation.transform<Value | \"unknown\", string>({\n decode: (wire) => Option.getOrElse(R.get(names, wire), () => \"unknown\" as const),\n encode: (value) =>\n Option.getOrElse(\n Arr.findFirst(R.toEntries(names), ([, name]) => name === value),\n () => [value, value] as const,\n )[0],\n }),\n ),\n );\n\n/** A field the payload may send as `null` or leave out; either decodes as an absent key. */\nexport const optionalNullable = <S extends Schema.Top>(schema: S) =>\n Schema.optional(\n Schema.NullOr(schema).pipe(\n Schema.decodeTo(\n Schema.UndefinedOr(Schema.toType(schema)),\n // oxlint-disable-next-line effect/prefer-option-over-null -- the payload's own `null`, read as the absent key the SDK's types use.\n SchemaTransformation.transform<S[\"Type\"] | undefined, S[\"Type\"] | null>({\n decode: (value) => value ?? undefined,\n encode: (value) => value ?? null,\n }),\n ),\n ),\n );\n\n/**\n * An ISO 8601 timestamp the payload may send, decoded as milliseconds since\n * the epoch. One that is `null`, left out, not a string, or that `Date`\n * cannot read decodes as an absent key: a date the SDK cannot read never\n * costs the entry it is on, so a grant with such an expiry still grants\n * access.\n */\nexport const OptionalEpochMillis = Schema.optional(\n Schema.Unknown.pipe(\n Schema.decodeTo(\n Schema.UndefinedOr(Schema.Finite),\n // oxlint-disable-next-line effect/prefer-option-over-null -- the payload's own `null`, read as the absent key the SDK's types use.\n SchemaTransformation.transform<number | undefined, unknown>({\n decode: (value) => {\n // oxlint-disable-next-line effect/use-clock-service -- parses a timestamp the server sent; no clock is read.\n const millis = P.isString(value) ? Date.parse(value) : Number.NaN;\n return Number.isFinite(millis) ? millis : undefined;\n },\n // oxlint-disable-next-line effect/use-clock-service -- formats a timestamp; no clock is read.\n encode: (millis) => (millis === undefined ? null : new Date(millis).toISOString()),\n }),\n ),\n ),\n);\nexport type OptionalEpochMillis = typeof OptionalEpochMillis.Type;\n\n/**\n * An array whose elements the SDK cannot read are left out, so one malformed\n * entry never costs the others.\n */\nexport const readableElements = <S extends Schema.Codec<unknown, unknown, never, never>>(\n element: S,\n) => {\n const decodeElement = Schema.decodeUnknownOption(element);\n return Schema.Array(Schema.Unknown).pipe(\n Schema.decodeTo(\n Schema.Array(Schema.toType(element)),\n SchemaTransformation.transform<ReadonlyArray<S[\"Type\"]>, ReadonlyArray<unknown>>({\n decode: (items) => Arr.getSomes(items.map((item) => decodeElement(item))),\n encode: (items) => items,\n }),\n ),\n );\n};\n\n/** A list the payload may leave out; decodes as empty then. */\nexport const listOrEmpty = <S extends Schema.Codec<unknown, unknown, never, never>>(element: S) =>\n readableElements(element).pipe(Schema.withDecodingDefaultKey(Effect.succeed([])));\n\n/** A `Price` as the native client sends it. */\nexport const PriceValue = Schema.Struct({\n amount: Schema.Number,\n amountMicros: Schema.Number,\n currencyCode: Schema.String,\n formatted: Schema.String,\n});\nexport type PriceValue = typeof PriceValue.Type;\n\n/** A `Period` as the native client sends it. */\nexport const PeriodValue = Schema.Struct({\n unit: enumOrUnknown([\"day\", \"week\", \"month\", \"year\"]),\n count: Schema.Number,\n iso8601: Schema.String,\n});\nexport type PeriodValue = typeof PeriodValue.Type;\n\n/** A pricing phase's payment mode as the native client sends it. */\nexport const PaymentModeValue = enumOrUnknown([\"freeTrial\", \"payAsYouGo\", \"payUpFront\"]);\n\n/** An environment as the native client sends it, in the SDK's names. */\nexport const EnvironmentValue = enumOrUnknown([\"production\", \"sandbox\", \"xcode\", \"development\"]);\n","import * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport type { PerkSlug, ProductSlug } from \"../schema/registry\";\nimport {\n enumOrUnknown,\n listOrEmpty,\n OptionalEpochMillis,\n optionalNullable,\n renamedEnumOrUnknown,\n} from \"./decoding\";\nimport type { Environment } from \"./transaction\";\n\n/*\n * The person as the Voidhash API reports them (its person snapshot), read\n * into the SDK's names: timestamps become milliseconds since the epoch,\n * `null` an absent field, and the server's snake_case values the SDK's\n * camelCase ones. Values a newer server adds read as `\"unknown\"`, and a list\n * entry this version cannot read is left out, so a snapshot always keeps the\n * access it grants.\n *\n * The field names are the server's (`SdkPerson` in its contract). Keep them in\n * step with the generated client in `networking/generated/sdk-client.ts` when\n * it is regenerated.\n */\n\n/** Where a subscription or grant comes from. */\nexport type PersonStore = \"appStore\" | \"googlePlay\" | \"stripe\" | \"other\" | \"unknown\";\n\n/** A perk the person has or had. */\nexport interface EntitlementGrant {\n readonly perkId: string;\n /** The perk's slug, which access is checked by; absent when the perk was deleted. */\n readonly perkSlug?: PerkSlug;\n /** `active` while the person has access, `expired` once it ended. */\n readonly status: \"active\" | \"expired\" | \"unknown\";\n /** What granted it: a `subscription`, a one-time `purchase`, or a `manual` grant. */\n readonly source: \"subscription\" | \"purchase\" | \"manual\" | \"unknown\";\n /** The id of the subscription or purchase that granted it; absent for a manual grant. */\n readonly sourceId?: string;\n /** The person who owns it: this person, one merged into them, or one sharing it with them. */\n readonly sourcePersonId: string;\n /** When the access ends, in milliseconds since the epoch; absent when it does not end. */\n readonly expiresAt?: number;\n}\n\n/**\n * A subscription's state:\n *\n * - `active`: paid and renewing (or canceled, running until it ends).\n * - `trialing`: in a free trial.\n * - `inGracePeriod`: a renewal payment failed and the store keeps access\n * until `gracePeriodExpiresAt` while it retries.\n * - `inBillingRetry`: a renewal payment failed and the store is retrying it.\n * - `onHold`: Google Play account hold: payment failed and access is paused.\n * - `paused`: the end user paused it on Google Play until `resumesAt`.\n * - `expired`: it ended.\n * - `revoked`: the store withdrew it, such as after a refund.\n */\nexport type SubscriptionStatus =\n | \"active\"\n | \"trialing\"\n | \"inGracePeriod\"\n | \"inBillingRetry\"\n | \"onHold\"\n | \"paused\"\n | \"expired\"\n | \"revoked\"\n | \"unknown\";\n\n/** Which price period a subscription is in: a free `trial`, an `intro` price, or the `regular` price. */\nexport type SubscriptionPeriodType = \"trial\" | \"intro\" | \"regular\" | \"unknown\";\n\n/** A price change the store announced for a subscription's next renewals. */\nexport interface SubscriptionPendingPrice {\n readonly amountMicros: number;\n /** ISO 4217 currency code. */\n readonly currency: string;\n /** When the new price takes effect, in milliseconds since the epoch. */\n readonly effectiveAt?: number;\n /** Whether the end user agreed to it, where the store asks; absent where it does not. */\n readonly consent?: \"pending\" | \"accepted\" | \"unknown\";\n}\n\n/**\n * A subscription that has not ended, as the server knows it across devices\n * and stores. Timestamps are milliseconds since the epoch. What the person\n * can use always comes from their entitlements, never from this.\n */\nexport interface Subscription {\n readonly subscriptionId: string;\n /** The Voidhash product id; absent when its store product is not linked to one. */\n readonly productId?: string;\n readonly productSlug?: ProductSlug;\n readonly store: PersonStore;\n /** Where it was bought; `development` for development-mode purchases. */\n readonly environment: Environment;\n readonly status: SubscriptionStatus;\n readonly periodType: SubscriptionPeriodType;\n readonly startsAt?: number;\n /** When the current period ends. */\n readonly expiresAt?: number;\n /** Whether it renews at `expiresAt`. */\n readonly willRenew: boolean;\n /** When auto-renewal was turned off or it was canceled. */\n readonly canceledAt?: number;\n /** The product it renews into at `expiresAt`: a downgrade or plan change waiting for renewal. */\n readonly renewsToProductSlug?: ProductSlug;\n readonly gracePeriodExpiresAt?: number;\n /** When the store first failed to charge the renewal. */\n readonly billingIssueDetectedAt?: number;\n /** When a paused subscription resumes (Google Play). */\n readonly resumesAt?: number;\n readonly pendingPrice?: SubscriptionPendingPrice;\n /** The offer it was bought with. */\n readonly offerId?: string;\n /** Whether the person has it through App Store Family Sharing. */\n readonly isFamilyShared: boolean;\n readonly refundedAt?: number;\n readonly revokedAt?: number;\n}\n\n/** One subscription the person owns or shares, ended or not. */\nexport interface SubscriptionHistoryEntry {\n readonly subscriptionId: string;\n readonly productId?: string;\n readonly productSlug?: ProductSlug;\n readonly store: PersonStore;\n readonly status: SubscriptionStatus;\n readonly isTrial: boolean;\n readonly startsAt?: number;\n readonly expiresAt?: number;\n readonly canceledAt?: number;\n readonly refundedAt?: number;\n readonly sourcePersonId: string;\n}\n\n/** One purchase the person owns or shares, one per store transaction. */\nexport interface PurchaseHistoryEntry {\n readonly purchaseId: string;\n readonly productId?: string;\n readonly productSlug?: ProductSlug;\n /** The store's id for the transaction, such as an App Store transaction id. */\n readonly providerKey: string;\n readonly type: \"oneTime\" | \"consumable\" | \"subscription\" | \"unknown\";\n /** When it was recorded. */\n readonly createdAt?: number;\n readonly refundedAt?: number;\n readonly revokedAt?: number;\n readonly sourcePersonId: string;\n}\n\n/** The end user as Voidhash knows them: who they are, what they can use and what they bought. */\nexport interface Person {\n readonly personId: string;\n readonly distinctId: string;\n readonly email?: string;\n readonly name?: string;\n readonly entitlements: {\n /** The perks the person has or had, one per perk. */\n readonly grants: ReadonlyArray<EntitlementGrant>;\n };\n readonly subscriptions: {\n /**\n * The subscription that matters most now, of the ones that have not\n * ended: active first, then trialing, in a grace period, in billing\n * retry, on hold, paused.\n */\n readonly current?: Subscription;\n /**\n * Every subscription that has not ended, including ones in a grace\n * period, in billing retry, on hold or paused: what a \"manage\n * subscription\" screen lists. Access comes from entitlements, never from\n * this list.\n */\n readonly all: ReadonlyArray<Subscription>;\n readonly history: ReadonlyArray<SubscriptionHistoryEntry>;\n };\n readonly purchases: {\n readonly history: ReadonlyArray<PurchaseHistoryEntry>;\n };\n}\n\nconst StoreValue = renamedEnumOrUnknown({\n app_store: \"appStore\",\n google_play: \"googlePlay\",\n stripe: \"stripe\",\n other: \"other\",\n});\n\n/** A field a server older than it left out. */\nconst withDefault = <S extends Schema.Top>(schema: S, value: S[\"Encoded\"]) =>\n schema.pipe(Schema.withDecodingDefaultKey(Effect.succeed(value)));\n\nconst GrantValue = Schema.Struct({\n perkId: Schema.String,\n perkSlug: optionalNullable(Schema.String),\n status: enumOrUnknown([\"active\", \"expired\"]),\n source: withDefault(enumOrUnknown([\"subscription\", \"purchase\", \"manual\"]), \"unknown\"),\n sourceId: optionalNullable(Schema.String),\n sourcePersonId: withDefault(Schema.String, \"\"),\n expiresAt: OptionalEpochMillis,\n});\n\n/** Statuses of current and past subscriptions alike: the server sends one list for both. */\nconst SubscriptionStatusValue = renamedEnumOrUnknown({\n active: \"active\",\n trialing: \"trialing\",\n in_grace_period: \"inGracePeriod\",\n in_billing_retry: \"inBillingRetry\",\n on_hold: \"onHold\",\n paused: \"paused\",\n expired: \"expired\",\n revoked: \"revoked\",\n});\n\nconst SubscriptionValue = Schema.Struct({\n subscriptionId: Schema.String,\n productId: optionalNullable(Schema.String),\n productSlug: optionalNullable(Schema.String),\n store: withDefault(StoreValue, \"unknown\"),\n environment: withDefault(\n renamedEnumOrUnknown({ production: \"production\", sandbox: \"sandbox\", test: \"development\" }),\n \"unknown\",\n ),\n status: SubscriptionStatusValue,\n periodType: withDefault(enumOrUnknown([\"trial\", \"intro\", \"regular\"]), \"unknown\"),\n startsAt: OptionalEpochMillis,\n expiresAt: OptionalEpochMillis,\n willRenew: withDefault(Schema.Boolean, false),\n canceledAt: OptionalEpochMillis,\n renewsToProductSlug: optionalNullable(Schema.String),\n gracePeriodExpiresAt: OptionalEpochMillis,\n billingIssueDetectedAt: OptionalEpochMillis,\n resumesAt: OptionalEpochMillis,\n pendingPrice: optionalNullable(\n Schema.Struct({\n amountMicros: Schema.Number,\n currency: Schema.String,\n effectiveAt: OptionalEpochMillis,\n consent: optionalNullable(enumOrUnknown([\"pending\", \"accepted\"])),\n }),\n ),\n offerId: optionalNullable(Schema.String),\n isFamilyShared: withDefault(Schema.Boolean, false),\n refundedAt: OptionalEpochMillis,\n revokedAt: OptionalEpochMillis,\n});\n\nconst SubscriptionHistoryEntryValue = Schema.Struct({\n subscriptionId: Schema.String,\n productId: optionalNullable(Schema.String),\n productSlug: optionalNullable(Schema.String),\n store: withDefault(StoreValue, \"unknown\"),\n status: SubscriptionStatusValue,\n isTrial: withDefault(Schema.Boolean, false),\n startsAt: OptionalEpochMillis,\n expiresAt: OptionalEpochMillis,\n canceledAt: OptionalEpochMillis,\n refundedAt: OptionalEpochMillis,\n sourcePersonId: withDefault(Schema.String, \"\"),\n});\n\nconst PurchaseHistoryEntryValue = Schema.Struct({\n purchaseId: Schema.String,\n productId: optionalNullable(Schema.String),\n productSlug: optionalNullable(Schema.String),\n providerKey: Schema.String,\n type: renamedEnumOrUnknown({\n one_time: \"oneTime\",\n consumable: \"consumable\",\n subscription: \"subscription\",\n }),\n createdAt: OptionalEpochMillis,\n refundedAt: OptionalEpochMillis,\n revokedAt: OptionalEpochMillis,\n sourcePersonId: withDefault(Schema.String, \"\"),\n});\n\n/**\n * A `current` subscription a snapshot cached before the server sent full\n * subscriptions cannot be read as one; it counts as none.\n */\nconst decodeCurrentSubscription = Schema.decodeUnknownOption(SubscriptionValue);\n\nconst PersonJson = Schema.fromJsonString(\n Schema.Struct({\n personId: withDefault(Schema.String, \"\"),\n distinctId: Schema.String,\n email: optionalNullable(Schema.String),\n name: optionalNullable(Schema.String),\n entitlements: withDefault(Schema.Struct({ grants: listOrEmpty(GrantValue) }), { grants: [] }),\n subscriptions: withDefault(\n Schema.Struct({\n current: optionalNullable(Schema.Unknown),\n all: listOrEmpty(SubscriptionValue),\n history: listOrEmpty(SubscriptionHistoryEntryValue),\n }),\n { all: [], history: [] },\n ),\n purchases: withDefault(Schema.Struct({ history: listOrEmpty(PurchaseHistoryEntryValue) }), {\n history: [],\n }),\n }),\n);\n\n/**\n * Reads a person snapshot the native client sent as JSON; `None` when it is\n * not one. Only `distinctId` is required: a snapshot that lacks something\n * else still answers the access it records.\n */\nexport const decodePerson = (json: string): Option.Option<Person> =>\n Option.map(Schema.decodeUnknownOption(PersonJson)(json), (wire): Person => {\n const current = Option.getOrUndefined(decodeCurrentSubscription(wire.subscriptions.current));\n return {\n ...wire,\n subscriptions: {\n all: wire.subscriptions.all,\n history: wire.subscriptions.history,\n ...(current === undefined ? {} : { current }),\n },\n };\n });\n","import * as Arr from \"effect/Array\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Str from \"effect/String\";\nimport { Atom, type AtomRegistry } from \"effect/reactivity\";\n\nimport type { VoidhashError } from \"../../errors\";\nimport type { Person } from \"../entities/person\";\nimport type { Product } from \"../entities/product\";\nimport type { FeatureFlagsResult } from \"../facade-types\";\nimport type { RuntimeSchema } from \"../schema/runtime\";\n\nexport type { FeatureFlagsResult };\n\n// The SDK's state atoms are `keepAlive`: they hold state rather than derive\n// it, so a value published while no component is subscribed (a background\n// refresh, a schema that lands after boot) must still be there for the next\n// read. Each client has its own registry, so nothing outlives the client.\n\n/**\n * Reactive store of the currently identified person. Published together with\n * its freshness through {@link publishCurrentPerson}; read by `useHasPerk`\n * and `useCurrentPerson`.\n */\nexport const currentPersonAtom: Atom.Writable<Option.Option<Person>> = Atom.keepAlive(\n Atom.make<Option.Option<Person>>(Option.none()),\n);\n\n/** How far a published person can be trusted, as the read that produced it reported. */\nexport interface PersonFreshness {\n /** Served from cache past its refresh window. */\n readonly isStale: boolean;\n /** Served from cache past its TTL. */\n readonly isExpired: boolean;\n}\n\n/** Freshness of a snapshot the server has just answered with. */\nexport const FRESH_PERSON: PersonFreshness = { isExpired: false, isStale: false };\n\n/**\n * Freshness of a person the server has not confirmed for this identity yet:\n * nothing is known about it, or all there is was carried over from another\n * identity. Matches what a read reports with nothing cached.\n */\nexport const UNCONFIRMED_PERSON: PersonFreshness = { isExpired: false, isStale: true };\n\n/** Freshness of the value in {@link currentPersonAtom}. */\nexport const currentPersonFreshnessAtom: Atom.Writable<PersonFreshness> = Atom.keepAlive(\n Atom.make<PersonFreshness>(FRESH_PERSON),\n);\n\n/**\n * Publishes the current person together with how far it can be trusted, in\n * one batch, so a hook never pairs a snapshot with another one's freshness.\n */\nexport const publishCurrentPerson = (\n registry: AtomRegistry.AtomRegistry,\n person: Option.Option<Person>,\n freshness: PersonFreshness,\n) =>\n Atom.batch(() => {\n registry.set(currentPersonFreshnessAtom, freshness);\n registry.set(currentPersonAtom, person);\n });\n\n/**\n * Reactive mirror of the runtime schema `SchemaManager` resolved at init and\n * refreshes in the background, for hooks that re-render when a newer schema\n * lands. `None` until init has resolved a schema. Operations read the schema\n * from `SchemaManager` itself, not from here.\n */\nexport const schemaAtom: Atom.Writable<Option.Option<RuntimeSchema>> = Atom.keepAlive(\n Atom.make<Option.Option<RuntimeSchema>>(Option.none()),\n);\n\n/** The products every `useProducts()` reads: one load for the whole client. */\nexport interface ProductsState {\n /** Every product the store returned, sorted by slug; `None` until a load answered. */\n readonly products: Option.Option<ReadonlyArray<Product>>;\n /** The error that stopped the last load; the products of the load before it are kept. */\n readonly error: Option.Option<VoidhashError>;\n /** A load is running. */\n readonly isLoading: boolean;\n}\n\n/** Products before any load. */\nexport const NO_PRODUCTS: ProductsState = {\n error: Option.none(),\n isLoading: false,\n products: Option.none(),\n};\n\n/**\n * The client's products, shared by every `useProducts()`. Loaded again when\n * the identity switches, the schema's product definitions change, or a\n * purchase completes, since offers and their eligibility are the end user's.\n */\nexport const productsAtom: Atom.Writable<ProductsState> = Atom.keepAlive(\n Atom.make<ProductsState>(NO_PRODUCTS),\n);\n\n/**\n * Reactive store of feature flag results, keyed by their normalized flag-key\n * request signature (see {@link normalizeFeatureFlagKeys}). Keeping every\n * request set in its own slot prevents one hook's fetch from overwriting the\n * value of another hook that asked for a different set of flags.\n */\nexport const featureFlagsByKeyAtom: Atom.Writable<Readonly<Record<string, FeatureFlagsResult>>> =\n Atom.keepAlive(Atom.make<Readonly<Record<string, FeatureFlagsResult>>>({}));\n\n/**\n * Counts identity switches: `identify()`, `reset()`, a switch the server\n * refused and the SDK undid. `identify()` and `reset()` clear the person and\n * the flags; hooks read this so a mounted hook refetches for the identity now\n * in place instead of showing the cleared state until it remounts.\n */\nexport const identityEpochAtom: Atom.Writable<number> = Atom.keepAlive(Atom.make(0));\n\n/**\n * Counts the runs of the client: every `init()` that started the native\n * client, the first one included. `end()` drops what a run loaded, such as\n * the products; a hook that loads on mount reads this, so it loads again when\n * the app calls `end()` and then `init()` while it stays mounted.\n */\nexport const clientRunAtom: Atom.Writable<number> = Atom.keepAlive(Atom.make(0));\n\nconst FeatureFlagKeysFromJson = Schema.fromJsonString(Schema.Array(Schema.String));\nconst encodeFeatureFlagKeys = Schema.encodeSync(FeatureFlagKeysFromJson);\n\nconst decodeFeatureFlagKeysFromJson = Schema.decodeSync(FeatureFlagKeysFromJson);\n\n/**\n * The sorted keys a signature other than `\"all\"` was built from; the inverse\n * of {@link normalizeFeatureFlagKeys}.\n */\nexport const decodeFeatureFlagKeys = (signature: string): ReadonlyArray<string> =>\n decodeFeatureFlagKeysFromJson(signature);\n\n/**\n * Normalizes a feature-flag request signature so that any callers asking for\n * the same set of keys (regardless of order) share the same atom slot. We\n * sort a copy because the caller's array is part of their input and must not\n * be mutated.\n */\nexport const normalizeFeatureFlagKeys = (flagKeys?: readonly string[]): string => {\n return Option.match(Option.fromUndefinedOr(flagKeys), {\n onNone: () => \"all\",\n onSome: (keys) =>\n Arr.match(keys, {\n onEmpty: () => \"all\",\n onNonEmpty: (values) => encodeFeatureFlagKeys(Arr.sort(values, Str.Order)),\n }),\n });\n};\n\nconst featureFlagsForNormalizedKeyAtom = Atom.family((normalizedKey: string) =>\n Atom.make((get): Option.Option<FeatureFlagsResult> => {\n const byKey = get(featureFlagsByKeyAtom);\n return Option.fromUndefinedOr(byKey[normalizedKey]);\n }),\n);\n\n/**\n * Derived atom that returns the cached `FeatureFlagsResult` for a particular\n * set of flag keys (or `null` if nothing has been published yet). Reusing\n * the same normalized key across requests means callers subscribe to the\n * minimum slice of state they care about.\n */\nexport const featureFlagsForKeysAtom = (flagKeys?: readonly string[]) =>\n featureFlagsForNormalizedKeyAtom(normalizeFeatureFlagKeys(flagKeys));\n","import * as Effect from \"effect/Effect\";\nimport * as R from \"effect/Record\";\nimport * as Schema from \"effect/Schema\";\n\nimport {\n RuntimePaywallLocationDefinition,\n RuntimePerkDefinition,\n RuntimeProductDefinition,\n type RuntimeSchema,\n} from \"./runtime\";\n\n/** A schema entry this SDK version could not read, left out of the decoded schema. */\nexport interface SkippedSchemaEntry {\n readonly collection: \"locations\" | \"perks\" | \"products\";\n readonly slug: string;\n}\n\nconst decodeLocation = Schema.decodeUnknownResult(RuntimePaywallLocationDefinition);\nconst decodePerk = Schema.decodeUnknownResult(RuntimePerkDefinition);\nconst decodeProduct = Schema.decodeUnknownResult(RuntimeProductDefinition);\n\nconst RuntimeSchemaDocument = Schema.Struct({\n locations: Schema.Record(Schema.String, Schema.Unknown),\n // The native iOS client's schema has no perks of its own; they are read from each product.\n perks: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n products: Schema.Record(Schema.String, Schema.Unknown),\n version: Schema.String,\n});\n\n/**\n * Decodes a schema entry by entry. A product, perk or location this SDK\n * version cannot read is left out and listed in `skipped`, so one entry a\n * newer server shapes differently never costs the app every other product.\n * Fails only when the document itself is not a schema.\n */\nexport const decodeRuntimeSchema = (input: unknown) =>\n Effect.map(Schema.decodeUnknownEffect(RuntimeSchemaDocument)(input), (document) => {\n const [locations, unreadableLocations] = R.partition(document.locations, (entry) =>\n decodeLocation(entry),\n );\n const [perks, unreadablePerks] = R.partition(document.perks ?? {}, (entry) =>\n decodePerk(entry),\n );\n const [products, unreadableProducts] = R.partition(document.products, (entry) =>\n decodeProduct(entry),\n );\n const skipped: ReadonlyArray<SkippedSchemaEntry> = [\n ...R.keys(unreadableLocations).map((slug) => ({ collection: \"locations\" as const, slug })),\n ...R.keys(unreadablePerks).map((slug) => ({ collection: \"perks\" as const, slug })),\n ...R.keys(unreadableProducts).map((slug) => ({ collection: \"products\" as const, slug })),\n ];\n const schema: RuntimeSchema = { locations, perks, products, version: document.version };\n return { schema, skipped };\n });\n","import * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\n/**\n * Product durations the server sends today. Decoded definitions accept any\n * string in their `duration` fields, so a duration added by a newer server\n * keeps its product readable; code that relies on the duration treats a\n * value outside this list as no duration.\n */\nexport const RuntimeProductDuration = Schema.Literals([\n \"weekly\",\n \"monthly\",\n \"quarterly\",\n \"semi-annual\",\n \"annual\",\n]);\nexport type RuntimeProductDuration = typeof RuntimeProductDuration.Type;\n\n/**\n * An offer of a product on one store: `id` is how paywalls and apps name it\n * (the same on every store), `offerId` the store's identifier.\n */\nexport const RuntimeStoreOffer = Schema.Struct({\n id: Schema.String,\n offerId: Schema.String,\n});\nexport type RuntimeStoreOffer = typeof RuntimeStoreOffer.Type;\n\nexport const RuntimeAppleAppStoreProductConfiguration = Schema.Struct({\n offers: Schema.optional(Schema.Array(RuntimeStoreOffer)),\n productId: Schema.String,\n});\nexport type RuntimeAppleAppStoreProductConfiguration =\n typeof RuntimeAppleAppStoreProductConfiguration.Type;\n\nexport const RuntimeGooglePlayProductConfiguration = Schema.Struct({\n basePlanId: Schema.optional(Schema.String),\n /** Developer offers on the base plan. */\n offers: Schema.optional(Schema.Array(RuntimeStoreOffer)),\n productId: Schema.String,\n});\nexport type RuntimeGooglePlayProductConfiguration =\n typeof RuntimeGooglePlayProductConfiguration.Type;\n\n/**\n * Development-mode pricing. `currencyCode` and `period` are plain strings so\n * a currency or period added by a newer server keeps the product readable.\n */\nexport const RuntimeDevelopmentProductConfiguration = Schema.Struct({\n currencyCode: Schema.String,\n duration: Schema.OptionFromNullOr(Schema.String),\n period: Schema.String,\n periodCount: Schema.Number,\n price: Schema.Number,\n priceInMinorUnits: Schema.Number,\n productId: Schema.String,\n warning: Schema.OptionFromNullOr(Schema.String),\n});\nexport type RuntimeDevelopmentProductConfiguration =\n typeof RuntimeDevelopmentProductConfiguration.Type;\n\nexport const RuntimeProductProviders = Schema.Struct({\n appleAppStore: Schema.optional(RuntimeAppleAppStoreProductConfiguration),\n development: Schema.optional(RuntimeDevelopmentProductConfiguration),\n googlePlay: Schema.optional(RuntimeGooglePlayProductConfiguration),\n});\nexport type RuntimeProductProviders = typeof RuntimeProductProviders.Type;\n\n/**\n * One product. `type` is a plain string (the server sends `subscription`,\n * `one-time` or `one-time-consumable` today) so a product type added by a\n * newer server keeps the product readable: only `one-time-consumable` is\n * ever consumed, anything else is finished as a non-consumable.\n */\nexport const RuntimeProductDefinition = Schema.Struct({\n configuration: Schema.Struct({\n perks: Schema.Record(Schema.String, Schema.Literal(true)),\n providers: RuntimeProductProviders,\n }),\n duration: Schema.optional(Schema.OptionFromNullOr(Schema.String)),\n id: Schema.optional(Schema.String),\n properties: Schema.Struct({ name: Schema.String }),\n slug: Schema.String,\n type: Schema.String,\n});\nexport type RuntimeProductDefinition = typeof RuntimeProductDefinition.Type;\n\nexport const RuntimePaywallLocationDefinition = Schema.Struct({\n description: Schema.OptionFromNullOr(Schema.String).pipe(\n Schema.withDecodingDefaultTypeKey(Effect.succeed(Option.none())),\n ),\n name: Schema.String,\n slug: Schema.String,\n});\nexport type RuntimePaywallLocationDefinition = typeof RuntimePaywallLocationDefinition.Type;\n\nexport const RuntimePerkDefinition = Schema.Struct({\n name: Schema.String,\n slug: Schema.String,\n});\nexport type RuntimePerkDefinition = typeof RuntimePerkDefinition.Type;\n\n/**\n * The full schema fetched from the server, decoded so nullable wire fields\n * are represented as `Option` inside the SDK.\n */\nexport const RuntimeSchemaValue = Schema.Struct({\n locations: Schema.Record(Schema.String, RuntimePaywallLocationDefinition),\n perks: Schema.Record(Schema.String, RuntimePerkDefinition),\n products: Schema.Record(Schema.String, RuntimeProductDefinition),\n version: Schema.String,\n});\nexport type RuntimeSchemaValue = typeof RuntimeSchemaValue.Type;\nexport type RuntimeSchema = RuntimeSchemaValue;\nexport type RuntimeSchemaEncoded = typeof RuntimeSchemaValue.Encoded;\n\nexport const createEmptyRuntimeSchema = (): RuntimeSchema => ({\n locations: {},\n perks: {},\n products: {},\n version: \"\",\n});\n","/**\n * Whether the end user agreed to usage analytics. `denied` and `pending` act\n * the same: nothing analytics-related is captured, stored or sent. Purchases,\n * restores, entitlements, identity, flags and paywalls are unaffected.\n */\nexport type AnalyticsConsent = \"granted\" | \"denied\" | \"pending\";\n\n/** Whether `value` is one of the {@link AnalyticsConsent} values. */\nexport const isAnalyticsConsent = (value: unknown): value is AnalyticsConsent =>\n value === \"granted\" || value === \"denied\" || value === \"pending\";\n\n/** What happens to analytics captured while consent is `\"pending\"`. */\nexport type AnalyticsWhilePending = \"drop\" | \"buffer\";\n","import * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\n\n/** What a rejection from a native hybrid says once the bridge's wrapping is removed. */\nexport interface NativeError {\n /** The leading `CODE` of a `\"CODE: detail\"` message, when it has one. */\n readonly code: Option.Option<string>;\n /**\n * The first line of the message. With a code, it starts at the code, so\n * the bridge's prefixes are dropped; without one, it is the whole line,\n * where the exception class or method name is the most useful part.\n */\n readonly message: string;\n}\n\n/** A stable failure code: `USER_CANCELLED`, `STOREKIT_NOT_INITIALIZED`, … */\nconst CODE = /^[A-Z][A-Z0-9_]*$/;\n\n/**\n * A `label: ` in front of the rest of the message: a code, a Java or Kotlin\n * exception class (`com.voidhash.core.billing.BillingEngineException`), or\n * the hybrid method Nitro names for a synchronous throw\n * (`GoogleBilling.buyItemByType(...)`). The rest may be empty: Play often\n * gives no detail, so Android's `\"CODE: detail\"` can end at the colon.\n */\nconst LABEL = /^`?([A-Za-z_$][\\w$.]*(?:\\(\\.\\.\\.\\))?)`?:(?:\\s+([\\s\\S]*))?$/;\n\n/** How many labels can wrap one message: a Nitro method name around an exception class. */\nconst MAX_LABELS = 3;\n\n/**\n * Reads the code and message a native hybrid rejected with.\n *\n * The native SDKs reject with `\"CODE: detail\"`, but the message reaches\n * JavaScript wrapped differently per platform. On Android it is\n * `\"<exception class>: CODE: detail\"`, possibly followed by `\\tat …` stack\n * frames. Nitro puts `\"<Hybrid>.<method>(...): \"` in front of anything a\n * method throws synchronously, on both platforms. An iOS rejection is the\n * Swift error's description, usually the bare `\"CODE: detail\"`.\n *\n * Only the first line is read, so a stack trace never reaches a code\n * comparison or a message shown to the app.\n */\nexport const readNativeError = (error: unknown): NativeError => {\n const raw = P.isError(error) ? error.message : P.isString(error) ? error : String(error);\n const firstLine = (raw.split(/\\r?\\n/, 1)[0] ?? \"\").trim();\n\n const findCode = (message: string, depth: number): Option.Option<NativeError> => {\n if (CODE.test(message)) return Option.some({ code: Option.some(message), message });\n const label = LABEL.exec(message);\n if (label === null) return Option.none();\n const [, name = \"\", rest = \"\"] = label;\n if (CODE.test(name)) return Option.some({ code: Option.some(name), message });\n return depth < MAX_LABELS ? findCode(rest, depth + 1) : Option.none();\n };\n\n return Option.getOrElse(findCode(firstLine, 0), () => ({\n code: Option.none<string>(),\n message: firstLine,\n }));\n};\n\n/** Whether a native rejection carries `code`. */\nexport const hasNativeErrorCode = (error: unknown, code: string): boolean =>\n Option.contains(readNativeError(error).code, code);\n","import * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\n\nimport type {\n NativeProduct,\n NativePurchaseResult,\n NativeTransaction,\n} from \"../../specs/VoidhashNativeClient.nitro\";\nimport { decodeAppStoreProduct, decodeAppStoreTransaction } from \"../entities/app-store\";\nimport { decodeGooglePlayProduct, decodeGooglePlayTransaction } from \"../entities/google-play\";\nimport type { Product } from \"../entities/product\";\nimport type { Transaction } from \"../entities/transaction\";\n\n/*\n * Reads the native SDK's products and transactions into the facade's types.\n * The generic fields arrive as Nitro structs shaped like the facade's own;\n * the `appStore` and `googlePlay` parts arrive as JSON and are decoded here.\n */\n\n/** Receives what the native client sent that breaks its contract; the facade reports it as a diagnostic. */\nexport type ContractViolation = (message: string) => void;\n\n/** The facade's result of a purchase that went through to the store. */\nexport type StorePurchaseResult =\n | { readonly status: \"purchased\"; readonly transaction: Transaction; readonly synced: boolean }\n | { readonly status: \"pending\" }\n | { readonly status: \"cancelled\" };\n\n/**\n * A store part sent as JSON, decoded. An unreadable part is left out and\n * reported: the product or transaction is still usable through its generic\n * fields.\n */\nconst decodePart = <A>(\n // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the Nitro contract, where an optional is `undefined`.\n json: string | undefined,\n decode: (json: string) => Option.Option<A>,\n onUnreadable: () => void,\n): Option.Option<A> =>\n Option.flatMap(Option.fromUndefinedOr(json), (value) => {\n const decoded = decode(value);\n if (Option.isNone(decoded)) onUnreadable();\n return decoded;\n });\n\n/**\n * A product as the facade types it. A `subscription` without its\n * subscription info breaks the contract and is left out (`None`), reported:\n * the types `voidhash-cli types generate` writes promise that a subscription\n * slug is a `SubscriptionProduct` or missing, never another type.\n */\nexport const toProduct = (\n native: NativeProduct,\n violation: ContractViolation,\n): Option.Option<Product> => {\n const appStore = decodePart(native.appStoreJson, decodeAppStoreProduct, () =>\n violation(`The App Store part of product \"${native.slug}\" could not be read`),\n );\n const googlePlay = decodePart(native.googlePlayJson, decodeGooglePlayProduct, () =>\n violation(`The Google Play part of product \"${native.slug}\" could not be read`),\n );\n const fields = {\n description: native.description,\n displayName: native.displayName,\n name: native.name,\n offers: native.offers,\n price: native.price,\n productId: native.productId,\n slug: native.slug,\n store: native.store,\n storeProductId: native.storeProductId,\n ...Option.match(appStore, { onNone: () => ({}), onSome: (part) => ({ appStore: part }) }),\n ...Option.match(googlePlay, { onNone: () => ({}), onSome: (part) => ({ googlePlay: part }) }),\n };\n return Match.value(native.type).pipe(\n Match.withReturnType<Option.Option<Product>>(),\n Match.when(\"subscription\", () => {\n if (native.subscription !== undefined) {\n return Option.some({ ...fields, subscription: native.subscription, type: \"subscription\" });\n }\n violation(\n `Subscription product \"${native.slug}\" came without its subscription info and is left out`,\n );\n return Option.none();\n }),\n Match.when(\"consumable\", (type) => Option.some({ ...fields, type })),\n Match.when(\"nonConsumable\", (type) => Option.some({ ...fields, type })),\n Match.when(\"nonRenewingSubscription\", (type) => Option.some({ ...fields, type })),\n Match.when(\"unknown\", () =>\n Option.some(\n native.subscription === undefined\n ? { ...fields, type: \"unknown\" }\n : { ...fields, subscription: native.subscription, type: \"unknown\" },\n ),\n ),\n Match.exhaustive,\n );\n};\n\n/** A transaction as the facade types it. */\nexport const toTransaction = (\n native: NativeTransaction,\n violation: ContractViolation,\n): Transaction => {\n const appStore = decodePart(native.appStoreJson, decodeAppStoreTransaction, () =>\n violation(`The App Store part of transaction ${native.id} could not be read`),\n );\n const googlePlay = decodePart(native.googlePlayJson, decodeGooglePlayTransaction, () =>\n violation(`The Google Play part of transaction ${native.id} could not be read`),\n );\n return {\n environment: native.environment,\n id: native.id,\n purchasedAt: native.purchasedAt,\n quantity: native.quantity,\n store: native.store,\n storeProductId: native.storeProductId,\n ...(native.originalId === undefined ? {} : { originalId: native.originalId }),\n ...(native.productSlug === undefined ? {} : { productSlug: native.productSlug }),\n ...(native.expiresAt === undefined ? {} : { expiresAt: native.expiresAt }),\n ...(native.isRenewal === undefined ? {} : { isRenewal: native.isRenewal }),\n ...(native.offer === undefined ? {} : { offer: native.offer }),\n ...Option.match(appStore, { onNone: () => ({}), onSome: (part) => ({ appStore: part }) }),\n ...Option.match(googlePlay, { onNone: () => ({}), onSome: (part) => ({ googlePlay: part }) }),\n };\n};\n\n/**\n * A purchase result as the facade types it. A `purchased` result without its\n * transaction breaks the contract and reads as `None`.\n */\nexport const toPurchaseResult = (\n native: NativePurchaseResult,\n violation: ContractViolation,\n): Option.Option<StorePurchaseResult> =>\n Match.value(native.outcome).pipe(\n Match.withReturnType<Option.Option<StorePurchaseResult>>(),\n Match.when(\"purchased\", () =>\n Option.map(Option.fromUndefinedOr(native.transaction), (transaction) => ({\n status: \"purchased\" as const,\n synced: native.synced ?? false,\n transaction: toTransaction(transaction, violation),\n })),\n ),\n Match.when(\"pending\", () => Option.some({ status: \"pending\" as const })),\n Match.when(\"cancelled\", () => Option.some({ status: \"cancelled\" as const })),\n Match.exhaustive,\n );\n","import * as Effect from \"effect/Effect\";\nimport type * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport { enumOrUnknown, listOrEmpty, optionalNullable, PriceValue } from \"./decoding\";\nimport type { Price } from \"./product\";\n\n/*\n * Google Play's own view of products and purchases, with Play Billing's field\n * names. The native client sends each as JSON; the decoders here read it\n * forward-compatibly.\n */\n\n/** Play Billing's `ProductType`: `subs` for subscriptions, `inapp` for one-time products. */\nexport type GooglePlayProductType = \"subs\" | \"inapp\" | \"unknown\";\n\n/** Play Billing's `RecurrenceMode` of a pricing phase. */\nexport type GooglePlayRecurrenceMode = \"infinite\" | \"finite\" | \"nonRecurring\" | \"unknown\";\n\n/** A Play Billing `PricingPhase`. */\nexport interface GooglePlayPricingPhase {\n readonly formattedPrice: string;\n readonly priceAmountMicros: number;\n readonly priceCurrencyCode: string;\n /** ISO 8601 duration, such as `P1M`. */\n readonly billingPeriod: string;\n readonly billingCycleCount: number;\n readonly recurrenceMode: GooglePlayRecurrenceMode;\n}\n\n/** A Play Billing installment plan of a subscription offer. */\nexport interface GooglePlayInstallmentPlan {\n readonly commitmentPaymentsCount: number;\n readonly subsequentCommitmentPaymentsCount: number;\n}\n\n/** A Play Billing `SubscriptionOfferDetails`: a base plan, or an offer on one. */\nexport interface GooglePlaySubscriptionOffer {\n readonly basePlanId: string;\n /** Absent for the base plan itself. */\n readonly offerId?: string;\n /** Pass it as `googlePlay.offerToken` to buy exactly this offer. */\n readonly offerToken: string;\n readonly offerTags: ReadonlyArray<string>;\n readonly pricingPhases: ReadonlyArray<GooglePlayPricingPhase>;\n readonly installmentPlan?: GooglePlayInstallmentPlan;\n}\n\n/** A Play Billing `OneTimePurchaseOfferDetails`. */\nexport interface GooglePlayOneTimeOffer {\n readonly purchaseOptionId?: string;\n readonly offerId?: string;\n /** Pass it as `googlePlay.offerToken` to buy exactly this offer. */\n readonly offerToken: string;\n readonly offerTags: ReadonlyArray<string>;\n readonly price: Price;\n /** The price before the discount. */\n readonly fullPrice?: Price;\n readonly discountPercentage?: number;\n readonly limitedQuantity?: {\n readonly maximumQuantity: number;\n readonly remainingQuantity: number;\n };\n /** When the offer can be bought; an open end is absent. */\n readonly validTimeWindow?: { readonly startTimeMillis?: number; readonly endTimeMillis?: number };\n readonly preorder?: { readonly releaseTimeMillis: number; readonly presaleEndTimeMillis: number };\n readonly rental?: { readonly rentalPeriod: string; readonly rentalExpirationPeriod?: string };\n}\n\n/** A Play Billing `ProductDetails` as Google Play reports it. */\nexport interface GooglePlayProductInfo {\n /** The Google Play product id. */\n readonly productId: string;\n readonly productType: GooglePlayProductType;\n /** The base plan this product is bound to in Studio. */\n readonly basePlanId?: string;\n /** Every offer Google Play returned, on every base plan. */\n readonly subscriptionOffers: ReadonlyArray<GooglePlaySubscriptionOffer>;\n readonly oneTimeOffers: ReadonlyArray<GooglePlayOneTimeOffer>;\n}\n\n/** Play Billing's `Purchase.PurchaseState`. */\nexport type GooglePlayPurchaseState = \"purchased\" | \"pending\" | \"unknown\";\n\n/** A Play Billing `Purchase` as Google Play reports it. */\nexport interface GooglePlayTransactionInfo {\n readonly orderId?: string;\n readonly purchaseToken: string;\n readonly productIds: ReadonlyArray<string>;\n readonly purchaseState: GooglePlayPurchaseState;\n readonly isAcknowledged: boolean;\n readonly isAutoRenewing?: boolean;\n /** The account id the purchase was made with: the end user's Voidhash identity. */\n readonly obfuscatedAccountId?: string;\n readonly obfuscatedProfileId?: string;\n /**\n * Whether Google Play suspended the subscription (its payment method\n * failed). A suspended purchase grants nothing.\n */\n readonly isSuspended: boolean;\n}\n\n/**\n * How `showInAppMessages()` ended: nothing to do, or the end user fixed their\n * payment method for the subscription whose purchase token it names.\n */\nexport type GooglePlayInAppMessageResult =\n | { readonly status: \"noActionNeeded\" }\n | { readonly status: \"subscriptionStatusUpdated\"; readonly purchaseToken: string };\n\n/** A Play Billing feature `isFeatureSupported()` asks about, by `BillingClient.FeatureType`. */\nexport type GooglePlayBillingFeature =\n | \"subscriptions\"\n | \"subscriptionsUpdate\"\n | \"inAppMessaging\"\n | \"productDetails\"\n | \"billingConfig\"\n | \"alternativeBillingOnly\"\n | \"externalOffer\";\n\nconst GooglePlaySubscriptionOfferValue = Schema.Struct({\n basePlanId: Schema.String,\n offerId: optionalNullable(Schema.String),\n offerToken: Schema.String,\n offerTags: listOrEmpty(Schema.String),\n pricingPhases: listOrEmpty(\n Schema.Struct({\n formattedPrice: Schema.String,\n priceAmountMicros: Schema.Number,\n priceCurrencyCode: Schema.String,\n billingPeriod: Schema.String,\n billingCycleCount: Schema.Number,\n recurrenceMode: enumOrUnknown([\"infinite\", \"finite\", \"nonRecurring\"]),\n }),\n ),\n installmentPlan: optionalNullable(\n Schema.Struct({\n commitmentPaymentsCount: Schema.Number,\n subsequentCommitmentPaymentsCount: Schema.Number,\n }),\n ),\n});\n\nconst GooglePlayOneTimeOfferValue = Schema.Struct({\n purchaseOptionId: optionalNullable(Schema.String),\n offerId: optionalNullable(Schema.String),\n offerToken: Schema.String,\n offerTags: listOrEmpty(Schema.String),\n price: PriceValue,\n fullPrice: optionalNullable(PriceValue),\n discountPercentage: optionalNullable(Schema.Number),\n limitedQuantity: optionalNullable(\n Schema.Struct({ maximumQuantity: Schema.Number, remainingQuantity: Schema.Number }),\n ),\n validTimeWindow: optionalNullable(\n Schema.Struct({\n startTimeMillis: optionalNullable(Schema.Number),\n endTimeMillis: optionalNullable(Schema.Number),\n }),\n ),\n preorder: optionalNullable(\n Schema.Struct({ releaseTimeMillis: Schema.Number, presaleEndTimeMillis: Schema.Number }),\n ),\n rental: optionalNullable(\n Schema.Struct({\n rentalPeriod: Schema.String,\n rentalExpirationPeriod: optionalNullable(Schema.String),\n }),\n ),\n});\n\nconst GooglePlayProductJson = Schema.fromJsonString(\n Schema.Struct({\n productId: Schema.String,\n productType: enumOrUnknown([\"subs\", \"inapp\"]),\n basePlanId: optionalNullable(Schema.String),\n subscriptionOffers: listOrEmpty(GooglePlaySubscriptionOfferValue),\n oneTimeOffers: listOrEmpty(GooglePlayOneTimeOfferValue),\n }),\n);\n\nconst GooglePlayTransactionJson = Schema.fromJsonString(\n Schema.Struct({\n orderId: optionalNullable(Schema.String),\n purchaseToken: Schema.String,\n productIds: listOrEmpty(Schema.String),\n purchaseState: enumOrUnknown([\"purchased\", \"pending\"]),\n isAcknowledged: Schema.Boolean,\n isAutoRenewing: optionalNullable(Schema.Boolean),\n obfuscatedAccountId: optionalNullable(Schema.String),\n obfuscatedProfileId: optionalNullable(Schema.String),\n isSuspended: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(false))),\n }),\n);\n\n/** Reads a product's Google Play part; `None` when it is not one. */\nexport const decodeGooglePlayProduct = (json: string): Option.Option<GooglePlayProductInfo> =>\n Schema.decodeUnknownOption(GooglePlayProductJson)(json);\n\n/** Reads a transaction's Google Play part; `None` when it is not one. */\nexport const decodeGooglePlayTransaction = (\n json: string,\n): Option.Option<GooglePlayTransactionInfo> =>\n Schema.decodeUnknownOption(GooglePlayTransactionJson)(json);\n","import * as Arr from \"effect/Array\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\nimport * as R from \"effect/Record\";\n\nimport { InvalidArgumentError } from \"../errors\";\n\n/** A value a person trait can hold. The person API stores flat scalars only. */\n// oxlint-disable-next-line effect/prefer-option-over-null -- a JSON trait value; `null` clears the trait.\ntype TraitValue = string | number | boolean | null;\n\nconst isTraitValue = (value: unknown): value is TraitValue =>\n value === null || P.isString(value) || P.isNumber(value) || P.isBoolean(value);\n\n/**\n * Why `attributes` can never be written, or `None` when they can. The person\n * API stores flat traits only, so a nested object or an array is refused here,\n * before anything is sent or queued, whether or not the device is online.\n */\nexport const invalidPersonAttributes = (\n attributes: unknown,\n): Option.Option<InvalidArgumentError> => {\n if (!P.isObject(attributes)) {\n return Option.some(new InvalidArgumentError(\"Person attributes must be an object\"));\n }\n const invalidKeys = R.keys(\n R.filter(attributes, (value, key) =>\n key === \"email\" || key === \"name\"\n ? value !== undefined && !P.isString(value)\n : value !== undefined && !isTraitValue(value),\n ),\n );\n return Arr.match(invalidKeys, {\n onEmpty: () => Option.none(),\n onNonEmpty: (keys) =>\n Option.some(\n new InvalidArgumentError(\n `Invalid person attributes (${keys.join(\", \")}): trait values must be strings, numbers, booleans or null, and email and name must be strings`,\n ),\n ),\n });\n};\n","import * as Arr from \"effect/Array\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\nimport * as R from \"effect/Record\";\nimport * as Result from \"effect/Result\";\n\nimport { SCREEN_PROPERTIES } from \"../analytics/constants\";\n\n/** Integration that observed a screen transition. */\nexport type ScreenSource =\n | \"expo-router\"\n | \"react-navigation\"\n | \"nitro-ui-navigation\"\n | \"uikit\"\n | \"swiftui\"\n | \"android-activity\"\n | \"android-fragment\"\n | \"compose-navigation\"\n | \"manual\";\n\n/** One screen the user arrived on, as reported by an integration. */\nexport interface ScreenView {\n /**\n * Router-owned token identifying this screen instance (route key, pathname,\n * controller instance). Two views with the same identity are the same screen\n * and only the first one emits.\n */\n identity: string;\n /** Stable, low-cardinality screen identity. Never contains ids. */\n name: string;\n /** Concrete location, with dynamic segment values filled in. */\n path: string;\n /** Human title when the platform exposes one. */\n title?: string;\n /** Route params. Only forwarded when `includeParams` is on. */\n params?: Record<string, unknown>;\n source: ScreenSource;\n}\n\nexport interface ScreenTrackerOptions {\n /** `false` turns every transition into a no-op. */\n enabled: boolean;\n /** Adds `$screen_params` to the emitted properties. */\n includeParams: boolean;\n /** Rewrites or drops a screen before it reaches the tracker. Return `None` to skip. */\n mapScreen?: (view: ScreenView) => Option.Option<ScreenView>;\n /** Clock used for `$previous_screen_duration_ms`. Defaults to `Date.now`. */\n now?: () => number;\n}\n\nexport interface ScreenTracker {\n /**\n * Feeds one screen arrival through the state machine. Returns the `$screen`\n * properties to capture, or `None` when nothing should be emitted (tracking\n * disabled, same screen instance, or dropped by `mapScreen`).\n */\n transition: (view: ScreenView) => Option.Option<Record<string, unknown>>;\n /** Forgets the current screen so the next transition has `null` previous fields. */\n reset: () => void;\n}\n\n/** Client-side bound on `$screen_name` and `$screen_path`. */\nexport const SCREEN_NAME_MAX_LENGTH = 200;\n/** Client-side bound on the number of `$screen_params` keys. */\nexport const SCREEN_PARAMS_MAX_KEYS = 20;\n\ninterface CurrentScreen {\n identity: string;\n name: string;\n path: string;\n arrivedAt: number;\n}\n\nconst truncate = (value: string) => value.slice(0, SCREEN_NAME_MAX_LENGTH);\n\n/**\n * A route param as text. An object with no text form (one without a\n * prototype, or whose `toString` throws) reads like any other object.\n */\nconst coerceParam = (value: unknown): string =>\n P.isString(value)\n ? value\n : Array.isArray(value)\n ? value.map(coerceParam).join(\",\")\n : Result.getOrElse(\n Result.try(() => String(value)),\n () => \"[object Object]\",\n );\n\nconst coerceParams = (params: Record<string, unknown>): Record<string, string> =>\n R.fromEntries(\n Arr.map(\n Arr.take(R.toEntries(params), SCREEN_PARAMS_MAX_KEYS),\n ([key, value]) => [key, coerceParam(value)] as const,\n ),\n );\n\n/**\n * Creates the pure screen transition state machine shared by every screen\n * tracking integration. It owns only the previous-screen state; capturing the\n * returned properties is the caller's job.\n */\nexport function createScreenTracker(options: ScreenTrackerOptions): ScreenTracker {\n // oxlint-disable-next-line effect/use-clock-service -- synchronous, non-Effect state machine: the `now` option is the injection seam (tests pass a fake clock) and `Date.now` is only the production default.\n const now = options.now ?? Date.now;\n let state = Option.none<CurrentScreen>();\n\n const transition = (input: ScreenView): Option.Option<Record<string, unknown>> => {\n if (!options.enabled) {\n return Option.none();\n }\n const mappedView = options.mapScreen ? options.mapScreen(input) : Option.some(input);\n if (Option.isNone(mappedView)) {\n return Option.none();\n }\n const mapped = mappedView.value;\n if (Option.isSome(state) && state.value.identity === mapped.identity) {\n return Option.none();\n }\n\n const arrivedAt = now();\n const name = truncate(mapped.name);\n const path = truncate(mapped.path);\n const previous = Option.getOrNull(state);\n\n const properties: Record<string, unknown> = {\n [SCREEN_PROPERTIES.NAME]: name,\n [SCREEN_PROPERTIES.PATH]: path,\n [SCREEN_PROPERTIES.SOURCE]: mapped.source,\n [SCREEN_PROPERTIES.PREVIOUS_NAME]: previous?.name ?? null,\n [SCREEN_PROPERTIES.PREVIOUS_PATH]: previous?.path ?? null,\n // A clock set back between two screens must not report a negative stay.\n [SCREEN_PROPERTIES.PREVIOUS_DURATION_MS]: previous\n ? Math.max(arrivedAt - previous.arrivedAt, 0)\n : null,\n };\n if (P.isString(mapped.title) && mapped.title !== \"\") {\n properties[SCREEN_PROPERTIES.TITLE] = mapped.title;\n }\n if (options.includeParams && P.isObject(mapped.params)) {\n properties[SCREEN_PROPERTIES.PARAMS] = coerceParams(mapped.params);\n }\n\n state = Option.some({ identity: mapped.identity, name, path, arrivedAt });\n return Option.some(properties);\n };\n\n return {\n transition,\n reset: () => {\n state = Option.none();\n },\n };\n}\n","/**\n * Prefix of the anonymous ids the SDK creates, `vh_anon_<uuid>`: only letters,\n * digits, `_` and `-`, so the id fits any payment provider's field.\n */\nexport const ANONYMOUS_DISTINCT_ID_PREFIX = \"vh_anon_\";\n\n/** Prefix of the anonymous ids earlier SDK builds created, which a stored id may still carry. */\nexport const LEGACY_ANONYMOUS_DISTINCT_ID_PREFIX = \"vh:anon:\";\n\n/**\n * Whether a distinct id is one the SDK made for an anonymous end user: `vh_anon_<uuid>`, or the\n * `vh:anon:` form a device may still hold from an earlier SDK build. Use it instead of checking a\n * prefix, for example to sign out only an identified person.\n */\nexport const isAnonymousDistinctId = (distinctId: string): boolean =>\n distinctId.startsWith(ANONYMOUS_DISTINCT_ID_PREFIX) ||\n distinctId.startsWith(LEGACY_ANONYMOUS_DISTINCT_ID_PREFIX);\n","export class Perk {}\n","import * as Result from \"effect/Result\";\nimport { Platform } from \"nitro-ui-core\";\n\nimport type { VoidhashClientOptions } from \"../../react-native/src/client\";\nimport { createVoidhashClientOnHost } from \"../../react-native/src/client-host\";\nimport * as NativeClientSpec from \"./specs/VoidhashNativeClient.nitro\";\n\n/**\n * A new native client, one per `VoidhashClient`: it holds a client's state,\n * so it is never shared. NitroUI links this package's native module into\n * every build of an app that depends on it, so the class is looked up and\n * constructed only here, when a client starts: a binary built before the app\n * added the package (a JavaScript update onto an older build) has no such\n * class, and its lookup or construction throws. That yields `None`, so the\n * client fails `init()` with a coded error instead of the app failing to load.\n */\nconst createVoidhashNativeClient = () =>\n Result.getSuccess(Result.try(() => new NativeClientSpec.VoidhashNativeClient()));\n\n/**\n * Bootstrap the Voidhash SDK for a NitroUI app.\n *\n * - There is no schema argument. The schema lives on the server and is\n * fetched on `Provider` mount.\n * - Type safety for product / location / perk slugs comes from the generated\n * `voidhash.gen.d.ts` (run `voidhash-cli types generate`).\n * - No `publishableKey` (`null`, `undefined` or blank), or\n * `options.enabled: false` returns a fully inert client: the provider and\n * every hook still mount (so hook order never changes), but nothing\n * initializes.\n * - An `analyticsConsent` other than `\"granted\"`, `\"denied\"` or `\"pending\"`\n * throws an `INVALID_ARGUMENT` error in development builds; release builds\n * use `\"granted\"` and report `INVALID_CONFIGURATION`.\n * - A `featureFlags.maxWaitMs` that is not zero or a positive integer, or a\n * `featureFlags.defaults` entry that is not a boolean, throws an\n * `INVALID_ARGUMENT` error in development builds; release builds ignore it\n * and report `INVALID_CONFIGURATION`.\n * - A blank `distinctId`, `baseUrl` or `ingestUrl` counts as absent, and\n * whitespace around a `baseUrl` or `ingestUrl` is removed. A\n * `baseUrl` or `ingestUrl` that is not an absolute `http(s)` URL throws an\n * `INVALID_ARGUMENT` error in development builds; release builds use the\n * default origin and report `INVALID_CONFIGURATION` through `onDiagnostic`.\n * - A build without this package's native module (a JavaScript update onto\n * an app binary built before the package was added) loads normally;\n * `init()` then fails with `FAILED_TO_INITIALIZE_VOIDHASH_CLIENT`.\n */\nexport function createVoidhashClient(\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK input from non-Effect app code; an environment without a key naturally holds null or undefined.\n publishableKey: string | null | undefined,\n options: VoidhashClientOptions = {},\n) {\n return createVoidhashClientOnHost(\n {\n createNativeClient: createVoidhashNativeClient,\n packageName: \"@voidhash/nitro-ui\",\n platform: Platform.OS,\n },\n publishableKey,\n options,\n );\n}\n","import * as Arr from \"effect/Array\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\nimport * as R from \"effect/Record\";\nimport { AtomRegistry } from \"effect/reactivity\";\n\nimport { type FeatureFlagsOptions, VoidhashClient, type VoidhashClientOptions } from \"./client\";\nimport { DIAGNOSTIC_CODES, makeDiagnosticEmitter } from \"./core/diagnostics/diagnostics\";\nimport { InvalidArgumentError } from \"./errors\";\nimport { isAnalyticsConsent } from \"./core/sdk-configuration\";\nimport type { NativeClientPort } from \"./core/native/native-client\";\nimport { DEFAULT_FLOW_CAPABILITIES } from \"./core/flows/flows\";\nimport { voidhashProviderFactory } from \"./react/components/provider\";\nimport { currentPersonHookFactory } from \"./react/hooks/use-person\";\nimport { featureFlagsHookFactory } from \"./react/hooks/use-feature-flags\";\nimport { hasPerkHookFactory } from \"./react/hooks/use-has-perk\";\nimport { presentFlowHookFactory } from \"./react/hooks/use-present-flow\";\nimport { productsHookFactory } from \"./react/hooks/use-products\";\nimport { purchaseHookFactory } from \"./react/hooks/use-purchase\";\nimport { restorePurchasesHookFactory } from \"./react/hooks/use-restore-purchases\";\nimport { subscriptionsHookFactory } from \"./react/hooks/use-subscriptions\";\n\nlet nativeEngineWarningShown = false;\n\nconst DEFAULT_BASE_URL = \"https://api.voidhash.com\";\n\n/**\n * An absolute `http(s)` URL with a host. Checked with a pattern rather than\n * `new URL()`: React Native's built-in `URL` accepts any string without\n * validating it, and apps may replace it with a stricter polyfill.\n */\nconst ABSOLUTE_HTTP_URL = /^https?:\\/\\/[^\\s/?#]+(?:[/?#]\\S*)?$/i;\n\n/**\n * Resolves a configured origin, without the whitespace around it: a value read\n * from an environment file often ends with a newline, which the native URL\n * parsers refuse or turn into a host that never resolves. A missing or blank\n * value is absent. Anything else must be an absolute `http(s)` URL: requests\n * to a relative or scheme-less origin fail like an outage forever, so\n * development builds throw and release builds fall back to the default origin\n * and report it once.\n */\nconst resolveOrigin = (\n option: \"baseUrl\" | \"ingestUrl\",\n configured: Option.Option<string>,\n emitDiagnostic: ReturnType<typeof makeDiagnosticEmitter>,\n): Option.Option<string> => {\n const value = Option.filter(\n Option.map(configured, (origin) => origin.trim()),\n (origin) => origin !== \"\",\n );\n if (Option.isNone(value) || ABSOLUTE_HTTP_URL.test(value.value)) return value;\n if (__DEV__) {\n throw new InvalidArgumentError(\n `${option} must be an absolute http(s) URL such as \"https://api.example.com\", got \"${value.value}\"`,\n );\n }\n emitDiagnostic({\n code: DIAGNOSTIC_CODES.INVALID_CONFIGURATION,\n kind: \"configuration\",\n message: `Ignored ${option} \"${value.value}\": it is not an absolute http(s) URL, so the default origin is used`,\n operation: \"createVoidhashClient\",\n retryable: false,\n });\n return Option.none();\n};\n\n/**\n * Validates the `featureFlags` option. A `maxWaitMs` that is not a\n * non-negative integer, or a default that is not a boolean, throws an\n * `INVALID_ARGUMENT` error in development builds; release builds ignore it\n * (the native default wait, or no default for that flag) and report it once.\n */\nconst resolveFeatureFlagOptions = (\n options: FeatureFlagsOptions,\n emitDiagnostic: ReturnType<typeof makeDiagnosticEmitter>,\n) => {\n const refuse = (message: string, fallback: string) => {\n if (__DEV__) throw new InvalidArgumentError(message);\n emitDiagnostic({\n code: DIAGNOSTIC_CODES.INVALID_CONFIGURATION,\n kind: \"configuration\",\n message: `Ignored ${message}; ${fallback}`,\n operation: \"createVoidhashClient\",\n retryable: false,\n });\n };\n const isValidWait = (wait: number) => Number.isInteger(wait) && wait >= 0;\n const maxWaitMs = Option.fromUndefinedOr(options.maxWaitMs);\n if (Option.isSome(maxWaitMs) && !isValidWait(maxWaitMs.value)) {\n refuse(\n `featureFlags.maxWaitMs must be zero or a positive integer, got ${String(maxWaitMs.value)}`,\n \"the default wait is used\",\n );\n }\n const configuredDefaults: Readonly<Record<string, unknown>> = options.defaults ?? {};\n R.toEntries(configuredDefaults).forEach(([key, value]) => {\n if (P.isBoolean(value)) return;\n refuse(\n `featureFlags.defaults[\"${key}\"] must be true or false, got ${String(value)}`,\n \"the flag has no default\",\n );\n });\n const defaults = R.filter(configuredDefaults, P.isBoolean);\n return { defaults, maxWaitMs: Option.filter(maxWaitMs, isValidWait) };\n};\n\n/**\n * What an app framework gives the SDK: the platform the app runs on and how\n * to create the native client there. React Native and NitroUI each supply\n * their own; the option handling and the client are the same for both.\n */\nexport interface VoidhashHost {\n /**\n * The platform the app runs on, as the framework's `Platform.OS` names it.\n * The client is enabled on `\"ios\"` and `\"android\"` only; Android runs one\n * native client per process.\n */\n readonly platform: string;\n /**\n * A new native client, one per `VoidhashClient`, or `None` where the\n * installed binary has none. It must not throw: a creation that fails\n * yields `None`, so `init()` fails with a coded error instead of the bundle\n * failing to load.\n */\n readonly createNativeClient: () => Option.Option<NativeClientPort>;\n /** The npm package the app installs, which a failure that needs a new native build names. */\n readonly packageName: string;\n}\n\n/**\n * Validates the options of `createVoidhashClient` and builds the client, its\n * provider and its hooks on `host`. Each framework's `createVoidhashClient`\n * documents the behaviour for app developers.\n */\nexport function createVoidhashClientOnHost(\n host: VoidhashHost,\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK input from non-Effect app code; an environment without a key naturally holds null or undefined.\n publishableKey: string | null | undefined,\n options: VoidhashClientOptions = {},\n) {\n const key = publishableKey?.trim() ?? \"\";\n const emitDiagnostic = makeDiagnosticEmitter(Option.fromUndefinedOr(options.onDiagnostic));\n const baseUrl = Option.getOrElse(\n resolveOrigin(\"baseUrl\", Option.fromUndefinedOr(options.baseUrl), emitDiagnostic),\n () => DEFAULT_BASE_URL,\n );\n const debug = options.debug ?? false;\n const dev = options.dev ?? false;\n const distinctId = Option.fromUndefinedOr(options.distinctId);\n const enabled =\n (options.enabled ?? true) &&\n key !== \"\" &&\n (host.platform === \"ios\" || host.platform === \"android\");\n const ingestUrl = resolveOrigin(\n \"ingestUrl\",\n Option.fromUndefinedOr(options.ingestUrl),\n emitDiagnostic,\n );\n const readOnly = options.readOnly ?? false;\n const analyticsConsent = options.analyticsConsent ?? \"granted\";\n if (!isAnalyticsConsent(analyticsConsent)) {\n const message = `analyticsConsent must be \"granted\", \"denied\" or \"pending\", got \"${String(analyticsConsent)}\"`;\n if (__DEV__) throw new InvalidArgumentError(message);\n emitDiagnostic({\n code: DIAGNOSTIC_CODES.INVALID_CONFIGURATION,\n kind: \"configuration\",\n message: `Ignored ${message}; \"granted\" is used`,\n operation: \"createVoidhashClient\",\n retryable: false,\n });\n }\n const featureFlags = resolveFeatureFlagOptions(options.featureFlags ?? {}, emitDiagnostic);\n if (options.unstable_nativeEngine === true && __DEV__ && !nativeEngineWarningShown) {\n nativeEngineWarningShown = true;\n // oxlint-disable-next-line effect/use-console-service -- a one-time development notice for the app developer, printed before any SDK runtime exists.\n console.warn(\n \"[voidhash] unstable_nativeEngine no longer has an effect; the SDK always runs on its native client.\",\n );\n }\n\n const client = new VoidhashClient({\n analyticsConsent: isAnalyticsConsent(analyticsConsent) ? analyticsConsent : \"granted\",\n analyticsWhilePending: options.analyticsWhilePending === \"buffer\" ? \"buffer\" : \"drop\",\n appStoreMessages:\n options.appStoreMessages === \"automatic\" ? \"automatic\" : \"deferWhileFlowPresented\",\n atomRegistry: AtomRegistry.make(),\n automaticLifecycleEvents: options.automaticLifecycleEvents ?? true,\n baseUrl,\n createNativeClient: host.createNativeClient,\n debug,\n developmentMode: __DEV__ && dev,\n // A blank configured id counts as absent: the SDK keeps (or mints) the\n // anonymous identity instead of adopting one no request can carry.\n distinctId: Option.filter(distinctId, (id) => P.isString(id) && id.trim() !== \"\"),\n enabled,\n featureFlagDefaults: featureFlags.defaults,\n featureFlagMaxWaitMs: featureFlags.maxWaitMs,\n grantConsentOnIdentify: options.grantConsentOnIdentify ?? false,\n flowCapabilities: Arr.dedupe(options.flowCapabilities ?? DEFAULT_FLOW_CAPABILITIES),\n flowRevisions: options.flowRevisions ?? {},\n flowRuntime: options.flowRuntime === \"module\" ? \"module\" : \"linked\",\n flowLoading: options.flowLoading === \"none\" ? \"none\" : \"standard\",\n ingestUrl,\n installAttribution: options.installAttribution ?? true,\n internalSchema: Option.fromUndefinedOr(options.unstable_internalSchema),\n metaAppId: Option.fromUndefinedOr(options.metaAppId),\n oneNativeClientPerProcess: host.platform === \"android\",\n onDiagnostic: Option.fromUndefinedOr(options.onDiagnostic),\n packageName: host.packageName,\n platform: host.platform,\n preloadLocations: options.preloadLocations ?? [],\n publishableKey: key,\n purchaseIntents: options.purchaseIntents === \"manual\" ? \"manual\" : \"purchaseWhenReady\",\n readOnly,\n scheme: options.scheme ?? \"\",\n screenTracking: options.screenTracking ?? {},\n unstableSwallowErrors: options.unstable_swallowErrors ?? false,\n });\n\n const { provider, context, useVoidhash } = voidhashProviderFactory(client);\n const useCurrentPerson = currentPersonHookFactory(client, context);\n\n return {\n Provider: provider,\n /** App Store actions, as `client.appStore`. */\n appStore: client.appStore,\n client,\n /** Google Play actions, as `client.googlePlay`. */\n googlePlay: client.googlePlay,\n useCurrentPerson,\n useFeatureFlags: featureFlagsHookFactory(client, context),\n useHasPerk: hasPerkHookFactory(client, context),\n usePresentFlow: presentFlowHookFactory(client, context),\n useProducts: productsHookFactory(client, context),\n usePurchase: purchaseHookFactory(client, context),\n useRestorePurchases: restorePurchasesHookFactory(client, context),\n useSubscriptions: subscriptionsHookFactory(\n currentPersonHookFactory(client, context, \"useSubscriptions\"),\n ),\n useVoidhash,\n };\n}\n","import React from \"react\";\nimport * as Option from \"effect/Option\";\n\nimport type { VoidhashClient } from \"../../client\";\nimport type { Person } from \"../../core/entities/person\";\nimport {\n currentPersonAtom,\n currentPersonFreshnessAtom,\n identityEpochAtom,\n} from \"../../core/reactivity/client-state\";\nimport type { VoidhashError } from \"../../errors\";\nimport { type VoidhashContext, useProviderStatus } from \"../components/provider\";\nimport useAsyncFunction from \"./use-async-function\";\nimport { useAtomValue } from \"./use-atom-value\";\n\nexport interface UseCurrentPersonResult {\n /** The person, or `null` until the first snapshot loads and while the client is disabled. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n readonly data: Person | null;\n /** The error that stopped the last read, or `null`. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n readonly error: VoidhashError | null;\n /** `true` while the provider initializes and until this hook's first read has answered. */\n readonly isLoading: boolean;\n /**\n * `true` while the person comes from a snapshot the server has not\n * confirmed recently: a cached one past its refresh window or TTL, or none\n * at all yet. Clears as soon as a refresh lands.\n */\n readonly isStale: boolean;\n readonly refetch: () => Promise<void>;\n}\n\nexport function currentPersonHookFactory(\n client: VoidhashClient,\n vhContext: React.Context<Option.Option<VoidhashContext>>,\n /** The hook's name in the error a development build throws outside a provider. */\n hookName = \"useCurrentPerson\",\n) {\n /**\n * Reads the current person snapshot. Re-renders when a refresh lands and\n * reads again after `identify()` or `reset()` switches the person.\n */\n function useCurrentPerson(): UseCurrentPersonResult {\n const status = useProviderStatus(vhContext, hookName);\n const registry = client.internal.getAtomRegistry();\n const identityEpoch = useAtomValue(registry, identityEpochAtom);\n\n const getPersonCallback = React.useCallback(\n () => client.getCurrentPerson(),\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- identityEpoch is the refetch trigger, not an input of the call.\n [identityEpoch],\n );\n\n const { isLoading, error, refetch } = useAsyncFunction(getPersonCallback, status);\n\n const person = useAtomValue(registry, currentPersonAtom);\n const freshness = useAtomValue(registry, currentPersonFreshnessAtom);\n\n return {\n data: Option.getOrNull(person),\n error,\n isLoading,\n // Staleness travels with the published snapshot, so a refresh that\n // lands in the background clears it.\n isStale: !isLoading && (freshness.isStale || freshness.isExpired),\n refetch,\n };\n }\n return useCurrentPerson;\n}\n","import type { Result } from \"better-result\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as EffectRuntime from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as React from \"react\";\n\nimport type { VoidhashError } from \"../../errors\";\nimport { UnknownVoidhashError } from \"../../errors\";\nimport type { VoidhashInitStatus } from \"../internal/client-lifecycle\";\n\ntype AsyncFunction<T> = () => Promise<Result<T, VoidhashError>>;\n\ninterface State<T> {\n data?: T;\n // oxlint-disable-next-line effect/prefer-option-over-null -- surfaced as-is by the public hooks, whose callers are non-Effect app code.\n error: VoidhashError | null;\n isLoading: boolean;\n /** The function the latest settled call ran; its answer is the one in `data`/`error`. */\n settledFunction?: AsyncFunction<T>;\n}\n\ntype Action<T> =\n | { type: \"loading\" }\n | { type: \"executed\"; fn: AsyncFunction<T>; payload: T }\n | { type: \"error\"; fn: AsyncFunction<T>; payload: VoidhashError };\n\ntype UseAsyncFunctionReturn<T> = Omit<State<T>, \"settledFunction\"> & {\n refetch: () => Promise<void>;\n};\n\n/**\n * Drives a `Promise<Result<T, VoidhashError>>` client call as hook state.\n * The `Err` channel becomes `error`; unexpected exceptions are normalized\n * into an `Err`-shaped state as well.\n *\n * `status` is the provider's lifecycle status (`None` outside a provider): the\n * function runs once the provider is `ready`, and again whenever it changes. `isLoading` is `true`\n * while the provider initializes and until the current function has answered,\n * so a hook never reports a settled empty answer it has not read yet; it is\n * `false` for a disabled or failed provider, where nothing is going to run.\n * A refetch keeps the previous `data` until the new answer arrives.\n */\nfunction useAsyncFunction<T = unknown>(\n asyncFn: AsyncFunction<T>,\n status: Option.Option<VoidhashInitStatus>,\n): UseAsyncFunctionReturn<T> {\n // Each call takes the next id; only the latest call may write its answer,\n // so a slow answer to a superseded or cancelled call never lands.\n const latestCall = React.useRef(0);\n\n const asyncFnReducer = (state: State<T>, action: Action<T>): State<T> => {\n if (action.type === \"loading\") return { data: state.data, error: null, isLoading: true };\n if (action.type === \"executed\") {\n return { data: action.payload, error: null, isLoading: false, settledFunction: action.fn };\n }\n return {\n data: state.data,\n error: action.payload,\n isLoading: false,\n settledFunction: action.fn,\n };\n };\n\n const [state, dispatch] = React.useReducer(asyncFnReducer, { error: null, isLoading: false });\n\n const executeAsyncFunction = React.useCallback(async () => {\n latestCall.current += 1;\n const call = latestCall.current;\n dispatch({ type: \"loading\" });\n\n const exit = await EffectRuntime.runPromise(\n Effect.exit(Effect.tryPromise({ try: () => asyncFn(), catch: (error) => error })),\n );\n\n if (latestCall.current !== call) {\n return;\n }\n\n if (Exit.isSuccess(exit)) {\n const result = exit.value;\n if (result.isOk()) {\n dispatch({ fn: asyncFn, payload: result.value, type: \"executed\" });\n } else {\n dispatch({ fn: asyncFn, payload: result.error, type: \"error\" });\n }\n return;\n }\n\n dispatch({\n fn: asyncFn,\n payload: new UnknownVoidhashError(Cause.squash(exit.cause)),\n type: \"error\",\n });\n }, [asyncFn]);\n\n const refetch = React.useCallback(async () => {\n await executeAsyncFunction();\n }, [executeAsyncFunction]);\n\n const enabled = Option.contains(status, \"ready\");\n React.useEffect(() => {\n if (!enabled) {\n return;\n }\n\n void executeAsyncFunction();\n\n // A call still running when the inputs change or the component unmounts\n // must not write its answer afterwards.\n return () => {\n latestCall.current += 1;\n };\n }, [executeAsyncFunction, enabled]);\n\n return {\n data: state.data,\n error: state.error,\n isLoading:\n Option.contains(status, \"initializing\") ||\n (enabled && (state.isLoading || state.settledFunction !== asyncFn)),\n refetch,\n };\n}\n\nexport default useAsyncFunction;\n","import React from \"react\";\nimport type { Atom, AtomRegistry } from \"effect/reactivity\";\n\ninterface AtomStore<A> {\n readonly subscribe: (notify: () => void) => () => void;\n readonly snapshot: () => A;\n}\n\n/**\n * Reads the value of an Effect `Atom` and re-renders whenever it changes.\n *\n * Internal binding around `React.useSyncExternalStore`, intentionally scoped\n * to the SDK so we don't pull in `@effect/atom-react` (which targets a newer\n * React peer range than this package currently supports).\n */\nexport function useAtomValue<A>(registry: AtomRegistry.AtomRegistry, atom: Atom.Atom<A>): A {\n const store = React.useMemo<AtomStore<A>>(\n () => ({\n subscribe: (notify) => registry.subscribe(atom, notify),\n snapshot: () => registry.get(atom),\n }),\n [registry, atom],\n );\n const value = React.useSyncExternalStore(store.subscribe, store.snapshot);\n\n // Atoms are lazy: without an active mount they may be removed from the\n // registry and lose listeners. Mounting on commit keeps the atom alive for\n // the lifetime of the component subscription.\n React.useEffect(() => registry.mount(atom), [registry, atom]);\n\n return value;\n}\n","import React from \"react\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\n\nimport type { VoidhashClient } from \"../../client\";\nimport type { SdkFeatureFlag } from \"../../core/facade-types\";\nimport type { FeatureFlagKey, FeatureFlagValue } from \"../../core/schema/registry\";\nimport {\n decodeFeatureFlagKeys,\n featureFlagsForKeysAtom,\n identityEpochAtom,\n normalizeFeatureFlagKeys,\n} from \"../../core/reactivity/client-state\";\nimport type { VoidhashError } from \"../../errors\";\nimport { type VoidhashContext, useProviderStatus } from \"../components/provider\";\nimport useAsyncFunction from \"./use-async-function\";\nimport { useAtomValue } from \"./use-atom-value\";\n\n/** One flag's evaluation as {@link UseFeatureFlagsResult.getVariant} reports it. */\nexport interface FeatureFlagVariant {\n enabled: boolean;\n /** The selected variant's key, or `null` for a flag without variants. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n variantKey: string | null;\n /** The selected variant's payload: untyped JSON, `null` when it has none. Validate before use. */\n payload: unknown;\n}\n\nexport interface UseFeatureFlagsResult {\n data: {\n /** Every flag evaluated for the requested keys (all flags when none were passed). */\n flags: ReadonlyArray<SdkFeatureFlag>;\n };\n /** The error that stopped the last evaluation, or `null`. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n error: VoidhashError | null;\n /** The flag's variant, or `null` while it is loading or unknown. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n getVariant: (key: FeatureFlagKey) => FeatureFlagVariant | null;\n /**\n * The value of the variant the flag selected, while the flag is enabled:\n * `null` while loading (`isLoading`), and once loaded when the flag is\n * off, has no variant (or one whose value is not text) or is unknown.\n * Typed by the variant values `voidhash.gen.d.ts` lists for the flag; a\n * variant added since generation is not in that union.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n getVariantValue: <K extends FeatureFlagKey>(key: K) => FeatureFlagValue<K> | null;\n /**\n * Whether the flag is enabled. A flag without an evaluated value (while\n * loading, unknown, or on a disabled client) reads as its\n * `featureFlags.defaults` entry, or `false`.\n */\n isEnabled: (key: FeatureFlagKey) => boolean;\n /** `true` while the provider initializes and until this hook's evaluation has answered. */\n isLoading: boolean;\n refetch: () => Promise<void>;\n}\n\nexport function featureFlagsHookFactory(\n client: VoidhashClient,\n vhContext: React.Context<Option.Option<VoidhashContext>>,\n) {\n /**\n * Evaluates `flagKeys` (every flag when omitted) for the current person and\n * re-renders when a newer evaluation lands, including after `identify()` or\n * `reset()` switches the person.\n */\n function useFeatureFlags(flagKeys?: ReadonlyArray<FeatureFlagKey>): UseFeatureFlagsResult {\n const status = useProviderStatus(vhContext, \"useFeatureFlags\");\n const registry = client.internal.getAtomRegistry();\n const identityEpoch = useAtomValue(registry, identityEpochAtom);\n\n // Callers overwhelmingly pass an inline array literal, which is a fresh\n // identity on every render. Depending on it directly would restart the\n // fetch after every state update, so everything downstream is keyed on\n // the normalized signature and the keys are read back from it.\n const normalizedKeys = normalizeFeatureFlagKeys(flagKeys);\n const stableFlagKeys = React.useMemo(\n () => (normalizedKeys === \"all\" ? undefined : decodeFeatureFlagKeys(normalizedKeys)),\n [normalizedKeys],\n );\n\n // The identity epoch is a dependency so a mounted hook evaluates again\n // for the person an `identify()` or `reset()` switched to.\n const fetchFlags = React.useCallback(\n () => client.getFeatureFlags(stableFlagKeys),\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- identityEpoch is the refetch trigger, not an input of the call.\n [stableFlagKeys, identityEpoch],\n );\n\n const { isLoading, error, refetch } = useAsyncFunction(fetchFlags, status);\n\n // Subscribe to only the slice of flag state matching our request. The\n // `featureFlagsForKeysAtom` family memoizes by normalized key so two\n // hooks asking for the same keys (in any order) share an atom, and hooks\n // asking for different keys can't trample each other.\n const flagsAtom = React.useMemo(\n () => featureFlagsForKeysAtom(stableFlagKeys),\n [stableFlagKeys],\n );\n const flags = useAtomValue(registry, flagsAtom);\n\n const findFlag = React.useCallback(\n (key: string) =>\n Option.flatMap(flags, (result) =>\n Option.fromUndefinedOr(result.flags.find((flag) => flag.key === key)),\n ),\n [flags],\n );\n\n const isEnabled = React.useCallback(\n (key: string) =>\n Option.match(findFlag(key), {\n onNone: () => client.internal.isFeatureEnabledByDefault(key),\n onSome: (flag) => flag.enabled,\n }),\n [findFlag],\n );\n\n const getVariantValue = React.useCallback(\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n <K extends FeatureFlagKey>(key: K): FeatureFlagValue<K> | null => {\n if (isLoading) return null;\n const flag = findFlag(key);\n return Option.isSome(flag) && flag.value.enabled && P.isString(flag.value.payload)\n ? flag.value.payload\n : null;\n },\n [findFlag, isLoading],\n );\n\n const getVariant = React.useCallback(\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n (key: string): FeatureFlagVariant | null =>\n Option.getOrNull(\n Option.map(findFlag(key), (flag) => ({\n enabled: flag.enabled,\n payload: flag.payload,\n variantKey: flag.variantKey,\n })),\n ),\n [findFlag],\n );\n\n const data = React.useMemo(\n () => ({\n flags: Option.match(flags, { onNone: () => [], onSome: (result) => result.flags }),\n }),\n [flags],\n );\n\n return {\n data,\n error,\n getVariant,\n getVariantValue,\n isEnabled,\n isLoading,\n refetch,\n };\n }\n return useFeatureFlags;\n}\n","import React from \"react\";\nimport * as Option from \"effect/Option\";\n\nimport type { VoidhashClient } from \"../../client\";\nimport { type EntitlementGrant, findActiveGrant } from \"../../core/entitlements/find-grant\";\nimport type { VoidhashError } from \"../../errors\";\nimport {\n currentPersonAtom,\n currentPersonFreshnessAtom,\n identityEpochAtom,\n} from \"../../core/reactivity/client-state\";\nimport type { PerkSlug } from \"../../core/schema/registry\";\nimport { type VoidhashContext, useProviderStatus } from \"../components/provider\";\nimport useAsyncFunction from \"./use-async-function\";\nimport { useAtomValue } from \"./use-atom-value\";\n\nexport interface UseHasPerkResult {\n /** The active grant behind `hasAccess`, or `null` when there is none. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n grant: EntitlementGrant | null;\n hasAccess: boolean;\n /**\n * `true` while the provider initializes and until this hook's first check\n * has answered, so `hasAccess: false` is never reported before the SDK has\n * looked. `false` for a disabled client.\n */\n isLoading: boolean;\n /**\n * True while `hasAccess` is answered from a snapshot the server has not\n * confirmed recently: a cached one past its refresh window or TTL, or none\n * at all yet. Clears as soon as a refresh lands, even one that runs in the\n * background. Pair with `error` to decide whether to fail open or closed.\n */\n isStale: boolean;\n /** The error that stopped the last check, or `null`. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n error: VoidhashError | null;\n refetch: () => Promise<void>;\n}\n\nexport function hasPerkHookFactory(\n client: VoidhashClient,\n vhContext: React.Context<Option.Option<VoidhashContext>>,\n) {\n /**\n * Checks whether the current person holds an active grant for `perkSlug`,\n * the perk slug configured in Studio. Re-renders when a refresh lands and\n * checks again after `identify()` or `reset()` switches the person.\n */\n function useHasPerk(perkSlug: PerkSlug): UseHasPerkResult {\n const status = useProviderStatus(vhContext, \"useHasPerk\");\n const registry = client.internal.getAtomRegistry();\n const identityEpoch = useAtomValue(registry, identityEpochAtom);\n\n const getPersonCallback = React.useCallback(\n () => client.getCurrentPerson(),\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- identityEpoch is the refetch trigger, not an input of the call.\n [identityEpoch],\n );\n\n const { isLoading, error, refetch } = useAsyncFunction(getPersonCallback, status);\n\n const person = useAtomValue(registry, currentPersonAtom);\n const freshness = useAtomValue(registry, currentPersonFreshnessAtom);\n\n const grant = React.useMemo(() => findActiveGrant(person, perkSlug), [person, perkSlug]);\n\n // Staleness travels with the published snapshot, not with this hook's\n // own read: a refresh that lands later (in the background, after a\n // purchase or a restore) publishes a fresh snapshot and clears it.\n // Transport failures never surface as errors (the cached snapshot is\n // served instead), so the error fallback only covers the rare failures\n // that do surface while a cached grant is being served.\n const isStale =\n !isLoading &&\n (freshness.isStale ||\n freshness.isExpired ||\n (error !== null && Option.isSome(person) && Option.isSome(grant)));\n\n return {\n error,\n grant: Option.getOrNull(grant),\n hasAccess: Option.isSome(grant),\n isLoading,\n isStale,\n refetch,\n };\n }\n return useHasPerk;\n}\n","import type * as Option from \"effect/Option\";\nimport * as React from \"react\";\n\nimport type { VoidhashClient } from \"../../client\";\nimport type { FlowResult, PresentFlowArguments } from \"../../core/flows/flows\";\nimport type { FlowInput, LocationSlug } from \"../../core/schema/registry\";\nimport { type VoidhashContext, useProviderStatus } from \"../components/provider\";\n\nexport function presentFlowHookFactory(\n client: VoidhashClient,\n vhContext: React.Context<Option.Option<VoidhashContext>>,\n) {\n /**\n * Presents the flow assigned to `location`. `present(options)` resolves with\n * how the flow ended and rejects with a `VoidhashError` when it cannot be\n * shown; `isPresenting` is `true` while a flow started by this hook is on\n * screen. `updateInput(values)` changes inputs of the flow on screen.\n */\n function usePresentFlow<const L extends LocationSlug>(location: L) {\n useProviderStatus(vhContext, \"usePresentFlow\");\n const [isPresenting, setIsPresenting] = React.useState(false);\n\n const present = React.useCallback(\n (...args: PresentFlowArguments<L>): Promise<FlowResult<L>> => {\n setIsPresenting(true);\n return client.presentFlow(location, ...args).finally(() => setIsPresenting(false));\n },\n [location],\n );\n\n const updateInput = React.useCallback(\n (values: Partial<FlowInput<L>>): Promise<void> => client.updateFlowInput<L>(values),\n [],\n );\n\n return { isPresenting, present, updateInput };\n }\n return usePresentFlow;\n}\n","import * as Option from \"effect/Option\";\nimport * as R from \"effect/Record\";\nimport * as Schema from \"effect/Schema\";\nimport React from \"react\";\n\nimport type { VoidhashClient } from \"../../client\";\nimport type { Product, ProductForSlug, ProductsForSlugs } from \"../../core/entities/product\";\nimport { clientRunAtom, productsAtom } from \"../../core/reactivity/client-state\";\nimport type { ProductSlug } from \"../../core/schema/registry\";\nimport type { VoidhashError } from \"../../errors\";\nimport { type VoidhashContext, useProviderStatus } from \"../components/provider\";\nimport { useAtomValue } from \"./use-atom-value\";\n\nconst encodeSlugs = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));\n\n/** How the products load is going, the same for every `useProducts()`. */\ninterface ProductsLoad {\n /** The error that stopped the last load, or `null`. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n readonly error: VoidhashError | null;\n /**\n * `true` while the provider initializes and until the products have\n * loaded; `false` while disabled.\n */\n readonly isLoading: boolean;\n /** Loads the products again. */\n readonly refetch: () => Promise<void>;\n}\n\n/** What `useProducts()` answers: every product. */\nexport interface UseProductsResult extends ProductsLoad {\n /** Every product the store sells this end user, sorted by slug; empty until loaded. */\n readonly products: ReadonlyArray<Product>;\n readonly data: {\n /** Each product by its slug; a slug the store has no product for is absent. */\n readonly bySlug: { readonly [Slug in ProductSlug]?: ProductForSlug<Slug> };\n /** The product a slug names, or `undefined` when the store has none. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n readonly get: <Slug extends ProductSlug>(slug: Slug) => ProductForSlug<Slug> | undefined;\n /** Every product, as `products`. */\n readonly toList: () => ReadonlyArray<Product>;\n };\n}\n\n/** What `useProducts(slugs)` answers: the products those slugs name, in their order. */\nexport interface UseProductsBySlugsResult<\n Slugs extends ReadonlyArray<ProductSlug>,\n> extends ProductsLoad {\n /**\n * The product of each slug, in the order given: `undefined` until loaded\n * and where the store has none. With generated types each is typed by its\n * slug, so a subscription's slug is a `SubscriptionProduct`.\n */\n readonly products: ProductsForSlugs<Slugs>;\n}\n\nexport function productsHookFactory(\n client: VoidhashClient,\n vhContext: React.Context<Option.Option<VoidhashContext>>,\n) {\n /**\n * The store products of the project, loaded once for every mounted hook\n * and loaded again when the identity changes, a purchase or restore\n * completes (in a flow too), the product definitions change, or the client\n * starts again after `end()`. Without arguments, every product; with\n * slugs, the products they name, in that order:\n *\n * ```ts\n * const { products: [yearly, monthly], isLoading } = voidhash.useProducts([\"yearly\", \"monthly\"]);\n * ```\n */\n function useProducts(): UseProductsResult;\n function useProducts<const Slugs extends ReadonlyArray<ProductSlug>>(\n slugs: Slugs,\n ): UseProductsBySlugsResult<Slugs>;\n function useProducts(\n slugs?: ReadonlyArray<ProductSlug>,\n ): UseProductsResult | UseProductsBySlugsResult<ReadonlyArray<ProductSlug>> {\n const status = useProviderStatus(vhContext, \"useProducts\");\n const registry = client.internal.getAtomRegistry();\n const state = useAtomValue(registry, productsAtom);\n const run = useAtomValue(registry, clientRunAtom);\n const ready = Option.contains(status, \"ready\");\n\n // The first hook to mount loads, a mount after a failed load tries again,\n // and so does a new run of the client (`end()` dropped the products); the\n // client keeps the products current from then on.\n React.useEffect(() => {\n if (!ready) return;\n const current = registry.get(productsAtom);\n if (Option.isNone(current.products) && !current.isLoading) void client.getProducts();\n }, [ready, registry, run]);\n\n const refetch = React.useCallback(async () => {\n await client.getProducts();\n }, []);\n\n const products = React.useMemo(\n () => Option.getOrElse(state.products, (): ReadonlyArray<Product> => []),\n [state.products],\n );\n\n // Callers pass an inline array literal, a new identity on every render;\n // the selection follows the slugs it holds.\n const slugsKey = slugs === undefined ? undefined : encodeSlugs(slugs);\n const selected = React.useMemo(\n () => slugs?.map((slug) => products.find((product) => product.slug === slug)),\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- the key is the slugs' content; the array identity changes every render.\n [products, slugsKey],\n );\n\n const data = React.useMemo(() => {\n const bySlug = R.fromIterableWith(products, (product) => [product.slug, product]);\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n function get<Slug extends ProductSlug>(slug: Slug): ProductForSlug<Slug> | undefined;\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n function get(slug: ProductSlug): Product | undefined {\n return bySlug[slug];\n }\n return { bySlug, get, toList: () => products };\n }, [products]);\n\n const load: ProductsLoad = {\n error: Option.getOrNull(state.error),\n isLoading:\n Option.contains(status, \"initializing\") ||\n (ready &&\n (state.isLoading || (Option.isNone(state.products) && Option.isNone(state.error)))),\n refetch,\n };\n return selected === undefined ? { ...load, data, products } : { ...load, products: selected };\n }\n return useProducts;\n}\n","import { Result } from \"better-result\";\nimport * as Option from \"effect/Option\";\nimport * as React from \"react\";\n\nimport type { PurchaseOptions, PurchaseResult, VoidhashClient } from \"../../client\";\nimport type { Product } from \"../../core/entities/product\";\nimport { PurchaseInProgressError, type VoidhashError } from \"../../errors\";\nimport { type VoidhashContext, useProviderStatus } from \"../components/provider\";\nimport { runHostCallback } from \"../internal/host-callback\";\n\n/** A purchase the store charged for, as `onSuccess` receives it. */\nexport type CompletedPurchase = Extract<PurchaseResult, { status: \"purchased\" }>;\n\n/**\n * Callbacks for a purchase's outcome. An exception a callback throws (or a\n * promise it returns that rejects) is reported through `onDiagnostic` as\n * `HOST_CALLBACK_FAILED` and never affects the purchase or the hook's state.\n */\nexport interface UsePurchaseOptions {\n /**\n * Runs when the store charged (`purchased`), whether or not Voidhash has\n * accepted the receipt yet (`synced`): the purchase is done either way.\n */\n onSuccess?: (result: CompletedPurchase) => void;\n onError?: (error: VoidhashError) => void;\n onSettled?: (result: Result<PurchaseResult, VoidhashError>) => void;\n}\n\n/**\n * What one `purchase()` call of the hook takes: its own callbacks, and the\n * purchase options `client.purchase()` takes.\n */\nexport interface UsePurchaseCallOptions extends UsePurchaseOptions, PurchaseOptions {}\n\nexport function purchaseHookFactory(\n client: VoidhashClient,\n vhContext: React.Context<Option.Option<VoidhashContext>>,\n) {\n /**\n * Buys products, for a Buy button. `purchase(product)` resolves with the\n * result of `client.purchase()` and never rejects; `pendingProduct` is the\n * product a purchase this hook started is buying. Pressing Buy again for\n * the same product with the same purchase options while it runs answers\n * that same purchase (its callbacks, not the second call's, run); a\n * purchase of another product, or of the same product with other options\n * (another offer, say), meanwhile resolves `Err(PURCHASE_IN_PROGRESS)` and\n * leaves the running one alone.\n */\n function usePurchase(hookOptions?: UsePurchaseOptions) {\n useProviderStatus(vhContext, \"usePurchase\");\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n const [pendingProduct, setPendingProduct] = React.useState<Product | undefined>(undefined);\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n const [error, setError] = React.useState<VoidhashError | null>(null);\n const running = React.useRef(\n Option.none<{\n /** What it buys; `None` for options `purchase()` refuses, which match nothing. */\n readonly key: Option.Option<string>;\n readonly settled: Promise<Result<PurchaseResult, VoidhashError>>;\n }>(),\n );\n\n const purchase = React.useCallback(\n (\n product: Product,\n options?: UsePurchaseCallOptions,\n ): Promise<Result<PurchaseResult, VoidhashError>> => {\n const { onError, onSettled, onSuccess, ...purchaseOptions } = {\n ...hookOptions,\n ...options,\n };\n const runCallbacks = (result: Result<PurchaseResult, VoidhashError>) => {\n if (result.isOk() && result.value.status === \"purchased\" && onSuccess) {\n const completed = result.value;\n runHostCallback(client, \"usePurchase.onSuccess\", () => onSuccess(completed));\n }\n if (result.isErr() && onError) {\n runHostCallback(client, \"usePurchase.onError\", () => onError(result.error));\n }\n if (onSettled) runHostCallback(client, \"usePurchase.onSettled\", () => onSettled(result));\n };\n\n const key = client.internal.purchaseKey(product, purchaseOptions);\n const current = running.current;\n if (Option.isSome(current)) {\n if (Option.isSome(key) && Option.contains(current.value.key, key.value)) {\n return current.value.settled;\n }\n const refused = Result.err<PurchaseResult, VoidhashError>(new PurchaseInProgressError());\n runCallbacks(refused);\n return Promise.resolve(refused);\n }\n\n setPendingProduct(product);\n setError(null);\n // `purchase` never rejects — every outcome is a Result — and the hook\n // settles before any callback runs, so a callback that throws cannot\n // leave it loading.\n const settled = client.purchase(product, purchaseOptions).then((result) => {\n running.current = Option.none();\n setPendingProduct(undefined);\n if (result.isErr()) setError(result.error);\n runCallbacks(result);\n return result;\n });\n running.current = Option.some({ key, settled });\n return settled;\n },\n [hookOptions],\n );\n\n return {\n /** The error of the last purchase this hook started, or `null`. */\n error,\n /** Whether a purchase this hook started is running. */\n isLoading: pendingProduct !== undefined,\n /** The product a purchase this hook started is buying, or `undefined`. */\n pendingProduct,\n purchase,\n };\n }\n return usePurchase;\n}\n","import * as P from \"effect/Predicate\";\n\nimport type { VoidhashClient } from \"../../client\";\n\n/**\n * Runs a callback the app passed to a hook. An exception it throws, or a\n * promise it returns that rejects, is reported through `onDiagnostic` as\n * `HOST_CALLBACK_FAILED` under `name`, so a bug in app code never leaves a\n * hook stuck or turns a finished purchase or restore into a failure.\n */\nexport function runHostCallback(\n client: VoidhashClient,\n name: string,\n callback: () => unknown,\n): void {\n const report = (callbackError: unknown) =>\n client.internal.reportHostCallbackFailure(name, callbackError);\n // oxlint-disable-next-line effect/avoid-try-catch -- boundary with host application code: the callback is a plain function the app supplies and may throw anything.\n try {\n const returned = callback();\n if (P.isPromiseLike(returned)) returned.then(undefined, report);\n } catch (callbackError) {\n report(callbackError);\n }\n}\n","import type { Result } from \"better-result\";\nimport type * as Option from \"effect/Option\";\nimport * as React from \"react\";\n\nimport type { VoidhashClient } from \"../../client\";\nimport type { Person } from \"../../core/entities/person\";\nimport type { VoidhashError } from \"../../errors\";\nimport { type VoidhashContext, useProviderStatus } from \"../components/provider\";\nimport { runHostCallback } from \"../internal/host-callback\";\n\n/**\n * Callbacks for a restore's outcome. An exception a callback throws (or a\n * promise it returns that rejects) is reported through `onDiagnostic` as\n * `HOST_CALLBACK_FAILED` and never affects the restore or the hook's state.\n */\nexport interface UseRestorePurchasesOptions {\n /**\n * Runs when the restore finished, with the refreshed person (`null` when\n * there is none). It does not mean the person has access: check their\n * entitlements, which mounted `useHasPerk` hooks already re-render with.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook callback consumed by non-Effect app code.\n onSuccess?: (person: Person | null) => void;\n onError?: (error: VoidhashError) => void;\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook callback consumed by non-Effect app code.\n onSettled?: (result: Result<Person | null, VoidhashError>) => void;\n}\n\nexport function restorePurchasesHookFactory(\n client: VoidhashClient,\n vhContext: React.Context<Option.Option<VoidhashContext>>,\n) {\n /**\n * Restores the current person's purchases, for a Restore button.\n * `restore()` resolves with the result of `client.restorePurchases()`, the\n * refreshed person, and never rejects; `isLoading` is `true` while a\n * restore this hook started runs. `restore` takes no arguments, so it can\n * be passed to `onPress` directly.\n */\n function useRestorePurchases(hookOptions?: UseRestorePurchasesOptions) {\n useProviderStatus(vhContext, \"useRestorePurchases\");\n const [isLoading, setIsLoading] = React.useState(false);\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n const [error, setError] = React.useState<VoidhashError | null>(null);\n\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n const restore = React.useCallback((): Promise<Result<Person | null, VoidhashError>> => {\n setIsLoading(true);\n setError(null);\n\n // `restorePurchases` never rejects — every outcome is a Result — and\n // the hook settles before any callback runs, so a callback that throws\n // cannot leave it loading.\n return client.restorePurchases().then((result) => {\n setIsLoading(false);\n if (result.isErr()) setError(result.error);\n\n const { onError, onSettled, onSuccess } = hookOptions ?? {};\n if (result.isOk() && onSuccess) {\n const person = result.value;\n runHostCallback(client, \"useRestorePurchases.onSuccess\", () => onSuccess(person));\n }\n if (result.isErr() && onError) {\n runHostCallback(client, \"useRestorePurchases.onError\", () => onError(result.error));\n }\n if (onSettled) {\n runHostCallback(client, \"useRestorePurchases.onSettled\", () => onSettled(result));\n }\n return result;\n });\n }, [hookOptions]);\n\n return {\n /** The error of the last restore, or `null`. */\n error,\n isLoading,\n restore,\n };\n }\n return useRestorePurchases;\n}\n","import type { Subscription } from \"../../core/entities/person\";\nimport type { UseCurrentPersonResult } from \"./use-person\";\n\nexport interface UseSubscriptionsResult extends Omit<UseCurrentPersonResult, \"data\"> {\n /**\n * Every subscription of the person that has not ended, including ones in a\n * grace period, in billing retry, on hold or paused: what a \"manage\n * subscription\" screen lists. Empty until the person loads. Access comes\n * from entitlements (`useHasPerk`), never from this list.\n */\n readonly all: ReadonlyArray<Subscription>;\n /** The subscription that matters most now, or `undefined` when there is none. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n readonly current: Subscription | undefined;\n}\n\nconst NO_SUBSCRIPTIONS: ReadonlyArray<Subscription> = [];\n\nexport function subscriptionsHookFactory(useCurrentPerson: () => UseCurrentPersonResult) {\n /**\n * The person's subscriptions as the server knows them across devices and\n * stores: renewal, grace period, billing retry, hold, pause and pending\n * changes. Re-renders with the person, as `useCurrentPerson()` does.\n */\n function useSubscriptions(): UseSubscriptionsResult {\n const { data: person, ...state } = useCurrentPerson();\n return {\n ...state,\n all: person?.subscriptions.all ?? NO_SUBSCRIPTIONS,\n current: person?.subscriptions.current,\n };\n }\n return useSubscriptions;\n}\n","// Generated by `pnpm specs` from the React Native SDK's\n// src/specs/VoidhashNativeClient.nitro.ts. Do not edit: change that spec and\n// run `pnpm specs` again.\nimport { Android, iOS, type HybridObject } from \"nitro-core\";\n\nexport * from \"#nitro/VoidhashNativeClient\";\n\n/*\n * The contract between the React Native facade and the native Voidhash client\n * (the Swift `VoidhashClient` and the Kotlin `com.voidhash.sdk.VoidhashClient`)\n * it is moving onto. The facade keeps its public surface: option validation,\n * the `Result` and `VoidhashError` shapes, the provider and the hooks stay in\n * TypeScript; identity, purchases, analytics, flags, the schema and paywalls\n * are the native client's.\n *\n * Shapes the SDK defines are Nitro structs. Payloads the Voidhash API defines\n * (a person snapshot, a paywall, a schema, a flag payload, event properties)\n * cross as JSON strings, so a server that adds a field needs no new binary.\n *\n * Errors: every promise rejects with an error whose message is\n * `\"<CODE>: <detail>\"`; the detail may be empty. On Android the message\n * reaches JavaScript as the throwable's printed stack trace and on both\n * platforms a synchronous throw gets the method's name in front; the facade\n * reads the code through all of that. Use a facade `VoidhashErrorCode` where\n * one fits (`AUTHENTICATION_FAILED`, `INVALID_ARGUMENT`, `OFFER_UNAVAILABLE`,\n * `PAYWALL_UNAVAILABLE`, `PURCHASE_IN_PROGRESS`,\n * `READ_ONLY_PURCHASE_NOT_ALLOWED`, `REPLACED_SUBSCRIPTION_NOT_OWNED`,\n * `SUBSCRIPTION_REPLACEMENT_REFUSED`, `UNSUPPORTED_PLATFORM`, a `FLOW_*`\n * code), `NOT_INITIALIZED` before `start()`, after `shutdown()` and from a\n * native client the native SDK made inert (nothing was done), and\n * `NOT_IMPLEMENTED` for a member a build does not support yet. A purchase the\n * store refused for a reason it named rejects with that reason's code:\n * `PAYMENT_DECLINED` (Android only: Play\n * `PAYMENT_DECLINED_DUE_TO_INSUFFICIENT_FUNDS`; StoreKit 2 has no declined\n * payment error) or `INELIGIBLE_FOR_OFFER` (Play `USER_INELIGIBLE`, StoreKit\n * `Product.PurchaseError.ineligibleForOffer`); the facade reports both as\n * `FAILED_TO_PURCHASE` with `reason` set. Each facade method keeps the codes it reports today: a code it\n * does not report reaches the app under that method's `FAILED_TO_*` code, its\n * native message kept.\n *\n * Store-specific members (`appStore*`, `googlePlay*`) exist on both\n * platforms, as Nitro requires; on the other platform they reject\n * `UNSUPPORTED_PLATFORM` without doing anything. The facade checks the\n * platform first, so that path is a safety net.\n *\n * Products and transactions: the fields every store has are the structs\n * below, filled from the native SDK's `VoidhashProduct` and\n * `VoidhashTransaction` field for field. Their `appStore` and `googlePlay`\n * parts cross as JSON (`appStoreJson`, `googlePlayJson`), shaped exactly as\n * the facade's `AppStoreProductInfo`, `GooglePlayProductInfo`,\n * `AppStoreTransactionInfo` and `GooglePlayTransactionInfo` types in\n * `src/core/entities/app-store.ts` and `google-play.ts` declare them, with the\n * stores' own field names: dates as milliseconds since the epoch, a `Price`\n * as `{ amount, amountMicros, currencyCode, formatted }`, a `Period` as\n * `{ unit, count, iso8601 }`, an absent value left out or `null`. Every enum\n * here has an `unknown` case: send it for a native case this contract does\n * not list.\n *\n * Rejected publishable key: while API requests are paused because the key\n * was rejected (`401`/`403`), the first `getPersonState`, `getFeatureFlags`\n * or `getPaywall` call that has nothing cached to answer with rejects\n * `AUTHENTICATION_FAILED`. That happens once per pause, shared across the\n * three reads; a request the pause lets through that succeeds, or a new\n * `start()`, ends the pause. Every later read answers as it would offline:\n * from its cache, with an empty answer marked stale, or for a paywall with\n * nothing cached `PAYWALL_UNAVAILABLE`. A read that can answer from its cache\n * never rejects with it. The rejection is reported through the `diagnostic`\n * event either way.\n *\n * Threading and ordering: methods may be called from the JS thread at any\n * time; promises and the event listener settle on the JS thread, in the order\n * the native client produced them. A call that emits events returns a pending\n * promise and settles it only after those events were dispatched to the\n * listener: a promise already settled when it is returned resolves in the\n * JavaScript microtask queue, ahead of any event the call emitted.\n *\n * Identity generations: every identity a client adopts gets the next\n * number of one counter that only grows for the life of the process, across\n * every instance and every `start()`/`shutdown()` (a re-init, another\n * project). Person and flag answers carry the generation they were read\n * under; the facade publishes only the current generation's, so a late answer\n * from an identity switched away from (or from a previous run) is never\n * published, even after a switch back to the same distinct id.\n */\n\n/** The end user's analytics consent, as `setAnalyticsConsent()` takes it. */\nexport type NativeAnalyticsConsent = \"granted\" | \"denied\" | \"pending\";\n\n/** What happens to events captured while analytics consent is `pending`. */\nexport type NativePendingAnalytics = \"drop\" | \"buffer\";\n\n/**\n * Why a person answer has the freshness it has: confirmed by the server just\n * now, served from cache while a refresh still runs, served from cache\n * because the refresh failed, or nothing was ever cached for this identity.\n */\nexport type NativeFreshnessReason = \"fresh\" | \"refreshInFlight\" | \"refreshFailed\" | \"noCache\";\n\n/**\n * How a person write ended: the server confirmed it, it waits in the\n * person-write outbox, or nothing was left to write (`skipped`). Person\n * attributes are written whatever the analytics consent, so `skipped` means\n * one thing only: the write held nothing but an agreement to ad data sharing\n * (`$ad_data_sharing` other than `false`), which is left out while consent is\n * not granted.\n */\nexport type NativeWriteStatus = \"confirmed\" | \"deferred\" | \"skipped\";\n\n/**\n * What Google Play charges when a purchase replaces a subscription; the\n * native SDK's replacement mode and the facade's\n * `SubscriptionReplacementMode`, value for value.\n */\nexport type NativeSubscriptionReplacementMode =\n | \"withTimeProration\"\n | \"chargeProratedPrice\"\n | \"chargeFullPrice\"\n | \"withoutProration\"\n | \"deferred\";\n\n/** The subscription a purchase replaces instead of adding a second one next to it. */\nexport interface NativeSubscriptionReplacement {\n /** Slug of the subscription product the end user has now. */\n readonly productSlug: string;\n readonly mode: NativeSubscriptionReplacementMode;\n}\n\n/** The store a reported transaction comes from. */\nexport type NativeStorePlatform = \"appStore\" | \"googlePlay\";\n\n/** The state another billing integration reported a Google Play purchase in. */\nexport type NativeReportedPurchaseState = \"purchased\" | \"pending\" | \"unspecified\";\n\n/** The interface revision an app was built against at one location. */\nexport interface NativeFlowRevision {\n readonly location: string;\n readonly revision: number;\n}\n\n/** What the app passes to one presentation of a flow. */\nexport interface NativeFlowPresentation {\n /**\n * The interface revision the app was built against; absent to use the one\n * configured for the location, or 0 when there is none.\n */\n readonly revision?: number;\n /** The flow's inputs by name, as a JSON object of strings, numbers and booleans. */\n readonly inputJson: string;\n /** Names of the app actions the app handles. */\n readonly actions: string[];\n}\n\n/**\n * Which flow runtime draws flows, process-wide: the one built into the SDK\n * (`linked`) or the flow runtime modules the server offers (`module`).\n */\nexport type NativeFlowRuntime = \"linked\" | \"module\";\nexport type NativeFlowLoading = \"standard\" | \"none\";\n\n/** What a flow may do beyond purchases, restores, closing and analytics. */\nexport type NativeFlowCapability = \"links\" | \"notifications\" | \"tracking\" | \"attributes\";\n\n/** Which payload a {@link NativeClientEvent} carries. */\nexport type NativeClientEventType =\n | \"person\"\n | \"identity\"\n | \"flags\"\n | \"schema\"\n | \"consent\"\n | \"diagnostic\"\n | \"transaction\"\n | \"purchaseIntent\";\n\n/**\n * When StoreKit shows its messages (price increase consent, billing issues,\n * win-back offers): at once (`automatic`), or held while a Voidhash flow is\n * on screen and shown once it closes (`deferWhileFlowPresented`). Google Play\n * ignores it.\n */\nexport type NativeAppStoreMessages = \"automatic\" | \"deferWhileFlowPresented\";\n\n/**\n * What happens to a purchase the end user started on the App Store (a\n * promoted in-app purchase, a win-back offer): bought through the normal\n * purchase path once `start()` has resolved its identity\n * (`purchaseWhenReady`), never before; or handed to the app as a\n * `purchaseIntent` event (`manual`). Google Play ignores it.\n */\nexport type NativePurchaseIntents = \"purchaseWhenReady\" | \"manual\";\n\n/** Coarse category of a diagnostic, the facade's `VoidhashDiagnosticKind`. */\nexport type NativeDiagnosticKind =\n | \"transport\"\n | \"eviction\"\n | \"breaker\"\n | \"auth\"\n | \"cache\"\n | \"configuration\"\n | \"consent\";\n\n/**\n * The facade's options after validation, as `configure()` receives them.\n * Native automatic screen tracking stays off under React Native: the facade's\n * navigation integrations report screens through `screen()`.\n */\nexport interface NativeClientConfiguration {\n readonly publishableKey: string;\n /** Absolute `http(s)` origin of the API, already validated. */\n readonly baseUrl: string;\n /** Origin of analytics ingest; `baseUrl` when absent. */\n readonly ingestUrl?: string;\n readonly debug: boolean;\n /** Development purchases: `dev: true` in a debug build. Always `false` in release builds. */\n readonly developmentMode: boolean;\n /** Adopted on the first `start()` of the process; later starts resume the stored identity. */\n readonly distinctId?: string;\n /** Observer mode at start; `setReadOnly()` changes it later. */\n readonly readOnly: boolean;\n /**\n * The `analyticsConsent` option: applies when no consent was chosen, in this\n * process or by an earlier `setAnalyticsConsent()` stored on the device.\n */\n readonly analyticsConsent: NativeAnalyticsConsent;\n /**\n * A consent the app chose with `setAnalyticsConsent()` in this process\n * before the client started. It wins over the stored one, is stored in its\n * place, and is in effect before `start()` captures or sends anything.\n */\n readonly chosenAnalyticsConsent?: NativeAnalyticsConsent;\n /**\n * The `analyticsWhilePending` option: `buffer` holds events captured while\n * consent is `pending` in memory and records them when it is granted.\n */\n readonly analyticsWhilePending: NativePendingAnalytics;\n /** The `grantConsentOnIdentify` option: `identify()` grants a `pending` consent. */\n readonly grantConsentOnIdentify: boolean;\n readonly automaticLifecycleEvents: boolean;\n /** Reads which ad brought this install, once per install; see the facade's option. */\n readonly installAttribution: boolean;\n /** The Meta app id to ask Meta's apps about on Android; iOS ignores it. */\n readonly metaAppId?: string;\n /** Locations whose flows are downloaded at start. */\n readonly preloadLocations: string[];\n /**\n * The interface revision the app was built against, per location. Used to\n * preload and as the revision of a presentation that names none.\n */\n readonly flowRevisions: NativeFlowRevision[];\n readonly flowCapabilities: NativeFlowCapability[];\n /**\n * The `flowRuntime` option. `module` switches the linked native renderer to\n * flow runtime modules before anything resolves a flow; set once per\n * process, it stays for the process.\n */\n readonly flowRuntime: NativeFlowRuntime;\n /**\n * The `flowLoading` option: `none` turns the linked native renderer's loading\n * screen off.\n */\n readonly flowLoading: NativeFlowLoading;\n /** `false` turns every `screen()` into a no-op. */\n readonly screenTrackingEnabled: boolean;\n /**\n * The `featureFlags.maxWaitMs` option: how long a flag read with nothing\n * cached waits for Voidhash, in milliseconds, a non-negative integer. The\n * native client's own default (2000) when absent. A binary built before\n * this field ignores it and waits its default.\n */\n readonly featureFlagMaxWaitMs?: number;\n /**\n * The `featureFlags.defaults` option: what each flag reads as while it has\n * no evaluated value. A binary built before this field ignores it; the\n * facade's hooks apply the defaults either way.\n */\n readonly featureFlagDefaults?: Record<string, boolean>;\n /** A runtime schema to use instead of fetching one (tests and previews only). */\n readonly internalSchemaJson?: string;\n /** The `appStoreMessages` option; see {@link NativeAppStoreMessages}. */\n readonly appStoreMessages: NativeAppStoreMessages;\n /** The `purchaseIntents` option; see {@link NativePurchaseIntents}. */\n readonly purchaseIntents: NativePurchaseIntents;\n /** The facade's package version, sent with every request. */\n readonly sdkVersion: string;\n}\n\n/** The identity the client adopted, and the generation it adopted it under. */\nexport interface NativeIdentityChange {\n readonly distinctId: string;\n /** The identity before the change; empty for the identity `start()` loaded. */\n readonly previousDistinctId: string;\n /** The adoption's identity generation; greater than every earlier one. */\n readonly generation: number;\n}\n\n/** A person snapshot with how far it can be trusted. */\nexport interface NativePersonState {\n /** The identity the snapshot belongs to. */\n readonly distinctId: string;\n /** The identity generation the snapshot was read under. */\n readonly generation: number;\n /** The server's person snapshot as JSON; absent when there is none. */\n readonly personJson?: string;\n /** Served from cache past its refresh window. */\n readonly isStale: boolean;\n /** Served from cache past its expiry. */\n readonly isExpired: boolean;\n readonly reason: NativeFreshnessReason;\n}\n\n/** Outcome of `identify()`. */\nexport interface NativeIdentifyResult {\n /** The identity in effect once the call settled: the one `identify()` switched to. */\n readonly identity: NativeIdentityChange;\n /** `confirmed` once the server linked the identities, `deferred` while the link is queued. */\n readonly status: NativeWriteStatus;\n /** The confirmed person, or the last known snapshot for a deferred switch, as JSON. */\n readonly personJson?: string;\n}\n\n/** Outcome of `setPersonAttributesState()`. */\nexport interface NativePersonWriteResult {\n readonly status: NativeWriteStatus;\n /** The confirmed person, or the last known snapshot for a deferred write, as JSON. */\n readonly personJson?: string;\n}\n\n/** One evaluated flag. */\nexport interface NativeFeatureFlag {\n readonly key: string;\n readonly enabled: boolean;\n /** The selected variant's key; absent for a flag without variants. */\n readonly variantKey?: string;\n /** The selected variant's payload as JSON; absent when it has none. */\n readonly payloadJson?: string;\n}\n\n/** A flag evaluation for one request: every flag, or the keys asked for. */\nexport interface NativeFeatureFlagsResult {\n /** The identity the evaluation belongs to. */\n readonly distinctId: string;\n /** The identity generation the evaluation was read under. */\n readonly generation: number;\n /**\n * The keys this evaluation answers; absent for every flag. A `flags` event\n * is stored under these; a read's answer is stored under the keys the\n * caller asked for, whatever comes back here.\n */\n readonly flagKeys?: string[];\n readonly flags: NativeFeatureFlag[];\n /** Served from cache past its refresh window, or no evaluation has ever succeeded. */\n readonly isStale: boolean;\n}\n\n/** The store a product or transaction belongs to; `development` for development-mode purchases. */\nexport type NativeStore = \"appStore\" | \"googlePlay\" | \"development\" | \"unknown\";\n\n/** The native SDK's product type. */\nexport type NativeProductType =\n | \"subscription\"\n | \"consumable\"\n | \"nonConsumable\"\n | \"nonRenewingSubscription\"\n | \"unknown\";\n\n/** The unit of a {@link NativePeriod}. */\nexport type NativePeriodUnit = \"day\" | \"week\" | \"month\" | \"year\" | \"unknown\";\n\n/** How a pricing phase is paid. */\nexport type NativePaymentMode = \"freeTrial\" | \"payAsYouGo\" | \"payUpFront\" | \"unknown\";\n\n/** The native SDK's offer kind. */\nexport type NativeOfferKind = \"introductory\" | \"promotional\" | \"winBack\" | \"oneTime\" | \"unknown\";\n\n/** The native SDK's `Price`. */\nexport interface NativePrice {\n /** The amount in the currency's units (the native `Decimal`/`BigDecimal` as a double). */\n readonly amount: number;\n /** The exact amount × 1,000,000. */\n readonly amountMicros: number;\n /** ISO 4217. */\n readonly currencyCode: string;\n /** The store's localized string, never re-formatted. */\n readonly formatted: string;\n}\n\n/** The native SDK's `Period`, already normalised (7 days are 1 week). */\nexport interface NativePeriod {\n readonly unit: NativePeriodUnit;\n /** At least 1. */\n readonly count: number;\n /** Generated from the normalised value: `P1W`, `P3M`, `P1Y`. */\n readonly iso8601: string;\n}\n\n/** The native SDK's `PricingPhase`. */\nexport interface NativePricingPhase {\n readonly paymentMode: NativePaymentMode;\n /** Per cycle; zero for a free trial. */\n readonly price: NativePrice;\n /** The length of one cycle. */\n readonly period: NativePeriod;\n /** How many cycles the phase lasts, at least 1. */\n readonly cycles: number;\n}\n\n/** The native SDK's `Offer`. */\nexport interface NativeOffer {\n /**\n * Google Play: the Studio offer id when the offer is configured in Studio,\n * else Play's offer id. App Store: a promotional offer's Studio id (only\n * Studio-configured ones are listed), a win-back offer's App Store id, `\"\"`\n * for the introductory offer.\n */\n readonly id: string;\n readonly kind: NativeOfferKind;\n /** Subscription offers: the phases before the regular price, in order. Empty for `oneTime`. */\n readonly phases: NativePricingPhase[];\n /** `oneTime` offers: what the product costs with it. Absent for subscription offers. */\n readonly price?: NativePrice;\n}\n\n/**\n * The native SDK's `SubscriptionInfo`. The four `pricePer*` prices are the\n * native SDK's, computed natively (rounded half-up to the currency's minor\n * units, formatted with the store's locale); never computed in JavaScript.\n */\nexport interface NativeSubscriptionInfo {\n readonly period: NativePeriod;\n /** The App Store subscription group id; on Google Play, the subscription's product id. */\n readonly groupId: string;\n /** The intro offer this end user is eligible for right now; absent otherwise. */\n readonly introOffer?: NativeOffer;\n readonly pricePerDay: NativePrice;\n readonly pricePerWeek: NativePrice;\n readonly pricePerMonth: NativePrice;\n readonly pricePerYear: NativePrice;\n}\n\n/** The native SDK's `VoidhashProduct`, one per Studio product slug. */\nexport interface NativeProduct {\n /** The Voidhash product id (the schema product's `id`). */\n readonly productId: string;\n readonly slug: string;\n readonly store: NativeStore;\n /** The App Store or Google Play product id. */\n readonly storeProductId: string;\n readonly type: NativeProductType;\n /** The Studio name. */\n readonly name: string;\n /** The store's localized title. */\n readonly displayName: string;\n /** The store's localized description. */\n readonly description: string;\n /** The regular price (Google Play: the recurring phase of the pinned base plan). */\n readonly price: NativePrice;\n /** Present exactly when `type` is `subscription`. */\n readonly subscription?: NativeSubscriptionInfo;\n /** The purchasable non-introductory offers for this end user. */\n readonly offers: NativeOffer[];\n /** The product's `appStore` part as JSON (`AppStoreProductInfo`); present exactly when `store` is `appStore`. */\n readonly appStoreJson?: string;\n /** The product's `googlePlay` part as JSON (`GooglePlayProductInfo`); present exactly when `store` is `googlePlay`. */\n readonly googlePlayJson?: string;\n}\n\n/** The kind of offer a transaction was bought with; `code` for a redeemed offer code. */\nexport type NativeTransactionOfferKind =\n | \"introductory\"\n | \"promotional\"\n | \"winBack\"\n | \"oneTime\"\n | \"code\"\n | \"unknown\";\n\n/** Where a transaction was made. */\nexport type NativeEnvironment = \"production\" | \"sandbox\" | \"xcode\" | \"development\" | \"unknown\";\n\n/** The offer of a transaction; every field absent when the store does not say. */\nexport interface NativeTransactionOffer {\n readonly id?: string;\n readonly kind?: NativeTransactionOfferKind;\n readonly paymentMode?: NativePaymentMode;\n}\n\n/** The native SDK's `VoidhashTransaction`. */\nexport interface NativeTransaction {\n /** Apple `transactionId` / Play `purchaseToken`: stable from pending to purchased. */\n readonly id: string;\n /** Apple `originalID`; absent on Google Play. */\n readonly originalId?: string;\n /** Resolved through the schema; absent when no product has the store product. */\n readonly productSlug?: string;\n readonly storeProductId: string;\n readonly store: NativeStore;\n /** Milliseconds since the epoch. */\n readonly purchasedAt: number;\n /** Milliseconds since the epoch. */\n readonly expiresAt?: number;\n /** What the store charged for (`Purchase.getQuantity()` on Google Play). */\n readonly quantity: number;\n /** Apple `reason == .renewal` (iOS 17 and later); absent where unknown (Google Play). */\n readonly isRenewal?: boolean;\n readonly offer?: NativeTransactionOffer;\n readonly environment: NativeEnvironment;\n /** The `appStore` part as JSON (`AppStoreTransactionInfo`); present exactly when `store` is `appStore`. */\n readonly appStoreJson?: string;\n /** The `googlePlay` part as JSON (`GooglePlayTransactionInfo`); present exactly when `store` is `googlePlay`. */\n readonly googlePlayJson?: string;\n}\n\n/**\n * Which offer `purchase()` buys:\n *\n * - `automatic`: a subscription's `introOffer` when it has one, else the\n * regular price. On Google Play this passes the intro offer's token.\n * - `regularPrice`: the regular price (Play: the base plan's token; the App\n * Store may still apply an intro offer the user is eligible for).\n * - `offer`: the offer `offerId` names, resolved against the product's\n * current `offers` and `subscription.introOffer` (of kind `offerKind` when\n * given). `offerKind: introductory` always means the product's current\n * `subscription.introOffer`, whatever `offerId` says (the App Store's has\n * no id of its own, so the app may pass an empty one). None matching\n * rejects `OFFER_UNAVAILABLE`, never buying at the regular price instead.\n */\nexport type NativeOfferSelection = \"automatic\" | \"regularPrice\" | \"offer\";\n\n/** App Store options of a purchase; Google Play ignores them. */\nexport interface NativeAppStorePurchaseOptions {\n /** StoreKit's `simulatesAskToBuyInSandbox` purchase option. */\n readonly simulatesAskToBuyInSandbox?: boolean;\n}\n\n/** Google Play options of a purchase; the App Store ignores them. */\nexport interface NativeGooglePlayPurchaseOptions {\n /** `BillingFlowParams.setIsOfferPersonalized`. */\n readonly isOfferPersonalized?: boolean;\n /** `BillingFlowParams.setObfuscatedProfileId`. */\n readonly obfuscatedProfileId?: string;\n /** Buys exactly this offer token, whatever `offerSelection` says. */\n readonly offerToken?: string;\n}\n\n/** What `purchase()` buys beyond the product. */\nexport interface NativePurchaseOptions {\n readonly offerSelection: NativeOfferSelection;\n /** With `offer`: the offer's id. */\n readonly offerId?: string;\n /** With `offer`: the offer's kind, when the app passed an offer rather than an id. */\n readonly offerKind?: NativeOfferKind;\n /**\n * At least 1. Anything but 1 is honoured for App Store consumables only;\n * elsewhere it rejects `INVALID_ARGUMENT` (the facade checks it first).\n */\n readonly quantity: number;\n readonly replacing?: NativeSubscriptionReplacement;\n readonly appStore?: NativeAppStorePurchaseOptions;\n readonly googlePlay?: NativeGooglePlayPurchaseOptions;\n}\n\n/**\n * How a purchase ended: the store charged (`purchased`), it needs outside\n * action such as Ask to Buy or a pending payment first (`pending`), or the\n * end user dismissed the sheet (`cancelled`).\n */\nexport type NativePurchaseOutcome = \"purchased\" | \"pending\" | \"cancelled\";\n\n/** The native SDK's purchase result. */\nexport interface NativePurchaseResult {\n readonly outcome: NativePurchaseOutcome;\n /** With `purchased`: the transaction. With a Play `deferred` replacement it names the old product. */\n readonly transaction?: NativeTransaction;\n /** With `purchased`: `true` once Voidhash accepted the receipt, `false` while it waits on the device. */\n readonly synced?: boolean;\n}\n\n/** A transaction the native SDK handled outside `purchase()`; its transaction update stream. */\nexport interface NativeTransactionUpdate {\n readonly transaction: NativeTransaction;\n /** `true` once Voidhash accepted the receipt, `false` while it waits on the device. */\n readonly synced: boolean;\n}\n\n/** A purchase the end user started on the App Store, as `purchaseIntents: manual` hands it over. */\nexport interface NativePurchaseIntent {\n readonly productSlug: string;\n /** The offer the end user chose (a win-back offer, iOS 18 and later). */\n readonly offer?: NativeOffer;\n}\n\n/** The storefront the end user buys from. */\nexport interface NativeStorefront {\n /** ISO 3166-1 alpha-2 (StoreKit's alpha-3 converted). */\n readonly countryCode: string;\n /** ISO 4217, when the store says. */\n readonly currencyCode?: string;\n}\n\n/** How a refund request ended. */\nexport type NativeRefundRequestStatus = \"success\" | \"userCancelled\";\n\n/** StoreKit's `RenewalState`. */\nexport type NativeAppStoreSubscriptionState =\n | \"subscribed\"\n | \"expired\"\n | \"inBillingRetryPeriod\"\n | \"inGracePeriod\"\n | \"revoked\"\n | \"unknown\";\n\n/** One StoreKit `Product.SubscriptionInfo.Status`. */\nexport interface NativeAppStoreSubscriptionStatus {\n readonly state: NativeAppStoreSubscriptionState;\n /** The status's verified transaction. */\n readonly transaction: NativeTransaction;\n /**\n * The verified `RenewalInfo` as JSON, shaped as the facade's\n * `AppStoreRenewalInfo`: `{ willAutoRenew, autoRenewProductId?,\n * expirationReason?, gracePeriodExpiresAt?, isInBillingRetry,\n * priceIncreaseStatus?, renewalPrice?, eligibleWinBackOfferIds }`.\n */\n readonly renewalInfoJson: string;\n}\n\n/** Which Google Play in-app message outcome `googlePlayShowInAppMessages()` had. */\nexport type NativeInAppMessageStatus = \"noActionNeeded\" | \"subscriptionStatusUpdated\";\n\n/** The outcome of Play's `showInAppMessages` (TRANSACTIONAL category). */\nexport interface NativeInAppMessageResult {\n readonly status: NativeInAppMessageStatus;\n /** With `subscriptionStatusUpdated`: the purchase token whose status changed. */\n readonly purchaseToken?: string;\n}\n\n/** A purchase another billing integration completed, by its store identifier only. */\nexport interface NativeReportedTransaction {\n readonly platform: NativeStorePlatform;\n /** App Store transaction id; required for `appStore`. */\n readonly transactionId?: string;\n /** Google Play purchase token; required for `googlePlay`. */\n readonly purchaseToken?: string;\n /**\n * Google Play: the state the integration reported. A `pending` or\n * `unspecified` purchase is ignored, as the facade does today; report it\n * again once it is purchased. Absent counts as purchased.\n */\n readonly purchaseState?: NativeReportedPurchaseState;\n /**\n * App Store: the transaction's JWS when the integration handed it over.\n * Sent as the proof a purchase or restore claim needs; without it the\n * native SDK reads it from the device's purchase history.\n */\n readonly signedTransaction?: string;\n}\n\n/** Outcome of a flush or a shutdown. */\nexport interface NativeFlushStatus {\n /** Events the server accepted. */\n readonly flushed: number;\n /** Events still queued. */\n readonly pending: number;\n /** Why delivery stopped, when it did. */\n readonly lastErrorMessage?: string;\n}\n\n/** A non-fatal event the native client handled on its own; the facade's `VoidhashDiagnostic`. */\nexport interface NativeDiagnostic {\n readonly kind: NativeDiagnosticKind;\n /** Stable code, for example `ANALYTICS_EVENT_DROPPED`. */\n readonly code: string;\n readonly operation: string;\n readonly retryable: boolean;\n readonly httpStatus?: number;\n readonly message?: string;\n}\n\n/**\n * One state change, delivered to the listener. `type` names the one payload\n * field that is set:\n *\n * - `identity` → `identity`: the identity `start()` loaded, and every later\n * switch (`identify`, `reset`, `signOut`, and the switch back when the\n * server refused an `identify`), each under a new generation. A switch's\n * event is dispatched before the promise of the call that caused it\n * settles, and before any `person` or `flags` event or read answer of the\n * new generation.\n * - `person` → `person`: the current person or its freshness changed (a\n * refresh, a purchase, a restore, a delivered identity link or attribute\n * write).\n * - `flags` → `flags`: an evaluation was refreshed, keyed by its `flagKeys`.\n * - `schema` → `schemaJson`: a runtime schema was loaded or fetched.\n * - `consent` → `consent`: the analytics consent in effect changed, including\n * the one `start()` settled on.\n * - `diagnostic` → `diagnostic`. Includes `PRODUCT_NOT_FOUND` and\n * `PRODUCT_TYPE_MISMATCH` (kind `configuration`, operation `getProducts`\n * on both platforms), once per slug per products load, its message naming\n * the slug and the store's reason or both types. A product Studio does not\n * sell in this store is not reported by a load of every product.\n * - `transaction` → `transaction`: every element of the native transaction\n * update stream (purchases completed outside `purchase()`: Ask to Buy\n * approvals, pending payments, offer codes, promoted purchases, and on the\n * App Store renewals seen on the device; Google Play reports no renewals),\n * after the native SDK handled it. Never one that `purchase()` itself\n * answers with.\n * - `purchaseIntent` → `purchaseIntent`: with `purchaseIntents: manual`, each\n * App Store purchase intent for a product the schema has; an intent for\n * another product is dropped and reported as `PRODUCT_NOT_FOUND`. Sent\n * from `start()` on, maybe before the app added a listener to the facade,\n * which holds them until it does.\n */\nexport interface NativeClientEvent {\n readonly type: NativeClientEventType;\n readonly identity?: NativeIdentityChange;\n readonly person?: NativePersonState;\n readonly flags?: NativeFeatureFlagsResult;\n readonly schemaJson?: string;\n readonly consent?: NativeAnalyticsConsent;\n readonly diagnostic?: NativeDiagnostic;\n readonly transaction?: NativeTransactionUpdate;\n readonly purchaseIntent?: NativePurchaseIntent;\n}\n\n/**\n * The native Voidhash client behind one React Native `VoidhashClient`: one\n * hybrid object per client, owning the storage namespace of its publishable\n * key and base URL.\n */\n@iOS({ language: \"swift\", implementation: { className: \"HybridVoidhashNativeClient\" } })\n@Android({ language: \"kotlin\", implementation: { className: \"HybridVoidhashNativeClient\" } })\nexport declare class VoidhashNativeClient extends HybridObject {\n public constructor();\n\n // ---- Lifecycle ----\n\n /**\n * The version of this contract the binary implements, the facade's\n * `NATIVE_CONTRACT_VERSION` (`src/core/native/native-client.ts`). The\n * facade reads it before anything else and starts no native client of\n * another version: a JavaScript bundle updated over the air onto a build\n * made for another version fails `init()`, asking for a new build, instead\n * of misreading the answers. A binary whose hybrid has no such member\n * implements version 0. Raise it with every change to this file that a\n * binary built before the change cannot honour. Synchronous; callable\n * before `configure()`.\n */\n contractVersion(): number;\n /**\n * Applies the configuration; touches neither storage nor the network.\n * Called before the first `start()`, and again after `shutdown()` resolved\n * to start once more (a re-init), possibly with other options.\n */\n configure(configuration: NativeClientConfiguration): void;\n /**\n * Starts the client from local state: identity, caches and queues are\n * loaded, store observation and background delivery begin, and the boot\n * refresh starts behind the call. Resolves without waiting for the network\n * (after the device's first unlock).\n *\n * Before it loads anything, it imports what earlier releases of this\n * package (its TypeScript core) stored on the device for this namespace:\n * the identity, the analytics consent and session, queued events, identity\n * links and store receipts, and the cached person, flags, schema and\n * paywalls. A queued receipt is never lost: a store is deleted only once\n * its records are in the native stores, and an import that fails is retried\n * at the next `start()`. The importers live in this module's native code\n * (`ios/` and `android/`), not in the SDKs.\n *\n * The analytics consent it settles on is the one chosen in this process\n * (`chosenAnalyticsConsent`), else the stored one, else the\n * `analyticsConsent` option. Events captured before `start()` are handed to\n * the native SDK, which records them when that consent is `granted`, holds\n * them when it is `pending` and pending events are buffered, and discards\n * them otherwise.\n *\n * Before resolving it dispatches, in this order: the loaded `identity`, the\n * `consent` in effect, the cached or injected `schema` (when there is one),\n * and the cached `person` (when there is one).\n *\n * Another instance that still owns the same storage namespace (a JavaScript\n * reload leaves the previous one running, never shut down) is retired first:\n * it persists its queues as `shutdown()` would, without waiting on the\n * network, and rejects every later call with `NOT_INITIALIZED`. A purchase\n * the retired instance had started is still recorded by it (its receipt in\n * the outbox, its SDK-started marker, on Google Play its unfinished-purchase\n * record), and this instance syncs and finishes it as its own.\n *\n * Android allows one live client per process: configuring a new instance\n * retires the previous one as above, whatever its storage namespace.\n *\n * A `start()` while another is in flight joins it and settles with it; a\n * `start()` on a started client resolves at once and changes nothing. A\n * `shutdown()` that overtakes a start waits for it: the start shuts down\n * whatever it built and rejects with `NOT_INITIALIZED` before `shutdown()`\n * resolves, so nothing it started keeps running.\n */\n start(): Promise<void>;\n /**\n * Flushes for at most about two seconds, persists what is still queued and\n * stops every observer, timer and listener. Every call still pending settles\n * (or rejects with `NOT_INITIALIZED`) before this resolves. Whatever was not\n * delivered goes out after the next `start()`.\n */\n shutdown(): Promise<NativeFlushStatus>;\n /** Registers the one listener for {@link NativeClientEvent}s, replacing any earlier one. */\n setEventListener(listener: (event: NativeClientEvent) => void): void;\n /** Removes the listener; nothing is delivered until the next `setEventListener()`. */\n removeEventListener(): void;\n\n // ---- Identity and person ----\n\n /** The current distinct id. */\n getDistinctId(): Promise<string>;\n /**\n * Switches to `externalUserId` and links the previous anonymous identity\n * onto it. Resolves `confirmed` with the person, or `deferred` with the last\n * known snapshot when the link is queued, together with the identity it\n * switched to. Rejects for an invalid id (`INVALID_ARGUMENT`) without\n * switching, or for a verdict of the API: the client then switches back to\n * the previous identity (a new generation, its `identity` dispatched before\n * the rejection), keeping what it cached for it. The facade puts back the\n * person and flag evaluations it held before the call, so nothing needs to\n * be re-sent for them.\n *\n * Identifying the current identity again adopts nothing: it resolves with\n * the current `NativeIdentityChange` and dispatches no `identity` event. A\n * profile that differs from the one last sent goes out as an identify\n * request, whatever the analytics consent; the same profile sends nothing.\n * Backs both `identify()` and `identifySync()`.\n */\n identify(externalUserId: string, email?: string, name?: string): Promise<NativeIdentifyResult>;\n /**\n * Starts a fresh visitor: a new anonymous identity and analytics session,\n * with what was cached for the previous identity dropped. When someone is\n * signed in this is `signOut()`, `$sign_out` and flush included; for an\n * anonymous identity nothing is captured or sent. Resolves with the\n * identity it switched to.\n */\n reset(): Promise<NativeIdentityChange>;\n /**\n * Signs the user out: captures `$sign_out` under the signing-out identity\n * (with automatic lifecycle events on and consent granted), switches to a\n * fresh anonymous identity, starts a new analytics\n * session, then flushes for at most about two seconds. Resolves with the\n * identity it switched to. Does nothing, and sends nothing, when nobody is\n * signed in: it resolves with the identity in effect.\n */\n signOut(): Promise<NativeIdentityChange>;\n /**\n * Puts the end user in group `groupKey` of `groupType`, which every event\n * captured after it resolves carries in `$groups`, and stores it with the\n * identity. `propertiesJson`, a JSON object of strings, numbers and\n * booleans, sets the group's properties; they go out as a `$groupidentify`\n * event, which is also sent when the group of that type changed. Rejects\n * `INVALID_ARGUMENT` for a type or key the native SDK would refuse. Runs in\n * call order with identity changes.\n */\n group(groupType: string, groupKey: string, propertiesJson?: string): Promise<void>;\n /**\n * Replaces every group the end user is in with the ones in `groupsJson`: an\n * object from group type to `{ id, properties? }`. A type it leaves out is\n * dropped. A `$groupidentify` is sent only for a group whose id or\n * properties changed since they were last sent. A type or id the native\n * SDK finds invalid is left out with a warning. Runs in call order with\n * identity changes; rejects `INVALID_ARGUMENT`, changing nothing, when\n * `groupsJson` is not such an object or an entry has no string `id`.\n */\n setGroups(groupsJson: string): Promise<void>;\n /** Takes the end user out of every group. Runs in call order with identity changes. */\n resetGroups(): Promise<void>;\n /** The groups the end user belongs to, by group type; empty before `start()`. Synchronous. */\n getGroups(): Record<string, string>;\n /**\n * Queues person attributes (`{ email?, name?, …traits }` as JSON, flat\n * values only) without waiting on the network, whatever the analytics\n * consent and in observer mode too. Only an agreement to ad data sharing is\n * left out while consent is not granted.\n */\n setPersonAttributes(attributesJson: string): Promise<void>;\n /**\n * Writes person attributes and reports whether the server confirmed them,\n * whatever the analytics consent and in observer mode too; see\n * {@link NativeWriteStatus} for `skipped`. A confirmed write's `person`\n * event is dispatched before the promise settles.\n */\n setPersonAttributesState(attributesJson: string): Promise<NativePersonWriteResult>;\n /**\n * The current person, cache-first: a fresh entry at once, a stale one after\n * at most 500 ms of waiting for its refresh. `forceFetch` prefers the server.\n * An answer read under an earlier generation still reaches the caller that\n * asked, but the facade does not publish it to the hooks.\n */\n getPersonState(forceFetch: boolean): Promise<NativePersonState>;\n /**\n * Drops the cached person snapshot; the next read asks the server. On both\n * platforms a `person` event with no person (stale, expired, `noCache`) is\n * dispatched before the promise settles.\n */\n resetPersonCache(): Promise<void>;\n\n // ---- Flags, paywalls and products ----\n\n /**\n * Evaluates `flagKeys` (every flag when absent), cache-first. With nothing\n * cached it waits at most `featureFlagMaxWaitMs` (2 s by default), then\n * answers with no flags; the evaluation goes on and lands as a `flags`\n * event. A requested key without an evaluated value is answered with its\n * `featureFlagDefaults` entry, enabled or not and without a variant, when\n * it has one.\n */\n getFeatureFlags(flagKeys?: string[]): Promise<NativeFeatureFlagsResult>;\n /**\n * The paywall assigned to `location` as JSON, `\"null\"` when none is.\n * Rejects `PAYWALL_UNAVAILABLE` when nothing is cached and the server\n * cannot be reached.\n */\n getPaywall(location: string): Promise<string>;\n /**\n * Every product the store returned, one per Studio product slug, sorted by\n * slug: the native SDK's `getProducts()`, one store query per call. A\n * product the store did not return is left out and reported once per load\n * as the `PRODUCT_NOT_FOUND` diagnostic, one it sells as another type than\n * Studio's as `PRODUCT_TYPE_MISMATCH`. Offers and intro eligibility are\n * this end user's: the facade calls it again after an identity change, a\n * completed purchase or restore (a flow's included) and a transaction\n * update other than a renewal. The products it answers are the ones\n * `purchase()` buys until the next call, a completed purchase or a restore.\n */\n getProducts(): Promise<NativeProduct[]>;\n\n // ---- Purchases ----\n\n /**\n * Buys the product with slug `productSlug` through the native SDK's\n * `purchase(product, options)`, with the product the last `getProducts()`\n * answered for that slug; one it does not hold (none loaded yet, or a\n * purchase or restore since) is asked of the store first (an unknown slug\n * rejects `INVALID_ARGUMENT`). Resolves\n * `purchased` with the transaction and whether Voidhash accepted the\n * receipt, `pending`, or `cancelled`: a cancelled sheet and a pending\n * payment are results, not rejections. A purchase in observer mode rejects\n * `READ_ONLY_PURCHASE_NOT_ALLOWED`; a second purchase while one is in\n * flight (including one a flow started) `PURCHASE_IN_PROGRESS`; an offer\n * that cannot be bought `OFFER_UNAVAILABLE`; a store refusal with a reason\n * `PAYMENT_DECLINED` (Android only) or `INELIGIBLE_FOR_OFFER` (both; the\n * products held are dropped then, and nothing is retried at the regular\n * price).\n *\n * When the purchase changed the person, its `person` event is dispatched\n * before the promise settles. A `pending` purchase stays this client's to\n * sync and finish when it completes, also after a relaunch; it later\n * arrives as a `transaction` event.\n *\n * With `replacing`, Google Play replaces that subscription and buys nothing\n * when it cannot: `REPLACED_SUBSCRIPTION_NOT_OWNED` when the account does\n * not own it, `INVALID_ARGUMENT` when either product is not a subscription\n * or both are the same, `SUBSCRIPTION_REPLACEMENT_REFUSED` when Google Play\n * refuses before its sheet opens. A `deferred` replacement resolves\n * `purchased` with the old product's transaction. The App Store ignores\n * `replacing`.\n */\n purchase(productSlug: string, options: NativePurchaseOptions): Promise<NativePurchaseResult>;\n /**\n * Revalidates the store's purchase history for the current identity and\n * resolves with the person the restore refreshed, read from the cache as\n * `getPersonState(false)` reads it: under the current generation, with\n * its real freshness (`fresh` only when the refresh after the restore\n * succeeded); with no person to answer, `personJson` absent. The person's\n * `person` event is dispatched before the promise settles.\n */\n restorePurchases(): Promise<NativePersonState>;\n /** Reports pending purchases and current store entitlements. */\n syncPurchases(): Promise<void>;\n /**\n * Reports a purchase another billing integration completed. Resolves once\n * the receipt is stored; delivery goes on in the background. `isRestore`\n * sends it as an explicit restore for the current identity.\n */\n reportTransaction(transaction: NativeReportedTransaction, isRestore: boolean): Promise<void>;\n\n // ---- Store actions, both stores ----\n\n /**\n * Opens the store's subscription management. App Store:\n * `AppStore.showManageSubscriptions(in:subscriptionGroupID:)` with the\n * group of the product `productSlug` names (iOS 17 and later), else without\n * a group. Google Play: opens\n * `https://play.google.com/store/account/subscriptions?sku=<storeProductId>&package=<package>`,\n * without `sku` when no product is named. Resolves once it was shown.\n */\n showManageSubscriptions(productSlug?: string): Promise<void>;\n /**\n * Opens offer-code redemption. App Store: the newest offer-code sheet the\n * SDK builds against (`presentOfferCodeRedeemSheet(in:)` on iOS 16 and\n * later), `code` ignored; a transaction it returns goes through the normal\n * receipt path and arrives as a `transaction` event. Google Play: opens\n * `https://play.google.com/redeem?code=<code>` (no `code` parameter without one).\n */\n presentCodeRedemption(code?: string): Promise<void>;\n /**\n * The storefront the end user buys from: StoreKit's `Storefront.current`\n * (country converted to alpha-2) or Play's `getBillingConfigAsync`.\n * Resolves `undefined` when the store has none to give; rejects when asking failed.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the Nitro contract, where an optional is `undefined`.\n getStorefront(): Promise<NativeStorefront | undefined>;\n /**\n * App Store: `AppStore.canMakePayments`. Google Play: the billing\n * connection is ready and billing is not unavailable.\n */\n canMakePayments(): Promise<boolean>;\n\n // ---- App Store (Google Play rejects UNSUPPORTED_PLATFORM) ----\n\n /**\n * StoreKit's refund request sheet for the transaction `transactionId`\n * (`Transaction.beginRefundRequest(for:in:)`). Rejects `INVALID_ARGUMENT`\n * for a transaction StoreKit does not know.\n */\n appStoreBeginRefundRequest(transactionId: string): Promise<NativeRefundRequestStatus>;\n /**\n * Every status of subscription group `groupId` the Apple account has\n * (`Product.SubscriptionInfo.status(for:)`), the current end user's first\n * (the one whose transaction carries their app account token), then the\n * others, Family Sharing ones included; verified ones only.\n */\n appStoreSubscriptionStatus(groupId: string): Promise<NativeAppStoreSubscriptionStatus[]>;\n /** The verified transactions of `Transaction.currentEntitlements`. */\n appStoreCurrentEntitlements(): Promise<NativeTransaction[]>;\n /**\n * The verified `AppTransaction.shared` as JSON, shaped as the facade's\n * `AppTransaction`: `{ originalAppVersion, originalPurchaseDate,\n * environment, appTransactionId?, originalPlatform?, jwsRepresentation }`,\n * the date in milliseconds since the epoch, `environment` one of\n * `production`, `sandbox`, `xcode`, `originalPlatform` one of `iOS`,\n * `macOS`, `tvOS`, `visionOS`.\n */\n appStoreAppTransaction(): Promise<string>;\n\n // ---- Google Play (the App Store rejects UNSUPPORTED_PLATFORM) ----\n\n /**\n * Play's `showInAppMessages` for the TRANSACTIONAL category, on the current\n * activity. On `subscriptionStatusUpdated` the native SDK syncs purchases\n * and refreshes the person (its `person` event before the promise settles).\n */\n googlePlayShowInAppMessages(): Promise<NativeInAppMessageResult>;\n /**\n * The account's purchases (subscriptions and one-time), suspended\n * subscriptions included when `includeSuspended`. A suspended purchase is\n * never submitted, acknowledged or consumed.\n */\n googlePlayQueryPurchases(includeSuspended: boolean): Promise<NativeTransaction[]>;\n /**\n * `BillingClient.isFeatureSupported` for the feature `feature` names:\n * `subscriptions`, `subscriptionsUpdate`, `inAppMessaging`,\n * `productDetails`, `billingConfig`, `alternativeBillingOnly`,\n * `externalOffer` (the `FeatureType` constants). Another name rejects\n * `INVALID_ARGUMENT`.\n */\n googlePlayIsFeatureSupported(feature: string): Promise<boolean>;\n\n // ---- Configuration at runtime ----\n\n /**\n * Records analytics consent; it applies at once. Resolves whether it was\n * also stored for later launches.\n *\n * Also accepted before `start()`: a consent other than `granted` then\n * discards the events captured so far, and the consent is stored by\n * `start()` (the facade also passes it as `chosenAnalyticsConsent`). It\n * resolves `false` then, as nothing is stored yet.\n */\n setAnalyticsConsent(consent: NativeAnalyticsConsent): Promise<boolean>;\n /**\n * The analytics consent in effect. Before `start()` the stored consent is\n * not loaded yet, so it answers the consent chosen through\n * `setAnalyticsConsent` or, without one, the configured\n * `analyticsConsent` option.\n */\n getAnalyticsConsent(): NativeAnalyticsConsent;\n /** Switches observer mode; a purchase already in flight keeps its mode. */\n setReadOnly(readOnly: boolean): void;\n isReadOnly(): boolean;\n\n // ---- Analytics ----\n\n /**\n * Queues an event. Synchronous and never throws: the call itself stamps the\n * event with the current identity, session and time and takes its place in\n * the queue, so events keep call order and the identity they were captured\n * under. On iOS this needs an intake outside the client's actor, called\n * synchronously from the bridge. `propertiesJson` is a JSON object the\n * facade already made safe.\n *\n * Allowed before `start()`: such events are kept in memory with their call\n * time and attributed to the identity `start()` loads; past 100 of them the\n * oldest is dropped, reported as `ANALYTICS_EVENT_DROPPED` once the listener\n * is set. What becomes of them depends on the consent `start()` settles on\n * (see `start()`); a `setAnalyticsConsent(\"denied\")` discards them at once.\n */\n capture(eventName: string, propertiesJson: string): void;\n /**\n * Queues a `$screen` event for the screen `name`, stamped and ordered like\n * `capture`. The facade's screen tracker has already applied the app's\n * screen-tracking settings (`mapScreen`, whether route params are kept):\n * `propertiesJson` holds the `$screen_*` properties to record as they are,\n * with nothing stripped again.\n */\n screen(name: string, propertiesJson: string): void;\n /**\n * `capture` for an event the facade held back, which it does while an\n * identity change the app called before the event has not switched the\n * identity yet: recorded under the identity and session now in effect, at\n * `capturedAt` (milliseconds since the epoch), the time the app captured it.\n * A binary built before this member has none; the facade then calls\n * `capture`, and the event takes the time of that call.\n */\n captureAt(eventName: string, propertiesJson: string, capturedAt: number): void;\n /** `screen` for a screen the facade held back; see `captureAt`. */\n screenAt(name: string, propertiesJson: string, capturedAt: number): void;\n /** Sends person writes, receipts and events, waiting at most about two seconds. */\n flush(): Promise<NativeFlushStatus>;\n /** The active analytics session id; empty when there is none. Synchronous. */\n getSessionId(): string;\n\n // ---- Flows ----\n\n /**\n * Presents the flow assigned to `location` and resolves once it ends, as\n * JSON, one of:\n *\n * - `{\"outcome\":\"<outcome>\",\"output\":{…}}`, with `\"productId\":\"<product\n * slug>\"` when the outcome is `purchased`. `purchased`, `restored`\n * and `dismissed` are built in (the last also when the app closed the\n * flow or another replaced it); any other outcome is the one the flow\n * finished with. `output` holds the flow's outputs by name.\n * - `{\"failure\":{\"code\":\"<FLOW_* code>\",\"message\":\"<FLOW_* code>: <detail>\"}}`\n * for a flow that could not be presented, where the code is one of\n * `FLOW_DISABLED`, `FLOW_NOT_ASSIGNED`, `FLOW_UNAVAILABLE`,\n * `FLOW_RENDERER_MISSING`, `FLOW_UNSUPPORTED_PACKAGE` and\n * `FLOW_PRESENTATION_FAILED`.\n *\n * `onAction` runs an app action the flow calls: it receives the action's\n * name and its arguments as a JSON object, and resolves with the reply as\n * a JSON object or rejects. It is called only for the names in\n * `presentation.actions`; the native side answers every other call itself.\n *\n * Purchases and restores the flow starts go through this client. Never\n * rejects for a flow that cannot be shown: that is a `failure`.\n */\n presentFlow(\n location: string,\n presentation: NativeFlowPresentation,\n onAction: (name: string, argsJson: string) => Promise<string>,\n ): Promise<string>;\n /**\n * Changes inputs of the flow on screen; `valuesJson` is a JSON object of\n * values by input name. Does nothing when no flow is shown.\n */\n updateFlowInput(valuesJson: string): Promise<void>;\n /** Closes the flow on screen, if any; its presentation resolves as dismissed. */\n dismissFlow(): Promise<void>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,UAAAA,eAAc;AACvB,YAAYC,UAAS;AACrB,YAAY,oBAAoB;AAChC,YAAY,oBAAoB;AAChC,YAAYC,cAAY;AACxB,YAAYC,QAAO;AACnB,YAAYC,QAAO;AACnB,YAAYC,mBAAkB;AAC9B,YAAYC,cAAY;;;ACDjB,IAAM,mBAAmB;AAAA;AAAA,EAE9B,eAAe;AAAA;AAAA,EAEf,aAAa;AAAA;AAAA,EAEb,YAAY;AAAA;AAAA,EAEZ,kBAAkB;AAAA;AAAA,EAElB,mBAAmB;AAAA;AAAA,EAEnB,aAAa;AAAA;AAAA,EAEb,UAAU;AAAA;AAAA,EAEV,QAAQ;AAAA;AAAA,EAER,aAAa;AACf;AAGO,IAAM,wBAAw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qBAAqB,4BAA4B,QAAQ,OAAO;AAAA,IAChE,kBAAkB;AAAA,MAChB,yBAAyB,QAAQ,SAAS,kBAAkB;AAAA,IAC9D;AAAA,IACA;AAAA,EACF;AACF;;;AYlPA;AAKA;AAAA,2CAAc;;;AbWd,IAAM,6BAA6B,MAC1B,mBAAkB,YAAI,MAAM,IAAqB,wDAAqB,CAAC,CAAC;AA6B1E,SAAS,qBAEd,gBACA,UAAiC,CAAC,GAClC;AACA,SAAO;AAAA,IACL;AAAA,MACE,oBAAoB;AAAA,MACpB,aAAa;AAAA,MACb,UAAU,SAAS;AAAA,IACrB;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["Result","Arr","Option","P","R","EffectResult","Schema","value","Result","Schema","Result","Arr","Effect","Match","Option","P","R","Schema","Atom","Arr","Option","P","Result","value","Arr","Option","Schema","Arr","Option","P","R","Schema","values","value","Effect","Option","Schema","value","Arr","Option","Schema","keys","values","get","Effect","R","Schema","Effect","Option","Schema","value","Option","P","Option","Effect","Schema","value","version","exit","Result","decodeJson","value","isCurrent","Atom","update","options","error","values","Arr","Option","P","R","value","keys","Arr","Option","P","R","Result","value","value","encodeJson","update","Result","values","native","Result","Arr","Option","P","R","React","Option","Cause","Effect","Exit","Option","state","call","exit","React","value","React","React","Option","P","React","React","Option","React","React","values","Option","R","Schema","React","React","get","Result","Option","React","P","Result","React","value"]}
|
|
1
|
+
{"version":3,"sources":["../../react-native/src/client.tsx","../../react-native/src/core/analytics/constants.ts","../../react-native/src/core/caching/namespace.ts","../../react-native/package.json","../../react-native/src/core/constants.ts","../../react-native/src/core/diagnostics/diagnostics.ts","../../react-native/src/core/entities/reported-transaction.ts","../../react-native/src/core/flows/flows.ts","../../react-native/src/core/native/native-client.ts","../../react-native/src/core/analytics/json-safe.ts","../../react-native/src/core/entitlements/find-grant.ts","../../react-native/src/core/entities/app-store.ts","../../react-native/src/core/entities/decoding.ts","../../react-native/src/core/entities/person.ts","../../react-native/src/core/reactivity/client-state.ts","../../react-native/src/core/schema/decode.ts","../../react-native/src/core/schema/runtime.ts","../../react-native/src/core/sdk-configuration.ts","../../react-native/src/core/utils/native-error.ts","../../react-native/src/core/native/billing.ts","../../react-native/src/core/entities/google-play.ts","../../react-native/src/core/person-attributes.ts","../../react-native/src/core/screens/screen-tracker.ts","../../react-native/src/constants.ts","../../react-native/src/core/entities/perk.ts","../src/client-nitro-ui.ts","../../react-native/src/client-host.ts","../../react-native/src/react/hooks/use-person.ts","../../react-native/src/react/hooks/use-async-function.ts","../../react-native/src/react/hooks/use-atom-value.ts","../../react-native/src/react/hooks/use-feature-flags.ts","../../react-native/src/react/hooks/use-has-perk.ts","../../react-native/src/react/hooks/use-present-flow.ts","../../react-native/src/react/hooks/use-products.ts","../../react-native/src/react/hooks/use-purchase.ts","../../react-native/src/react/internal/host-callback.ts","../../react-native/src/react/hooks/use-restore-purchases.ts","../../react-native/src/react/hooks/use-subscriptions.ts","../src/specs/VoidhashNativeClient.nitro.ts"],"sourcesContent":["import { Result } from \"better-result\";\nimport * as Arr from \"effect/Array\";\nimport * as MutableHashMap from \"effect/MutableHashMap\";\nimport * as MutableHashSet from \"effect/MutableHashSet\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\nimport * as R from \"effect/Record\";\nimport * as EffectResult from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport type { AtomRegistry } from \"effect/reactivity\";\n\nimport {\n AUTOMATIC_EVENTS,\n PUSH_SEND_ID_DATA_KEY,\n PUSH_SEND_ID_PROPERTY,\n SCREEN_PROPERTIES,\n} from \"./core/analytics/constants\";\nimport { buildCacheNamespace } from \"./core/caching/namespace\";\nimport { SDK_VERSION } from \"./core/constants\";\nimport {\n makeDiagnosticEmitter,\n type VoidhashDiagnostic,\n type VoidhashDiagnosticHandler,\n} from \"./core/diagnostics/diagnostics\";\nimport type {\n AppStorePurchaseIntent,\n AppStoreSubscriptionStatus,\n AppTransaction,\n RefundRequestStatus,\n} from \"./core/entities/app-store\";\nimport type {\n GooglePlayBillingFeature,\n GooglePlayInAppMessageResult,\n} from \"./core/entities/google-play\";\nimport type { EntitlementGrant, Person } from \"./core/entities/person\";\nimport type {\n Offer,\n OfferKind,\n Product,\n ProductsForSlugs,\n SubscriptionReplacement,\n SubscriptionReplacementMode,\n} from \"./core/entities/product\";\nimport {\n fromReportedTransaction,\n type StoreReport,\n type StoreTransaction,\n} from \"./core/entities/reported-transaction\";\nimport type { Transaction, TransactionUpdate } from \"./core/entities/transaction\";\nimport type {\n FeatureFlagsResult,\n Group,\n GroupProperties,\n GroupPropertyValue,\n Groups,\n PersonAttributes,\n ResolvedPaywall,\n} from \"./core/facade-types\";\nimport {\n type FlowCapability,\n flowError,\n type FlowResult,\n type FlowLoading,\n type FlowRuntime,\n type PresentFlowArguments,\n type PresentFlowOptions,\n} from \"./core/flows/flows\";\nimport {\n makeNativeClientAdapter,\n type NativeClientAdapter,\n type NativeClientPort,\n} from \"./core/native/native-client\";\nimport { invalidPersonAttributes } from \"./core/person-attributes\";\nimport { clientRunAtom, schemaAtom } from \"./core/reactivity/client-state\";\nimport type {\n FeatureFlagKey,\n FeatureFlagValue,\n FlowInput,\n FlowValues,\n LocationSlug,\n PerkSlug,\n ProductSlug,\n} from \"./core/schema/registry\";\nimport { RuntimeSchemaValue, type RuntimeSchema } from \"./core/schema/runtime\";\nimport {\n createScreenTracker,\n type ScreenTracker,\n type ScreenView,\n} from \"./core/screens/screen-tracker\";\nimport {\n type AnalyticsConsent,\n type AnalyticsWhilePending,\n isAnalyticsConsent,\n} from \"./core/sdk-configuration\";\nimport {\n InvalidArgumentError,\n NotInitializedError,\n PurchaseInProgressError,\n ReadOnlyModePurchaseNotAllowedError,\n UnsupportedPlatformError,\n VoidhashError,\n} from \"./errors\";\nimport type {\n NativeClientConfiguration,\n NativePurchaseOptions,\n NativeReportedTransaction,\n NativeSubscriptionReplacement,\n} from \"./specs/VoidhashNativeClient.nitro\";\n\nexport type {\n FeatureFlagsResult,\n Group,\n GroupProperties,\n GroupPropertyValue,\n Groups,\n PersonAttributes,\n ResolvedPaywall,\n};\n\n/**\n * The native flow module as earlier releases drove it from JavaScript.\n * @deprecated No longer used: the native client presents flows itself. Kept\n * so code that imports the type still compiles; removed in a future release.\n */\nexport interface VoidhashFlowsPort {\n readonly isRendererAvailable: boolean;\n engineCapabilities?(): string;\n present(\n requestJson: string,\n purchase: (productId: string, offerId: string) => Promise<void>,\n restore: () => Promise<void>,\n setAttribute: (name: string, valueJson: string) => Promise<void>,\n loadState: (key: string) => Promise<string>,\n saveState: (key: string, variablesJson: string) => Promise<void>,\n clearState: (key: string) => Promise<void>,\n track: (name: string, propertiesJson: string) => void,\n screen: (name: string, propertiesJson: string) => void,\n ): Promise<string>;\n preload(requestJson: string): Promise<void>;\n dismiss(): Promise<void>;\n}\n\n/**\n * A reachability source as the `connectivity` option took it: a subscribe\n * function returning an unsubscribe callback.\n */\nexport interface ConnectivityPort {\n readonly subscribe: (listener: (online: boolean) => void) => () => void;\n}\n\n/** Controls the built-in `$screen` event. */\nexport interface ScreenTrackingOptions {\n /** Default `true`. `false` makes every integration and `screen()` a no-op. */\n enabled?: boolean;\n /** Default `false`. Adds `$screen_params` (route params, string-coerced, max 20 keys). */\n includeParams?: boolean;\n /**\n * Rewrites or drops a screen before capture. Return `null` to skip it. A\n * throw, or a result whose `identity`, `name` or `path` is not a string,\n * tracks the screen unmapped and is reported as `HOST_CALLBACK_FAILED`.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK option consumed by non-Effect app code; `null` is the documented \"drop this screen\" answer and mirrors the iOS and Android SDKs.\n mapScreen?: (view: ScreenView) => ScreenView | null;\n}\n\n/** How feature flag reads behave before Voidhash has answered them. */\nexport interface FeatureFlagsOptions {\n /**\n * What a flag reads as while it has no evaluated value: before its first\n * evaluation arrives, and when Voidhash cannot be reached and nothing is\n * cached. `useFeatureFlags().isEnabled()` answers it, on a disabled client\n * too, and `getFeatureFlags()` answers each requested key that has one as\n * a flag without a variant. Flags without a default read as `false`. Use\n * `true` for a flag whose feature must stay on when Voidhash is unreachable.\n */\n readonly defaults?: Readonly<Record<string, boolean>>;\n /**\n * How long a flag read with nothing cached waits for Voidhash before it\n * answers with no flags, in milliseconds (default 2000). The evaluation\n * carries on in the background, and the hooks update when it lands. A\n * cached value never waits more than 500 ms. A request gives up after 10\n * seconds, so a longer wait ends there.\n */\n readonly maxWaitMs?: number;\n}\n\nexport interface VoidhashClientOptions {\n /**\n * The end user's consent to usage analytics (default `\"granted\"`). While it\n * is `\"denied\"` or `\"pending\"` the SDK captures, stores and sends no\n * analytics: no custom events, screens, lifecycle or install events or\n * paywall impressions. What the app says about the end user is not\n * analytics: `identify()`, person attributes and groups are sent whatever\n * the consent, and purchases, restores, entitlements, feature flags and\n * paywalls work as usual.\n * A consent set later with `client.setAnalyticsConsent()` is stored on the\n * device and takes precedence over this option on the next launch.\n */\n analyticsConsent?: AnalyticsConsent;\n /**\n * What happens to analytics captured while consent is `\"pending\"` (default\n * `\"drop\"`). `\"buffer\"` holds up to 100 events in memory, with the time\n * each happened, and records them once consent is granted; a denial\n * discards them. Nothing is sent or stored while they are held. Person\n * attributes and groups are never held: they are sent whatever the consent.\n */\n analyticsWhilePending?: AnalyticsWhilePending;\n /**\n * `true` makes `identify()` grant a `\"pending\"` consent, for apps whose\n * sign-in accepts their terms (default `false`). A `\"denied\"` consent is\n * never overridden. `signOut()` and `reset()` send what was recorded and\n * return that consent to `\"pending\"`; a consent set with\n * `setAnalyticsConsent()` is the app's own decision and stays.\n */\n grantConsentOnIdentify?: boolean;\n /**\n * Captures `$app_installed`, `$app_updated`, `$app_opened`,\n * `$app_backgrounded`, `$app_became_active`, `$app_crashed` and `$sign_out`\n * automatically (default `true`). Turn it off when the app reports these\n * events itself.\n */\n automaticLifecycleEvents?: boolean;\n baseUrl?: string;\n debug?: boolean;\n /** Enables isolated test purchases in debug builds. Release builds always ignore this option. */\n dev?: boolean;\n distinctId?: string;\n /**\n * Reads which ad brought this install and records it on the person as a\n * touch (default `true`): Apple Ads on iOS, the Google Play install referrer\n * and, with `metaAppId`, Meta's apps on Android. Runs once per install, in\n * the background, only with analytics consent. An install that predates this\n * option is not read.\n */\n installAttribution?: boolean;\n /**\n * The app's Meta (Facebook) app id. On Android, `installAttribution` then also\n * asks the Facebook, Instagram and Facebook Lite apps on the device for the ad\n * behind the install, which is preferred over the Play referrer. iOS ignores it.\n */\n metaAppId?: string;\n /**\n * When StoreKit shows its own messages, such as a price increase to agree\n * to or a billing issue (default `\"deferWhileFlowPresented\"`): at once\n * (`\"automatic\"`), or held while a Voidhash flow is on screen and shown once\n * it closes. Google Play ignores it.\n */\n appStoreMessages?: \"automatic\" | \"deferWhileFlowPresented\";\n /**\n * What happens to a purchase the end user starts on the App Store, such as\n * a promoted in-app purchase or a win-back offer (default\n * `\"purchaseWhenReady\"`). `\"purchaseWhenReady\"` buys it once `init()` has\n * finished, never before. `\"manual\"` hands it to the listeners of\n * `client.appStore.addPurchaseIntentListener()`, to complete with\n * `purchase()` when the app is ready; one that arrives before a listener\n * is added waits for the first. Google Play ignores it.\n */\n purchaseIntents?: \"purchaseWhenReady\" | \"manual\";\n /**\n * Ships the SDK fully disabled (default `true`). A disabled client never\n * connects to the native store, never talks to the network and never\n * registers listeners: `init()` and every side-effect method resolve as\n * no-ops, and reads answer with their empty shape. Intended for\n * feature-flagged rollouts, where mounting the provider unconditionally\n * avoids hook-order violations.\n *\n * Fixed at construction. Enabling the SDK later means creating a new client\n * — cheap, because a disabled client never builds its Effect runtime and so\n * holds no store connection, timers or listeners.\n */\n enabled?: boolean;\n /**\n * What flows may do in this app (default `[\"links\"]`). Purchases, restores,\n * closing and analytics need no grant. `notifications` and `tracking` let a\n * flow ask for those system permissions, `attributes` lets it set person\n * attributes and `links` lets it open links outside the app. A flow action\n * needing a capability that is not granted is ignored.\n */\n flowCapabilities?: ReadonlyArray<FlowCapability>;\n /**\n * Which flow runtime draws flows (default `linked`, the one built into the\n * SDK). `module` draws them with the flow runtime module each flow names,\n * downloaded once, verified and cached. It applies to the whole app process\n * from the first `init()`, on iOS and Android, and needs the native flow\n * renderer; `linked` leaves the renderer as native code set it.\n */\n flowRuntime?: FlowRuntime;\n /**\n * What a paywall shows while it waits for the network (default `standard`):\n * the native SDK's loading screen, shown 0.4 seconds after `presentFlow` until\n * the paywall takes its place, which the end user can close (`presentFlow`\n * then resolves with the outcome `dismissed` and `wasShown: false`). `none`\n * keeps the app's screen as it is until the paywall is shown. A paywall\n * already on the device appears before then either way.\n */\n flowLoading?: FlowLoading;\n /** How feature flag reads behave before Voidhash has answered them; see {@link FeatureFlagsOptions}. */\n featureFlags?: FeatureFlagsOptions;\n ingestUrl?: string;\n /**\n * @deprecated No longer needed: the SDK observes reachability and the app\n * lifecycle natively and recovers on its own when the device comes back\n * online or to the foreground. Still accepted, and ignored.\n */\n connectivity?: ConnectivityPort;\n /**\n * Called for every non-fatal event the SDK handled itself — a request that\n * failed and will be retried, an event evicted from a full queue, a rejected\n * publishable key. Purely informational; exceptions thrown here are\n * swallowed. Prefer this over `unstable_swallowErrors`.\n */\n onDiagnostic?: VoidhashDiagnosticHandler;\n /**\n * Locations whose flows are downloaded at boot, so their first\n * `presentFlow()` shows without a round trip. Locations the device has\n * presented before are preloaded anyway. Nothing is preloaded when the app\n * does not include the flow renderer.\n */\n preloadLocations?: string[];\n /**\n * The interface revision the app was built against, by location slug. Pass\n * the `flowRevisions` constant of the generated declarations: a location's\n * revision is then used to preload its flow and by every `presentFlow()`\n * that names none. A location that is not listed counts as revision 0.\n */\n flowRevisions?: Readonly<Record<string, number>>;\n /**\n * Starts the SDK in observer mode: transactions are reported to Voidhash but\n * never finished/acknowledged with the store, and purchases are blocked, so\n * another billing integration can own them. Off by default. Can be flipped\n * later with `client.setReadOnly()`.\n */\n readOnly?: boolean;\n scheme?: string;\n /**\n * Automatic screen tracking (`$screen`). On by default; the Expo Router and\n * React Navigation integrations under `@voidhash/react-native/expo-router`\n * and `@voidhash/react-native/react-navigation` feed it, as does\n * `client.screen()`.\n */\n screenTracking?: ScreenTrackingOptions;\n /**\n * @deprecated Transport failures no longer surface as errors, so there is\n * nothing left for this to swallow. Use `onDiagnostic` to observe recovered\n * failures instead. Removed in a future release.\n */\n unstable_swallowErrors?: boolean;\n /**\n * Test/internal escape hatch — inject a known runtime schema instead of\n * letting the SDK fetch from the server on init. Not part of the public\n * API; production code should rely on the server-side schema endpoint.\n */\n unstable_internalSchema?: RuntimeSchema;\n /**\n * @deprecated No longer has an effect: the SDK always runs on its native client.\n * Still accepted; development builds log a one-time notice when it is set.\n */\n unstable_nativeEngine?: boolean;\n}\n\n/**\n * How a {@link VoidhashClient.purchase} call ended. Every failure is the\n * `Err` of the returned `Result`.\n *\n * - `purchased`: the store charged. `synced` is `true` once Voidhash\n * accepted the receipt; `false` while it waits on the device, sent again\n * at launch, in the foreground and when the device is back online, and\n * access arrives once it lands. Either way the purchase is done: do not\n * offer it again.\n * - `pending`: the store needs outside action first, such as Ask to Buy\n * approval or a pending payment. It completes later, as a transaction\n * update (`addTransactionListener()`), and access arrives with it.\n * - `cancelled`: the end user dismissed the store sheet.\n * - `disabled`: the client was created with `enabled: false`; nothing was bought.\n */\nexport type PurchaseResult =\n | { readonly status: \"purchased\"; readonly transaction: Transaction; readonly synced: boolean }\n | { readonly status: \"pending\" }\n | { readonly status: \"cancelled\" }\n | { readonly status: \"disabled\" };\n\n/**\n * Which offer a purchase buys:\n *\n * - `\"automatic\"` (default): a subscription's `introOffer` when the end user\n * is eligible for one, otherwise the regular price.\n * - `\"none\"`: the regular price. The App Store may still apply an\n * introductory offer the end user is eligible for.\n * - an `Offer` from `product.offers` or `product.subscription.introOffer`.\n * - an offer's `id`, looked up in the same offers.\n *\n * An offer that cannot be bought fails the purchase with `OFFER_UNAVAILABLE`;\n * the product is never bought at its regular price instead.\n */\n// `string & Record<never, never>` keeps the two words above suggested next to any offer id.\nexport type OfferSelection = \"automatic\" | \"none\" | Offer | (string & Record<never, never>);\n\n/** What a {@link VoidhashClient.purchase} call may ask for beyond the product. */\nexport interface PurchaseOptions {\n /** The offer to buy; see {@link OfferSelection}. Default `\"automatic\"`. */\n readonly offer?: OfferSelection;\n /**\n * How many to buy, default 1. Only App Store consumables can be bought\n * several at once; on Google Play the end user picks the quantity in the\n * store's sheet. Anything but 1 elsewhere is an `INVALID_ARGUMENT` error.\n * The transaction reports the quantity the store charged.\n */\n readonly quantity?: number;\n /**\n * The subscription the user has now, which this purchase replaces: an\n * upgrade, a downgrade or a change of plan. Google Play only. Without it,\n * buying another subscription product there adds a second subscription\n * next to the first, and Google Play bills both.\n *\n * Nothing is bought when the replacement cannot be made. The purchase\n * fails with `REPLACED_SUBSCRIPTION_NOT_OWNED` when the signed-in Google\n * Play account does not own the named subscription, with\n * `INVALID_ARGUMENT` when either product is not a subscription, both are\n * the same product, or the option names no product or an unknown mode, and\n * with `SUBSCRIPTION_REPLACEMENT_REFUSED` when Google Play rejects the\n * replacement before its sheet opens.\n *\n * Ignored on iOS, where the App Store moves a subscriber between the\n * products of one subscription group by itself.\n */\n readonly replacing?: SubscriptionReplacement;\n /** App Store options; Google Play ignores them. */\n readonly appStore?: {\n /** Simulates Ask to Buy in the sandbox, so the purchase ends `pending`. */\n readonly simulatesAskToBuyInSandbox?: boolean;\n };\n /** Google Play options; the App Store ignores them. */\n readonly googlePlay?: {\n /** Tells Google Play the price was personalized for the end user (an EU disclosure). */\n readonly isOfferPersonalized?: boolean;\n /** Google Play's obfuscated profile id, for apps with several profiles per account. */\n readonly obfuscatedProfileId?: string;\n /**\n * Buys exactly this Google Play offer token, from\n * `product.googlePlay.subscriptionOffers` or `oneTimeOffers`, instead of\n * what `offer` selects.\n */\n readonly offerToken?: string;\n };\n}\n\n/** The storefront the end user buys from. */\nexport interface Storefront {\n /** ISO 3166-1 alpha-2 country code, such as `US`. */\n readonly countryCode: string;\n /** ISO 4217 currency code, when the store says. */\n readonly currencyCode?: string;\n}\n\n/** Outcome of an identity switch reported by {@link VoidhashClient.identifySync}. */\nexport type IdentifyResult =\n | {\n /** The server confirmed the identity and returned the person. */\n status: \"confirmed\";\n person: Person;\n }\n | {\n /**\n * The server has not confirmed the switch yet (it was unreachable, or\n * the key was rejected). The device already runs under the new distinct\n * id, and the link from the previous identity is queued on the device\n * and delivered once the server can be reached.\n */\n status: \"deferred\";\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n person: Person | null;\n }\n | {\n /** The client was created with `enabled: false`, so nothing was recorded. */\n status: \"disabled\";\n person: null;\n };\n\n/** Answer to an entitlement check for one perk. */\nexport interface HasPerkResult {\n /** The active grant behind `hasAccess`, when one exists. */\n grant?: EntitlementGrant;\n hasAccess: boolean;\n /**\n * The answer came from a cached snapshot that is past its refresh window,\n * either because a refresh is still running or because the server could not\n * be reached.\n */\n isStale: boolean;\n /**\n * The cached snapshot is past its two-day TTL. Access is still reported as\n * the snapshot recorded it; apps gating high-value content can decide to\n * treat this as untrusted.\n */\n isExpired: boolean;\n /**\n * Why the answer has the freshness it has.\n *\n * - `fresh`: confirmed by the server just now.\n * - `refresh-in-flight`: served from cache while a refresh is still running;\n * its result lands for the next read.\n * - `refresh-failed`: served from cache because the refresh could not\n * complete.\n * - `no-cache`: the SDK has never seen a snapshot for this identity, so\n * `hasAccess` is `false` for lack of evidence rather than because access\n * was denied.\n */\n reason: \"fresh\" | \"refresh-in-flight\" | \"refresh-failed\" | \"no-cache\";\n}\n\n/** Person snapshot together with how much to trust it. */\nexport interface CurrentPersonResult {\n /** The snapshot, or `null` before the SDK has ever seen one. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n person: Person | null;\n /** Served from cache past its refresh window. */\n isStale: boolean;\n /** Served from cache past its TTL. */\n isExpired: boolean;\n /** Why the snapshot has the freshness it has; see {@link HasPerkResult.reason}. */\n reason: \"fresh\" | \"refresh-in-flight\" | \"refresh-failed\" | \"no-cache\";\n}\n\n/** Outcome of a synchronous person-attribute update. */\nexport type SetPersonAttributesResult =\n | {\n /** The server accepted and returned the updated snapshot. */\n status: \"confirmed\";\n person: Person;\n }\n | {\n /** The server was unreachable; the update is queued and will be retried. */\n status: \"deferred\";\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n person: Person | null;\n }\n | {\n /** The client was created with `enabled: false`, so nothing was recorded. */\n status: \"disabled\";\n person: null;\n }\n | {\n /**\n * Nothing was left to write: the only attribute was an agreement to ad\n * data sharing, which waits for analytics consent.\n */\n status: \"skipped\";\n person: null;\n };\n\n/** Outcome of an analytics flush. */\nexport interface FlushResult {\n /** Events the server accepted during this flush. */\n flushed: number;\n /** Events still queued, waiting for their next attempt. */\n pending: number;\n /** The failure that stopped the flush, when one did. */\n lastError?: VoidhashError;\n}\n\n/** Feature flag answer of a disabled client: no flags were ever evaluated. */\nconst DISABLED_FEATURE_FLAGS: FeatureFlagsResult = { flags: [], isStale: false };\n\n/** Where the JavaScript runtime holds {@link liveClients}. */\nconst LIVE_CLIENTS = Symbol.for(\"@voidhash/react-native/live-clients\");\n\n/**\n * The client that owns each storage namespace (publishable key and base URL)\n * right now. A client that initializes ends the one it replaces first, so two\n * native clients never write the same queues. Where the platform runs one\n * native client per process, every client shares {@link PROCESS_SLOT} instead,\n * so a client of another project is ended as well: its native client stops\n * when the next one starts.\n *\n * Kept on the JavaScript runtime rather than in this module: a module\n * evaluated again in the same runtime (Fast Refresh of linked package sources,\n * or a second copy of the SDK in one bundle) must still find, and end, the\n * client the earlier evaluation started. A new runtime (a full reload) starts\n * empty; the native SDK then retires the client the old runtime left over the\n * same storage.\n */\nconst runtimeState: typeof globalThis & {\n [LIVE_CLIENTS]?: MutableHashMap.MutableHashMap<string, VoidhashClient>;\n} = globalThis;\nconst liveClients = (runtimeState[LIVE_CLIENTS] ??= MutableHashMap.empty());\n\n/** The key in {@link liveClients} of the one client a process can run. */\nconst PROCESS_SLOT = \"process\";\n\n/** How many purchase intents a client holds while no listener is registered; older ones are dropped. */\nconst MAX_HELD_PURCHASE_INTENTS = 10;\n\n/**\n * How many events and screens a client holds while an identity change called\n * before them has not switched the identity yet; older ones are dropped. The\n * same number the native client holds before it starts.\n */\nconst MAX_EVENTS_HELD_FOR_IDENTITY = 100;\n\n/**\n * Whether a value is a string with something besides whitespace. A blank\n * distinct id cannot identify anyone (HTTP trims header values, so it would\n * reach the server as a missing one).\n */\nconst isNonBlankString = (value: unknown): value is string =>\n P.isString(value) && value.trim() !== \"\";\n\nconst encodeProjectSchemaJson = Schema.encodeSync(Schema.fromJsonString(RuntimeSchemaValue));\nconst encodeJson = Schema.encodeUnknownOption(Schema.fromJsonString(Schema.Unknown));\n\n/**\n * Whether a screen, as an integration, `screen()` or `mapScreen` handed it\n * over, has the strings it is tracked by. Types do not guarantee it: a\n * `mapScreen` that looks a title up yields `undefined` for a missing key.\n */\nconst isTrackableScreen = (view: unknown): view is ScreenView =>\n P.hasProperty(view, \"identity\") &&\n P.isString(view.identity) &&\n P.hasProperty(view, \"name\") &&\n P.isString(view.name) &&\n P.hasProperty(view, \"path\") &&\n P.isString(view.path);\n\nconst REPLACEMENT_MODES: ReadonlyArray<SubscriptionReplacementMode> = [\n \"withTimeProration\",\n \"chargeProratedPrice\",\n \"chargeFullPrice\",\n \"withoutProration\",\n \"deferred\",\n];\n\nconst isReplacementMode = (value: unknown): value is SubscriptionReplacementMode =>\n REPLACEMENT_MODES.some((mode) => mode === value);\n\n/**\n * The subscription `purchase()` was asked to replace, as the native client\n * takes it, or an argument error when it names no product or a mode the SDK\n * does not have. Types do not guarantee either.\n */\nconst toNativeReplacement = (\n replacing: SubscriptionReplacement,\n): EffectResult.Result<NativeSubscriptionReplacement, InvalidArgumentError> => {\n const product: unknown = P.hasProperty(replacing, \"product\") ? replacing.product : undefined;\n const productSlug: unknown = P.hasProperty(product, \"slug\") ? product.slug : undefined;\n if (!isNonBlankString(productSlug)) {\n return EffectResult.fail(\n new InvalidArgumentError(\n \"purchase() needs `replacing.product` to be the product being replaced, from getProducts()\",\n ),\n );\n }\n const mode: unknown =\n (P.hasProperty(replacing, \"mode\") ? replacing.mode : undefined) ?? \"withTimeProration\";\n return isReplacementMode(mode)\n ? EffectResult.succeed({ mode, productSlug })\n : EffectResult.fail(\n new InvalidArgumentError(\n `purchase() needs \\`replacing.mode\\` to be one of ${REPLACEMENT_MODES.join(\", \")}${P.isString(mode) ? `, got \"${mode}\"` : \"\"}`,\n ),\n );\n};\n\n/** The offer `purchase()` was asked for, as the native client takes it. */\nconst toNativeOfferSelection = (\n offer: unknown,\n): EffectResult.Result<\n Pick<NativePurchaseOptions, \"offerSelection\" | \"offerId\" | \"offerKind\">,\n InvalidArgumentError\n> => {\n if (offer === undefined || offer === \"automatic\") {\n return EffectResult.succeed({ offerSelection: \"automatic\" });\n }\n if (offer === \"none\") return EffectResult.succeed({ offerSelection: \"regularPrice\" });\n if (isNonBlankString(offer))\n return EffectResult.succeed({ offerId: offer, offerSelection: \"offer\" });\n // An offer from the product names itself by its kind as well: the App Store's introductory\n // offer has no id of its own, so its `id` may be empty.\n const kind: unknown = P.hasProperty(offer, \"kind\") ? offer.kind : undefined;\n const offerKind = Option.filter(\n Option.some(kind),\n (value): value is Exclude<OfferKind, \"unknown\"> =>\n value === \"introductory\" ||\n value === \"promotional\" ||\n value === \"winBack\" ||\n value === \"oneTime\",\n );\n const id: unknown = P.hasProperty(offer, \"id\") ? offer.id : undefined;\n if (P.isString(id) && (Option.isSome(offerKind) || isNonBlankString(id))) {\n return EffectResult.succeed({\n offerId: id,\n offerSelection: \"offer\",\n ...Option.match(offerKind, { onNone: () => ({}), onSome: (value) => ({ offerKind: value }) }),\n });\n }\n return EffectResult.fail(\n new InvalidArgumentError(\n 'purchase() needs `offer` to be \"automatic\", \"none\", an offer of the product or its id',\n ),\n );\n};\n\n/**\n * A purchase's options as the native client takes them, or an argument error\n * for options no store could honour: a quantity that is not a whole number of\n * at least 1, several of anything but an App Store consumable, an offer or a\n * replacement that names nothing. They come from app code, so types guarantee\n * none of it.\n */\nconst toNativePurchaseOptions = (\n product: Product,\n options: PurchaseOptions,\n): EffectResult.Result<NativePurchaseOptions, InvalidArgumentError> => {\n const quantity: unknown = options.quantity ?? 1;\n if (!P.isNumber(quantity) || !Number.isInteger(quantity) || quantity < 1) {\n return EffectResult.fail(\n new InvalidArgumentError(\"purchase() needs `quantity` to be a whole number of at least 1\"),\n );\n }\n if (quantity !== 1 && !(product.store === \"appStore\" && product.type === \"consumable\")) {\n return EffectResult.fail(\n new InvalidArgumentError(\n `purchase() can buy several only of an App Store consumable; \"${product.slug}\" is bought one at a time`,\n ),\n );\n }\n const offer = toNativeOfferSelection(options.offer);\n if (EffectResult.isFailure(offer)) return EffectResult.fail(offer.failure);\n const replacing = Option.map(Option.fromNullishOr(options.replacing), toNativeReplacement);\n if (Option.isSome(replacing) && EffectResult.isFailure(replacing.value)) {\n return EffectResult.fail(replacing.value.failure);\n }\n const { appStore, googlePlay } = options;\n return EffectResult.succeed({\n ...offer.success,\n quantity,\n ...(Option.isSome(replacing) && EffectResult.isSuccess(replacing.value)\n ? { replacing: replacing.value.success }\n : {}),\n ...(appStore?.simulatesAskToBuyInSandbox === undefined\n ? {}\n : { appStore: { simulatesAskToBuyInSandbox: appStore.simulatesAskToBuyInSandbox } }),\n ...(googlePlay === undefined\n ? {}\n : {\n googlePlay: {\n ...(googlePlay.isOfferPersonalized === undefined\n ? {}\n : { isOfferPersonalized: googlePlay.isOfferPersonalized }),\n ...(googlePlay.obfuscatedProfileId === undefined\n ? {}\n : { obfuscatedProfileId: googlePlay.obfuscatedProfileId }),\n ...(googlePlay.offerToken === undefined ? {} : { offerToken: googlePlay.offerToken }),\n },\n }),\n });\n};\n\n/**\n * Why `groups` cannot be set, or `None` when they can: a group's id is a\n * string or a finite number, as the web SDK takes it. Types do not guarantee\n * it, and an id read as text would put the end user in a group named\n * `\"undefined\"`. A type given as `null` or `undefined` is not in the set.\n */\nconst invalidGroups = (groups: Groups): Option.Option<InvalidArgumentError> => {\n const invalidTypes = R.keys(\n R.filter(groups, (group: unknown) => {\n if (P.isNullish(group)) return false;\n const id: unknown = P.hasProperty(group, \"id\") ? group.id : group;\n return !(P.isString(id) || (P.isNumber(id) && Number.isFinite(id)));\n }),\n );\n return Arr.match(invalidTypes, {\n onEmpty: () => Option.none(),\n onNonEmpty: (types) =>\n Option.some(\n new InvalidArgumentError(\n `setGroups() needs each group's id to be a string or a finite number (${types.join(\", \")})`,\n ),\n ),\n });\n};\n\n/** A host report as the native client takes it: the store identifier and, on iOS, its JWS. */\nconst toNativeReport = (report: StoreReport): NativeReportedTransaction =>\n report.platform === \"ios\"\n ? {\n platform: \"appStore\",\n transactionId: report.transactionId,\n ...(report.signedTransaction === undefined\n ? {}\n : { signedTransaction: report.signedTransaction }),\n }\n : {\n platform: \"googlePlay\",\n purchaseToken: report.purchaseToken,\n ...(report.purchaseState === undefined ? {} : { purchaseState: report.purchaseState }),\n };\n\n/**\n * What {@link VoidhashClient} is built from: the options `createVoidhashClient`\n * validated, and where the native client comes from.\n * @internal\n */\nexport interface VoidhashClientSetup {\n readonly publishableKey: string;\n readonly baseUrl: string;\n readonly ingestUrl: Option.Option<string>;\n readonly distinctId: Option.Option<string>;\n readonly scheme: string;\n readonly readOnly: boolean;\n readonly debug: boolean;\n /** `dev: true` in a debug build. */\n readonly developmentMode: boolean;\n readonly enabled: boolean;\n readonly analyticsConsent: AnalyticsConsent;\n readonly analyticsWhilePending: AnalyticsWhilePending;\n readonly grantConsentOnIdentify: boolean;\n readonly automaticLifecycleEvents: boolean;\n readonly installAttribution: boolean;\n readonly metaAppId: Option.Option<string>;\n readonly flowCapabilities: ReadonlyArray<FlowCapability>;\n /** The validated `featureFlags.maxWaitMs`; `None` keeps the native client's default. */\n readonly featureFlagMaxWaitMs: Option.Option<number>;\n /** The validated `featureFlags.defaults`. */\n readonly featureFlagDefaults: Readonly<Record<string, boolean>>;\n readonly flowRuntime: FlowRuntime;\n readonly flowLoading: FlowLoading;\n readonly preloadLocations: ReadonlyArray<string>;\n readonly flowRevisions: Readonly<Record<string, number>>;\n readonly screenTracking: ScreenTrackingOptions;\n readonly internalSchema: Option.Option<RuntimeSchema>;\n readonly unstableSwallowErrors: boolean;\n readonly onDiagnostic: Option.Option<VoidhashDiagnosticHandler>;\n readonly atomRegistry: AtomRegistry.AtomRegistry;\n /** A new native client for this facade, or `None` where the binary has none. */\n readonly createNativeClient: () => Option.Option<NativeClientPort>;\n /**\n * Whether the platform runs one native client per process (Android): starting\n * a client there stops the one running, whatever project it belongs to.\n */\n readonly oneNativeClientPerProcess: boolean;\n /** `Platform.OS`: the `appStore` actions run on `ios` only, the `googlePlay` ones on `android`. */\n readonly platform: string;\n /** The npm package the app installs, which a failure that needs a new native build names. */\n readonly packageName: string;\n readonly appStoreMessages: \"automatic\" | \"deferWhileFlowPresented\";\n readonly purchaseIntents: \"purchaseWhenReady\" | \"manual\";\n}\n\n/**\n * App Store actions, on `client.appStore`. On any other platform each one\n * answers `UNSUPPORTED_PLATFORM`. While the client is disabled the reads\n * answer empty and `beginRefundRequest()` and `appTransaction()`, which have\n * no empty answer, `VOIDHASH_CLIENT_NOT_INITIALIZED`.\n */\nexport interface AppStoreActions {\n /**\n * Shows Apple's refund request sheet for a transaction, by its App Store\n * transaction id (`transaction.id`). `success` means Apple received the\n * request, not that it refunded anything: a refund arrives later and\n * reaches the person's subscriptions and entitlements.\n */\n readonly beginRefundRequest: (\n transactionId: string,\n ) => Promise<Result<RefundRequestStatus, VoidhashError>>;\n /**\n * Every status the Apple account has in an App Store subscription group\n * (`subscription.groupId`), as StoreKit reports them on this device: state,\n * latest transaction and renewal info. The current person's comes first (the\n * one bought for them), then the account's others, ones shared through\n * Family Sharing included. For what the person can use, read their\n * entitlements; the server knows subscriptions across devices and stores,\n * see `useSubscriptions()`.\n */\n readonly subscriptionStatus: (\n groupId: string,\n ) => Promise<Result<ReadonlyArray<AppStoreSubscriptionStatus>, VoidhashError>>;\n /** StoreKit's verified current entitlements on this device. */\n readonly currentEntitlements: () => Promise<Result<ReadonlyArray<Transaction>, VoidhashError>>;\n /** How the end user got the app: StoreKit's verified `AppTransaction`. */\n readonly appTransaction: () => Promise<Result<AppTransaction, VoidhashError>>;\n /**\n * Calls `listener` with each purchase the end user starts on the App Store\n * (a promoted in-app purchase, a win-back offer) while the\n * `purchaseIntents` option is `\"manual\"`; complete it with `purchase()`.\n * Intents that arrived while no listener was registered (they can arrive\n * as soon as `init()` starts) are held, the 10 latest, and handed to the\n * first listener added, at once. Returns the function that removes the\n * listener. Never called on another platform.\n */\n readonly addPurchaseIntentListener: (\n listener: (intent: AppStorePurchaseIntent) => void,\n ) => () => void;\n}\n\n/**\n * Google Play actions, on `client.googlePlay`. On any other platform each one\n * answers `UNSUPPORTED_PLATFORM`. While the client is disabled each answers\n * empty: `noActionNeeded`, no purchases, `false`.\n */\nexport interface GooglePlayActions {\n /**\n * Shows Google Play's in-app messages for the end user's subscriptions,\n * such as a prompt to fix a declined payment. When they fixed it, the\n * answer names the purchase token, and the SDK has synced purchases and\n * refreshed the person.\n */\n readonly showInAppMessages: () => Promise<Result<GooglePlayInAppMessageResult, VoidhashError>>;\n /**\n * The Google Play account's purchases on this device, suspended\n * subscriptions included unless `includeSuspended` is `false`\n * (`transaction.googlePlay.isSuspended`). For what the person can use, read\n * their entitlements.\n */\n readonly queryPurchases: (options?: {\n readonly includeSuspended?: boolean;\n }) => Promise<Result<ReadonlyArray<Transaction>, VoidhashError>>;\n /** Whether Google Play supports a billing feature on this device. */\n readonly isFeatureSupported: (\n feature: GooglePlayBillingFeature,\n ) => Promise<Result<boolean, VoidhashError>>;\n}\n\n/**\n * The Voidhash client: the public facade over the native Voidhash client.\n * Every method answers with a `Result` carrying a coded `VoidhashError`\n * instead of throwing, and a client created with `enabled: false` never\n * touches the native client and answers every read with its empty shape.\n */\nexport class VoidhashClient {\n private readonly setup: VoidhashClientSetup;\n private readonly atomRegistry: AtomRegistry.AtomRegistry;\n private readonly namespace: string;\n /** What this client holds in `liveClients` while it runs: its namespace, or the process. */\n private readonly slot: string;\n private readonly emitDiagnostic: (diagnostic: VoidhashDiagnostic) => void;\n private readonly screenTracker: ScreenTracker;\n private manualScreenCounter = 0;\n /** The send id `trackPushOpened()` reported last. */\n private lastPushOpenedSendId = Option.none<string>();\n /** The native client and its adapter, made on first use. */\n private native = Option.none<NativeClientAdapter>();\n /** Seeds the first `init()` of the process; cleared once applied or by an identity change. */\n private initialDistinctId: Option.Option<string>;\n /** The consent in effect, mirrored from the native client once it runs. */\n private analyticsConsent: AnalyticsConsent;\n /** A consent `setAnalyticsConsent()` chose before `init()`; it wins over the stored one. */\n private chosenAnalyticsConsent = Option.none<AnalyticsConsent>();\n private analyticsConsentDeniedReported = false;\n private readOnly: boolean;\n private _isInitialized = false;\n /** Set by `end()` until the next `init()`. */\n private ended = false;\n /**\n * The `init()` or `end()` called last, until it settles. A call for the\n * same transition joins it and a call for the other one runs after it, so\n * the client ends up in the state asked for last.\n */\n private transition = Option.none<{\n readonly to: \"initialized\" | \"ended\";\n readonly settled: Promise<Result<void, VoidhashError>>;\n }>();\n private flushInFlight = Option.none<Promise<Result<FlushResult, VoidhashError>>>();\n /** The purchase this client runs, until it settles; a second one fails `PURCHASE_IN_PROGRESS`. */\n private purchaseInFlight = Option.none<Promise<Result<PurchaseResult, VoidhashError>>>();\n private identityChangeTail: Promise<void> = Promise.resolve();\n /**\n * The `identify()`, `reset()` and `signOut()` calls made, and how many of\n * them, in call order, have switched the identity or settled without doing\n * so. An event, a screen or a purchase report waits for the ones called\n * before it, so it is recorded for the person the app switched to; see\n * {@link identityChangeSwitched}.\n */\n private identityChangesCalled = 0;\n private identityChangesSwitched = 0;\n /** The identity change the native client is running now, by its number among those called. */\n private identityChangeRunning = Option.none<number>();\n private readonly eventsHeldForIdentity: Array<{\n readonly after: number;\n readonly name: string;\n readonly operation: \"capture\" | \"screen\";\n readonly send: () => void;\n }> = [];\n private readonly reportsHeldForIdentity: Array<{\n readonly after: number;\n readonly proceed: () => void;\n }> = [];\n /**\n * One entry per `addTransactionListener()` call, each its own function, so\n * adding a listener twice calls it twice.\n */\n private readonly transactionListeners =\n MutableHashSet.empty<(update: TransactionUpdate) => void>();\n private readonly purchaseIntentListeners =\n MutableHashSet.empty<(intent: AppStorePurchaseIntent) => void>();\n /**\n * Purchase intents that arrived while no listener was registered (they\n * arrive from `init()` on, before the app may have added one), oldest\n * first, for the first listener the app adds.\n */\n private heldPurchaseIntents: Array<AppStorePurchaseIntent> = [];\n\n /**\n * @internal Not part of the public API: create clients with\n * `createVoidhashClient()`, which validates the options and builds the\n * provider and hooks. The parameters change between releases.\n */\n constructor(setup: VoidhashClientSetup) {\n this.setup = setup;\n this.atomRegistry = setup.atomRegistry;\n this.namespace = buildCacheNamespace(setup.publishableKey, setup.baseUrl);\n this.slot = setup.oneNativeClientPerProcess ? PROCESS_SLOT : this.namespace;\n this.emitDiagnostic = makeDiagnosticEmitter(setup.onDiagnostic);\n this.initialDistinctId = setup.distinctId;\n this.analyticsConsent = setup.analyticsConsent;\n this.readOnly = setup.readOnly;\n const mapScreen = setup.screenTracking.mapScreen;\n this.screenTracker = createScreenTracker({\n enabled: setup.enabled && (setup.screenTracking.enabled ?? true),\n includeParams: setup.screenTracking.includeParams ?? false,\n mapScreen: mapScreen\n ? (view) => {\n // oxlint-disable-next-line effect/avoid-try-catch -- boundary with host application code: `mapScreen` is a plain function the app supplies and may throw anything; the throw must not escape into the navigation listener that reported the screen.\n try {\n const mapped: unknown = mapScreen(view);\n if (P.isNullish(mapped)) return Option.none();\n if (isTrackableScreen(mapped)) return Option.some(mapped);\n this.emitDiagnostic({\n code: \"HOST_CALLBACK_FAILED\",\n kind: \"configuration\",\n message:\n \"screenTracking.mapScreen returned a screen whose identity, name or path is not a string; the screen was tracked unmapped\",\n operation: \"screenTracking.mapScreen\",\n retryable: false,\n });\n return Option.some(view);\n } catch (error) {\n this.reportHostCallbackFailure(\"screenTracking.mapScreen\", error);\n return Option.some(view);\n }\n }\n : undefined,\n });\n }\n\n /** The adapter over this client's native client, created on first use. */\n private nativeClient(): Option.Option<NativeClientAdapter> {\n if (Option.isSome(this.native)) return this.native;\n this.native = Option.map(this.setup.createNativeClient(), (native) =>\n makeNativeClientAdapter({\n atomRegistry: this.atomRegistry,\n native,\n packageName: this.setup.packageName,\n onAnalyticsConsentChanged: (consent) => {\n this.analyticsConsent = consent;\n if (consent === \"granted\") this.analyticsConsentDeniedReported = false;\n },\n // The switch a running identity change made: what waited for it goes on\n // now, not once Voidhash answered the call.\n onIdentitySwitched: () => {\n Option.map(this.identityChangeRunning, (change) => this.identityChangeSwitched(change));\n },\n onDiagnostic: this.emitDiagnostic,\n onPurchaseIntent: (intent) => this.receivePurchaseIntent(intent),\n onTransaction: (update) =>\n this.notify(\"addTransactionListener\", this.transactionListeners, update),\n }),\n );\n return this.native;\n }\n\n /** The configuration the next `start()` runs with. */\n private configuration(): NativeClientConfiguration {\n const setup = this.setup;\n return {\n analyticsConsent: setup.analyticsConsent,\n analyticsWhilePending: setup.analyticsWhilePending,\n appStoreMessages: setup.appStoreMessages,\n automaticLifecycleEvents: setup.automaticLifecycleEvents,\n baseUrl: setup.baseUrl,\n grantConsentOnIdentify: setup.grantConsentOnIdentify,\n debug: setup.debug,\n developmentMode: setup.developmentMode,\n featureFlagDefaults: { ...setup.featureFlagDefaults },\n flowCapabilities: [...setup.flowCapabilities],\n flowRuntime: setup.flowRuntime,\n flowLoading: setup.flowLoading,\n installAttribution: setup.installAttribution,\n flowRevisions: R.collect(setup.flowRevisions, (location, revision) => ({\n location,\n revision,\n })),\n preloadLocations: [...setup.preloadLocations],\n publishableKey: setup.publishableKey,\n purchaseIntents: setup.purchaseIntents,\n readOnly: this.readOnly,\n screenTrackingEnabled: setup.screenTracking.enabled ?? true,\n sdkVersion: SDK_VERSION,\n ...Option.match(this.initialDistinctId, {\n onNone: () => ({}),\n onSome: (distinctId) => ({ distinctId }),\n }),\n ...Option.match(setup.metaAppId, {\n onNone: () => ({}),\n onSome: (metaAppId) => ({ metaAppId }),\n }),\n ...Option.match(this.chosenAnalyticsConsent, {\n onNone: () => ({}),\n onSome: (chosenAnalyticsConsent) => ({ chosenAnalyticsConsent }),\n }),\n ...Option.match(setup.ingestUrl, {\n onNone: () => ({}),\n onSome: (ingestUrl) => ({ ingestUrl }),\n }),\n ...Option.match(setup.featureFlagMaxWaitMs, {\n onNone: () => ({}),\n onSome: (featureFlagMaxWaitMs) => ({ featureFlagMaxWaitMs }),\n }),\n ...Option.match(setup.internalSchema, {\n onNone: () => ({}),\n onSome: (schema) => ({ internalSchemaJson: encodeProjectSchemaJson(schema) }),\n }),\n };\n }\n\n /**\n * The answer of a side-effect call, unless `unstable_swallowErrors` asks for\n * failures to be logged and answered as success.\n */\n private swallowed(\n operation: string,\n result: Result<void, VoidhashError>,\n ): Result<void, VoidhashError> {\n if (result.isErr() && this.setup.unstableSwallowErrors) {\n // oxlint-disable-next-line effect/use-console-service -- the deprecated escape hatch logs what it swallows, outside any runtime.\n console.warn(`[voidhash] swallowed error in ${operation}`, result.error);\n return Result.ok(undefined);\n }\n return result;\n }\n\n /** The started adapter, or `NOT_INITIALIZED`. */\n private started(): Result<NativeClientAdapter, VoidhashError> {\n return this._isInitialized && Option.isSome(this.native)\n ? Result.ok(this.native.value)\n : Result.err(new NotInitializedError());\n }\n\n /**\n * Joins an `init()` in progress or starts one — after `end()` and behind an\n * `end()` still running too — the way identity calls do, so a purchase\n * reported during launch or teardown is not refused.\n */\n private async whenInitialized(): Promise<Result<NativeClientAdapter, VoidhashError>> {\n await this.init();\n return this.started();\n }\n\n /** Runs an `init()` or `end()` as the transition called last. */\n private runTransition(\n to: \"initialized\" | \"ended\",\n run: () => Promise<Result<void, VoidhashError>>,\n ): Promise<Result<void, VoidhashError>> {\n const settled = run().finally(() => {\n if (Option.exists(this.transition, (current) => current.settled === settled)) {\n this.transition = Option.none();\n }\n });\n this.transition = Option.some({ settled, to });\n return settled;\n }\n\n /**\n * The client that took over this client's storage namespace while this one\n * is not running. Identity and purchase calls on a replaced instance go to\n * it: starting this instance again would end the live one. A live client of\n * another project is never a replacement: nothing made for one project is\n * handed to another.\n */\n private replacement(): Option.Option<VoidhashClient> {\n const starting = Option.exists(this.transition, (current) => current.to === \"initialized\");\n if (this._isInitialized || starting) return Option.none();\n return Option.filter(\n MutableHashMap.get(liveClients, this.slot),\n (owner) => owner !== this && owner.namespace === this.namespace,\n );\n }\n\n /**\n * Runs an identity change in call order. Events, screens and purchase\n * reports made after it wait until it switched the identity, which the\n * native client announces at once, before it waits for Voidhash. A change\n * that switches nothing lets them go on when it starts (an `identify()` of\n * `target`, already the identity) or when it settles.\n */\n private enqueueIdentityChange<T>(\n operation: () => Promise<Result<T, VoidhashError>>,\n target: Option.Option<string> = Option.none(),\n ): Promise<Result<T, VoidhashError>> {\n this.initialDistinctId = Option.none();\n this.identityChangesCalled += 1;\n const change = this.identityChangesCalled;\n const settled = this.enqueueInIdentityOrder(() => {\n this.identityChangeRunning = Option.some(change);\n const current = Option.flatMap(this.native, (native) => native.currentDistinctId());\n // With a consent the identify() may still grant, events wait for it to settle.\n if (\n Option.isSome(target) &&\n Option.contains(current, target.value) &&\n this.analyticsConsent === \"granted\"\n ) {\n this.identityChangeSwitched(change);\n }\n return operation();\n });\n const switched = () => {\n // An identity announced from here on is not this change's switch.\n if (Option.contains(this.identityChangeRunning, change)) {\n this.identityChangeRunning = Option.none();\n }\n this.identityChangeSwitched(change);\n };\n void settled.then(switched, switched);\n return settled;\n }\n\n /**\n * Identity change number `change` switched the identity, or will not: sends\n * the events and screens held for it and lets the purchase reports go on.\n * Changes run one at a time, so the ones before it have switched too.\n */\n private identityChangeSwitched(change: number) {\n if (change <= this.identityChangesSwitched) return;\n this.identityChangesSwitched = change;\n const isDue = (held: { readonly after: number }) => held.after <= change;\n const events = this.eventsHeldForIdentity.splice(\n 0,\n this.eventsHeldForIdentity.filter(isDue).length,\n );\n events.forEach((event) => event.send());\n const reports = this.reportsHeldForIdentity.splice(\n 0,\n this.reportsHeldForIdentity.filter(isDue).length,\n );\n reports.forEach((report) => report.proceed());\n }\n\n /** Whether an identity change called before now has not switched the identity yet. */\n private awaitsIdentityChange() {\n return this.identityChangesSwitched < this.identityChangesCalled;\n }\n\n /**\n * Keeps an event or a screen until the identity changes called before it\n * switched the identity, then calls `send` with the time it was captured\n * at. In memory, as the native client holds events before it starts: past\n * {@link MAX_EVENTS_HELD_FOR_IDENTITY} the oldest is dropped and reported.\n */\n private holdEventForIdentity(\n operation: \"capture\" | \"screen\",\n name: string,\n send: (capturedAt: number) => void,\n ) {\n // oxlint-disable-next-line effect/use-clock-service -- the time of the app's call, outside any Effect, as the native client stamps an event it is handed.\n const capturedAt = Date.now();\n this.eventsHeldForIdentity.push({\n after: this.identityChangesCalled,\n name,\n operation,\n // Whether it may be recorded is settled as it is sent: the consent may\n // have changed since, and an `identify()` can grant a pending one.\n send: () => {\n if (Option.isSome(this.analyticsIntake(operation, name))) send(capturedAt);\n },\n });\n if (this.eventsHeldForIdentity.length <= MAX_EVENTS_HELD_FOR_IDENTITY) return;\n Option.map(Option.fromUndefinedOr(this.eventsHeldForIdentity.shift()), (dropped) =>\n this.emitDiagnostic({\n code: \"ANALYTICS_EVENT_DROPPED\",\n kind: \"eviction\",\n message: `Dropped \"${dropped.name}\": more than ${MAX_EVENTS_HELD_FOR_IDENTITY} events were captured while identify(), reset() or signOut() was switching the identity`,\n operation: dropped.operation,\n retryable: false,\n }),\n );\n }\n\n /** Resolves once the identity changes called before now switched the identity. */\n private afterIdentityChanges(): Promise<void> {\n if (!this.awaitsIdentityChange()) return Promise.resolve();\n return new Promise((proceed) => {\n this.reportsHeldForIdentity.push({ after: this.identityChangesCalled, proceed });\n });\n }\n\n /**\n * Runs `operation` once `init()` has settled, after every identity change\n * and group call made before it.\n */\n private enqueueInIdentityOrder<T>(\n operation: () => Promise<Result<T, VoidhashError>>,\n ): Promise<Result<T, VoidhashError>> {\n const next = this.identityChangeTail.then(async () => {\n const initialized = await this.init();\n if (initialized.isErr()) return Result.err(initialized.error);\n return operation();\n });\n this.identityChangeTail = next.then(\n () => undefined,\n () => undefined,\n );\n return next;\n }\n\n /**\n * Starts the native client from local state: identity, caches and queues\n * are loaded without waiting for the network, and the refreshes, store\n * observation and delivery continue in the background. Resolves\n * immediately without touching the native client when the client was\n * created with `enabled: false`.\n *\n * An app launched in the background before the device has been unlocked\n * since it started (on Android, only an app with a `directBootAware`\n * component) cannot read anything the SDK stored, so this waits for that\n * first unlock; events captured meanwhile are kept.\n *\n * Idempotent: a call that overlaps a running `init()` joins it, and a call\n * on an initialized client resolves at once. A call made while `end()` is\n * still running waits for it and then starts the client again, unless\n * another client took over its storage meanwhile: then this one stays ended\n * and the call answers `VOIDHASH_CLIENT_NOT_INITIALIZED`.\n */\n async init(): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const pending = this.transition;\n if (Option.isSome(pending) && pending.value.to === \"initialized\") {\n return pending.value.settled;\n }\n if (Option.isNone(pending) && this._isInitialized) return Result.ok(undefined);\n return this.runTransition(\"initialized\", async () => {\n if (Option.isSome(pending)) {\n await pending.value.settled;\n // A client that took the namespace over meanwhile has asked this one\n // to end, and waits for that. Starting here would in turn wait for\n // that client to end, so neither would ever finish.\n const takenOver = Option.exists(\n MutableHashMap.get(liveClients, this.slot),\n (owner) => owner !== this,\n );\n if (takenOver && Option.exists(this.transition, (current) => current.to === \"ended\")) {\n return Result.err(new NotInitializedError());\n }\n }\n return this.runInit();\n });\n }\n\n private async runInit(): Promise<Result<void, VoidhashError>> {\n await this.claimNamespace();\n const native = this.nativeClient();\n if (Option.isNone(native)) {\n this.releaseNamespace();\n return this.swallowed(\n \"init\",\n Result.err(\n new VoidhashError(\n \"FAILED_TO_INITIALIZE_VOIDHASH_CLIENT\",\n `FAILED_TO_INITIALIZE_VOIDHASH_CLIENT: the Voidhash native module is missing. Rebuild the app after installing ${this.setup.packageName}.`,\n ),\n ),\n );\n }\n const started = await native.value.start(this.configuration());\n if (started.isErr()) {\n this.releaseNamespace();\n return this.swallowed(\"init\", started);\n }\n this.initialDistinctId = Option.none();\n this.chosenAnalyticsConsent = Option.none();\n // A native client that cannot say leaves the consent this facade configured.\n this.analyticsConsent = Option.getOrElse(\n native.value.getAnalyticsConsent(),\n () => this.analyticsConsent,\n );\n this.ended = false;\n this._isInitialized = true;\n // Hooks that loaded for the previous run (an `end()` dropped what it loaded) load again.\n this.atomRegistry.update(clientRunAtom, (runs) => runs + 1);\n return Result.ok(undefined);\n }\n\n /**\n * Makes this client the owner of its storage namespace (of the process,\n * where it runs one native client), ending the client that owned it until\n * now. It is the owner before that client has ended, so identity and\n * purchase calls made on a replaced client of the same namespace meanwhile\n * already go to this one instead of starting the replaced one again.\n */\n private async claimNamespace(): Promise<void> {\n const owner = MutableHashMap.get(liveClients, this.slot);\n MutableHashMap.set(liveClients, this.slot, this);\n if (Option.isNone(owner) || owner.value === this) return;\n if (__DEV__) {\n // oxlint-disable-next-line effect/use-console-service -- development-only guidance for a misconfigured integration, outside any SDK runtime.\n console.warn(\n owner.value.namespace === this.namespace\n ? \"[voidhash] A second client for the same publishable key and base URL replaced the first one. Create the client once, at module scope.\"\n : \"[voidhash] A client for another publishable key or base URL ended the one that was running: Android runs one Voidhash client at a time.\",\n );\n }\n await owner.value.end();\n }\n\n /** Gives up this client's storage namespace, if it still owns it. */\n private releaseNamespace() {\n if (Option.exists(MutableHashMap.get(liveClients, this.slot), (owner) => owner === this)) {\n MutableHashMap.remove(liveClients, this.slot);\n }\n }\n\n /**\n * Ends the client: flushes for at most about two seconds, persists what is\n * still queued and stops every observer, timer and listener. Whatever was\n * not delivered goes out after the next `init()`. An `init()` still running\n * is waited for first. The client stops being initialized as soon as the\n * teardown begins: reads answer `VOIDHASH_CLIENT_NOT_INITIALIZED` from then\n * on. Afterwards `capture()` drops events with a diagnostic and `init()`\n * starts the client again. Overlapping calls share one teardown. No-ops on\n * a disabled client.\n */\n async end(): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const pending = this.transition;\n if (Option.isSome(pending) && pending.value.to === \"ended\") return pending.value.settled;\n return this.runTransition(\"ended\", async () => {\n if (Option.isSome(pending)) await pending.value.settled;\n const started = this.started();\n if (started.isErr()) {\n this.releaseNamespace();\n return Result.err(started.error);\n }\n // Events still waiting for an identity change were captured before this\n // call: the native client takes them now, under the identity in effect,\n // and its shutdown stores them with the rest.\n this.eventsHeldForIdentity.splice(0).forEach((event) => event.send());\n // Not initialized while the native client shuts down: it refuses calls\n // from here on, and an `init()` made meanwhile has to start it again.\n this._isInitialized = false;\n const shutdown = await started.value.shutdown().finally(() => {\n // Torn down whatever the native client answered: a client left\n // half-running would keep owning its storage namespace.\n this.ended = true;\n this.releaseNamespace();\n });\n return shutdown.map(() => undefined);\n });\n }\n\n /** Whether the client is initialized. Always false while the client is disabled. */\n get isInitialized() {\n return this._isInitialized;\n }\n\n /** Whether this client does anything at all, fixed at construction by the `enabled` option. */\n get isEnabled() {\n return this.setup.enabled;\n }\n\n /** Whether the SDK currently runs in observer (\"read-only\") mode. */\n get isReadOnly() {\n return this.readOnly;\n }\n\n /**\n * Switches observer mode at runtime, so an app migrating onto Voidhash can\n * flip from watching another SDK's purchases to owning them without\n * recreating the client. A purchase that already started keeps the mode it\n * started with. No-ops in effect on a disabled client.\n */\n setReadOnly(readOnly: boolean) {\n this.readOnly = readOnly;\n Option.map(this.native, (native) => native.setReadOnly(readOnly));\n }\n\n /**\n * The end user's analytics consent in effect: the last\n * {@link setAnalyticsConsent} value, else (once `init()` has read it) the\n * stored one, else the `analyticsConsent` option.\n */\n getAnalyticsConsent(): AnalyticsConsent {\n return this.analyticsConsent;\n }\n\n /**\n * Records whether the end user consents to usage analytics. Takes effect\n * immediately and is stored on the device, where it takes precedence over\n * the `analyticsConsent` option on later launches; `reset()` and\n * `signOut()` keep it.\n *\n * `\"denied\"` and `\"pending\"` stop all analytics: events, screens, lifecycle\n * and install events and paywall impressions are dropped, and every event\n * still queued on the device is discarded together with the analytics\n * session. Purchases, restores, entitlements, `identify()`, person\n * attributes, groups, feature flags and paywalls are unaffected. `\"granted\"`\n * resumes analytics for what is captured from then on.\n *\n * Called before `init()` the consent applies at once and is stored when\n * `init()` runs. An `Err` with `FAILED_TO_SET_ANALYTICS_CONSENT` means the\n * consent applies to this process but could not be stored; an invalid value\n * is an `INVALID_ARGUMENT` error and changes nothing.\n */\n async setAnalyticsConsent(consent: AnalyticsConsent): Promise<Result<void, VoidhashError>> {\n if (!isAnalyticsConsent(consent)) {\n return Result.err(\n new InvalidArgumentError(\n `setAnalyticsConsent() needs \"granted\", \"denied\" or \"pending\", got ${String(consent)}`,\n ),\n );\n }\n this.analyticsConsent = consent;\n if (consent === \"granted\") this.analyticsConsentDeniedReported = false;\n if (!this.setup.enabled) return Result.ok(undefined);\n if (Option.isSome(this.transition)) await this.transition.value.settled;\n const started = this.started();\n if (started.isErr()) {\n // Stored by the next start, and told to a native client that already\n // holds events captured before it, so a consent other than granted\n // discards them.\n this.chosenAnalyticsConsent = Option.some(consent);\n await Option.match(this.native, {\n onNone: () => Promise.resolve(),\n onSome: (native) => native.setAnalyticsConsent(consent),\n });\n return Result.ok(undefined);\n }\n const stored = await started.value.setAnalyticsConsent(consent);\n if (stored.isErr()) return Result.err(stored.error);\n return stored.value\n ? Result.ok(undefined)\n : Result.err(\n new VoidhashError(\n \"FAILED_TO_SET_ANALYTICS_CONSENT\",\n \"FAILED_TO_SET_ANALYTICS_CONSENT: the consent applies now but could not be stored on the device\",\n ),\n );\n }\n\n /**\n * Returns the current person snapshot together with how much to trust it.\n * The answer comes from cache whenever one exists — a stale entry is served\n * while a refresh runs behind the read — so this never waits long on the\n * network and never fails because the server is unreachable. Pass\n * `{ forceFetch: true }` to prefer the server. Answers an empty snapshot\n * while disabled.\n */\n async getCurrentPerson(\n options: { forceFetch?: boolean } = {},\n ): Promise<Result<CurrentPersonResult, VoidhashError>> {\n if (!this.setup.enabled) {\n return Result.ok({ isExpired: false, isStale: false, person: null, reason: \"no-cache\" });\n }\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.getCurrentPerson(options);\n }\n\n /**\n * Checks whether the current person holds an active grant for a perk.\n *\n * Cache-first: a fresh snapshot answers immediately, a stale one is served\n * while a refresh runs behind the read, and an entitlement granted before\n * the device went offline keeps answering `true`. The result always says how\n * fresh it is (`isStale`, `isExpired`, `reason`) — it never fails because\n * the server is unreachable. Pass `{ forceFetch: true }` to prefer the\n * server.\n */\n async hasPerk(\n perkSlug: PerkSlug,\n options: {\n /**\n * @deprecated No longer read. A stale answer beats no answer, so the\n * cached grant is always served. Branch on `isStale`/`isExpired` in the\n * result instead. Removed in a future release.\n */\n allowStale?: boolean;\n /** Prefer the server, waiting for it before answering. */\n forceFetch?: boolean;\n } = {},\n ): Promise<Result<HasPerkResult, VoidhashError>> {\n if (!this.setup.enabled) {\n return Result.ok({\n hasAccess: false,\n isExpired: false,\n isStale: false,\n reason: \"no-cache\",\n });\n }\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.hasPerk(perkSlug, { forceFetch: options.forceFetch });\n }\n\n /**\n * Sets person attributes without waiting on the network. Reserved\n * `email`/`name` keys map to the dedicated server fields (strings); any\n * other key is a custom trait whose value must be a string, a number, a\n * boolean or `null`. Anything else is an `INVALID_ARGUMENT` error and\n * nothing is written. The update is stored on the device and sent right\n * away, then retried until the server applies it; `flush()` waits for it.\n * Attributes are written whatever the analytics consent, except that the\n * native SDK leaves `$ad_data_sharing` set to anything but `false` out until\n * it is granted: see {@link setAdDataSharing}.\n *\n * Like identity calls, it waits for initialization and runs in call order\n * with `identify()`, `reset()` and `signOut()`, so the attributes belong to\n * the person identified when this was called. Called right after an\n * `identify()` that wasn't awaited, it resolves once that identify settles.\n */\n async setPersonAttributes(attributes: PersonAttributes): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const invalid = invalidPersonAttributes(attributes);\n if (Option.isSome(invalid)) return Result.err(invalid.value);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.setPersonAttributes(attributes);\n return this.enqueueInIdentityOrder(async () => {\n const started = this.started();\n if (started.isErr()) return this.swallowed(\"setPersonAttributes\", Result.err(started.error));\n return this.swallowed(\n \"setPersonAttributes\",\n await started.value.setPersonAttributes(attributes),\n );\n });\n }\n\n /**\n * Records whether the end user agreed to you sharing their purchases with ad\n * platforms, as the person trait `$ad_data_sharing`. Voidhash sends a\n * person's purchases to a Conversions API you turned on only when it is\n * `true`.\n *\n * `true` needs analytics consent: it does nothing while that is not\n * granted. Once written, it also drops a revocation\n * still queued for the person. `false` is a revocation, which analytics\n * consent neither blocks nor discards: the native SDK stores it on the device\n * and retries it until Voidhash has written it, or for 48 hours while Voidhash\n * has no such person, and it records no analytics. When someone rejects\n * everything, call it next to `setAnalyticsConsent(\"denied\")`. Withdrawing\n * analytics consent does not take this back by itself.\n *\n * Waits for initialization and runs in call order with identity changes, as\n * {@link setPersonAttributes} does.\n */\n async setAdDataSharing(granted: boolean): Promise<Result<void, VoidhashError>> {\n return this.setPersonAttributes({ $ad_data_sharing: granted === true });\n }\n\n /**\n * Sets person attributes and reports whether the server confirmed them.\n * When the server cannot confirm the update now (it is unreachable, the key\n * was rejected, or an earlier write for this person is still queued) the\n * update is queued and the result is `deferred` with the last known\n * snapshot, rather than an error. Values, ordering and observer mode follow\n * {@link setPersonAttributes}: attributes are written whatever the analytics\n * consent and whether or not the client is read-only. The result is\n * `skipped` only when the one attribute was an agreement to ad data sharing\n * made without analytics consent: see {@link setAdDataSharing}.\n */\n async setPersonAttributesSync(\n attributes: PersonAttributes,\n ): Promise<Result<SetPersonAttributesResult, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok({ person: null, status: \"disabled\" });\n const invalid = invalidPersonAttributes(attributes);\n if (Option.isSome(invalid)) return Result.err(invalid.value);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.setPersonAttributesSync(attributes);\n return this.enqueueInIdentityOrder(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.setPersonAttributesSync(attributes);\n });\n }\n\n /**\n * Returns the active analytics session id, or `undefined` before `init()`,\n * while disabled, or once the session has been idle past the inactivity\n * timeout. Reading does not extend the session.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK method consumed by non-Effect app code; `undefined` is the documented \"no active session\" answer and mirrors the iOS and Android SDKs.\n getSessionId(): string | undefined {\n const started = this.started();\n return this.setup.enabled && started.isOk() ? started.value.getSessionId() : undefined;\n }\n\n /** Returns the current distinct id, or `Ok(null)` while disabled. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK method consumed by non-Effect app code; `null` is the documented answer of a disabled client.\n async getDistinctId(): Promise<Result<string | null, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(null);\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.getDistinctId();\n }\n\n /**\n * Identifies the user by switching the current distinct id. The switch\n * happens locally first, and the link from the previous (anonymous)\n * identity is stored on the device before it is sent; when the server\n * cannot confirm it now, the link is retried until it lands rather than\n * failing, and an anonymous purchaser keeps their cached access meanwhile.\n * Use {@link identifySync} to learn which of the two happened. Identity\n * calls wait for initialization and run in invocation order. Repeating the\n * same ID without profile changes preserves the session and cached state.\n * A blank ID is an `INVALID_ARGUMENT` error and leaves the identity alone.\n */\n async identify(\n externalUserId: string,\n options: { email?: string; name?: string } = {},\n ): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n if (!isNonBlankString(externalUserId)) {\n return Result.err(new InvalidArgumentError(\"identify() needs a non-blank distinct id\"));\n }\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.identify(externalUserId, options);\n return this.enqueueIdentityChange(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\"identify\", await started.value.identify(externalUserId, options));\n }, Option.some(externalUserId));\n }\n\n /**\n * Identifies the user and reports whether the server confirmed the switch\n * (`confirmed`, with the person) or the device switched locally and queued\n * the link for later delivery (`deferred`, with the last known snapshot\n * for that identity, if any). Only a verdict the Voidhash API will not\n * change — which also restores the previous identity — or a blank ID\n * (`INVALID_ARGUMENT`) is an `Err`.\n */\n async identifySync(\n externalUserId: string,\n options: { email?: string; name?: string } = {},\n ): Promise<Result<IdentifyResult, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok({ person: null, status: \"disabled\" });\n if (!isNonBlankString(externalUserId)) {\n return Result.err(new InvalidArgumentError(\"identifySync() needs a non-blank distinct id\"));\n }\n const replacement = this.replacement();\n if (Option.isSome(replacement)) {\n return replacement.value.identifySync(externalUserId, options);\n }\n return this.enqueueIdentityChange(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.identifySync(externalUserId, options);\n }, Option.some(externalUserId));\n }\n\n /**\n * Starts a fresh visitor: a new anonymous distinct id and analytics session,\n * with no groups. When someone is signed in this is exactly `signOut()`;\n * when nobody is, `signOut()` does nothing and this still starts over, with\n * no event recorded. Use it for a shared device, or a guest starting over.\n */\n async reset(): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.reset();\n return this.enqueueIdentityChange(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\"reset\", await started.value.reset());\n });\n }\n\n /**\n * Signs the current user out: captures the built-in `$sign_out` event\n * (unless automatic lifecycle events are off or analytics consent is not\n * granted), flushes it under the signing-out identity, then resets to a\n * fresh anonymous distinct id and starts a new analytics session. Does\n * nothing when nobody is signed in, so it is safe to call whenever the app\n * finds no session; `reset()` is the call for a fresh anonymous visitor.\n */\n async signOut(): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.signOut();\n return this.enqueueIdentityChange(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\"signOut\", await started.value.signOut());\n });\n }\n\n /**\n * Puts the end user in a group, such as the company or workspace they use\n * your app as part of. Every event captured after the returned promise\n * resolves carries it in `$groups`, until `resetGroups()`, `reset()` or\n * `signOut()`; the native SDK stores it on the device with the distinct id,\n * one group per type.\n *\n * `properties` set the group's own properties, such as its `name` and\n * `plan`: strings, numbers or booleans. They are sent as a `$groupidentify`\n * event when given, or when the end user's group of that type changed.\n * Groups and their properties are sent whatever the analytics consent;\n * without it the `$groupidentify` goes out at once, on its own, and is not\n * retried if it fails.\n *\n * A group type is a lower-case letter followed by up to 63 lower-case\n * letters, digits or underscores, such as `company`, and a key has 1 to 256\n * characters; a number is kept as text. Any other is an `INVALID_ARGUMENT`\n * error. `null` properties count as none. Like identity calls, it waits for initialization and runs in call\n * order with `identify()`, `reset()` and `signOut()`.\n */\n async group(\n groupType: string,\n groupKey: string | number,\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK input from non-Effect app code, where a group without properties is naturally passed as null.\n properties?: GroupProperties | null,\n ): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const key = String(groupKey);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.group(groupType, key, properties);\n return this.enqueueInIdentityOrder(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\n \"group\",\n await started.value.group(groupType, key, Option.fromNullishOr(properties)),\n );\n });\n }\n\n /**\n * Replaces every group the end user is in, in one call: the groups to be in\n * by type, each an id or `{ id, ...properties }`. A type left out, or given\n * as `null` or `undefined`, is dropped. Safe to call whenever the groups\n * might have changed: a `$groupidentify` is sent only for a group whose id\n * or properties differ from what was last sent, so repeating a call sends\n * nothing. An empty object behaves like `resetGroups()`.\n *\n * An id is a string or a finite number. A group given with any other id, or\n * with none, is an `INVALID_ARGUMENT` error for the whole call, and nothing\n * changes. Types and ids otherwise follow the rules of `group()`: a group\n * whose type or id those refuse is left out. Runs in call order with `identify()`, `reset()` and `signOut()`.\n */\n async setGroups(groups: Groups): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.setGroups(groups);\n const invalid = invalidGroups(groups);\n if (Option.isSome(invalid)) return Result.err(invalid.value);\n return this.enqueueInIdentityOrder(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\"setGroups\", await started.value.setGroups(groups));\n });\n }\n\n /** Takes the end user out of every group; later events carry no `$groups`. */\n async resetGroups(): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.resetGroups();\n return this.enqueueInIdentityOrder(async () => {\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\"resetGroups\", await started.value.resetGroups());\n });\n }\n\n /**\n * The groups the end user belongs to, by group type, as `group()` set them:\n * `{}` before `init()` resolves, while disabled, and when they belong to none.\n */\n getGroups(): Readonly<Record<string, string>> {\n const started = this.started();\n return this.setup.enabled && started.isOk() ? started.value.getGroups() : {};\n }\n\n /**\n * Evaluates feature flags for the current person, cache-first: `flagKeys`\n * (every flag when omitted), each with its enabled state, variant key\n * (`null` without a variant) and payload. Returns no flags while disabled.\n */\n async getFeatureFlags(\n flagKeys?: ReadonlyArray<FeatureFlagKey>,\n ): Promise<Result<FeatureFlagsResult, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(DISABLED_FEATURE_FLAGS);\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.getFeatureFlags(flagKeys);\n }\n\n /**\n * The value of the variant flag `key` selected for the current person: the\n * variant's value when the flag is enabled and evaluated, `null` when it is\n * off, has no variant (or one whose value is not text), is unknown, or was\n * not evaluated within `featureFlags.maxWaitMs`. Evaluates `key`\n * cache-first, as `getFeatureFlags([key])` does. Answers `Ok(null)` while\n * disabled. Typed by the variant values `voidhash.gen.d.ts` lists for the\n * flag; a variant added since generation is not in that union.\n */\n async getVariantValue<K extends FeatureFlagKey>(\n key: K,\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK method consumed by non-Effect app code; `null` is the documented \"no variant\" answer.\n ): Promise<Result<FeatureFlagValue<K> | null, VoidhashError>> {\n const evaluation = await this.getFeatureFlags([key]);\n return evaluation.map(({ flags }) => {\n const flag = flags.find((candidate) => candidate.key === key);\n return flag?.enabled === true && P.isString(flag.payload) ? flag.payload : null;\n });\n }\n\n /**\n * Resolves the currently assigned paywall showing for a location slug.\n * Answers `Ok(null)` while disabled.\n */\n async getPaywallForLocation(\n locationSlug: LocationSlug,\n ): Promise<Result<ResolvedPaywall, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(null);\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.getPaywallForLocation(String(locationSlug));\n }\n\n /**\n * The products the store sells this end user, sorted by slug, with the\n * offers they can buy them with. With `slugs`, the products those slugs\n * name, in that order: `undefined` where the store has none, which the\n * `onDiagnostic` handler hears about as `PRODUCT_NOT_FOUND`. With the types\n * `voidhash-cli types generate` writes, each is typed by its slug, so a\n * subscription's slug is a `SubscriptionProduct`.\n *\n * One load serves every caller and every `useProducts()`; it runs again\n * after an identity change, a completed purchase or new product\n * definitions. Answers no products while disabled.\n */\n getProducts(): Promise<Result<ReadonlyArray<Product>, VoidhashError>>;\n getProducts<const Slugs extends ReadonlyArray<ProductSlug>>(\n slugs: Slugs,\n ): Promise<Result<ProductsForSlugs<Slugs>, VoidhashError>>;\n async getProducts(\n slugs?: ReadonlyArray<ProductSlug>,\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n ): Promise<Result<ReadonlyArray<Product | undefined>, VoidhashError>> {\n if (!this.setup.enabled) {\n return Result.ok(slugs === undefined ? [] : slugs.map(() => undefined));\n }\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return (await started.value.loadProducts()).map((products) =>\n slugs === undefined\n ? products\n : slugs.map((slug) => products.find((product) => product.slug === slug)),\n );\n }\n\n /**\n * Buys a product from `getProducts()` or `useProducts()`. By default a\n * subscription comes with the free trial or introductory price the end\n * user is eligible for; `options.offer` picks another offer or the regular\n * price. Resolves to a `Result`: `purchased`, `pending` and `cancelled` are\n * outcomes, every failure is an `Err` carrying a coded\n * {@link VoidhashError}. Answers `Ok({ status: \"disabled\" })` while\n * disabled.\n *\n * Waits for `init()`. One purchase runs at a time: another started while\n * it runs fails with `PURCHASE_IN_PROGRESS` and buys nothing. Blocked in\n * observer mode; the mode in effect when the purchase starts decides, so a\n * `setReadOnly()` landing later doesn't abandon it. Options no store could\n * honour are an `INVALID_ARGUMENT` error, and nothing is bought.\n */\n async purchase(\n product: Product,\n options: PurchaseOptions = {},\n ): Promise<Result<PurchaseResult, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok({ status: \"disabled\" });\n const slug: unknown = P.hasProperty(product, \"slug\") ? product.slug : undefined;\n if (!isNonBlankString(slug)) {\n return Result.err(\n new InvalidArgumentError(\"purchase() needs a product from getProducts() or useProducts()\"),\n );\n }\n const nativeOptions = toNativePurchaseOptions(product, options);\n if (EffectResult.isFailure(nativeOptions)) return Result.err(nativeOptions.failure);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.purchase(product, options);\n if (Option.isSome(this.purchaseInFlight)) return Result.err(new PurchaseInProgressError());\n const purchased = (async (): Promise<Result<PurchaseResult, VoidhashError>> => {\n const initialized = await this.whenInitialized();\n if (initialized.isErr()) return Result.err(initialized.error);\n if (this.readOnly) return Result.err(new ReadOnlyModePurchaseNotAllowedError());\n return initialized.value.purchase(slug, nativeOptions.success);\n })().finally(() => {\n this.purchaseInFlight = Option.none();\n });\n this.purchaseInFlight = Option.some(purchased);\n return purchased;\n }\n\n /**\n * Revalidates restorable purchases for the user who requested the restore,\n * and answers the refreshed person, `null` when there is none, so a\n * \"nothing to restore\" needs no second read: check the person's\n * entitlements. Call from a user action: iOS may prompt for App Store\n * authentication. Known consumables are excluded. Waits for `init()`;\n * answers `Ok(null)` while disabled.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n async restorePurchases(): Promise<Result<Person | null, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(null);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.restorePurchases();\n const initialized = await this.whenInitialized();\n if (initialized.isErr()) return Result.err(initialized.error);\n const restored = await initialized.value.restorePurchases();\n return restored.isOk()\n ? restored\n : this.swallowed(\"restorePurchases\", Result.err(restored.error)).map(() => null);\n }\n\n /**\n * Calls `listener` with each purchase that completes outside `purchase()`:\n * an approved Ask to Buy, a pending payment that went through, a redeemed\n * offer code, a promoted purchase, and on iOS a renewal seen on the device\n * (`transaction.isRenewal`; Google Play does not report renewals to the\n * device). A purchase or restore made in a flow is not one: `presentFlow()`\n * answers it. It is called once the SDK handled the purchase; `synced`\n * says whether Voidhash already accepted it. A signal for the UI, not a\n * delivery guarantee: access always comes from the person's entitlements,\n * which hooks re-render with. Returns the function that removes the\n * listener. Never called while disabled.\n */\n addTransactionListener(listener: (update: TransactionUpdate) => void): () => void {\n const entry = (update: TransactionUpdate) => listener(update);\n MutableHashSet.add(this.transactionListeners, entry);\n return () => {\n MutableHashSet.remove(this.transactionListeners, entry);\n };\n }\n\n /**\n * Opens the store's subscription management: the App Store's sheet (for\n * `product`'s subscription group, on iOS 17 and later) or Google Play's\n * subscriptions page (for `product`, when given). No-op while disabled.\n */\n async showManageSubscriptions(product?: Product): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\n \"showManageSubscriptions\",\n await started.value.showManageSubscriptions(product?.slug),\n );\n }\n\n /**\n * Lets the end user redeem an offer code: Apple's redemption sheet (where\n * they type the code; `code` is ignored), or Google Play's redeem page\n * filled in with `code`. A redeemed code arrives as a transaction update.\n * No-op while disabled.\n */\n async presentCodeRedemption(code?: string): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return this.swallowed(\"presentCodeRedemption\", await started.value.presentCodeRedemption(code));\n }\n\n /**\n * The storefront the end user buys from: its ISO 3166-1 alpha-2 country,\n * and currency where the store says. `undefined` when the store has none to\n * give, and while disabled.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n async getStorefront(): Promise<Result<Storefront | undefined, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.getStorefront();\n }\n\n /**\n * Whether this device can make purchases: payments are not restricted (App\n * Store) and billing is available (Google Play). `false` while disabled.\n */\n async canMakePayments(): Promise<Result<boolean, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(false);\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return started.value.canMakePayments();\n }\n\n /**\n * Hands a purchase intent to the listeners, or holds it for the first one\n * while there is none: the native client sends intents from `init()` on,\n * possibly before the app added its listener.\n */\n private receivePurchaseIntent(intent: AppStorePurchaseIntent) {\n if (MutableHashSet.size(this.purchaseIntentListeners) > 0) {\n this.notify(\"appStore.addPurchaseIntentListener\", this.purchaseIntentListeners, intent);\n return;\n }\n this.heldPurchaseIntents.push(intent);\n if (this.heldPurchaseIntents.length <= MAX_HELD_PURCHASE_INTENTS) return;\n const dropped = this.heldPurchaseIntents.shift();\n this.emitDiagnostic({\n code: \"PURCHASE_INTENT_DROPPED\",\n kind: \"eviction\",\n message: `Dropped the purchase intent for \"${dropped?.productSlug}\": ${MAX_HELD_PURCHASE_INTENTS} are held until a listener is added`,\n operation: \"appStore.addPurchaseIntentListener\",\n retryable: false,\n });\n }\n\n /** App Store actions; see {@link AppStoreActions}. */\n readonly appStore: AppStoreActions = {\n addPurchaseIntentListener: (listener) => {\n const entry = (intent: AppStorePurchaseIntent) => listener(intent);\n MutableHashSet.add(this.purchaseIntentListeners, entry);\n const held = this.heldPurchaseIntents.splice(0);\n held.forEach((intent) => this.notify(\"appStore.addPurchaseIntentListener\", [entry], intent));\n return () => {\n MutableHashSet.remove(this.purchaseIntentListeners, entry);\n };\n },\n appTransaction: () =>\n this.storeAction(\n \"appStore\",\n \"appTransaction\",\n () => Result.err(new NotInitializedError()),\n (native) => native.appStoreAppTransaction(),\n ),\n beginRefundRequest: (transactionId) =>\n this.storeAction(\n \"appStore\",\n \"beginRefundRequest\",\n () => Result.err(new NotInitializedError()),\n (native) => native.appStoreBeginRefundRequest(transactionId),\n ),\n currentEntitlements: () =>\n this.storeAction(\n \"appStore\",\n \"currentEntitlements\",\n () => Result.ok([]),\n (native) => native.appStoreCurrentEntitlements(),\n ),\n subscriptionStatus: (groupId) =>\n this.storeAction(\n \"appStore\",\n \"subscriptionStatus\",\n () => Result.ok([]),\n (native) => native.appStoreSubscriptionStatus(groupId),\n ),\n };\n\n /** Google Play actions; see {@link GooglePlayActions}. */\n readonly googlePlay: GooglePlayActions = {\n isFeatureSupported: (feature) =>\n this.storeAction(\n \"googlePlay\",\n \"isFeatureSupported\",\n () => Result.ok(false),\n (native) => native.googlePlayIsFeatureSupported(feature),\n ),\n queryPurchases: (options = {}) =>\n this.storeAction(\n \"googlePlay\",\n \"queryPurchases\",\n () => Result.ok([]),\n (native) => native.googlePlayQueryPurchases(options.includeSuspended ?? true),\n ),\n showInAppMessages: () =>\n this.storeAction(\n \"googlePlay\",\n \"showInAppMessages\",\n () => Result.ok({ status: \"noActionNeeded\" }),\n (native) => native.googlePlayShowInAppMessages(),\n ),\n };\n\n /**\n * Runs an action of one store: `UNSUPPORTED_PLATFORM` on the other\n * platform, `whileDisabled` on a disabled client, and\n * `VOIDHASH_CLIENT_NOT_INITIALIZED` before `init()`.\n */\n private async storeAction<A>(\n store: \"appStore\" | \"googlePlay\",\n operation: string,\n whileDisabled: () => Result<A, VoidhashError>,\n run: (native: NativeClientAdapter) => Promise<Result<A, VoidhashError>>,\n ): Promise<Result<A, VoidhashError>> {\n const platform = store === \"appStore\" ? \"ios\" : \"android\";\n if (this.setup.platform !== platform) {\n return Result.err(\n new UnsupportedPlatformError(\n this.setup.platform,\n `${store}.${operation}() is available on ${store === \"appStore\" ? \"iOS\" : \"Android\"} only`,\n ),\n );\n }\n if (!this.setup.enabled) return whileDisabled();\n const started = this.started();\n if (started.isErr()) return Result.err(started.error);\n return run(started.value);\n }\n\n /** Calls every listener with `value`; one that throws is reported and the others still run. */\n private notify<A>(operation: string, listeners: Iterable<(value: A) => void>, value: A) {\n Array.from(listeners).forEach((listener) => {\n // oxlint-disable-next-line effect/avoid-try-catch -- boundary with host application code: the listener is a plain function the app supplies and may throw anything.\n try {\n listener(value);\n } catch (error) {\n this.reportHostCallbackFailure(operation, error);\n }\n });\n }\n\n /**\n * Presents the flow assigned to a location and resolves once it ends, with\n * its `outcome` (`purchased`, `restored`, `dismissed`, or the outcome the\n * flow finished with), its `output` and the `productId` of a purchase.\n *\n * `options.input` are the flow's inputs and `options.actions` a handler per\n * app action the flow can call; a handler that throws or rejects makes the\n * flow run that action's failure path. `options.revision` is the interface\n * revision the app was built against, by default the one the\n * `flowRevisions` option sets for the location.\n *\n * Rejects with a {@link VoidhashError} when the flow cannot be shown; its\n * `code` says why (`FLOW_NOT_ASSIGNED`, `FLOW_UNAVAILABLE`,\n * `FLOW_RENDERER_MISSING`, …).\n *\n * The location's assignment is served from cache when the server cannot be\n * reached. Purchases started from the flow go through the SDK's purchase\n * path, so observer mode blocks them and the flow shows the failure. A flow\n * already on screen is closed first and resolves as `dismissed`.\n */\n presentFlow<const L extends LocationSlug>(\n location: L,\n ...args: PresentFlowArguments<L>\n ): Promise<FlowResult<L>>;\n async presentFlow(location: string, options?: PresentFlowOptions): Promise<FlowResult> {\n if (!this.setup.enabled) throw flowError(\"FLOW_DISABLED\", \"Voidhash is disabled\");\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.presentFlow(location, options);\n const initialized = await this.whenInitialized();\n if (initialized.isErr()) throw flowError(\"FLOW_UNAVAILABLE\", initialized.error.message);\n return initialized.value.presentFlow(location, options);\n }\n\n /**\n * Changes inputs of the flow on screen; inputs that are not named keep\n * their values. No-op when no flow is shown and while disabled.\n */\n updateFlowInput<L extends string = string>(values: Partial<FlowInput<L>>): Promise<void>;\n async updateFlowInput(values: FlowValues): Promise<void> {\n const started = this.started();\n if (!this.setup.enabled || started.isErr()) return;\n await started.value.updateFlowInput(values);\n }\n\n /**\n * Closes the flow on screen, if any; its `presentFlow()` resolves as\n * `dismissed`. No-op while disabled.\n */\n async dismissFlow(): Promise<void> {\n const started = this.started();\n if (!this.setup.enabled || started.isErr()) return;\n await started.value.dismissFlow();\n }\n\n /**\n * Reports a purchase your own billing integration completed: its Apple\n * transaction (ID or JWS) or its Google Play token. Other purchase metadata\n * is optional and discarded. On iOS, a JWS is sent as the device's proof of\n * the purchase; with an ID only, the native SDK reads the JWS from the\n * device's purchase history.\n *\n * The report is a purchase the user just made: it goes to the current\n * user, even when an earlier purchase of the Apple Account or Google account\n * belongs to another user. Voidhash moves a purchase only when the store\n * shows it was made in the last 24 hours, and on iOS only with the JWS;\n * otherwise it is recorded for its current owner. A purchase is claimed\n * once from a device: reporting it again, also after another user signed\n * in, cannot move it.\n *\n * A report made after an `identify()`, `reset()` or `signOut()` that was\n * not awaited goes to the user that call switches to: it waits until the\n * device has switched, not for Voidhash to answer.\n *\n * Does not query, finish, acknowledge or consume the purchase. Pending\n * Android purchases are ignored; report them again when purchased.\n * Delivery failures remain queued for retry, so success does not imply\n * server acceptance.\n */\n async reportTransaction(\n transaction: StoreTransaction,\n options?: {\n /**\n * Reports a transaction your own restore flow returned after the user\n * asked to restore purchases. It is sent as an explicit restore, like\n * `restorePurchases()`, even when Voidhash accepted it before, and\n * keeps that intent across retries and relaunches: the project's paid\n * access sharing setting then decides whether a purchase another user\n * has is shared, moved or kept.\n */\n readonly isRestore?: boolean;\n },\n ): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) {\n return replacement.value.reportTransaction(transaction, options);\n }\n const report = EffectResult.try({\n catch: (error) =>\n new VoidhashError(\n \"FAILED_TO_REPORT_TRANSACTION\",\n `FAILED_TO_REPORT_TRANSACTION: ${P.isError(error) ? error.message : String(error)}`,\n { cause: error },\n ),\n try: () => toNativeReport(fromReportedTransaction(transaction)),\n });\n if (EffectResult.isFailure(report)) {\n return this.swallowed(\"reportTransaction\", Result.err(report.failure));\n }\n await this.afterIdentityChanges();\n const initialized = await this.whenInitialized();\n if (initialized.isErr()) return Result.err(initialized.error);\n return this.swallowed(\n \"reportTransaction\",\n await initialized.value.reportTransaction(report.success, options?.isRestore === true),\n );\n }\n\n /**\n * Reports pending purchases and current store entitlements to Voidhash.\n * Recovery fallback when a host callback exposes no transaction values. Prefer\n * reportTransaction for purchase results, especially consumables already finalized.\n * In observer mode transactions are never finished. Delivery failures stay\n * queued and emit diagnostics; success does not imply server acceptance.\n */\n async syncPurchases(): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const replacement = this.replacement();\n if (Option.isSome(replacement)) return replacement.value.syncPurchases();\n await this.afterIdentityChanges();\n const initialized = await this.whenInitialized();\n if (initialized.isErr()) return Result.err(initialized.error);\n return this.swallowed(\"syncPurchases\", await initialized.value.syncPurchases());\n }\n\n /**\n * Captures a product analytics event.\n * Events are batched and delivered on size/time thresholds. Dropped — not\n * buffered — while disabled or while analytics consent is not granted\n * (unless `analyticsWhilePending` holds them for a pending one).\n * Events captured before `init()` resolves are kept and sent once it has,\n * provided the analytics consent `init()` settles on (the one chosen with\n * `setAnalyticsConsent()`, else the stored one, else the option) is\n * `\"granted\"`; a consent other than `\"granted\"` chosen meanwhile discards them.\n *\n * An event captured after an `identify()`, `reset()` or `signOut()` that\n * was not awaited is recorded for the person that call switches to: it\n * waits, in memory, until the device has switched, not for Voidhash to\n * answer, and keeps the time it was captured at. That is a moment after\n * `identify()`, and up to about two seconds after a `signOut()` or\n * `reset()` of a signed-in user, whose last events are sent first. An\n * identity call runs after the identity, group and person calls made\n * before it have settled, so behind several of those the wait is as long\n * as they take, which on a slow network is seconds each. Past 100 events\n * waiting, the oldest is dropped and reported as `ANALYTICS_EVENT_DROPPED`;\n * `end()` hands the waiting ones over as they are.\n *\n * Property values are copied as the event is captured, into what JSON can\n * hold: a `bigint` is sent as its decimal string, a `Date` as its ISO\n * string, a non-finite number as `null`, and functions, symbols,\n * `undefined` and circular references are left out. An event whose\n * properties cannot be copied at all (more than 10,000 values, or a getter\n * that throws) is dropped and reported as `ANALYTICS_EVENT_DROPPED`. Never\n * throws.\n */\n capture(eventName: string, properties: Record<string, unknown> = {}) {\n if (!this.setup.enabled) return;\n const normalized = P.isString(eventName) ? eventName.trim() : \"\";\n if (!normalized) return;\n if (!this.awaitsIdentityChange()) {\n Option.map(this.analyticsIntake(\"capture\", normalized), (native) =>\n native.capture(normalized, properties),\n );\n return;\n }\n // Copied now and queued once the identity switched.\n const native = this.ended ? Option.none<NativeClientAdapter>() : this.nativeClient();\n if (Option.isNone(native)) {\n this.analyticsIntake(\"capture\", normalized);\n return;\n }\n Option.map(native.value.holdEvent(\"capture\", normalized, properties), (send) =>\n this.holdEventForIdentity(\"capture\", normalized, send),\n );\n }\n\n /**\n * Reports that the end user opened a notification, as `$push_opened` naming\n * its send. Call it from your notification library's opened-notification\n * handler, with the notification's data: the SDK has no notification handling\n * of its own. A notification not sent through Voidhash is ignored, and so is\n * one reported again right after its first report, as a handler that reads\n * the last opened notification on every mount does. Dropped while disabled or\n * while analytics consent is not granted. Never throws.\n */\n trackPushOpened(data?: Readonly<Record<string, unknown>>) {\n const sendId = data?.[PUSH_SEND_ID_DATA_KEY];\n if (!P.isString(sendId) || sendId.trim() === \"\") return;\n if (Option.contains(this.lastPushOpenedSendId, sendId)) return;\n this.lastPushOpenedSendId = Option.some(sendId);\n this.capture(AUTOMATIC_EVENTS.PUSH_OPENED, { [PUSH_SEND_ID_PROPERTY]: sendId });\n }\n\n /**\n * The native client an event for `name` can be handed to, or `None` when it\n * is dropped: without consent (reported once) unless the native client\n * holds it for a pending one, after `end()`, or without\n * the native module (each reported).\n *\n * Before the client has started only the native client can know the consent\n * stored on the device, so the event is handed over for it to keep or\n * discard at start, whatever the `analyticsConsent` option says. A consent\n * `setAnalyticsConsent()` chose in this process is the exception: it wins\n * over the stored one, so it decides here already.\n */\n private analyticsIntake(\n operation: \"capture\" | \"screen\",\n name: string,\n ): Option.Option<NativeClientAdapter> {\n const known = this._isInitialized\n ? Option.some(this.analyticsConsent)\n : this.chosenAnalyticsConsent;\n const isRefused = Option.exists(\n known,\n (consent) =>\n consent !== \"granted\" &&\n !(consent === \"pending\" && this.setup.analyticsWhilePending === \"buffer\"),\n );\n if (isRefused) {\n this.reportAnalyticsConsentDenied(operation);\n return Option.none();\n }\n const native = this.ended ? Option.none<NativeClientAdapter>() : this.nativeClient();\n if (Option.isNone(native)) {\n this.emitDiagnostic({\n code: \"ANALYTICS_EVENT_DROPPED\",\n kind: \"eviction\",\n message: this.ended\n ? `Dropped \"${name}\" — captured after end()`\n : `Dropped \"${name}\" — the Voidhash native module is missing`,\n operation,\n retryable: false,\n });\n }\n return native;\n }\n\n /**\n * Captures a `$screen` event for a screen the SDK cannot observe itself\n * (custom navigation, onboarding steps, pager pages). Every call is a new\n * screen instance, so calling it twice with the same name emits twice.\n * No-op while disabled or when `screenTracking.enabled` is `false`. Never\n * throws: a screen whose name is not a string, or that cannot be read, is\n * dropped and reported as `ANALYTICS_EVENT_DROPPED`.\n */\n screen(name: string, properties: Record<string, unknown> = {}) {\n this.manualScreenCounter += 1;\n // A name that is not a string is dropped below; it is kept out of the\n // identity because not every value has a text form.\n const identity = `${P.isString(name) ? name : \"\"}#${this.manualScreenCounter}`;\n this.trackScreenView({ identity, name, path: name, source: \"manual\" }, properties);\n }\n\n /**\n * Feeds a screen arrival observed by an integration through the screen\n * tracker and captures `$screen` when it is a new screen instance. Whether\n * the event may be recorded is settled first: a screen seen without consent\n * neither runs `mapScreen` nor becomes the previous screen of a later one.\n * Never throws: it runs inside the host's navigation listeners and effects, so a\n * screen that cannot be tracked is dropped and reported instead.\n * @internal\n */\n trackScreenView(view: ScreenView, properties: Record<string, unknown> = {}) {\n if (!this.setup.enabled || this.setup.screenTracking.enabled === false) return;\n const failure = isTrackableScreen(view)\n ? Option.map(\n EffectResult.getFailure(\n EffectResult.try(() => {\n const native = this.analyticsIntake(\"screen\", view.name);\n if (Option.isNone(native)) return;\n const screenProperties = this.screenTracker.transition(view);\n if (Option.isNone(screenProperties)) return;\n // The tracker applied `mapScreen` and the include-params rule; the native\n // client records `$screen` with these properties as they are.\n const mappedName = screenProperties.value[SCREEN_PROPERTIES.NAME];\n const screenName = P.isString(mappedName) ? mappedName : view.name;\n const recorded = { ...properties, ...screenProperties.value };\n if (!this.awaitsIdentityChange()) {\n native.value.screen(screenName, recorded);\n return;\n }\n Option.map(native.value.holdEvent(\"screen\", screenName, recorded), (send) =>\n this.holdEventForIdentity(\"screen\", screenName, send),\n );\n }),\n ),\n (error) => (P.isError(error) ? error.message : \"it could not be read\"),\n )\n : Option.some(\"its identity, name or path is not a string\");\n if (Option.isSome(failure)) {\n this.emitDiagnostic({\n code: \"ANALYTICS_EVENT_DROPPED\",\n kind: \"eviction\",\n message: `Dropped a screen: ${failure.value}`,\n operation: \"screen\",\n retryable: false,\n });\n }\n }\n\n /**\n * Sends everything queued now: person writes (`identify()` links and\n * attributes) first, then store receipts and analytics events, and reports\n * the analytics outcome. Waits at most about two seconds; delivery goes on\n * past that. Events still waiting for an identity change to switch the\n * person are sent too: the flush starts once it has. Nothing is ever queued\n * while disabled, so this no-ops.\n */\n async flush(): Promise<Result<FlushResult, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok({ flushed: 0, pending: 0 });\n if (this.awaitsIdentityChange()) await this.afterIdentityChanges();\n if (Option.isSome(this.flushInFlight)) return this.flushInFlight.value;\n const started = this.started();\n if (started.isErr()) return Result.ok({ flushed: 0, pending: 0 });\n const inFlight = started.value.flush().finally(() => {\n this.flushInFlight = Option.none();\n });\n this.flushInFlight = Option.some(inFlight);\n return inFlight;\n }\n\n /** Clears the cached person snapshot. The next read refetches from the server. */\n async resetCache(): Promise<Result<void, VoidhashError>> {\n if (!this.setup.enabled) return Result.ok(undefined);\n const started = this.started();\n if (started.isErr()) return this.swallowed(\"resetCache\", Result.err(started.error));\n return this.swallowed(\"resetCache\", await started.value.resetCache());\n }\n\n /**\n * Internal surface used by the SDK's React bindings.\n * Not part of the public API — may change or disappear at any time.\n */\n readonly internal = {\n getAtomRegistry: () => this.atomRegistry,\n /** What flag `key` reads as while it has no evaluated value: its `featureFlags.defaults` entry, or `false`. */\n isFeatureEnabledByDefault: (key: string): boolean =>\n Option.getOrElse(R.get(this.setup.featureFlagDefaults, key), () => false),\n /**\n * What a purchase of `product` with `options` buys, as text: two\n * purchases with the same key buy the same product the same way. `None`\n * for options `purchase()` refuses.\n */\n purchaseKey: (product: Product, options: PurchaseOptions): Option.Option<string> =>\n Option.flatMap(EffectResult.getSuccess(toNativePurchaseOptions(product, options)), (native) =>\n encodeJson({ ...native, productSlug: product.slug }),\n ),\n getSchema: (): Option.Option<RuntimeSchema> =>\n this._isInitialized ? this.atomRegistry.get(schemaAtom) : Option.none(),\n getSuccessCallbackBaseUrl: () => `${this.setup.scheme}://voidhash/callback/success`,\n getErrorCallbackBaseUrl: () => `${this.setup.scheme}://voidhash/callback/error`,\n reportHostCallbackFailure: (operation: string, error: unknown) =>\n this.reportHostCallbackFailure(operation, error),\n };\n\n /** Reports an exception a callback the app supplied threw; the SDK carried on without it. */\n private reportHostCallbackFailure(operation: string, error: unknown) {\n this.emitDiagnostic({\n code: \"HOST_CALLBACK_FAILED\",\n kind: \"configuration\",\n message: `${operation} threw: ${P.isError(error) ? error.message : String(error)}`,\n operation,\n retryable: false,\n });\n }\n\n /**\n * Reports, once until consent is granted again, that analytics work was\n * skipped for lack of consent.\n */\n private reportAnalyticsConsentDenied(operation: string) {\n if (this.analyticsConsentDeniedReported) return;\n this.analyticsConsentDeniedReported = true;\n this.emitDiagnostic({\n code: \"ANALYTICS_CONSENT_DENIED\",\n kind: \"consent\",\n message: `Skipped ${operation}: analytics consent is \"${this.analyticsConsent}\", so no analytics are captured or sent until it is granted`,\n operation,\n retryable: false,\n });\n }\n}\n\n/** Convenience re-export to keep `ProductSlug` reachable from this module. */\nexport type { ProductSlug };\nexport type { AnalyticsConsent };\n","/**\n * Names of analytics events the SDK captures automatically on the user's\n * behalf. The leading `$` marks them as built-in/reserved — mirroring the\n * convention used for standardized properties (`$app_version`, `$platform`,\n * …) — so they can be told apart from custom product events captured via\n * `capture(...)`.\n */\nexport const AUTOMATIC_EVENTS = {\n /** First launch the SDK has seen on this install (no cached release). */\n APP_INSTALLED: \"$app_installed\",\n /** Launch where the app build/version differs from the last seen one. */\n APP_UPDATED: \"$app_updated\",\n /** Every SDK startup, after install/update has been resolved. */\n APP_OPENED: \"$app_opened\",\n /** App moved to the background. */\n APP_BACKGROUNDED: \"$app_backgrounded\",\n /** App returned to the foreground from a non-active state. */\n APP_BECAME_ACTIVE: \"$app_became_active\",\n /** The app ended in a crash the system recorded, reported natively at a later launch. */\n APP_CRASHED: \"$app_crashed\",\n /** User signed out (identity reset triggered via `signOut`). */\n SIGN_OUT: \"$sign_out\",\n /** The user arrived on a screen (route, view controller, activity, …). */\n SCREEN: \"$screen\",\n /** The user opened a notification sent through Voidhash; see `client.trackPushOpened()`. */\n PUSH_OPENED: \"$push_opened\",\n} as const;\n\n/** The custom data key Voidhash adds to every notification it sends, holding its send's id. */\nexport const PUSH_SEND_ID_DATA_KEY = \"voidhash_send_id\";\n\n/** The `$push_opened` property naming the send. */\nexport const PUSH_SEND_ID_PROPERTY = \"push_notification_send_id\";\n\n/**\n * Property names stamped on the built-in `$screen` event. The `$` prefix\n * marks them as reserved, next to the standardized `$app_version`-style\n * properties every event carries.\n */\nexport const SCREEN_PROPERTIES = {\n /** Stable, low-cardinality identity of the screen (route pattern, route or class name). */\n NAME: \"$screen_name\",\n /** Concrete location, including dynamic segment values where the router has them. */\n PATH: \"$screen_path\",\n /** Human title when the platform exposes one. */\n TITLE: \"$screen_title\",\n /** `$screen_name` of the screen the user came from; `null` for the first screen. */\n PREVIOUS_NAME: \"$previous_screen_name\",\n /** `$screen_path` of the screen the user came from; `null` for the first screen. */\n PREVIOUS_PATH: \"$previous_screen_path\",\n /** Wall-clock milliseconds spent on the previous screen; `null` for the first screen. */\n PREVIOUS_DURATION_MS: \"$previous_screen_duration_ms\",\n /** Integration that produced the event (`expo-router`, `react-navigation`, `manual`, …). */\n SOURCE: \"$screen_source\",\n /** Route params, string-coerced and capped at 20 keys. Only with `includeParams`. */\n PARAMS: \"$screen_params\",\n} as const;\n","import * as Arr from \"effect/Array\";\n\n/**\n * Version of the on-device cache layout. Bumping it moves every entry to a new\n * namespace, so a future SDK release can change the envelope or key scheme\n * without having to recognise and migrate old entries one by one.\n */\nexport const CACHE_SCHEMA_VERSION = 1;\n\n/**\n * FNV-1a, 32-bit, over the UTF-8 bytes of `value`. Small, dependency-free and\n * stable across JS engines; the same digest the native SDKs derive, so the\n * embedded native client and this SDK land in one namespace on a device.\n */\nexport const hashCacheNamespace = (value: string) =>\n (\n Arr.reduce(Array.from(new TextEncoder().encode(value)), 0x811c9dc5, (hash, byte) =>\n Math.imul(hash ^ byte, 0x01000193),\n ) >>> 0\n )\n .toString(16)\n .padStart(8, \"0\");\n\n/**\n * Builds the storage-key prefix for one project on one host:\n * `vh:<cacheSchemaVersion>:<hash(publishableKey + baseUrl)>:`.\n *\n * Namespacing matters because on iOS the SDK's cache entries live in\n * `UserDefaults.standard`, which the host app also uses: unprefixed keys can\n * collide with the app's own. Keying by publishable key and base URL\n * additionally keeps a staging build's cache from being read by a production\n * one, on both platforms. The queues' record files are named after the same\n * namespace.\n */\nexport const buildCacheNamespace = (publishableKey: string, baseUrl: string) =>\n `vh:${CACHE_SCHEMA_VERSION}:${hashCacheNamespace(`${publishableKey}|${baseUrl}`)}:`;\n","{\n \"name\": \"@voidhash/react-native\",\n \"version\": \"0.5.0\",\n \"private\": false,\n \"description\": \"Voidhash React Native SDK for in-app purchases.\",\n \"keywords\": [\n \"expo\",\n \"nitro\",\n \"payments\",\n \"react-native\",\n \"sdk\",\n \"voidhash\"\n ],\n \"homepage\": \"https://voidhash.com/docs\",\n \"bugs\": {\n \"url\": \"https://github.com/voidhashcom/voidhash/issues\"\n },\n \"license\": \"MIT\",\n \"author\": \"Voidhash (https://voidhash.com)\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/voidhashcom/voidhash\",\n \"directory\": \"libraries/react-native\"\n },\n \"source\": \"src/index\",\n \"files\": [\n \"*.podspec\",\n \"app.plugin.js\",\n \"build\",\n \"nitrogen\",\n \"plugin/build\",\n \"react-native.config.js\",\n \"README.md\",\n \"src\",\n \"android/build.gradle\",\n \"android/CMakeLists.txt\",\n \"android/consumer-rules.pro\",\n \"android/gradle.properties\",\n \"android/src\",\n \"ios/**/*.cpp\",\n \"ios/**/*.h\",\n \"ios/**/*.m\",\n \"ios/**/*.mm\",\n \"ios/**/*.swift\"\n ],\n \"main\": \"build/index\",\n \"module\": \"build/index\",\n \"types\": \"build/index.d.ts\",\n \"react-native\": \"src/index\",\n \"exports\": {\n \"./app.plugin.js\": \"./app.plugin.js\",\n \"./package.json\": \"./package.json\",\n \"./expo-router\": {\n \"types\": \"./build/expo-router.d.ts\",\n \"react-native\": \"./src/expo-router.tsx\",\n \"default\": \"./build/expo-router.js\"\n },\n \"./metro\": {\n \"types\": \"./build/metro/index.d.ts\",\n \"node\": \"./build/metro/index.js\"\n },\n \"./react-navigation\": {\n \"types\": \"./build/react-navigation.d.ts\",\n \"react-native\": \"./src/react-navigation.tsx\",\n \"default\": \"./build/react-navigation.js\"\n },\n \".\": {\n \"types\": \"./build/index.d.ts\",\n \"react-native\": \"./src/index.ts\",\n \"default\": \"./build/index.js\"\n }\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n },\n \"scripts\": {\n \"typecheck\": \"tsrs --noEmit -p tsconfig.json\",\n \"test:types\": \"tsrs -p tests/types/tsconfig.sdk.json && tsrs --noEmit -p tests/types/tsconfig.json && tsrs --noEmit -p tests/types/untyped/tsconfig.json\",\n \"build\": \"expo-module build && tsrs -p tsconfig.metro.json && tsrs -p plugin/tsconfig.json && vp fmt plugin/build\",\n \"test\": \"vp test run -c vitest.unit.mts && pnpm run test:types\",\n \"test:artifact\": \"node ../../scripts/smoke-react-native-artifact.mjs\",\n \"test:android-engine\": \"ANDROID_HOME=\\\"${ANDROID_HOME:-$HOME/Library/Android/sdk}\\\" \\\"$(node -p \\\"require('node:path').dirname(require.resolve('@react-native/gradle-plugin/package.json'))\\\")/gradlew\\\" -p ../android :react-native-engine-tests:testDebugUnitTest --no-daemon\",\n \"test:android-purchase-coordinator\": \"\\\"$(node -p \\\"require('node:path').dirname(require.resolve('@react-native/gradle-plugin/package.json'))\\\")/gradlew\\\" -p android/coordinator-tests test --no-daemon\",\n \"test:storekit-purchase-coordinator\": \"swift test --package-path .\",\n \"test:storekit-simulator\": \"bash ios-storekit-tests/run-tests.sh\",\n \"clean\": \"rm -rf android/build node_modules/**/android/build lib\",\n \"lint\": \"vp check\",\n \"lint-ci\": \"vp check\",\n \"format\": \"vp check --fix\",\n \"typescript\": \"tsrs -p tsconfig.test.json --noEmit\",\n \"specs\": \"pnpm run typescript && nitrogen --logLevel=\\\"debug\\\"\"\n },\n \"dependencies\": {\n \"better-result\": \"3.0.1\",\n \"pathe\": \"^2.0.3\"\n },\n \"devDependencies\": {\n \"@effect/platform-node\": \"catalog:\",\n \"@effect/vitest\": \"catalog:\",\n \"@react-navigation/native\": \"^7.3.17\",\n \"@srsholmes/vitest-react-native\": \"^0.1.5\",\n \"@types/node\": \"^24.0.12\",\n \"@types/react\": \"~19.1.10\",\n \"@vitejs/plugin-react\": \"catalog:\",\n \"@voidhash/generated-clients\": \"workspace:*\",\n \"@voidhash/shared\": \"workspace:*\",\n \"expo\": \"54.0.33\",\n \"expo-module-scripts\": \"^5.0.8\",\n \"expo-router\": \"~55.0.18\",\n \"nitrogen\": \"0.37.1\",\n \"react\": \"19.1.0\",\n \"react-native\": \"0.81.5\",\n \"react-native-nitro-modules\": \"0.37.1\",\n \"typescript\": \"5.9.3\",\n \"vite-tsconfig-paths\": \"catalog:\",\n \"vitest\": \"catalog:\"\n },\n \"peerDependencies\": {\n \"@react-navigation/native\": \"*\",\n \"effect\": \"^4.0.7\",\n \"expo\": \"*\",\n \"expo-router\": \"*\",\n \"react\": \"*\",\n \"react-native\": \"*\",\n \"react-native-nitro-modules\": \"^0.37.1\"\n },\n \"peerDependenciesMeta\": {\n \"@react-navigation/native\": {\n \"optional\": true\n },\n \"expo\": {\n \"optional\": true\n },\n \"expo-router\": {\n \"optional\": true\n }\n },\n \"packageManager\": \"pnpm@10.19.0\"\n}\n","// A named import, so a bundler keeps just the version, not the whole manifest.\nimport { version } from \"../../package.json\";\n\n/** The published package version, reported as `x-sdk-version` and `$sdk_version`. */\nexport const SDK_VERSION: string = version;\n","import * as Option from \"effect/Option\";\n\n/**\n * Coarse category of a diagnostic, so hosts can route to logging versus\n * alerting without matching on individual codes.\n */\nexport type VoidhashDiagnosticKind =\n | \"transport\"\n | \"eviction\"\n | \"breaker\"\n | \"auth\"\n | \"cache\"\n | \"configuration\"\n | \"consent\";\n\n/**\n * A non-fatal event the SDK handled on its own. Diagnostics are informational:\n * every one of them describes a situation the SDK already recovered from\n * (retry scheduled, cache served, event evicted). They never require the host\n * app to act.\n */\nexport interface VoidhashDiagnostic {\n /** Category used for routing (logging vs. alerting). */\n readonly kind: VoidhashDiagnosticKind;\n /** Stable, machine-matchable identifier — see {@link DIAGNOSTIC_CODES}. */\n readonly code: string;\n /** SDK operation that produced the diagnostic (`capture`, `getPerson`, …). */\n readonly operation: string;\n /** Whether the SDK will try the same work again on its own. */\n readonly retryable: boolean;\n /** HTTP status behind the diagnostic, when there was a response. */\n readonly httpStatus?: number;\n /** Human-readable detail. Not stable; do not parse. */\n readonly message?: string;\n}\n\n/** Stable diagnostic codes emitted by the SDK. */\nexport const DIAGNOSTIC_CODES = {\n /**\n * An analytics event was dropped: evicted because the queue hit its cap,\n * refused by the ingest API with a verdict re-sending cannot change, or\n * captured with properties that could not be copied into JSON.\n */\n ANALYTICS_EVENT_DROPPED: \"ANALYTICS_EVENT_DROPPED\",\n /**\n * Analytics work (an event, a screen, an opened notification) was skipped\n * because analytics consent is not granted. Reported once until consent is\n * granted again.\n */\n ANALYTICS_CONSENT_DENIED: \"ANALYTICS_CONSENT_DENIED\",\n /** The publishable key was rejected; outbound traffic is paused. */\n AUTHENTICATION_FAILED: \"AUTHENTICATION_FAILED\",\n /** The store could not say which ad brought the install yet; a later launch asks again. */\n INSTALL_ATTRIBUTION_DEFERRED: \"INSTALL_ATTRIBUTION_DEFERRED\",\n /** The SDK stopped asking the store which ad brought the install, without an answer. */\n INSTALL_ATTRIBUTION_ABANDONED: \"INSTALL_ATTRIBUTION_ABANDONED\",\n /**\n * Device storage could not be read, or a stored entry could not be decoded.\n * An unreadable value counts as unknown, never as absent: the SDK does not\n * overwrite it. A corrupt entry is discarded and treated as a miss.\n */\n CACHE_READ_FAILED: \"CACHE_READ_FAILED\",\n /** A write to device storage failed; the value is still held in memory. */\n CACHE_WRITE_FAILED: \"CACHE_WRITE_FAILED\",\n /**\n * @deprecated No longer emitted: the SDK has no pre-namespace entries to\n * migrate. Kept so handlers that match on it still compile.\n */\n CACHE_MIGRATION_FAILED: \"CACHE_MIGRATION_FAILED\",\n /** The breaker for a host is open, so the request was skipped. */\n CIRCUIT_OPEN: \"CIRCUIT_OPEN\",\n /**\n * A callback the app handed the SDK threw (a `usePurchase` callback,\n * `screenTracking.mapScreen`, the `connectivity` source). The SDK carried on\n * without it: the purchase kept its result, the screen was tracked unmapped.\n */\n HOST_CALLBACK_FAILED: \"HOST_CALLBACK_FAILED\",\n /** A client option was invalid and the SDK fell back to its default (release builds only). */\n INVALID_CONFIGURATION: \"INVALID_CONFIGURATION\",\n /** A request failed and the SDK fell back to cache or a retry. */\n REQUEST_FAILED: \"REQUEST_FAILED\",\n /** A request exceeded the per-attempt timeout. */\n REQUEST_TIMEOUT: \"REQUEST_TIMEOUT\",\n /** A background task the SDK owns failed outright. */\n BACKGROUND_TASK_FAILED: \"BACKGROUND_TASK_FAILED\",\n /**\n * A product, perk or paywall location in the project schema could not be\n * read by this SDK version and was left out. Every other entry is still\n * served; updating the SDK makes the entry available.\n */\n SCHEMA_ENTRY_SKIPPED: \"SCHEMA_ENTRY_SKIPPED\",\n /**\n * A queued `identify` or person-attribute write was dropped because the\n * Voidhash API refused it with a verdict re-sending cannot change.\n */\n PERSON_WRITE_REJECTED: \"PERSON_WRITE_REJECTED\",\n /**\n * A product the project defines was not returned by the store, so\n * `getProducts()` and `useProducts()` leave it out. Reported once per\n * product per load; the message names its slug and the store's reason.\n * Check the store product id in Studio and the product's state in App Store\n * Connect or the Play Console.\n */\n PRODUCT_NOT_FOUND: \"PRODUCT_NOT_FOUND\",\n /**\n * The store sells a product as another type than Studio, such as a Studio\n * subscription the App Store sells as a non-renewing one or Google Play as\n * an in-app product, so `getProducts()` and `useProducts()` leave it out.\n * The message names its slug and both types.\n */\n PRODUCT_TYPE_MISMATCH: \"PRODUCT_TYPE_MISMATCH\",\n /**\n * iOS, with `purchaseIntents: \"manual\"`: more App Store purchase intents\n * arrived before any `appStore.addPurchaseIntentListener()` than the SDK\n * holds for it (10), so the oldest was dropped. The end user can start that\n * purchase again on the App Store.\n */\n PURCHASE_INTENT_DROPPED: \"PURCHASE_INTENT_DROPPED\",\n /** A queued transaction receipt was discarded as unsendable. */\n TRANSACTION_RECEIPT_DROPPED: \"TRANSACTION_RECEIPT_DROPPED\",\n /**\n * The Voidhash API refused a store receipt with a verdict re-sending cannot\n * change on its own: the store is not configured for this app, or the\n * transaction is unknown or belongs to another environment. The receipt\n * stays queued and is sent again at the next launch or after six hours.\n * Reported once per receipt.\n */\n TRANSACTION_REJECTED: \"TRANSACTION_REJECTED\",\n /**\n * Android: a purchase the SDK started was still not recorded by Voidhash 48\n * hours after its payment went through, so the background check acknowledged\n * it on the device before Google Play refunds it. The SDK still holds the\n * receipt and delivers it.\n */\n PURCHASE_FINISHED_BEFORE_SYNC: \"PURCHASE_FINISHED_BEFORE_SYNC\",\n /** A transaction receipt is waiting in the outbox for a successful sync. */\n TRANSACTION_SYNC_DEFERRED: \"TRANSACTION_SYNC_DEFERRED\",\n /**\n * iOS: what an earlier release of this package stored on the device was not\n * carried over, because the storage it was kept under doesn't match the\n * configured base URL. Reported once per start.\n */\n LEGACY_IMPORT_SKIPPED: \"LEGACY_IMPORT_SKIPPED\",\n} as const;\n\n/** Handler supplied through the `onDiagnostic` client option. */\n// oxlint-disable-next-line effect/prefer-option-over-null -- public SDK option consumed by non-Effect app code.\nexport type VoidhashDiagnosticHandler = (diagnostic: VoidhashDiagnostic) => void;\n\n/** Delivers diagnostics to an optional host handler, swallowing whatever it throws. */\nexport const makeDiagnosticEmitter =\n (handler: Option.Option<VoidhashDiagnosticHandler>) => (diagnostic: VoidhashDiagnostic) => {\n if (Option.isNone(handler)) return;\n // oxlint-disable-next-line effect/avoid-try-catch -- boundary with host application code: the handler is a plain callback the app supplies and may throw anything.\n try {\n handler.value(diagnostic);\n } catch {\n // A throwing host handler is never allowed to fail the SDK operation\n // that emitted the diagnostic.\n }\n };\n","import { Base64Url } from \"effect/encoding\";\nimport * as Result from \"effect/Result\";\nimport * as P from \"effect/Predicate\";\nimport * as Schema from \"effect/Schema\";\n\n/** Only the store identifier is required. Legacy metadata is accepted but discarded. */\nexport type ReportedTransaction = {\n productId?: string;\n purchaseDate?: number;\n quantity?: number;\n receipt?: string;\n appAccountToken?: string;\n} & (\n | { platform: \"ios\"; transactionId: string }\n | {\n platform: \"android\";\n purchaseToken: string;\n transactionId?: string;\n /** If supplied, pending/unspecified purchases are ignored until reported as purchased. */\n purchaseState?: \"purchased\" | \"pending\" | \"unspecified\";\n }\n);\n\n/** Original bridge data accepted as a convenience; only the token and state are read. */\nexport interface GooglePlayPurchaseData {\n readonly originalJson: string;\n readonly signature?: string;\n}\n\n/** Minimal store identifiers, or original store data from which the SDK extracts them. */\nexport type StoreTransaction = ReportedTransaction | string | GooglePlayPurchaseData;\n\n/** What Voidhash needs of a reported purchase: its store identifier and, on Google Play, its state. */\nexport type StoreReport =\n | {\n readonly platform: \"ios\";\n readonly transactionId: string;\n /** The JWS the report was made from, the proof a purchase or restore claim needs. */\n readonly signedTransaction?: string;\n }\n | {\n readonly platform: \"android\";\n readonly purchaseToken: string;\n readonly purchaseState?: \"purchased\" | \"pending\" | \"unspecified\";\n };\n\nconst identifier = Schema.String.check(Schema.isPattern(/\\S/));\nconst decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));\nconst decodeReport = Schema.decodeUnknownSync(\n Schema.Union([\n Schema.Struct({\n platform: Schema.Literal(\"ios\"),\n transactionId: identifier,\n signedTransaction: Schema.optional(identifier),\n }),\n Schema.Struct({\n platform: Schema.Literal(\"android\"),\n purchaseToken: identifier,\n purchaseState: Schema.optional(Schema.Literals([\"purchased\", \"pending\", \"unspecified\"])),\n }),\n ]),\n);\n\n// The server fetches the transaction with Apple by its ID; the JWS goes along as the device's\n// proof of a purchase or restore claim, so the native SDK need not look it up in the history.\nconst fromStoreKitJws = (jws: string): StoreReport => {\n const parts = jws.split(\".\");\n if (parts.length !== 3 || !parts[1]) throw new TypeError(\"Expected a StoreKit transaction JWS\");\n const payload = Schema.decodeUnknownSync(Schema.Struct({ transactionId: identifier }))(\n Result.match(Base64Url.decodeString(parts[1]), {\n onFailure: () => {\n throw new TypeError(\"Invalid StoreKit transaction encoding\");\n },\n onSuccess: decodeJson,\n }),\n );\n return { platform: \"ios\", signedTransaction: jws, transactionId: payload.transactionId };\n};\n\nconst fromPlayPurchase = (input: GooglePlayPurchaseData): ReportedTransaction => {\n const payload = Schema.decodeUnknownSync(\n Schema.Struct({\n token: Schema.optional(identifier),\n purchaseToken: Schema.optional(identifier),\n purchaseState: Schema.optional(Schema.Literals([0, 1, 4])),\n productIds: Schema.optional(Schema.Array(Schema.Unknown)),\n }),\n )(decodeJson(input.originalJson));\n if (payload.productIds && payload.productIds.length > 1) {\n throw new TypeError(\"Multi-product purchases are not supported\");\n }\n const token = payload.token ?? payload.purchaseToken;\n if (!token) throw new TypeError(\"A Google Play purchase token is required\");\n return {\n platform: \"android\",\n purchaseToken: token,\n purchaseState: payload.purchaseState === 4 ? \"pending\" : \"purchased\",\n };\n};\n\n/**\n * Extracts only the store identifiers of a purchase another billing\n * integration reported, leaving its finalization with that integration.\n * Throws for input that names no purchase.\n */\nexport const fromReportedTransaction = (input: StoreTransaction): StoreReport =>\n decodeReport(\n P.isString(input)\n ? fromStoreKitJws(input)\n : input && \"originalJson\" in input\n ? fromPlayPurchase(input)\n : input,\n );\n","import * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\n\nimport { VoidhashError, type VoidhashErrorCode } from \"../../errors\";\nimport type { FlowActions, FlowInput, FlowOutcome, FlowOutput } from \"../schema/registry\";\n\n/**\n * What an app lets its flows do, granted at SDK setup. Purchases, restores,\n * closing and analytics need no grant; an action needing a capability the\n * app did not grant is dropped with a warning.\n *\n * - `notifications`: ask the user to allow notifications.\n * - `tracking`: ask the user to allow tracking (App Tracking Transparency on iOS).\n * - `attributes`: set attributes on the current person.\n * - `links`: open links outside the app.\n */\nexport type FlowCapability = \"notifications\" | \"tracking\" | \"attributes\" | \"links\";\n\n/**\n * Which flow runtime draws flows, for the whole app process.\n *\n * - `linked`: the runtime built into the SDK (the default).\n * - `module`: the flow runtime module each flow names, which the SDK\n * downloads once, verifies and caches, so flows can use flow editor\n * features newer than the SDK. Not yet recommended for production.\n */\nexport type FlowRuntime = \"linked\" | \"module\";\n\n/**\n * What a paywall shows while it waits for the network: `standard` (the default),\n * the native SDK's loading screen 0.4 seconds after `presentFlow`, which the end\n * user can close; `none`, the app's screen as it is until the paywall is shown.\n */\nexport type FlowLoading = \"standard\" | \"none\";\n\n/** Capabilities granted when `flowCapabilities` is not set. */\nexport const DEFAULT_FLOW_CAPABILITIES: ReadonlyArray<FlowCapability> = [\"links\"];\n\n/** Codes of the errors a failed flow presentation carries. */\nexport type FlowErrorCode = Extract<VoidhashErrorCode, `FLOW_${string}`>;\n\n/**\n * How a presented flow ended.\n *\n * - `outcome`: `purchased` when a purchase ended the flow, `restored` when a\n * restore did, `dismissed` when the user or the app closed it or another\n * flow replaced it; otherwise the outcome the flow finished with.\n * - `output`: the flow's outputs by name; empty when it declares none.\n * - `productId`: the store product bought, when the outcome is `purchased`.\n *\n * A flow that could not be presented is not a result: `presentFlow()` rejects.\n */\nexport interface FlowResult<L extends string = string> {\n readonly outcome: FlowOutcome<L>;\n readonly output: FlowOutput<L>;\n readonly productId?: string;\n /**\n * `false` when the presentation ended before the paywall reached the screen,\n * with the outcome `dismissed`: the end user closed the loading screen, or the\n * app dismissed it or presented another paywall while it loaded. Absent from\n * native SDKs that do not report it; read absent as `true`.\n */\n readonly wasShown?: boolean;\n}\n\ntype RequiredWhenNotEmpty<Key extends string, Value> =\n Record<never, never> extends Value\n ? { readonly [K in Key]?: Value }\n : { readonly [K in Key]: Value };\n\n/**\n * What an app passes to one presentation of the flow at location `L`.\n *\n * - `input`: the flow's inputs by name.\n * - `actions`: a handler per app action the flow can call.\n * - `revision`: the interface revision the app was built against. Leave it\n * out to use the one set for the location in the `flowRevisions` option.\n */\nexport type PresentFlowOptions<L extends string = string> = {\n readonly revision?: number;\n} & RequiredWhenNotEmpty<\"input\", FlowInput<L>> &\n RequiredWhenNotEmpty<\"actions\", FlowActions<L>>;\n\n/**\n * The arguments of a presentation after its location: the options are\n * required when the location's flow has required inputs or app actions.\n */\nexport type PresentFlowArguments<L extends string = string> =\n Record<never, never> extends PresentFlowOptions<L>\n ? [options?: PresentFlowOptions<L>]\n : [options: PresentFlowOptions<L>];\n\n/** The error a presentation that could not be shown rejects with. */\nexport const flowError = (code: FlowErrorCode, message: string): VoidhashError =>\n new VoidhashError(code, `${code}: ${message}`);\n\nconst NativeFlowValue = Schema.Union([\n Schema.String,\n Schema.Number,\n Schema.Boolean,\n Schema.Array(Schema.String),\n]);\n\nconst NativeFlowResult = Schema.Union([\n Schema.Struct({\n outcome: Schema.String,\n output: Schema.Record(Schema.String, NativeFlowValue),\n productId: Schema.optional(Schema.String),\n wasShown: Schema.optional(Schema.Boolean),\n }),\n Schema.Struct({\n failure: Schema.Struct({\n code: Schema.Literals([\n \"FLOW_DISABLED\",\n \"FLOW_NOT_ASSIGNED\",\n \"FLOW_UNAVAILABLE\",\n \"FLOW_RENDERER_MISSING\",\n \"FLOW_UNSUPPORTED_PACKAGE\",\n \"FLOW_PRODUCTS_UNAVAILABLE\",\n \"FLOW_PRESENTATION_FAILED\",\n ]),\n message: Schema.String,\n }),\n }),\n]);\n\nconst decodeNativeFlowResult = Schema.decodeUnknownResult(Schema.fromJsonString(NativeFlowResult));\n\n/**\n * Reads the answer of the native coordinator: how the flow ended, or the\n * error of a flow that could not be presented. An answer this SDK does not\n * understand (a native module from another SDK version) is such an error too.\n */\nexport const parseFlowResult = (json: string): Result.Result<FlowResult, VoidhashError> => {\n const decoded = decodeNativeFlowResult(json);\n if (Result.isFailure(decoded)) {\n return Result.fail(flowError(\"FLOW_PRESENTATION_FAILED\", `unreadable flow result ${json}`));\n }\n const native = decoded.success;\n // The native message already starts with its code.\n if (\"failure\" in native) {\n return Result.fail(new VoidhashError(native.failure.code, native.failure.message));\n }\n return Result.succeed({\n outcome: native.outcome,\n output: native.output,\n ...(native.productId === undefined ? {} : { productId: native.productId }),\n ...(native.wasShown === undefined ? {} : { wasShown: native.wasShown }),\n });\n};\n","import { Result } from \"better-result\";\nimport * as Arr from \"effect/Array\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Match from \"effect/Match\";\nimport * as MutableRef from \"effect/MutableRef\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\nimport * as R from \"effect/Record\";\nimport * as EffectResult from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { Atom, type AtomRegistry } from \"effect/reactivity\";\n\nimport type {\n CurrentPersonResult,\n FlushResult,\n HasPerkResult,\n IdentifyResult,\n SetPersonAttributesResult,\n} from \"../../client\";\nimport {\n NotInitializedError,\n VOIDHASH_ERROR_CODES,\n VoidhashError,\n type VoidhashErrorCode,\n type VoidhashErrorReason,\n} from \"../../errors\";\nimport type {\n NativeAnalyticsConsent,\n NativeClientConfiguration,\n NativeClientEvent,\n NativeDiagnostic,\n NativeFeatureFlag,\n NativeFeatureFlagsResult,\n NativeFlushStatus,\n NativeFreshnessReason,\n NativeIdentityChange,\n NativePersonState,\n NativePersonWriteResult,\n NativePurchaseOptions,\n NativeReportedTransaction,\n NativeStorefront,\n VoidhashNativeClient,\n} from \"../../specs/VoidhashNativeClient.nitro\";\nimport { toJsonSafeProperties } from \"../analytics/json-safe\";\nimport type { VoidhashDiagnostic } from \"../diagnostics/diagnostics\";\nimport { findActiveGrant } from \"../entitlements/find-grant\";\nimport {\n type AppStorePurchaseIntent,\n type AppStoreSubscriptionStatus,\n type AppTransaction,\n decodeAppStoreRenewalInfo,\n decodeAppTransaction,\n type RefundRequestStatus,\n} from \"../entities/app-store\";\nimport type { GooglePlayInAppMessageResult } from \"../entities/google-play\";\nimport { decodePerson, type Person } from \"../entities/person\";\nimport type { Product } from \"../entities/product\";\nimport type { TransactionUpdate } from \"../entities/transaction\";\nimport {\n flowError,\n type FlowErrorCode,\n type FlowResult,\n parseFlowResult,\n type PresentFlowOptions,\n} from \"../flows/flows\";\nimport type {\n FeatureFlagsResult,\n GroupProperties,\n Groups,\n PersonAttributes,\n ResolvedPaywall,\n SdkFeatureFlag,\n} from \"../facade-types\";\nimport {\n currentPersonAtom,\n currentPersonFreshnessAtom,\n featureFlagsByKeyAtom,\n identityEpochAtom,\n NO_PRODUCTS,\n normalizeFeatureFlagKeys,\n productsAtom,\n publishCurrentPerson,\n schemaAtom,\n UNCONFIRMED_PERSON,\n} from \"../reactivity/client-state\";\nimport type { FlowValues, PerkSlug } from \"../schema/registry\";\nimport { decodeRuntimeSchema } from \"../schema/decode\";\nimport { type AnalyticsConsent, isAnalyticsConsent } from \"../sdk-configuration\";\nimport { readNativeError } from \"../utils/native-error\";\nimport { type StorePurchaseResult, toProduct, toPurchaseResult, toTransaction } from \"./billing\";\n\n/**\n * The members every Nitro hybrid object has (`HybridObject` in both Nitro\n * generations), which the adapter never calls. Named here rather than taken\n * from a Nitro package, so the facade's types do not depend on which Nitro\n * the host app runs.\n */\ntype HybridObjectMember = \"__type\" | \"name\" | \"toString\" | \"equals\" | \"dispose\";\n\n/**\n * The hybrid as the adapter uses it: its members without Nitro's own object\n * plumbing, so tests can hand in an in-memory implementation.\n */\nexport type NativeClientPort = Omit<VoidhashNativeClient, HybridObjectMember>;\n\n/** What the adapter reports to and through, besides the hybrid itself. */\nexport interface NativeClientAdapterOptions {\n readonly native: NativeClientPort;\n /** The npm package the app installs, which a failure that needs a new native build names. */\n readonly packageName: string;\n /** The client's registry; the hooks read the atoms the adapter writes into it. */\n readonly atomRegistry: AtomRegistry.AtomRegistry;\n /** Receives every native diagnostic; the facade's `onDiagnostic` dispatch. */\n readonly onDiagnostic: (diagnostic: VoidhashDiagnostic) => void;\n /**\n * Called when the native client switched to another identity, as soon as it\n * says so: the events it is handed from here on are recorded under it.\n */\n readonly onIdentitySwitched?: () => void;\n /** Called when the analytics consent in effect changes natively, including at start. */\n readonly onAnalyticsConsentChanged?: (consent: AnalyticsConsent) => void;\n /** Receives each purchase the native client completed outside `purchase()`. */\n readonly onTransaction?: (update: TransactionUpdate) => void;\n /** Receives each App Store purchase intent, with `purchaseIntents: \"manual\"`. */\n readonly onPurchaseIntent?: (intent: AppStorePurchaseIntent) => void;\n}\n\n/**\n * The version of the contract in `VoidhashNativeClient.nitro.ts` this facade\n * speaks; the native client's `contractVersion()` must answer the same.\n */\nexport const NATIVE_CONTRACT_VERSION = 1;\n\n/**\n * The contract version `native` implements: 0 for a binary built before\n * `contractVersion()` existed, whose hybrid has no such member, and for one\n * that answers no number.\n */\nconst contractVersionOf = (native: NativeClientPort): number => {\n const version = EffectResult.try(() =>\n P.isFunction(Reflect.get(native, \"contractVersion\")) ? native.contractVersion() : 0,\n );\n return EffectResult.isSuccess(version) && P.isNumber(version.success) ? version.success : 0;\n};\n\n/** Native codes for a client that is not started, the facade's `VOIDHASH_CLIENT_NOT_INITIALIZED`. */\nconst NOT_STARTED_CODES: ReadonlyArray<string> = [\"NOT_INITIALIZED\", \"NOT_CONFIGURED\"];\n\n/**\n * How one facade method reports a native failure: under its own code, except\n * for the codes it reports today, which pass through.\n */\ninterface FailureCodes {\n readonly fallback: VoidhashErrorCode;\n /** Codes the facade method reports today besides `fallback`. */\n readonly passThrough?: ReadonlyArray<VoidhashErrorCode>;\n /**\n * Whether a client that is not started is reported as\n * `VOIDHASH_CLIENT_NOT_INITIALIZED`, as every facade method but `init()`\n * does. Default `true`.\n */\n readonly notStarted?: boolean;\n}\n\n/**\n * Maps a native rejection to the error the facade method reports. The code\n * is read through the bridge's wrapping (`readNativeError`): a code the method\n * reports today keeps it, a client that is not started is the facade's\n * `NotInitializedError`, and anything else is reported as the method's own\n * code with the native message's first line kept, so no stack trace reaches\n * the app.\n */\nexport const toVoidhashError = (error: unknown, codes: FailureCodes): VoidhashError => {\n if (error instanceof VoidhashError) return error;\n const native = readNativeError(error);\n const code = Option.getOrElse(native.code, () => \"\");\n if ((codes.notStarted ?? true) && NOT_STARTED_CODES.includes(code)) {\n return new NotInitializedError();\n }\n const passing = Arr.findFirst(codes.passThrough ?? [], (known) => known === code);\n return Option.match(passing, {\n onNone: () =>\n new VoidhashError(codes.fallback, `${codes.fallback}: ${native.message}`, { cause: error }),\n onSome: (known) => new VoidhashError(known, native.message, { cause: error }),\n });\n};\n\n/** What every facade method below reports, keyed by the method. */\nconst FAILURES = {\n appStoreAppTransaction: {\n fallback: \"FAILED_TO_GET_APP_TRANSACTION\",\n passThrough: [\"UNSUPPORTED_PLATFORM\"],\n },\n appStoreBeginRefundRequest: {\n fallback: \"FAILED_TO_BEGIN_REFUND_REQUEST\",\n passThrough: [\"INVALID_ARGUMENT\", \"UNSUPPORTED_PLATFORM\"],\n },\n appStoreCurrentEntitlements: {\n fallback: \"FAILED_TO_GET_CURRENT_ENTITLEMENTS\",\n passThrough: [\"UNSUPPORTED_PLATFORM\"],\n },\n appStoreSubscriptionStatus: {\n fallback: \"FAILED_TO_GET_SUBSCRIPTION_STATUS\",\n passThrough: [\"UNSUPPORTED_PLATFORM\"],\n },\n canMakePayments: { fallback: \"FAILED_TO_CHECK_CAN_MAKE_PAYMENTS\" },\n dismissFlow: { fallback: \"FLOW_PRESENTATION_FAILED\" },\n updateFlowInput: { fallback: \"FLOW_PRESENTATION_FAILED\" },\n flush: { fallback: \"FAILED_TO_FLUSH_ANALYTICS\" },\n getCurrentPerson: {\n fallback: \"FAILED_TO_GET_CURRENT_PERSON\",\n passThrough: [\"AUTHENTICATION_FAILED\"],\n },\n getDistinctId: { fallback: \"FAILED_TO_GET_DISTINCT_ID\" },\n getFeatureFlags: {\n fallback: \"FAILED_TO_GET_FEATURE_FLAGS\",\n passThrough: [\"AUTHENTICATION_FAILED\"],\n },\n getPaywallForLocation: {\n fallback: \"FAILED_TO_GET_PAYWALL_FOR_LOCATION\",\n passThrough: [\"AUTHENTICATION_FAILED\", \"PAYWALL_UNAVAILABLE\"],\n },\n getProducts: { fallback: \"FAILED_TO_GET_PRODUCTS\" },\n getStorefront: { fallback: \"FAILED_TO_GET_STOREFRONT\" },\n googlePlayIsFeatureSupported: {\n fallback: \"FAILED_TO_CHECK_FEATURE_SUPPORT\",\n passThrough: [\"INVALID_ARGUMENT\", \"UNSUPPORTED_PLATFORM\"],\n },\n googlePlayQueryPurchases: {\n fallback: \"FAILED_TO_QUERY_PURCHASES\",\n passThrough: [\"UNSUPPORTED_PLATFORM\"],\n },\n googlePlayShowInAppMessages: {\n fallback: \"FAILED_TO_SHOW_IN_APP_MESSAGES\",\n passThrough: [\"UNSUPPORTED_PLATFORM\"],\n },\n group: { fallback: \"FAILED_TO_SET_GROUP\", passThrough: [\"INVALID_ARGUMENT\"] },\n setGroups: { fallback: \"FAILED_TO_SET_GROUP\", passThrough: [\"INVALID_ARGUMENT\"] },\n identify: { fallback: \"FAILED_TO_IDENTIFY\", passThrough: [\"INVALID_ARGUMENT\"] },\n presentCodeRedemption: { fallback: \"FAILED_TO_PRESENT_CODE_REDEMPTION\" },\n purchase: {\n fallback: \"FAILED_TO_PURCHASE\",\n passThrough: [\n \"INVALID_ARGUMENT\",\n \"OFFER_UNAVAILABLE\",\n \"PURCHASE_IN_PROGRESS\",\n \"READ_ONLY_PURCHASE_NOT_ALLOWED\",\n \"REPLACED_SUBSCRIPTION_NOT_OWNED\",\n \"SUBSCRIPTION_REPLACEMENT_REFUSED\",\n ],\n },\n reportTransaction: { fallback: \"FAILED_TO_REPORT_TRANSACTION\" },\n reset: { fallback: \"FAILED_TO_RESET\" },\n resetCache: { fallback: \"FAILED_TO_RESET_PERSON_CACHE\" },\n resetGroups: { fallback: \"FAILED_TO_RESET_GROUPS\" },\n restorePurchases: { fallback: \"FAILED_TO_RESTORE_PURCHASES\" },\n setAnalyticsConsent: { fallback: \"FAILED_TO_SET_ANALYTICS_CONSENT\" },\n setPersonAttributes: {\n fallback: \"FAILED_TO_SET_PERSON_ATTRIBUTES\",\n passThrough: [\"INVALID_ARGUMENT\"],\n },\n setPersonAttributesSync: {\n fallback: \"FAILED_TO_SET_PERSON_ATTRIBUTES_SYNC\",\n passThrough: [\"INVALID_ARGUMENT\", \"READ_ONLY_PURCHASE_NOT_ALLOWED\"],\n },\n showManageSubscriptions: { fallback: \"FAILED_TO_SHOW_MANAGE_SUBSCRIPTIONS\" },\n shutdown: { fallback: \"FAILED_TO_END_VOIDHASH_CLIENT\" },\n signOut: { fallback: \"FAILED_TO_SIGN_OUT\" },\n start: { fallback: \"FAILED_TO_INITIALIZE_VOIDHASH_CLIENT\", notStarted: false },\n syncPurchases: { fallback: \"FAILED_TO_SYNC_PURCHASES\" },\n} as const satisfies Record<string, FailureCodes>;\n\n/**\n * Runs one native call and answers it as the facade does: `Ok` with the\n * mapped value, or `Err` with the mapped error. A native call that throws\n * synchronously is a rejection like any other.\n */\nconst call = async <A>(\n codes: FailureCodes,\n run: () => Promise<A>,\n): Promise<Result<A, VoidhashError>> => {\n const exit = await Effect.runPromiseExit(\n Effect.tryPromise({ catch: (error) => error, try: () => run() }),\n );\n return Exit.isSuccess(exit)\n ? Result.ok(exit.value)\n : Result.err(toVoidhashError(Cause.squash(exit.cause), codes));\n};\n\n/** The native codes of a purchase the store refused for a reason, and the reason each is. */\nconst PURCHASE_FAILURE_REASONS: Readonly<Record<string, VoidhashErrorReason>> = {\n INELIGIBLE_FOR_OFFER: \"ineligibleForOffer\",\n PAYMENT_DECLINED: \"paymentDeclined\",\n};\n\nconst decodeJson = Schema.decodeUnknownResult(Schema.fromJsonString(Schema.Unknown));\nconst encodeJson = Schema.encodeUnknownResult(Schema.fromJsonString(Schema.Unknown));\n\nconst PaywallValue = Schema.declare(\n (value: unknown): value is ResolvedPaywall => value === null || P.isObject(value),\n);\nconst decodePaywall = Schema.decodeUnknownResult(PaywallValue);\n\n/** A person snapshot crossing as JSON; one that is absent or unreadable counts as none. */\nconst personOf = (payload: { readonly personJson?: string }): Option.Option<Person> =>\n Option.flatMap(Option.fromUndefinedOr(payload.personJson), decodePerson);\n\nconst REASONS: Readonly<Record<NativeFreshnessReason, CurrentPersonResult[\"reason\"]>> = {\n fresh: \"fresh\",\n noCache: \"no-cache\",\n refreshFailed: \"refresh-failed\",\n refreshInFlight: \"refresh-in-flight\",\n};\n\nconst toCurrentPerson = (state: NativePersonState): CurrentPersonResult => ({\n isExpired: state.isExpired,\n isStale: state.isStale,\n person: Option.getOrNull(personOf(state)),\n reason: REASONS[state.reason],\n});\n\nconst toFlag = (flag: NativeFeatureFlag): SdkFeatureFlag => ({\n enabled: flag.enabled,\n key: flag.key,\n payload: Option.getOrNull(\n Option.flatMap(Option.fromUndefinedOr(flag.payloadJson), (json) =>\n EffectResult.getSuccess(decodeJson(json)),\n ),\n ),\n variantKey: flag.variantKey ?? null,\n});\n\nconst toFlags = (result: NativeFeatureFlagsResult): FeatureFlagsResult => ({\n flags: result.flags.map(toFlag),\n isStale: result.isStale,\n});\n\nconst toDiagnostic = (diagnostic: NativeDiagnostic): VoidhashDiagnostic => ({\n code: diagnostic.code,\n kind: diagnostic.kind,\n operation: diagnostic.operation,\n retryable: diagnostic.retryable,\n ...(diagnostic.httpStatus === undefined ? {} : { httpStatus: diagnostic.httpStatus }),\n ...(diagnostic.message === undefined ? {} : { message: diagnostic.message }),\n});\n\nconst toFlushResult = (status: NativeFlushStatus): FlushResult => ({\n flushed: status.flushed,\n pending: status.pending,\n ...(status.lastErrorMessage === undefined\n ? {}\n : {\n lastError: new VoidhashError(\n \"FAILED_TO_FLUSH_ANALYTICS\",\n `FAILED_TO_FLUSH_ANALYTICS: ${status.lastErrorMessage}`,\n ),\n }),\n});\n\n/** Inputs, action arguments and action replies as the native side carries them. */\nconst FlowValuesFromJson = Schema.fromJsonString(\n Schema.Record(\n Schema.String,\n Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Array(Schema.String)]),\n ),\n);\nconst decodeFlowValues = Schema.decodeUnknownSync(FlowValuesFromJson);\nconst encodeFlowValues = Schema.encodeSync(FlowValuesFromJson);\n\n/** Whether a native code is one of the `FLOW_*` codes a presentation rejects with. */\nconst isFlowErrorCode = (code: string): code is FlowErrorCode =>\n code.startsWith(\"FLOW_\") && VOIDHASH_ERROR_CODES.some((known) => known === code);\n\n/**\n * The facade's view of the native Voidhash client: every method answers in\n * the facade's types (`Result` with a coded `VoidhashError`), and every native\n * state change lands in the reactive atoms the hooks read, so the hooks work\n * unchanged whichever side produced the state.\n *\n * The adapter follows the identity generation the native client last\n * announced, by event or in the answer of the call that switched it. A person\n * or flag answer, read or event, from any other generation is not published:\n * it belongs to a switch that has already been superseded, or to an earlier\n * run of the client (generations grow for the life of the process), even when\n * the identity has since switched back to the same distinct id. A read still\n * answers its caller with what it read.\n */\nexport const makeNativeClientAdapter = (options: NativeClientAdapterOptions) => {\n const { atomRegistry, native } = options;\n const currentIdentity = MutableRef.make(Option.none<NativeIdentityChange>());\n /** The generation person or flags were last published for; `-1` before any. */\n const publishedGeneration = MutableRef.make(-1);\n const listening = MutableRef.make(false);\n /**\n * Counts what made the products this client holds outdated: identity\n * switches, product definition changes, purchases and restores. A load\n * publishes only when nothing outdated it while it ran.\n */\n const productsRevision = MutableRef.make(0);\n const productsLoad = MutableRef.make(\n Option.none<{\n readonly revision: number;\n readonly settled: Promise<Result<ReadonlyArray<Product>, VoidhashError>>;\n }>(),\n );\n /** The reload `invalidateProducts()` scheduled for the next tick, until it starts. */\n const scheduledReload = MutableRef.make(Option.none<ReturnType<typeof setTimeout>>());\n /** The product definitions of the schema published last, encoded; empty before any. */\n const productDefinitions = MutableRef.make(\"\");\n\n /** The host's diagnostic handler, which must not take the adapter down with it. */\n const report = (diagnostic: VoidhashDiagnostic) => {\n EffectResult.try(() => options.onDiagnostic(diagnostic));\n };\n\n const cancelScheduledReload = () => {\n Option.map(MutableRef.get(scheduledReload), clearTimeout);\n MutableRef.set(scheduledReload, Option.none());\n };\n\n /**\n * Loads the products, one native call for every caller of the same\n * revision, and publishes them for the hooks. A load that an identity\n * switch, a schema change or a purchase outdated while it ran answers its\n * caller but publishes nothing: the load started for the new revision does.\n *\n * Never rejects: a product this SDK cannot read fails the load as\n * `FAILED_TO_GET_PRODUCTS`, like a native failure, and a settled load\n * never leaves the products loading.\n */\n const loadProducts = (): Promise<Result<ReadonlyArray<Product>, VoidhashError>> => {\n const revision = MutableRef.get(productsRevision);\n const running = MutableRef.get(productsLoad);\n if (Option.isSome(running) && running.value.revision === revision) {\n return running.value.settled;\n }\n // This load serves every change so far; a reload scheduled for them is not needed.\n cancelScheduledReload();\n atomRegistry.update(productsAtom, (state) => ({ ...state, isLoading: true }));\n const settled: Promise<Result<ReadonlyArray<Product>, VoidhashError>> = call(\n FAILURES.getProducts,\n async () =>\n Arr.getSomes(\n (await native.getProducts()).map((product) =>\n toProduct(product, (message) => reportContractViolation(\"getProducts\", message)),\n ),\n ),\n ).then((products) => {\n const isCurrent = MutableRef.get(productsRevision) === revision;\n if (Option.exists(MutableRef.get(productsLoad), (load) => load.settled === settled)) {\n MutableRef.set(productsLoad, Option.none());\n }\n if (isCurrent) {\n atomRegistry.update(productsAtom, (state) =>\n products.isOk()\n ? { error: Option.none(), isLoading: false, products: Option.some(products.value) }\n : { ...state, error: Option.some(products.error), isLoading: false },\n );\n } else if (\n Option.isNone(MutableRef.get(productsLoad)) &&\n Option.isNone(MutableRef.get(scheduledReload))\n ) {\n // Outdated, and no load for the new revision runs or is due.\n atomRegistry.update(productsAtom, (state) => ({ ...state, isLoading: false }));\n }\n return products;\n });\n MutableRef.set(productsLoad, Option.some({ revision, settled }));\n return settled;\n };\n\n /**\n * The products held are outdated. They load again when anything asked for\n * them before (otherwise the first `useProducts()` or `getProducts()` loads\n * them), on the next tick: changes that land together, such as an identity\n * switch and a schema, or several transactions, load once.\n */\n const invalidateProducts = () => {\n MutableRef.update(productsRevision, (revision) => revision + 1);\n if (Option.isSome(MutableRef.get(scheduledReload))) return;\n const state = atomRegistry.get(productsAtom);\n if (Option.isNone(state.products) && Option.isNone(state.error) && !state.isLoading) return;\n MutableRef.set(\n scheduledReload,\n Option.some(\n setTimeout(() => {\n MutableRef.set(scheduledReload, Option.none());\n void loadProducts();\n }, 0),\n ),\n );\n };\n\n const isCurrent = (generation: number) =>\n Option.exists(\n MutableRef.get(currentIdentity),\n (identity) => identity.generation === generation,\n );\n\n const publishPerson = (state: NativePersonState) => {\n if (!isCurrent(state.generation)) return;\n MutableRef.set(publishedGeneration, state.generation);\n publishCurrentPerson(atomRegistry, personOf(state), {\n isExpired: state.isExpired,\n isStale: state.isStale,\n });\n };\n\n /** Stores an evaluation under `signature`, the key set it is published for. */\n const publishFlags = (result: NativeFeatureFlagsResult, signature: string) => {\n if (!isCurrent(result.generation)) return;\n MutableRef.set(publishedGeneration, result.generation);\n atomRegistry.update(featureFlagsByKeyAtom, (current) => ({\n ...current,\n [signature]: toFlags(result),\n }));\n };\n\n /**\n * Adopts the identity the native client switched to. A switch clears the\n * person and every flag evaluation and counts in `identityEpochAtom`, so\n * mounted hooks read again for the new identity, as `IdentityManager` does\n * for the TypeScript core. A generation no newer than the current one (the\n * event of a switch whose answer was already adopted, say) changes nothing.\n */\n const adoptIdentity = (change: NativeIdentityChange) => {\n if (\n Option.exists(\n MutableRef.get(currentIdentity),\n (current) => current.generation >= change.generation,\n )\n ) {\n return;\n }\n MutableRef.set(currentIdentity, Option.some(change));\n options.onIdentitySwitched?.();\n Atom.batch(() => {\n atomRegistry.set(featureFlagsByKeyAtom, {});\n publishCurrentPerson(atomRegistry, Option.none(), UNCONFIRMED_PERSON);\n atomRegistry.update(identityEpochAtom, (switches) => switches + 1);\n });\n // Offers and intro eligibility are the end user's.\n invalidateProducts();\n };\n\n const reportContractViolation = (operation: string, message: string) =>\n report({\n code: \"BACKGROUND_TASK_FAILED\",\n kind: \"configuration\",\n message,\n operation,\n retryable: false,\n });\n\n /**\n * Publishes a schema event. Decoded entry by entry like a fetched schema:\n * an entry this SDK version cannot read is left out (the native client\n * reports it); a document that is no schema at all is reported and dropped.\n */\n const publishSchema = (schemaJson: string) => {\n const decoded = EffectResult.flatMap(decodeJson(schemaJson), (document) => {\n const exit = Effect.runSyncExit(decodeRuntimeSchema(document));\n return Exit.isSuccess(exit)\n ? EffectResult.succeed(exit.value.schema)\n : EffectResult.fail(Cause.squash(exit.cause));\n });\n if (EffectResult.isSuccess(decoded)) {\n atomRegistry.set(schemaAtom, Option.some(decoded.success));\n // Every refresh publishes a new schema; only changed product definitions outdate the products.\n const definitions = EffectResult.getOrElse(encodeJson(decoded.success.products), () => \"\");\n if (definitions !== MutableRef.get(productDefinitions)) {\n MutableRef.set(productDefinitions, definitions);\n invalidateProducts();\n }\n return;\n }\n reportContractViolation(\"getSchema\", \"The native client sent a schema this SDK cannot read\");\n };\n\n /** Routes one event; the event's `type` names the payload it carries. */\n const routeEvent = (event: NativeClientEvent) =>\n Match.value(event.type).pipe(\n Match.when(\"identity\", () =>\n Option.map(Option.fromUndefinedOr(event.identity), adoptIdentity),\n ),\n Match.when(\"person\", () => Option.map(Option.fromUndefinedOr(event.person), publishPerson)),\n Match.when(\"flags\", () =>\n Option.map(Option.fromUndefinedOr(event.flags), (flags) =>\n publishFlags(flags, normalizeFeatureFlagKeys(flags.flagKeys)),\n ),\n ),\n Match.when(\"schema\", () =>\n Option.map(Option.fromUndefinedOr(event.schemaJson), publishSchema),\n ),\n Match.when(\"consent\", () =>\n Option.map(Option.fromUndefinedOr(event.consent), (consent) =>\n options.onAnalyticsConsentChanged?.(consent),\n ),\n ),\n Match.when(\"diagnostic\", () =>\n Option.map(Option.fromUndefinedOr(event.diagnostic), (diagnostic) =>\n report(toDiagnostic(diagnostic)),\n ),\n ),\n Match.when(\"transaction\", () =>\n Option.map(Option.fromUndefinedOr(event.transaction), (update) => {\n // A completed purchase can change which offers the end user is eligible for; a\n // renewal of a subscription they already have cannot.\n if (update.transaction.isRenewal !== true) invalidateProducts();\n options.onTransaction?.({\n synced: update.synced,\n transaction: toTransaction(update.transaction, (message) =>\n reportContractViolation(\"transactionUpdates\", message),\n ),\n });\n }),\n ),\n Match.when(\"purchaseIntent\", () =>\n Option.map(Option.fromUndefinedOr(event.purchaseIntent), (intent) =>\n options.onPurchaseIntent?.({\n productSlug: intent.productSlug,\n ...(intent.offer === undefined ? {} : { offer: intent.offer }),\n }),\n ),\n ),\n Match.exhaustive,\n );\n\n /**\n * The listener handed to the native client. Whatever goes wrong while an\n * event is handled (a host callback or a hook's render throwing) is\n * reported as a diagnostic instead of escaping into the native bridge.\n */\n const handleEvent = (event: NativeClientEvent) => {\n if (!MutableRef.get(listening)) return;\n const handled = EffectResult.try(() => routeEvent(event));\n if (EffectResult.isFailure(handled)) {\n report({\n code: \"BACKGROUND_TASK_FAILED\",\n kind: \"configuration\",\n message: `Handling a native ${event.type} event failed: ${String(handled.failure)}`,\n operation: \"nativeEvent\",\n retryable: false,\n });\n }\n };\n\n /**\n * Reports a synchronous native call that threw. These calls answer no\n * `Result`, so the failure is a diagnostic rather than an exception that\n * would escape the facade.\n */\n const reportThrow = (operation: string, error: unknown) =>\n report({\n code: \"BACKGROUND_TASK_FAILED\",\n kind: \"configuration\",\n message: `${operation} failed: ${readNativeError(error).message}`,\n operation,\n retryable: false,\n });\n\n /** Runs a synchronous native call, reporting a throw; `None` when it threw. */\n const trySync = <A>(operation: string, run: () => A): Option.Option<A> => {\n const ran = EffectResult.try(run);\n if (EffectResult.isSuccess(ran)) return Option.some(ran.success);\n reportThrow(operation, ran.failure);\n return Option.none();\n };\n\n const stopListening = () => {\n MutableRef.set(listening, false);\n trySync(\"removeEventListener\", () => native.removeEventListener());\n };\n\n /** Reads the person and publishes it, unless the identity changed meanwhile. */\n const readPerson = (forceFetch: boolean) =>\n call(FAILURES.getCurrentPerson, async () => {\n const state = await native.getPersonState(forceFetch);\n publishPerson(state);\n return state;\n });\n\n /**\n * Switches the identity through the native client. The switch is adopted\n * from the answer as well as from the event, so the atoms follow it however\n * the two arrive. A switch the server refused leaves the native client back\n * on the previous identity; the person and flag evaluations held before the\n * call are then put back, as `IdentityManager` does for the TypeScript core,\n * unless something was already published for the generations since. An\n * identify of the current identity adopts nothing and leaves both alone.\n */\n const switchIdentity = async (\n externalUserId: string,\n profile: { email?: string; name?: string },\n ) => {\n const before = MutableRef.get(currentIdentity);\n const held = {\n flags: atomRegistry.get(featureFlagsByKeyAtom),\n freshness: atomRegistry.get(currentPersonFreshnessAtom),\n person: atomRegistry.get(currentPersonAtom),\n };\n const result = await call(FAILURES.identify, () =>\n native.identify(externalUserId, profile.email, profile.name),\n );\n if (result.isOk()) {\n adoptIdentity(result.value.identity);\n return result;\n }\n const after = MutableRef.get(currentIdentity);\n const restored =\n Option.isSome(before) &&\n Option.isSome(after) &&\n after.value.distinctId === before.value.distinctId &&\n after.value.generation > before.value.generation &&\n MutableRef.get(publishedGeneration) <= before.value.generation;\n if (restored) {\n Atom.batch(() => {\n atomRegistry.set(featureFlagsByKeyAtom, held.flags);\n publishCurrentPerson(atomRegistry, held.person, held.freshness);\n });\n }\n return result;\n };\n\n /** Resets or signs out, adopting the fresh identity from the answer too. */\n const switchToAnonymous = async (codes: FailureCodes, run: () => Promise<NativeIdentityChange>) =>\n (await call(codes, run)).map((identity) => {\n adoptIdentity(identity);\n return undefined;\n });\n\n const toAttributesResult = (result: NativePersonWriteResult): SetPersonAttributesResult => {\n const person = personOf(result);\n if (result.status === \"skipped\") return { person: null, status: \"skipped\" };\n return result.status === \"confirmed\" && Option.isSome(person)\n ? { person: person.value, status: \"confirmed\" }\n : { person: Option.getOrNull(person), status: \"deferred\" };\n };\n\n /**\n * Encodes person attributes for the bridge. Attributes JSON cannot hold\n * are an `INVALID_ARGUMENT`, never sent as something else.\n */\n const encodeAttributes = (attributes: PersonAttributes) =>\n Option.match(EffectResult.getSuccess(encodeJson(attributes)), {\n onNone: () =>\n Result.err(\n new VoidhashError(\n \"INVALID_ARGUMENT\",\n \"INVALID_ARGUMENT: person attributes must be values JSON can hold\",\n ),\n ),\n onSome: (json) => Result.ok(json),\n });\n\n /**\n * An event's (or a screen's) properties, copied into what JSON can hold as\n * the TypeScript core does. `None` for an event they cannot be copied for,\n * which is dropped and reported.\n */\n const encodeEvent = (\n operation: \"capture\" | \"screen\",\n name: string,\n properties: Record<string, unknown>,\n ): Option.Option<string> => {\n const json = EffectResult.flatMap(toJsonSafeProperties(properties), (copied) =>\n Option.match(EffectResult.getSuccess(encodeJson(copied)), {\n onNone: () => EffectResult.fail(\"cannot be encoded as JSON\"),\n onSome: (encoded) => EffectResult.succeed(encoded),\n }),\n );\n if (EffectResult.isFailure(json)) {\n report({\n code: \"ANALYTICS_EVENT_DROPPED\",\n kind: \"eviction\",\n message: `Dropped \"${name}\": its properties ${json.failure}`,\n operation,\n retryable: false,\n });\n return Option.none();\n }\n return Option.some(json.success);\n };\n\n // A binary built before `captureAt` and `screenAt` has neither; an event the\n // facade held back then takes the time it is handed over at.\n const takesCaptureTime =\n P.isFunction(Reflect.get(native, \"captureAt\")) && P.isFunction(Reflect.get(native, \"screenAt\"));\n\n /**\n * Queues an encoded event (or screen) through a synchronous native call,\n * at `capturedAt` for one the facade held back. A native call that throws\n * is reported: capturing never throws.\n */\n const sendEvent = (\n operation: \"capture\" | \"screen\",\n name: string,\n propertiesJson: string,\n capturedAt: Option.Option<number>,\n ) => {\n const sent = EffectResult.try(() => {\n if (Option.isSome(capturedAt) && takesCaptureTime) {\n if (operation === \"capture\") native.captureAt(name, propertiesJson, capturedAt.value);\n else native.screenAt(name, propertiesJson, capturedAt.value);\n return;\n }\n if (operation === \"capture\") native.capture(name, propertiesJson);\n else native.screen(name, propertiesJson);\n });\n if (EffectResult.isFailure(sent)) {\n report({\n code: \"ANALYTICS_EVENT_DROPPED\",\n kind: \"eviction\",\n message: `Dropped \"${name}\": ${readNativeError(sent.failure).message}`,\n operation,\n retryable: false,\n });\n }\n };\n\n return {\n /**\n * Configures and starts the native client, also again after `shutdown()`\n * (a re-init). The listener is attached first, so what `start()`\n * announces reaches the atoms. The identity a new run loads has a newer\n * generation than anything of the previous run, so a read the previous\n * run left pending is never published. A failed start detaches the\n * listener again.\n */\n start: async (\n configuration: NativeClientConfiguration,\n ): Promise<Result<void, VoidhashError>> => {\n // An over-the-air bundle onto a build made for another contract would misread every\n // answer: nothing of it is started.\n const version = contractVersionOf(native);\n if (version !== NATIVE_CONTRACT_VERSION) {\n return Result.err(\n new VoidhashError(\n \"FAILED_TO_INITIALIZE_VOIDHASH_CLIENT\",\n `FAILED_TO_INITIALIZE_VOIDHASH_CLIENT: the app's native Voidhash module implements version ${version} of its contract, and this JavaScript bundle needs version ${NATIVE_CONTRACT_VERSION}. Make a new native build of the app with this version of ${options.packageName}; an over-the-air update cannot change the native module.`,\n ),\n );\n }\n MutableRef.set(listening, true);\n const started = await call(FAILURES.start, async () => {\n native.setEventListener(handleEvent);\n native.configure(configuration);\n await native.start();\n });\n if (started.isErr()) stopListening();\n return started;\n },\n\n /**\n * Shuts the native client down; events it emits from then on are ignored.\n * The products go with it: a later run loads them for its own identity.\n */\n shutdown: async () => {\n const result = await call(FAILURES.shutdown, () => native.shutdown());\n stopListening();\n MutableRef.update(productsRevision, (revision) => revision + 1);\n cancelScheduledReload();\n MutableRef.set(productsLoad, Option.none());\n atomRegistry.set(productsAtom, NO_PRODUCTS);\n return result.map(toFlushResult);\n },\n\n getDistinctId: () => call(FAILURES.getDistinctId, () => native.getDistinctId()),\n\n /** Backs `identify()`: the switch, without the confirmation. */\n identify: async (externalUserId: string, profile: { email?: string; name?: string } = {}) =>\n (await switchIdentity(externalUserId, profile)).map(() => undefined),\n\n /** Backs `identifySync()`: the switch and whether the server confirmed it. */\n identifySync: async (externalUserId: string, profile: { email?: string; name?: string } = {}) =>\n (await switchIdentity(externalUserId, profile)).map((result): IdentifyResult => {\n const person = personOf(result);\n return result.status === \"confirmed\" && Option.isSome(person)\n ? { person: person.value, status: \"confirmed\" }\n : { person: Option.getOrNull(person), status: \"deferred\" };\n }),\n\n reset: () => switchToAnonymous(FAILURES.reset, () => native.reset()),\n signOut: () => switchToAnonymous(FAILURES.signOut, () => native.signOut()),\n\n /**\n * Backs `group()`. The native SDK checks the type and key (an invalid one\n * rejects `INVALID_ARGUMENT`), keeps the group with the identity and sends\n * the `$groupidentify`.\n */\n group: async (\n groupType: string,\n groupKey: string,\n properties: Option.Option<GroupProperties>,\n ): Promise<Result<void, VoidhashError>> => {\n if (Option.isNone(properties)) {\n return call(FAILURES.group, () => native.group(groupType, groupKey, undefined));\n }\n return Option.match(EffectResult.getSuccess(encodeJson(properties.value)), {\n onNone: () =>\n Promise.resolve(\n Result.err(\n new VoidhashError(\n \"INVALID_ARGUMENT\",\n \"INVALID_ARGUMENT: group properties must be values JSON can hold\",\n ),\n ),\n ),\n onSome: (json) => call(FAILURES.group, () => native.group(groupType, groupKey, json)),\n });\n },\n /**\n * Backs `setGroups()`. The native SDK replaces the held groups, checks\n * each type and id, and sends a `$groupidentify` only for what changed.\n */\n setGroups: async (groups: Groups): Promise<Result<void, VoidhashError>> => {\n const entries = R.filterMap(groups, (group) => {\n if (P.isNullish(group)) return EffectResult.failVoid;\n if (!P.isObject(group)) return EffectResult.succeed({ id: String(group), properties: {} });\n const { id, ...properties } = group;\n return EffectResult.succeed({ id: String(id), properties });\n });\n return Option.match(EffectResult.getSuccess(encodeJson(entries)), {\n onNone: () =>\n Promise.resolve(\n Result.err(\n new VoidhashError(\n \"INVALID_ARGUMENT\",\n \"INVALID_ARGUMENT: group properties must be values JSON can hold\",\n ),\n ),\n ),\n onSome: (json) => call(FAILURES.setGroups, () => native.setGroups(json)),\n });\n },\n resetGroups: () => call(FAILURES.resetGroups, () => native.resetGroups()),\n /** The groups the native client holds; none when it could not say. */\n getGroups: (): Readonly<Record<string, string>> =>\n Option.getOrElse(\n trySync(\"getGroups\", () => native.getGroups()),\n () => ({}),\n ),\n\n setPersonAttributes: async (\n attributes: PersonAttributes,\n ): Promise<Result<void, VoidhashError>> => {\n const encoded = encodeAttributes(attributes);\n if (encoded.isErr()) return Result.err(encoded.error);\n return call(FAILURES.setPersonAttributes, () => native.setPersonAttributes(encoded.value));\n },\n\n setPersonAttributesSync: async (\n attributes: PersonAttributes,\n ): Promise<Result<SetPersonAttributesResult, VoidhashError>> => {\n const encoded = encodeAttributes(attributes);\n if (encoded.isErr()) return Result.err(encoded.error);\n return (\n await call(FAILURES.setPersonAttributesSync, () =>\n native.setPersonAttributesState(encoded.value),\n )\n ).map(toAttributesResult);\n },\n\n getCurrentPerson: async (options: { forceFetch?: boolean } = {}) =>\n (await readPerson(options.forceFetch ?? false)).map(toCurrentPerson),\n\n /** Answers an entitlement check from the person read, as the TypeScript core does. */\n hasPerk: async (perkSlug: PerkSlug, options: { forceFetch?: boolean } = {}) =>\n (await readPerson(options.forceFetch ?? false)).map((state): HasPerkResult => {\n const snapshot = toCurrentPerson(state);\n const grant = findActiveGrant(Option.fromNullOr(snapshot.person), perkSlug);\n return {\n ...Option.match(grant, { onNone: () => ({}), onSome: (found) => ({ grant: found }) }),\n hasAccess: Option.isSome(grant),\n isExpired: snapshot.isExpired,\n isStale: snapshot.isStale,\n reason: snapshot.reason,\n };\n }),\n\n resetCache: () => call(FAILURES.resetCache, () => native.resetPersonCache()),\n\n /**\n * Evaluates flags and stores the answer under the keys asked for, which\n * is where the hook that asked reads it, whatever the native side echoes.\n */\n getFeatureFlags: (flagKeys?: ReadonlyArray<string>) =>\n call(FAILURES.getFeatureFlags, async () => {\n const result = await native.getFeatureFlags(\n flagKeys === undefined ? undefined : [...flagKeys],\n );\n publishFlags(result, normalizeFeatureFlagKeys(flagKeys));\n return toFlags(result);\n }),\n\n getPaywallForLocation: async (location: string) => {\n const json = await call(FAILURES.getPaywallForLocation, () => native.getPaywall(location));\n return json.andThen((value) =>\n EffectResult.match(EffectResult.flatMap(decodeJson(value), decodePaywall), {\n onFailure: () =>\n Result.err(\n new VoidhashError(\n \"FAILED_TO_GET_PAYWALL_FOR_LOCATION\",\n `FAILED_TO_GET_PAYWALL_FOR_LOCATION: unreadable paywall for \"${location}\"`,\n ),\n ),\n onSuccess: (paywall) => Result.ok(paywall),\n }),\n );\n },\n\n /** Loads the products, sharing a load already running; see `loadProducts`. */\n loadProducts,\n\n /**\n * Buys a product. A cancelled sheet and a pending payment are results; a\n * native client that rejects them with `USER_CANCELLED` or\n * `PURCHASE_PENDING` is read the same way. A store refusal with a reason\n * is `FAILED_TO_PURCHASE` with that reason. A completed purchase, and an\n * offer the end user could not get (`INELIGIBLE_FOR_OFFER` or\n * `OFFER_UNAVAILABLE`), outdate the products: the offers they list may\n * have changed.\n */\n purchase: async (\n productSlug: string,\n purchaseOptions: NativePurchaseOptions,\n ): Promise<Result<StorePurchaseResult, VoidhashError>> => {\n const exit = await Effect.runPromiseExit(\n Effect.tryPromise({\n catch: (error) => error,\n try: () => native.purchase(productSlug, purchaseOptions),\n }),\n );\n if (Exit.isSuccess(exit)) {\n const result = toPurchaseResult(exit.value, (message) =>\n reportContractViolation(\"purchase\", message),\n );\n if (Option.isNone(result)) {\n return Result.err(\n new VoidhashError(\n \"FAILED_TO_PURCHASE\",\n \"FAILED_TO_PURCHASE: the native client reported a purchase without its transaction\",\n ),\n );\n }\n if (result.value.status === \"purchased\") invalidateProducts();\n return Result.ok(result.value);\n }\n const error = Cause.squash(exit.cause);\n const failure = readNativeError(error);\n const code = Option.getOrElse(failure.code, () => \"\");\n if (code === \"USER_CANCELLED\") return Result.ok({ status: \"cancelled\" });\n if (code === \"PURCHASE_PENDING\") return Result.ok({ status: \"pending\" });\n if (code === \"INELIGIBLE_FOR_OFFER\" || code === \"OFFER_UNAVAILABLE\") invalidateProducts();\n const reason = R.get(PURCHASE_FAILURE_REASONS, code);\n if (Option.isSome(reason)) {\n return Result.err(\n new VoidhashError(\"FAILED_TO_PURCHASE\", `FAILED_TO_PURCHASE: ${failure.message}`, {\n cause: error,\n reason: reason.value,\n }),\n );\n }\n return Result.err(toVoidhashError(error, FAILURES.purchase));\n },\n\n /**\n * Revalidates the store's purchase history and answers the refreshed\n * person (`null` when there is none), publishing it as a read does. A\n * restore outdates the products: what was restored can change the\n * offers the end user is eligible for.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n restorePurchases: async (): Promise<Result<Person | null, VoidhashError>> => {\n const restored = await call(FAILURES.restorePurchases, async () => {\n const state = await native.restorePurchases();\n publishPerson(state);\n return state;\n });\n if (restored.isOk()) invalidateProducts();\n return restored.map((state) => Option.getOrNull(personOf(state)));\n },\n\n syncPurchases: () => call(FAILURES.syncPurchases, () => native.syncPurchases()),\n reportTransaction: (transaction: NativeReportedTransaction, isRestore: boolean) =>\n call(FAILURES.reportTransaction, () => native.reportTransaction(transaction, isRestore)),\n\n /** Answers whether the consent was also stored for later launches. */\n setAnalyticsConsent: (consent: NativeAnalyticsConsent) =>\n call(FAILURES.setAnalyticsConsent, () => native.setAnalyticsConsent(consent)),\n /** The consent the native client has in effect; `None` when it could not say. */\n getAnalyticsConsent: (): Option.Option<AnalyticsConsent> =>\n Option.filter(\n trySync(\"getAnalyticsConsent\", () => native.getAnalyticsConsent()),\n isAnalyticsConsent,\n ),\n /** Switches observer mode natively; a throw is reported, the facade's mode still switches. */\n setReadOnly: (readOnly: boolean) => {\n trySync(\"setReadOnly\", () => native.setReadOnly(readOnly));\n },\n\n flush: async () => (await call(FAILURES.flush, () => native.flush())).map(toFlushResult),\n\n /** The active session id, or `undefined` when there is none. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the facade's `getSessionId()` answer.\n getSessionId: (): string | undefined =>\n Option.getOrUndefined(\n Option.filter(\n trySync(\"getSessionId\", () => native.getSessionId()),\n (sessionId) => sessionId !== \"\",\n ),\n ),\n\n capture: (eventName: string, properties: Record<string, unknown> = {}) =>\n Option.map(encodeEvent(\"capture\", eventName, properties), (json) =>\n sendEvent(\"capture\", eventName, json, Option.none()),\n ),\n screen: (name: string, properties: Record<string, unknown> = {}) =>\n Option.map(encodeEvent(\"screen\", name, properties), (json) =>\n sendEvent(\"screen\", name, json, Option.none()),\n ),\n /**\n * Copies an event's (or a screen's) properties now and answers what\n * queues it later, given the time it was captured at: for an event the\n * facade holds back until an identity change switched the identity.\n * `None` for an event whose properties cannot be copied, already reported.\n */\n holdEvent: (\n operation: \"capture\" | \"screen\",\n name: string,\n properties: Record<string, unknown>,\n ): Option.Option<(capturedAt: number) => void> =>\n Option.map(\n encodeEvent(operation, name, properties),\n (json) => (capturedAt: number) => sendEvent(operation, name, json, Option.some(capturedAt)),\n ),\n /** The distinct id in effect, as last announced; `None` before the first `start()`. */\n currentDistinctId: (): Option.Option<string> =>\n Option.map(MutableRef.get(currentIdentity), (identity) => identity.distinctId),\n\n // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the Nitro contract, where an optional is `undefined`.\n showManageSubscriptions: (productSlug: string | undefined) =>\n call(FAILURES.showManageSubscriptions, () => native.showManageSubscriptions(productSlug)),\n // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the Nitro contract, where an optional is `undefined`.\n presentCodeRedemption: (code: string | undefined) =>\n call(FAILURES.presentCodeRedemption, () => native.presentCodeRedemption(code)),\n getStorefront: async () =>\n (await call(FAILURES.getStorefront, () => native.getStorefront())).map(\n // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the Nitro contract, where an optional is `undefined`.\n (storefront: NativeStorefront | undefined) =>\n storefront === undefined\n ? undefined\n : {\n countryCode: storefront.countryCode,\n ...(storefront.currencyCode === undefined\n ? {}\n : { currencyCode: storefront.currencyCode }),\n },\n ),\n canMakePayments: () => call(FAILURES.canMakePayments, () => native.canMakePayments()),\n\n appStoreBeginRefundRequest: (transactionId: string) =>\n call(FAILURES.appStoreBeginRefundRequest, (): Promise<RefundRequestStatus> =>\n native.appStoreBeginRefundRequest(transactionId),\n ),\n /**\n * The group's statuses. One whose renewal info cannot be read breaks the\n * contract: it is left out and reported.\n */\n appStoreSubscriptionStatus: async (groupId: string) =>\n (\n await call(FAILURES.appStoreSubscriptionStatus, () =>\n native.appStoreSubscriptionStatus(groupId),\n )\n ).map((statuses): ReadonlyArray<AppStoreSubscriptionStatus> =>\n Arr.filterMap(statuses, (status) => {\n const renewalInfo = decodeAppStoreRenewalInfo(status.renewalInfoJson);\n if (Option.isNone(renewalInfo)) {\n reportContractViolation(\n \"appStore.subscriptionStatus\",\n `The renewal info of transaction ${status.transaction.id} could not be read`,\n );\n return EffectResult.failVoid;\n }\n return EffectResult.succeed({\n renewalInfo: renewalInfo.value,\n state: status.state,\n transaction: toTransaction(status.transaction, (message) =>\n reportContractViolation(\"appStore.subscriptionStatus\", message),\n ),\n });\n }),\n ),\n appStoreCurrentEntitlements: async () =>\n (\n await call(FAILURES.appStoreCurrentEntitlements, () => native.appStoreCurrentEntitlements())\n ).map((transactions) =>\n transactions.map((transaction) =>\n toTransaction(transaction, (message) =>\n reportContractViolation(\"appStore.currentEntitlements\", message),\n ),\n ),\n ),\n appStoreAppTransaction: async () =>\n (await call(FAILURES.appStoreAppTransaction, () => native.appStoreAppTransaction())).andThen(\n (json): Result<AppTransaction, VoidhashError> =>\n Option.match(decodeAppTransaction(json), {\n onNone: () =>\n Result.err(\n new VoidhashError(\n \"FAILED_TO_GET_APP_TRANSACTION\",\n \"FAILED_TO_GET_APP_TRANSACTION: the native client sent an app transaction this SDK cannot read\",\n ),\n ),\n onSome: (appTransaction) => Result.ok(appTransaction),\n }),\n ),\n\n googlePlayShowInAppMessages: async () =>\n (\n await call(FAILURES.googlePlayShowInAppMessages, () => native.googlePlayShowInAppMessages())\n ).map((result): GooglePlayInAppMessageResult =>\n result.status === \"subscriptionStatusUpdated\" && result.purchaseToken !== undefined\n ? { purchaseToken: result.purchaseToken, status: \"subscriptionStatusUpdated\" }\n : { status: \"noActionNeeded\" },\n ),\n googlePlayQueryPurchases: async (includeSuspended: boolean) =>\n (\n await call(FAILURES.googlePlayQueryPurchases, () =>\n native.googlePlayQueryPurchases(includeSuspended),\n )\n ).map((transactions) =>\n transactions.map((transaction) =>\n toTransaction(transaction, (message) =>\n reportContractViolation(\"googlePlay.queryPurchases\", message),\n ),\n ),\n ),\n googlePlayIsFeatureSupported: (feature: string) =>\n call(FAILURES.googlePlayIsFeatureSupported, () =>\n native.googlePlayIsFeatureSupported(feature),\n ),\n\n /**\n * Resolves with how the flow ended and rejects with a `VoidhashError` when\n * it could not be presented. A `FLOW_*` code the native side gives is\n * kept; a client that is not started is `FLOW_UNAVAILABLE`.\n *\n * The native coordinator runs the flow: it calls back only for the\n * actions named here, and answers a rejected call, a slow one and one\n * whose flow has ended itself.\n * A flow that ended in a purchase or a restore outdates the products, as\n * `purchase()` and `restorePurchases()` do: the native client reports\n * neither as a transaction update.\n */\n presentFlow: async (\n location: string,\n options: PresentFlowOptions = {},\n ): Promise<FlowResult> => {\n const handlers = options.actions ?? {};\n const onAction = async (name: string, argsJson: string) => {\n const handler = handlers[name];\n if (handler === undefined) {\n throw new VoidhashError(\"INVALID_ARGUMENT\", `no handler for app action \"${name}\"`);\n }\n const reply = await handler(decodeFlowValues(argsJson));\n return encodeFlowValues(reply ?? {});\n };\n const exit = await Effect.runPromiseExit(\n Effect.tryPromise({\n catch: (error) => error,\n try: () =>\n native.presentFlow(\n location,\n {\n actions: R.keys(handlers),\n inputJson: encodeFlowValues(options.input ?? {}),\n ...(options.revision === undefined ? {} : { revision: options.revision }),\n },\n onAction,\n ),\n }),\n );\n if (Exit.isSuccess(exit)) {\n const parsed = parseFlowResult(exit.value);\n if (EffectResult.isFailure(parsed)) throw parsed.failure;\n if (parsed.success.outcome === \"purchased\" || parsed.success.outcome === \"restored\") {\n invalidateProducts();\n }\n return parsed.success;\n }\n const failure = readNativeError(Cause.squash(exit.cause));\n const code = Option.getOrElse(failure.code, () => \"\");\n if (NOT_STARTED_CODES.includes(code)) {\n throw flowError(\"FLOW_UNAVAILABLE\", new NotInitializedError().message);\n }\n throw isFlowErrorCode(code)\n ? new VoidhashError(code, failure.message)\n : flowError(\"FLOW_PRESENTATION_FAILED\", failure.message);\n },\n updateFlowInput: (values: FlowValues) =>\n call(FAILURES.updateFlowInput, () => native.updateFlowInput(encodeFlowValues(values))),\n dismissFlow: () => call(FAILURES.dismissFlow, () => native.dismissFlow()),\n } as const;\n};\n\n/** The facade-facing client over one native hybrid. */\nexport type NativeClientAdapter = ReturnType<typeof makeNativeClientAdapter>;\n","import * as Arr from \"effect/Array\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\nimport * as R from \"effect/Record\";\nimport * as Result from \"effect/Result\";\n\n/**\n * Values, nested ones included, that one event's properties may hold. No\n * product event comes close; an object graph passed by mistake (a press\n * event, a navigation or error object) runs to many thousands, and copying it\n * would hold up the thread that captured it.\n */\nexport const EVENT_PROPERTY_VALUE_LIMIT = 10_000;\n\nclass EventPropertyValueLimitExceeded extends Error {\n constructor() {\n super(`holds more than ${EVENT_PROPERTY_VALUE_LIMIT} values`);\n }\n}\n\n/**\n * Copies an event's properties into values JSON can always hold, the way\n * `JSON.stringify` would write them except where it would throw or write\n * nothing useful: a `bigint` becomes its decimal string, a non-finite number\n * `null`, and a reference back to an object that contains it is left out.\n * `undefined`, functions and symbols are left out (`null` inside an array),\n * and `toJSON` is honoured, so a `Date` becomes its ISO string.\n *\n * The copy is taken as the event is captured, so a host that mutates the\n * object afterwards does not change the queued event. Fails with the reason\n * when the properties cannot be copied at all: more than\n * {@link EVENT_PROPERTY_VALUE_LIMIT} values, or a getter or `toJSON` that\n * throws.\n */\nexport const toJsonSafeProperties = (\n properties: Record<string, unknown>,\n): Result.Result<Record<string, unknown>, string> => {\n let remaining = EVENT_PROPERTY_VALUE_LIMIT;\n // By identity: a structural set would hash, and so read, the host's whole\n // object graph.\n const ancestors = new WeakSet<object>();\n\n const copy = (value: unknown): Option.Option<unknown> => {\n remaining -= 1;\n if (remaining < 0) throw new EventPropertyValueLimitExceeded();\n if (P.isString(value) || P.isBoolean(value)) return Option.some(value);\n // oxlint-disable-next-line effect/prefer-option-over-null -- JSON `null` is the value written for a number JSON cannot hold.\n if (P.isNumber(value)) return Option.some(Number.isFinite(value) ? value : null);\n if (P.isBigInt(value)) return Option.some(value.toString());\n // oxlint-disable-next-line effect/prefer-option-over-null -- JSON `null` is a property value like any other.\n if (P.isNull(value)) return Option.some(null);\n // Functions, symbols and `undefined` have no JSON form.\n return P.isObjectOrArray(value) ? copyObject(value) : Option.none();\n };\n\n const copyEntries = (value: object): Option.Option<unknown> => {\n if (Array.isArray(value)) {\n // oxlint-disable-next-line effect/prefer-option-over-null -- JSON writes `null` for an array item it cannot hold.\n return Option.some(value.map((item: unknown) => Option.getOrNull(copy(item))));\n }\n if (!P.isObject(value)) return Option.none();\n return Option.some(\n R.fromEntries(\n R.keys(value).flatMap((key) =>\n Arr.fromOption(Option.map(copy(value[key]), (item) => [key, item] as const)),\n ),\n ),\n );\n };\n\n const copyObject = (value: object): Option.Option<unknown> => {\n if (ancestors.has(value)) return Option.none();\n ancestors.add(value);\n const toJson = Reflect.get(value, \"toJSON\");\n const json: unknown = P.isFunction(toJson) ? Reflect.apply(toJson, value, []) : value;\n const copied = json === value ? copyEntries(value) : copy(json);\n ancestors.delete(value);\n return copied;\n };\n\n return Result.try({\n catch: (error) =>\n error instanceof EventPropertyValueLimitExceeded\n ? error.message\n : `could not be read${P.isError(error) ? ` (${error.message})` : \"\"}`,\n try: () => Option.getOrElse(Option.filter(copy(properties), P.isObject), () => ({})),\n });\n};\n","import * as Arr from \"effect/Array\";\nimport * as Option from \"effect/Option\";\n\nimport type { EntitlementGrant, Person } from \"../entities/person\";\n\nexport type { EntitlementGrant };\n\n/**\n * Finds the active grant for a perk in a person snapshot. `None` when the\n * person has no snapshot or no active grant for the perk — both mean \"no\n * access\".\n *\n * `perkSlug` is the slug configured in Studio, matched against the grant's\n * `perkSlug`. A grant's `perkId` (the perk's internal id) matches too, so a\n * snapshot cached before grants carried a slug, or a check by id, still\n * answers.\n */\nexport const findActiveGrant = (\n person: Option.Option<Person>,\n perkSlug: string,\n): Option.Option<EntitlementGrant> =>\n Option.flatMap(person, (snapshot) =>\n Arr.findFirst(\n snapshot.entitlements.grants,\n (grant) =>\n grant.status === \"active\" && (grant.perkSlug === perkSlug || grant.perkId === perkSlug),\n ),\n );\n","import * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport type { ProductSlug } from \"../schema/registry\";\nimport {\n EnvironmentValue,\n enumOrUnknown,\n listOrEmpty,\n optionalNullable,\n PaymentModeValue,\n PeriodValue,\n PriceValue,\n} from \"./decoding\";\nimport type { Offer, PaymentMode, Period, Price } from \"./product\";\nimport type { Environment, Transaction } from \"./transaction\";\n\n/*\n * The App Store's own view of products and transactions, with StoreKit's\n * field names. The native client sends each as JSON (dates as milliseconds\n * since the epoch); the decoders here read it forward-compatibly.\n */\n\n/** StoreKit's `Product.ProductType`. */\nexport type AppStoreProductType =\n | \"consumable\"\n | \"nonConsumable\"\n | \"autoRenewable\"\n | \"nonRenewable\"\n | \"unknown\";\n\n/** StoreKit's `Product.SubscriptionOffer.OfferType`. */\nexport type AppStoreOfferType = \"introductory\" | \"promotional\" | \"winBack\" | \"unknown\";\n\n/** A StoreKit `Product.SubscriptionOffer`, whether or not this end user can buy it. */\nexport interface AppStoreOffer {\n /** The offer's id in App Store Connect; absent for the introductory offer. */\n readonly id?: string;\n readonly type: AppStoreOfferType;\n readonly paymentMode: PaymentMode;\n /** The length of one period of the offer. */\n readonly period: Period;\n /** How many periods the offer lasts. */\n readonly periodCount: number;\n /** What one period costs; zero for a free trial. */\n readonly price: Price;\n}\n\n/** A StoreKit `Product` as the App Store reports it. */\nexport interface AppStoreProductInfo {\n readonly subscriptionGroupId?: string;\n /** The product's level in its subscription group (iOS 16.4 and later). */\n readonly subscriptionGroupLevel?: number;\n /** The subscription group's name (iOS 16.4 and later). */\n readonly subscriptionGroupDisplayName?: string;\n readonly isFamilyShareable: boolean;\n readonly productType: AppStoreProductType;\n /** The introductory offer, whether or not this end user is eligible for it. */\n readonly introductoryOffer?: AppStoreOffer;\n readonly promotionalOffers: ReadonlyArray<AppStoreOffer>;\n /** Win-back offers (iOS 18 and later). */\n readonly winBackOffers: ReadonlyArray<AppStoreOffer>;\n /** Whether this end user can get the group's introductory offer; absent when unknown. */\n readonly isEligibleForIntroOffer?: boolean;\n}\n\n/** StoreKit's `Transaction.OwnershipType`. */\nexport type AppStoreOwnershipType = \"purchased\" | \"familyShared\" | \"unknown\";\n\n/** StoreKit's `Transaction.RevocationReason`. */\nexport type AppStoreRevocationReason = \"developerIssue\" | \"other\" | \"unknown\";\n\n/** A StoreKit `Transaction` as the App Store reports it. */\nexport interface AppStoreTransactionInfo {\n readonly ownershipType: AppStoreOwnershipType;\n /** The ISO 3166-1 alpha-2 country of the storefront it was bought in. */\n readonly storefrontCountryCode?: string;\n /** Whether the end user upgraded to another subscription in the group. */\n readonly isUpgraded: boolean;\n /** When the App Store refunded or revoked it, in milliseconds since the epoch. */\n readonly revocationDate?: number;\n readonly revocationReason?: AppStoreRevocationReason;\n readonly appTransactionId?: string;\n /** The transaction's signed JWS, for your own server to verify. */\n readonly jwsRepresentation: string;\n}\n\n/** StoreKit's `Product.SubscriptionInfo.RenewalState`. */\nexport type AppStoreSubscriptionState =\n | \"subscribed\"\n | \"expired\"\n | \"inBillingRetryPeriod\"\n | \"inGracePeriod\"\n | \"revoked\"\n | \"unknown\";\n\n/** StoreKit's `RenewalInfo.ExpirationReason`. */\nexport type AppStoreExpirationReason =\n | \"autoRenewDisabled\"\n | \"billingError\"\n | \"didNotConsentToPriceIncrease\"\n | \"productUnavailable\"\n | \"unknown\";\n\n/** StoreKit's `RenewalInfo.PriceIncreaseStatus`. */\nexport type AppStorePriceIncreaseStatus = \"noIncreasePending\" | \"pending\" | \"agreed\" | \"unknown\";\n\n/** A StoreKit `Product.SubscriptionInfo.RenewalInfo`. */\nexport interface AppStoreRenewalInfo {\n readonly willAutoRenew: boolean;\n /** The product the subscription renews into. */\n readonly autoRenewProductId?: string;\n readonly expirationReason?: AppStoreExpirationReason;\n /** When the billing grace period ends, in milliseconds since the epoch. */\n readonly gracePeriodExpiresAt?: number;\n readonly isInBillingRetry: boolean;\n readonly priceIncreaseStatus?: AppStorePriceIncreaseStatus;\n /** What the next renewal costs. */\n readonly renewalPrice?: Price;\n readonly eligibleWinBackOfferIds: ReadonlyArray<string>;\n}\n\n/** One of a subscription group's statuses on this device: the end user's own. */\nexport interface AppStoreSubscriptionStatus {\n readonly state: AppStoreSubscriptionState;\n /** The subscription's latest transaction. */\n readonly transaction: Transaction;\n readonly renewalInfo: AppStoreRenewalInfo;\n}\n\n/** StoreKit's `AppStore.Platform`. */\nexport type AppStorePlatform = \"iOS\" | \"macOS\" | \"tvOS\" | \"visionOS\" | \"unknown\";\n\n/** StoreKit's `AppTransaction`: how the end user got the app. */\nexport interface AppTransaction {\n /** The app version the end user first got. */\n readonly originalAppVersion: string;\n /** When the end user first got the app, in milliseconds since the epoch. */\n readonly originalPurchaseDate: number;\n readonly environment: Environment;\n readonly appTransactionId?: string;\n readonly originalPlatform?: AppStorePlatform;\n /** The app transaction's signed JWS, for your own server to verify. */\n readonly jwsRepresentation: string;\n}\n\n/** How `beginRefundRequest()` ended: Apple received the request, or the end user closed the sheet. */\nexport type RefundRequestStatus = \"success\" | \"userCancelled\";\n\n/**\n * A purchase the end user started outside the app, such as a promoted\n * in-app purchase or a win-back offer on the App Store. Complete it with\n * `purchase()`.\n */\nexport interface AppStorePurchaseIntent {\n readonly productSlug: ProductSlug;\n /** The offer the end user chose, when they chose one. */\n readonly offer?: Offer;\n}\n\nconst AppStoreOfferValue = Schema.Struct({\n id: optionalNullable(Schema.String),\n type: enumOrUnknown([\"introductory\", \"promotional\", \"winBack\"]),\n paymentMode: PaymentModeValue,\n period: PeriodValue,\n periodCount: Schema.Number,\n price: PriceValue,\n});\n\nconst AppStoreProductJson = Schema.fromJsonString(\n Schema.Struct({\n subscriptionGroupId: optionalNullable(Schema.String),\n subscriptionGroupLevel: optionalNullable(Schema.Number),\n subscriptionGroupDisplayName: optionalNullable(Schema.String),\n isFamilyShareable: Schema.Boolean,\n productType: enumOrUnknown([\"consumable\", \"nonConsumable\", \"autoRenewable\", \"nonRenewable\"]),\n introductoryOffer: optionalNullable(AppStoreOfferValue),\n promotionalOffers: listOrEmpty(AppStoreOfferValue),\n winBackOffers: listOrEmpty(AppStoreOfferValue),\n isEligibleForIntroOffer: optionalNullable(Schema.Boolean),\n }),\n);\n\nconst AppStoreTransactionJson = Schema.fromJsonString(\n Schema.Struct({\n ownershipType: enumOrUnknown([\"purchased\", \"familyShared\"]),\n storefrontCountryCode: optionalNullable(Schema.String),\n isUpgraded: Schema.Boolean,\n revocationDate: optionalNullable(Schema.Number),\n revocationReason: optionalNullable(enumOrUnknown([\"developerIssue\", \"other\"])),\n appTransactionId: optionalNullable(Schema.String),\n jwsRepresentation: Schema.String,\n }),\n);\n\nconst AppStoreRenewalInfoJson = Schema.fromJsonString(\n Schema.Struct({\n willAutoRenew: Schema.Boolean,\n autoRenewProductId: optionalNullable(Schema.String),\n expirationReason: optionalNullable(\n enumOrUnknown([\n \"autoRenewDisabled\",\n \"billingError\",\n \"didNotConsentToPriceIncrease\",\n \"productUnavailable\",\n ]),\n ),\n gracePeriodExpiresAt: optionalNullable(Schema.Number),\n isInBillingRetry: Schema.Boolean,\n priceIncreaseStatus: optionalNullable(\n enumOrUnknown([\"noIncreasePending\", \"pending\", \"agreed\"]),\n ),\n renewalPrice: optionalNullable(PriceValue),\n eligibleWinBackOfferIds: listOrEmpty(Schema.String),\n }),\n);\n\nconst AppTransactionJson = Schema.fromJsonString(\n Schema.Struct({\n originalAppVersion: Schema.String,\n originalPurchaseDate: Schema.Number,\n environment: EnvironmentValue,\n appTransactionId: optionalNullable(Schema.String),\n originalPlatform: optionalNullable(enumOrUnknown([\"iOS\", \"macOS\", \"tvOS\", \"visionOS\"])),\n jwsRepresentation: Schema.String,\n }),\n);\n\n/** Reads a product's App Store part; `None` when it is not one. */\nexport const decodeAppStoreProduct = (json: string): Option.Option<AppStoreProductInfo> =>\n Schema.decodeUnknownOption(AppStoreProductJson)(json);\n\n/** Reads a transaction's App Store part; `None` when it is not one. */\nexport const decodeAppStoreTransaction = (json: string): Option.Option<AppStoreTransactionInfo> =>\n Schema.decodeUnknownOption(AppStoreTransactionJson)(json);\n\n/** Reads a subscription status's renewal info; `None` when it is not one. */\nexport const decodeAppStoreRenewalInfo = (json: string): Option.Option<AppStoreRenewalInfo> =>\n Schema.decodeUnknownOption(AppStoreRenewalInfoJson)(json);\n\n/** Reads the app transaction; `None` when it is not one. */\nexport const decodeAppTransaction = (json: string): Option.Option<AppTransaction> =>\n Schema.decodeUnknownOption(AppTransactionJson)(json);\n","import * as Arr from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\nimport * as R from \"effect/Record\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\n\n/*\n * Schema building blocks for the payloads the SDK reads but does not define:\n * the server's person snapshot and the store parts the native client sends as\n * JSON. They read forward-compatibly: a value a newer server or store adds\n * never fails decoding.\n */\n\n/**\n * A string from a closed set the SDK knows. A value outside `values` decodes\n * as `\"unknown\"`, so a newer server or store never breaks decoding.\n */\nexport const enumOrUnknown = <const Value extends string>(values: ReadonlyArray<Value>) => {\n const isKnown = (value: string): value is Value => values.some((known) => known === value);\n return Schema.String.pipe(\n Schema.decodeTo(\n Schema.Literals([...values, \"unknown\"]),\n SchemaTransformation.transform<Value | \"unknown\", string>({\n decode: (value) => (isKnown(value) ? value : \"unknown\"),\n encode: (value) => value,\n }),\n ),\n );\n};\n\n/**\n * A string from a closed set the server names its own way (`app_store`),\n * decoded to the SDK's name for it (`appStore`). A value missing from `names`\n * decodes as `\"unknown\"`.\n */\nexport const renamedEnumOrUnknown = <const Value extends string>(\n names: Readonly<Record<string, Value>>,\n) =>\n Schema.String.pipe(\n Schema.decodeTo(\n Schema.Literals([...R.values(names), \"unknown\"]),\n SchemaTransformation.transform<Value | \"unknown\", string>({\n decode: (wire) => Option.getOrElse(R.get(names, wire), () => \"unknown\" as const),\n encode: (value) =>\n Option.getOrElse(\n Arr.findFirst(R.toEntries(names), ([, name]) => name === value),\n () => [value, value] as const,\n )[0],\n }),\n ),\n );\n\n/** A field the payload may send as `null` or leave out; either decodes as an absent key. */\nexport const optionalNullable = <S extends Schema.Top>(schema: S) =>\n Schema.optional(\n Schema.NullOr(schema).pipe(\n Schema.decodeTo(\n Schema.UndefinedOr(Schema.toType(schema)),\n // oxlint-disable-next-line effect/prefer-option-over-null -- the payload's own `null`, read as the absent key the SDK's types use.\n SchemaTransformation.transform<S[\"Type\"] | undefined, S[\"Type\"] | null>({\n decode: (value) => value ?? undefined,\n encode: (value) => value ?? null,\n }),\n ),\n ),\n );\n\n/**\n * An ISO 8601 timestamp the payload may send, decoded as milliseconds since\n * the epoch. One that is `null`, left out, not a string, or that `Date`\n * cannot read decodes as an absent key: a date the SDK cannot read never\n * costs the entry it is on, so a grant with such an expiry still grants\n * access.\n */\nexport const OptionalEpochMillis = Schema.optional(\n Schema.Unknown.pipe(\n Schema.decodeTo(\n Schema.UndefinedOr(Schema.Finite),\n // oxlint-disable-next-line effect/prefer-option-over-null -- the payload's own `null`, read as the absent key the SDK's types use.\n SchemaTransformation.transform<number | undefined, unknown>({\n decode: (value) => {\n // oxlint-disable-next-line effect/use-clock-service -- parses a timestamp the server sent; no clock is read.\n const millis = P.isString(value) ? Date.parse(value) : Number.NaN;\n return Number.isFinite(millis) ? millis : undefined;\n },\n // oxlint-disable-next-line effect/use-clock-service -- formats a timestamp; no clock is read.\n encode: (millis) => (millis === undefined ? null : new Date(millis).toISOString()),\n }),\n ),\n ),\n);\nexport type OptionalEpochMillis = typeof OptionalEpochMillis.Type;\n\n/**\n * An array whose elements the SDK cannot read are left out, so one malformed\n * entry never costs the others.\n */\nexport const readableElements = <S extends Schema.Codec<unknown, unknown, never, never>>(\n element: S,\n) => {\n const decodeElement = Schema.decodeUnknownOption(element);\n return Schema.Array(Schema.Unknown).pipe(\n Schema.decodeTo(\n Schema.Array(Schema.toType(element)),\n SchemaTransformation.transform<ReadonlyArray<S[\"Type\"]>, ReadonlyArray<unknown>>({\n decode: (items) => Arr.getSomes(items.map((item) => decodeElement(item))),\n encode: (items) => items,\n }),\n ),\n );\n};\n\n/** A list the payload may leave out; decodes as empty then. */\nexport const listOrEmpty = <S extends Schema.Codec<unknown, unknown, never, never>>(element: S) =>\n readableElements(element).pipe(Schema.withDecodingDefaultKey(Effect.succeed([])));\n\n/** A `Price` as the native client sends it. */\nexport const PriceValue = Schema.Struct({\n amount: Schema.Number,\n amountMicros: Schema.Number,\n currencyCode: Schema.String,\n formatted: Schema.String,\n});\nexport type PriceValue = typeof PriceValue.Type;\n\n/** A `Period` as the native client sends it. */\nexport const PeriodValue = Schema.Struct({\n unit: enumOrUnknown([\"day\", \"week\", \"month\", \"year\"]),\n count: Schema.Number,\n iso8601: Schema.String,\n});\nexport type PeriodValue = typeof PeriodValue.Type;\n\n/** A pricing phase's payment mode as the native client sends it. */\nexport const PaymentModeValue = enumOrUnknown([\"freeTrial\", \"payAsYouGo\", \"payUpFront\"]);\n\n/** An environment as the native client sends it, in the SDK's names. */\nexport const EnvironmentValue = enumOrUnknown([\"production\", \"sandbox\", \"xcode\", \"development\"]);\n","import * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport type { PerkSlug, ProductSlug } from \"../schema/registry\";\nimport {\n enumOrUnknown,\n listOrEmpty,\n OptionalEpochMillis,\n optionalNullable,\n renamedEnumOrUnknown,\n} from \"./decoding\";\nimport type { Environment } from \"./transaction\";\n\n/*\n * The person as the Voidhash API reports them (its person snapshot), read\n * into the SDK's names: timestamps become milliseconds since the epoch,\n * `null` an absent field, and the server's snake_case values the SDK's\n * camelCase ones. Values a newer server adds read as `\"unknown\"`, and a list\n * entry this version cannot read is left out, so a snapshot always keeps the\n * access it grants.\n *\n * The field names are the server's (`SdkPerson` in its contract). Keep them in\n * step with the generated client in `networking/generated/sdk-client.ts` when\n * it is regenerated.\n */\n\n/** Where a subscription or grant comes from. */\nexport type PersonStore = \"appStore\" | \"googlePlay\" | \"stripe\" | \"other\" | \"unknown\";\n\n/** A perk the person has or had. */\nexport interface EntitlementGrant {\n readonly perkId: string;\n /** The perk's slug, which access is checked by; absent when the perk was deleted. */\n readonly perkSlug?: PerkSlug;\n /** `active` while the person has access, `expired` once it ended. */\n readonly status: \"active\" | \"expired\" | \"unknown\";\n /** What granted it: a `subscription`, a one-time `purchase`, or a `manual` grant. */\n readonly source: \"subscription\" | \"purchase\" | \"manual\" | \"unknown\";\n /** The id of the subscription or purchase that granted it; absent for a manual grant. */\n readonly sourceId?: string;\n /** The person who owns it: this person, one merged into them, or one sharing it with them. */\n readonly sourcePersonId: string;\n /** When the access ends, in milliseconds since the epoch; absent when it does not end. */\n readonly expiresAt?: number;\n}\n\n/**\n * A subscription's state:\n *\n * - `active`: paid and renewing (or canceled, running until it ends).\n * - `trialing`: in a free trial.\n * - `inGracePeriod`: a renewal payment failed and the store keeps access\n * until `gracePeriodExpiresAt` while it retries.\n * - `inBillingRetry`: a renewal payment failed and the store is retrying it.\n * - `onHold`: Google Play account hold: payment failed and access is paused.\n * - `paused`: the end user paused it on Google Play until `resumesAt`.\n * - `expired`: it ended.\n * - `revoked`: the store withdrew it, such as after a refund.\n */\nexport type SubscriptionStatus =\n | \"active\"\n | \"trialing\"\n | \"inGracePeriod\"\n | \"inBillingRetry\"\n | \"onHold\"\n | \"paused\"\n | \"expired\"\n | \"revoked\"\n | \"unknown\";\n\n/** Which price period a subscription is in: a free `trial`, an `intro` price, or the `regular` price. */\nexport type SubscriptionPeriodType = \"trial\" | \"intro\" | \"regular\" | \"unknown\";\n\n/** A price change the store announced for a subscription's next renewals. */\nexport interface SubscriptionPendingPrice {\n readonly amountMicros: number;\n /** ISO 4217 currency code. */\n readonly currency: string;\n /** When the new price takes effect, in milliseconds since the epoch. */\n readonly effectiveAt?: number;\n /** Whether the end user agreed to it, where the store asks; absent where it does not. */\n readonly consent?: \"pending\" | \"accepted\" | \"unknown\";\n}\n\n/**\n * A subscription that has not ended, as the server knows it across devices\n * and stores. Timestamps are milliseconds since the epoch. What the person\n * can use always comes from their entitlements, never from this.\n */\nexport interface Subscription {\n readonly subscriptionId: string;\n /** The Voidhash product id; absent when its store product is not linked to one. */\n readonly productId?: string;\n readonly productSlug?: ProductSlug;\n readonly store: PersonStore;\n /** Where it was bought; `development` for development-mode purchases. */\n readonly environment: Environment;\n readonly status: SubscriptionStatus;\n readonly periodType: SubscriptionPeriodType;\n readonly startsAt?: number;\n /** When the current period ends. */\n readonly expiresAt?: number;\n /** Whether it renews at `expiresAt`. */\n readonly willRenew: boolean;\n /** When auto-renewal was turned off or it was canceled. */\n readonly canceledAt?: number;\n /** The product it renews into at `expiresAt`: a downgrade or plan change waiting for renewal. */\n readonly renewsToProductSlug?: ProductSlug;\n readonly gracePeriodExpiresAt?: number;\n /** When the store first failed to charge the renewal. */\n readonly billingIssueDetectedAt?: number;\n /** When a paused subscription resumes (Google Play). */\n readonly resumesAt?: number;\n readonly pendingPrice?: SubscriptionPendingPrice;\n /** The offer it was bought with. */\n readonly offerId?: string;\n /** Whether the person has it through App Store Family Sharing. */\n readonly isFamilyShared: boolean;\n readonly refundedAt?: number;\n readonly revokedAt?: number;\n}\n\n/** One subscription the person owns or shares, ended or not. */\nexport interface SubscriptionHistoryEntry {\n readonly subscriptionId: string;\n readonly productId?: string;\n readonly productSlug?: ProductSlug;\n readonly store: PersonStore;\n readonly status: SubscriptionStatus;\n readonly isTrial: boolean;\n readonly startsAt?: number;\n readonly expiresAt?: number;\n readonly canceledAt?: number;\n readonly refundedAt?: number;\n readonly sourcePersonId: string;\n}\n\n/** One purchase the person owns or shares, one per store transaction. */\nexport interface PurchaseHistoryEntry {\n readonly purchaseId: string;\n readonly productId?: string;\n readonly productSlug?: ProductSlug;\n /** The store's id for the transaction, such as an App Store transaction id. */\n readonly providerKey: string;\n readonly type: \"oneTime\" | \"consumable\" | \"subscription\" | \"unknown\";\n /** When it was recorded. */\n readonly createdAt?: number;\n readonly refundedAt?: number;\n readonly revokedAt?: number;\n readonly sourcePersonId: string;\n}\n\n/** The end user as Voidhash knows them: who they are, what they can use and what they bought. */\nexport interface Person {\n readonly personId: string;\n readonly distinctId: string;\n readonly email?: string;\n readonly name?: string;\n readonly entitlements: {\n /** The perks the person has or had, one per perk. */\n readonly grants: ReadonlyArray<EntitlementGrant>;\n };\n readonly subscriptions: {\n /**\n * The subscription that matters most now, of the ones that have not\n * ended: active first, then trialing, in a grace period, in billing\n * retry, on hold, paused.\n */\n readonly current?: Subscription;\n /**\n * Every subscription that has not ended, including ones in a grace\n * period, in billing retry, on hold or paused: what a \"manage\n * subscription\" screen lists. Access comes from entitlements, never from\n * this list.\n */\n readonly all: ReadonlyArray<Subscription>;\n readonly history: ReadonlyArray<SubscriptionHistoryEntry>;\n };\n readonly purchases: {\n readonly history: ReadonlyArray<PurchaseHistoryEntry>;\n };\n}\n\nconst StoreValue = renamedEnumOrUnknown({\n app_store: \"appStore\",\n google_play: \"googlePlay\",\n stripe: \"stripe\",\n other: \"other\",\n});\n\n/** A field a server older than it left out. */\nconst withDefault = <S extends Schema.Top>(schema: S, value: S[\"Encoded\"]) =>\n schema.pipe(Schema.withDecodingDefaultKey(Effect.succeed(value)));\n\nconst GrantValue = Schema.Struct({\n perkId: Schema.String,\n perkSlug: optionalNullable(Schema.String),\n status: enumOrUnknown([\"active\", \"expired\"]),\n source: withDefault(enumOrUnknown([\"subscription\", \"purchase\", \"manual\"]), \"unknown\"),\n sourceId: optionalNullable(Schema.String),\n sourcePersonId: withDefault(Schema.String, \"\"),\n expiresAt: OptionalEpochMillis,\n});\n\n/** Statuses of current and past subscriptions alike: the server sends one list for both. */\nconst SubscriptionStatusValue = renamedEnumOrUnknown({\n active: \"active\",\n trialing: \"trialing\",\n in_grace_period: \"inGracePeriod\",\n in_billing_retry: \"inBillingRetry\",\n on_hold: \"onHold\",\n paused: \"paused\",\n expired: \"expired\",\n revoked: \"revoked\",\n});\n\nconst SubscriptionValue = Schema.Struct({\n subscriptionId: Schema.String,\n productId: optionalNullable(Schema.String),\n productSlug: optionalNullable(Schema.String),\n store: withDefault(StoreValue, \"unknown\"),\n environment: withDefault(\n renamedEnumOrUnknown({ production: \"production\", sandbox: \"sandbox\", test: \"development\" }),\n \"unknown\",\n ),\n status: SubscriptionStatusValue,\n periodType: withDefault(enumOrUnknown([\"trial\", \"intro\", \"regular\"]), \"unknown\"),\n startsAt: OptionalEpochMillis,\n expiresAt: OptionalEpochMillis,\n willRenew: withDefault(Schema.Boolean, false),\n canceledAt: OptionalEpochMillis,\n renewsToProductSlug: optionalNullable(Schema.String),\n gracePeriodExpiresAt: OptionalEpochMillis,\n billingIssueDetectedAt: OptionalEpochMillis,\n resumesAt: OptionalEpochMillis,\n pendingPrice: optionalNullable(\n Schema.Struct({\n amountMicros: Schema.Number,\n currency: Schema.String,\n effectiveAt: OptionalEpochMillis,\n consent: optionalNullable(enumOrUnknown([\"pending\", \"accepted\"])),\n }),\n ),\n offerId: optionalNullable(Schema.String),\n isFamilyShared: withDefault(Schema.Boolean, false),\n refundedAt: OptionalEpochMillis,\n revokedAt: OptionalEpochMillis,\n});\n\nconst SubscriptionHistoryEntryValue = Schema.Struct({\n subscriptionId: Schema.String,\n productId: optionalNullable(Schema.String),\n productSlug: optionalNullable(Schema.String),\n store: withDefault(StoreValue, \"unknown\"),\n status: SubscriptionStatusValue,\n isTrial: withDefault(Schema.Boolean, false),\n startsAt: OptionalEpochMillis,\n expiresAt: OptionalEpochMillis,\n canceledAt: OptionalEpochMillis,\n refundedAt: OptionalEpochMillis,\n sourcePersonId: withDefault(Schema.String, \"\"),\n});\n\nconst PurchaseHistoryEntryValue = Schema.Struct({\n purchaseId: Schema.String,\n productId: optionalNullable(Schema.String),\n productSlug: optionalNullable(Schema.String),\n providerKey: Schema.String,\n type: renamedEnumOrUnknown({\n one_time: \"oneTime\",\n consumable: \"consumable\",\n subscription: \"subscription\",\n }),\n createdAt: OptionalEpochMillis,\n refundedAt: OptionalEpochMillis,\n revokedAt: OptionalEpochMillis,\n sourcePersonId: withDefault(Schema.String, \"\"),\n});\n\n/**\n * A `current` subscription a snapshot cached before the server sent full\n * subscriptions cannot be read as one; it counts as none.\n */\nconst decodeCurrentSubscription = Schema.decodeUnknownOption(SubscriptionValue);\n\nconst PersonJson = Schema.fromJsonString(\n Schema.Struct({\n personId: withDefault(Schema.String, \"\"),\n distinctId: Schema.String,\n email: optionalNullable(Schema.String),\n name: optionalNullable(Schema.String),\n entitlements: withDefault(Schema.Struct({ grants: listOrEmpty(GrantValue) }), { grants: [] }),\n subscriptions: withDefault(\n Schema.Struct({\n current: optionalNullable(Schema.Unknown),\n all: listOrEmpty(SubscriptionValue),\n history: listOrEmpty(SubscriptionHistoryEntryValue),\n }),\n { all: [], history: [] },\n ),\n purchases: withDefault(Schema.Struct({ history: listOrEmpty(PurchaseHistoryEntryValue) }), {\n history: [],\n }),\n }),\n);\n\n/**\n * Reads a person snapshot the native client sent as JSON; `None` when it is\n * not one. Only `distinctId` is required: a snapshot that lacks something\n * else still answers the access it records.\n */\nexport const decodePerson = (json: string): Option.Option<Person> =>\n Option.map(Schema.decodeUnknownOption(PersonJson)(json), (wire): Person => {\n const current = Option.getOrUndefined(decodeCurrentSubscription(wire.subscriptions.current));\n return {\n ...wire,\n subscriptions: {\n all: wire.subscriptions.all,\n history: wire.subscriptions.history,\n ...(current === undefined ? {} : { current }),\n },\n };\n });\n","import * as Arr from \"effect/Array\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Str from \"effect/String\";\nimport { Atom, type AtomRegistry } from \"effect/reactivity\";\n\nimport type { VoidhashError } from \"../../errors\";\nimport type { Person } from \"../entities/person\";\nimport type { Product } from \"../entities/product\";\nimport type { FeatureFlagsResult } from \"../facade-types\";\nimport type { RuntimeSchema } from \"../schema/runtime\";\n\nexport type { FeatureFlagsResult };\n\n// The SDK's state atoms are `keepAlive`: they hold state rather than derive\n// it, so a value published while no component is subscribed (a background\n// refresh, a schema that lands after boot) must still be there for the next\n// read. Each client has its own registry, so nothing outlives the client.\n\n/**\n * Reactive store of the currently identified person. Published together with\n * its freshness through {@link publishCurrentPerson}; read by `useHasPerk`\n * and `useCurrentPerson`.\n */\nexport const currentPersonAtom: Atom.Writable<Option.Option<Person>> = Atom.keepAlive(\n Atom.make<Option.Option<Person>>(Option.none()),\n);\n\n/** How far a published person can be trusted, as the read that produced it reported. */\nexport interface PersonFreshness {\n /** Served from cache past its refresh window. */\n readonly isStale: boolean;\n /** Served from cache past its TTL. */\n readonly isExpired: boolean;\n}\n\n/** Freshness of a snapshot the server has just answered with. */\nexport const FRESH_PERSON: PersonFreshness = { isExpired: false, isStale: false };\n\n/**\n * Freshness of a person the server has not confirmed for this identity yet:\n * nothing is known about it, or all there is was carried over from another\n * identity. Matches what a read reports with nothing cached.\n */\nexport const UNCONFIRMED_PERSON: PersonFreshness = { isExpired: false, isStale: true };\n\n/** Freshness of the value in {@link currentPersonAtom}. */\nexport const currentPersonFreshnessAtom: Atom.Writable<PersonFreshness> = Atom.keepAlive(\n Atom.make<PersonFreshness>(FRESH_PERSON),\n);\n\n/**\n * Publishes the current person together with how far it can be trusted, in\n * one batch, so a hook never pairs a snapshot with another one's freshness.\n */\nexport const publishCurrentPerson = (\n registry: AtomRegistry.AtomRegistry,\n person: Option.Option<Person>,\n freshness: PersonFreshness,\n) =>\n Atom.batch(() => {\n registry.set(currentPersonFreshnessAtom, freshness);\n registry.set(currentPersonAtom, person);\n });\n\n/**\n * Reactive mirror of the runtime schema `SchemaManager` resolved at init and\n * refreshes in the background, for hooks that re-render when a newer schema\n * lands. `None` until init has resolved a schema. Operations read the schema\n * from `SchemaManager` itself, not from here.\n */\nexport const schemaAtom: Atom.Writable<Option.Option<RuntimeSchema>> = Atom.keepAlive(\n Atom.make<Option.Option<RuntimeSchema>>(Option.none()),\n);\n\n/** The products every `useProducts()` reads: one load for the whole client. */\nexport interface ProductsState {\n /** Every product the store returned, sorted by slug; `None` until a load answered. */\n readonly products: Option.Option<ReadonlyArray<Product>>;\n /** The error that stopped the last load; the products of the load before it are kept. */\n readonly error: Option.Option<VoidhashError>;\n /** A load is running. */\n readonly isLoading: boolean;\n}\n\n/** Products before any load. */\nexport const NO_PRODUCTS: ProductsState = {\n error: Option.none(),\n isLoading: false,\n products: Option.none(),\n};\n\n/**\n * The client's products, shared by every `useProducts()`. Loaded again when\n * the identity switches, the schema's product definitions change, or a\n * purchase completes, since offers and their eligibility are the end user's.\n */\nexport const productsAtom: Atom.Writable<ProductsState> = Atom.keepAlive(\n Atom.make<ProductsState>(NO_PRODUCTS),\n);\n\n/**\n * Reactive store of feature flag results, keyed by their normalized flag-key\n * request signature (see {@link normalizeFeatureFlagKeys}). Keeping every\n * request set in its own slot prevents one hook's fetch from overwriting the\n * value of another hook that asked for a different set of flags.\n */\nexport const featureFlagsByKeyAtom: Atom.Writable<Readonly<Record<string, FeatureFlagsResult>>> =\n Atom.keepAlive(Atom.make<Readonly<Record<string, FeatureFlagsResult>>>({}));\n\n/**\n * Counts identity switches: `identify()`, `reset()`, a switch the server\n * refused and the SDK undid. `identify()` and `reset()` clear the person and\n * the flags; hooks read this so a mounted hook refetches for the identity now\n * in place instead of showing the cleared state until it remounts.\n */\nexport const identityEpochAtom: Atom.Writable<number> = Atom.keepAlive(Atom.make(0));\n\n/**\n * Counts the runs of the client: every `init()` that started the native\n * client, the first one included. `end()` drops what a run loaded, such as\n * the products; a hook that loads on mount reads this, so it loads again when\n * the app calls `end()` and then `init()` while it stays mounted.\n */\nexport const clientRunAtom: Atom.Writable<number> = Atom.keepAlive(Atom.make(0));\n\nconst FeatureFlagKeysFromJson = Schema.fromJsonString(Schema.Array(Schema.String));\nconst encodeFeatureFlagKeys = Schema.encodeSync(FeatureFlagKeysFromJson);\n\nconst decodeFeatureFlagKeysFromJson = Schema.decodeSync(FeatureFlagKeysFromJson);\n\n/**\n * The sorted keys a signature other than `\"all\"` was built from; the inverse\n * of {@link normalizeFeatureFlagKeys}.\n */\nexport const decodeFeatureFlagKeys = (signature: string): ReadonlyArray<string> =>\n decodeFeatureFlagKeysFromJson(signature);\n\n/**\n * Normalizes a feature-flag request signature so that any callers asking for\n * the same set of keys (regardless of order) share the same atom slot. We\n * sort a copy because the caller's array is part of their input and must not\n * be mutated.\n */\nexport const normalizeFeatureFlagKeys = (flagKeys?: readonly string[]): string => {\n return Option.match(Option.fromUndefinedOr(flagKeys), {\n onNone: () => \"all\",\n onSome: (keys) =>\n Arr.match(keys, {\n onEmpty: () => \"all\",\n onNonEmpty: (values) => encodeFeatureFlagKeys(Arr.sort(values, Str.Order)),\n }),\n });\n};\n\nconst featureFlagsForNormalizedKeyAtom = Atom.family((normalizedKey: string) =>\n Atom.make((get): Option.Option<FeatureFlagsResult> => {\n const byKey = get(featureFlagsByKeyAtom);\n return Option.fromUndefinedOr(byKey[normalizedKey]);\n }),\n);\n\n/**\n * Derived atom that returns the cached `FeatureFlagsResult` for a particular\n * set of flag keys (or `null` if nothing has been published yet). Reusing\n * the same normalized key across requests means callers subscribe to the\n * minimum slice of state they care about.\n */\nexport const featureFlagsForKeysAtom = (flagKeys?: readonly string[]) =>\n featureFlagsForNormalizedKeyAtom(normalizeFeatureFlagKeys(flagKeys));\n","import * as Effect from \"effect/Effect\";\nimport * as R from \"effect/Record\";\nimport * as Schema from \"effect/Schema\";\n\nimport {\n RuntimePaywallLocationDefinition,\n RuntimePerkDefinition,\n RuntimeProductDefinition,\n type RuntimeSchema,\n} from \"./runtime\";\n\n/** A schema entry this SDK version could not read, left out of the decoded schema. */\nexport interface SkippedSchemaEntry {\n readonly collection: \"locations\" | \"perks\" | \"products\";\n readonly slug: string;\n}\n\nconst decodeLocation = Schema.decodeUnknownResult(RuntimePaywallLocationDefinition);\nconst decodePerk = Schema.decodeUnknownResult(RuntimePerkDefinition);\nconst decodeProduct = Schema.decodeUnknownResult(RuntimeProductDefinition);\n\nconst RuntimeSchemaDocument = Schema.Struct({\n locations: Schema.Record(Schema.String, Schema.Unknown),\n // The native iOS client's schema has no perks of its own; they are read from each product.\n perks: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n products: Schema.Record(Schema.String, Schema.Unknown),\n version: Schema.String,\n});\n\n/**\n * Decodes a schema entry by entry. A product, perk or location this SDK\n * version cannot read is left out and listed in `skipped`, so one entry a\n * newer server shapes differently never costs the app every other product.\n * Fails only when the document itself is not a schema.\n */\nexport const decodeRuntimeSchema = (input: unknown) =>\n Effect.map(Schema.decodeUnknownEffect(RuntimeSchemaDocument)(input), (document) => {\n const [locations, unreadableLocations] = R.partition(document.locations, (entry) =>\n decodeLocation(entry),\n );\n const [perks, unreadablePerks] = R.partition(document.perks ?? {}, (entry) =>\n decodePerk(entry),\n );\n const [products, unreadableProducts] = R.partition(document.products, (entry) =>\n decodeProduct(entry),\n );\n const skipped: ReadonlyArray<SkippedSchemaEntry> = [\n ...R.keys(unreadableLocations).map((slug) => ({ collection: \"locations\" as const, slug })),\n ...R.keys(unreadablePerks).map((slug) => ({ collection: \"perks\" as const, slug })),\n ...R.keys(unreadableProducts).map((slug) => ({ collection: \"products\" as const, slug })),\n ];\n const schema: RuntimeSchema = { locations, perks, products, version: document.version };\n return { schema, skipped };\n });\n","import * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\n/**\n * Product durations the server sends today. Decoded definitions accept any\n * string in their `duration` fields, so a duration added by a newer server\n * keeps its product readable; code that relies on the duration treats a\n * value outside this list as no duration.\n */\nexport const RuntimeProductDuration = Schema.Literals([\n \"weekly\",\n \"monthly\",\n \"quarterly\",\n \"semi-annual\",\n \"annual\",\n]);\nexport type RuntimeProductDuration = typeof RuntimeProductDuration.Type;\n\n/**\n * An offer of a product on one store: `id` is how paywalls and apps name it\n * (the same on every store), `offerId` the store's identifier.\n */\nexport const RuntimeStoreOffer = Schema.Struct({\n id: Schema.String,\n offerId: Schema.String,\n});\nexport type RuntimeStoreOffer = typeof RuntimeStoreOffer.Type;\n\nexport const RuntimeAppleAppStoreProductConfiguration = Schema.Struct({\n offers: Schema.optional(Schema.Array(RuntimeStoreOffer)),\n productId: Schema.String,\n});\nexport type RuntimeAppleAppStoreProductConfiguration =\n typeof RuntimeAppleAppStoreProductConfiguration.Type;\n\nexport const RuntimeGooglePlayProductConfiguration = Schema.Struct({\n basePlanId: Schema.optional(Schema.String),\n /** Developer offers on the base plan. */\n offers: Schema.optional(Schema.Array(RuntimeStoreOffer)),\n productId: Schema.String,\n});\nexport type RuntimeGooglePlayProductConfiguration =\n typeof RuntimeGooglePlayProductConfiguration.Type;\n\n/**\n * Development-mode pricing. `currencyCode` and `period` are plain strings so\n * a currency or period added by a newer server keeps the product readable.\n */\nexport const RuntimeDevelopmentProductConfiguration = Schema.Struct({\n currencyCode: Schema.String,\n duration: Schema.OptionFromNullOr(Schema.String),\n period: Schema.String,\n periodCount: Schema.Number,\n price: Schema.Number,\n priceInMinorUnits: Schema.Number,\n productId: Schema.String,\n warning: Schema.OptionFromNullOr(Schema.String),\n});\nexport type RuntimeDevelopmentProductConfiguration =\n typeof RuntimeDevelopmentProductConfiguration.Type;\n\nexport const RuntimeProductProviders = Schema.Struct({\n appleAppStore: Schema.optional(RuntimeAppleAppStoreProductConfiguration),\n development: Schema.optional(RuntimeDevelopmentProductConfiguration),\n googlePlay: Schema.optional(RuntimeGooglePlayProductConfiguration),\n});\nexport type RuntimeProductProviders = typeof RuntimeProductProviders.Type;\n\n/**\n * One product. `type` is a plain string (the server sends `subscription`,\n * `one-time` or `one-time-consumable` today) so a product type added by a\n * newer server keeps the product readable: only `one-time-consumable` is\n * ever consumed, anything else is finished as a non-consumable.\n */\nexport const RuntimeProductDefinition = Schema.Struct({\n configuration: Schema.Struct({\n perks: Schema.Record(Schema.String, Schema.Literal(true)),\n providers: RuntimeProductProviders,\n }),\n duration: Schema.optional(Schema.OptionFromNullOr(Schema.String)),\n id: Schema.optional(Schema.String),\n properties: Schema.Struct({ name: Schema.String }),\n slug: Schema.String,\n type: Schema.String,\n});\nexport type RuntimeProductDefinition = typeof RuntimeProductDefinition.Type;\n\nexport const RuntimePaywallLocationDefinition = Schema.Struct({\n description: Schema.OptionFromNullOr(Schema.String).pipe(\n Schema.withDecodingDefaultTypeKey(Effect.succeed(Option.none())),\n ),\n name: Schema.String,\n slug: Schema.String,\n});\nexport type RuntimePaywallLocationDefinition = typeof RuntimePaywallLocationDefinition.Type;\n\nexport const RuntimePerkDefinition = Schema.Struct({\n name: Schema.String,\n slug: Schema.String,\n});\nexport type RuntimePerkDefinition = typeof RuntimePerkDefinition.Type;\n\n/**\n * The full schema fetched from the server, decoded so nullable wire fields\n * are represented as `Option` inside the SDK.\n */\nexport const RuntimeSchemaValue = Schema.Struct({\n locations: Schema.Record(Schema.String, RuntimePaywallLocationDefinition),\n perks: Schema.Record(Schema.String, RuntimePerkDefinition),\n products: Schema.Record(Schema.String, RuntimeProductDefinition),\n version: Schema.String,\n});\nexport type RuntimeSchemaValue = typeof RuntimeSchemaValue.Type;\nexport type RuntimeSchema = RuntimeSchemaValue;\nexport type RuntimeSchemaEncoded = typeof RuntimeSchemaValue.Encoded;\n\nexport const createEmptyRuntimeSchema = (): RuntimeSchema => ({\n locations: {},\n perks: {},\n products: {},\n version: \"\",\n});\n","/**\n * Whether the end user agreed to usage analytics. `denied` and `pending` act\n * the same: nothing analytics-related is captured, stored or sent. Purchases,\n * restores, entitlements, identity, flags and paywalls are unaffected.\n */\nexport type AnalyticsConsent = \"granted\" | \"denied\" | \"pending\";\n\n/** Whether `value` is one of the {@link AnalyticsConsent} values. */\nexport const isAnalyticsConsent = (value: unknown): value is AnalyticsConsent =>\n value === \"granted\" || value === \"denied\" || value === \"pending\";\n\n/** What happens to analytics captured while consent is `\"pending\"`. */\nexport type AnalyticsWhilePending = \"drop\" | \"buffer\";\n","import * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\n\n/** What a rejection from a native hybrid says once the bridge's wrapping is removed. */\nexport interface NativeError {\n /** The leading `CODE` of a `\"CODE: detail\"` message, when it has one. */\n readonly code: Option.Option<string>;\n /**\n * The first line of the message. With a code, it starts at the code, so\n * the bridge's prefixes are dropped; without one, it is the whole line,\n * where the exception class or method name is the most useful part.\n */\n readonly message: string;\n}\n\n/** A stable failure code: `USER_CANCELLED`, `STOREKIT_NOT_INITIALIZED`, … */\nconst CODE = /^[A-Z][A-Z0-9_]*$/;\n\n/**\n * A `label: ` in front of the rest of the message: a code, a Java or Kotlin\n * exception class (`com.voidhash.core.billing.BillingEngineException`), or\n * the hybrid method Nitro names for a synchronous throw\n * (`GoogleBilling.buyItemByType(...)`). The rest may be empty: Play often\n * gives no detail, so Android's `\"CODE: detail\"` can end at the colon.\n */\nconst LABEL = /^`?([A-Za-z_$][\\w$.]*(?:\\(\\.\\.\\.\\))?)`?:(?:\\s+([\\s\\S]*))?$/;\n\n/** How many labels can wrap one message: a Nitro method name around an exception class. */\nconst MAX_LABELS = 3;\n\n/**\n * Reads the code and message a native hybrid rejected with.\n *\n * The native SDKs reject with `\"CODE: detail\"`, but the message reaches\n * JavaScript wrapped differently per platform. On Android it is\n * `\"<exception class>: CODE: detail\"`, possibly followed by `\\tat …` stack\n * frames. Nitro puts `\"<Hybrid>.<method>(...): \"` in front of anything a\n * method throws synchronously, on both platforms. An iOS rejection is the\n * Swift error's description, usually the bare `\"CODE: detail\"`.\n *\n * Only the first line is read, so a stack trace never reaches a code\n * comparison or a message shown to the app.\n */\nexport const readNativeError = (error: unknown): NativeError => {\n const raw = P.isError(error) ? error.message : P.isString(error) ? error : String(error);\n const firstLine = (raw.split(/\\r?\\n/, 1)[0] ?? \"\").trim();\n\n const findCode = (message: string, depth: number): Option.Option<NativeError> => {\n if (CODE.test(message)) return Option.some({ code: Option.some(message), message });\n const label = LABEL.exec(message);\n if (label === null) return Option.none();\n const [, name = \"\", rest = \"\"] = label;\n if (CODE.test(name)) return Option.some({ code: Option.some(name), message });\n return depth < MAX_LABELS ? findCode(rest, depth + 1) : Option.none();\n };\n\n return Option.getOrElse(findCode(firstLine, 0), () => ({\n code: Option.none<string>(),\n message: firstLine,\n }));\n};\n\n/** Whether a native rejection carries `code`. */\nexport const hasNativeErrorCode = (error: unknown, code: string): boolean =>\n Option.contains(readNativeError(error).code, code);\n","import * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\n\nimport type {\n NativeProduct,\n NativePurchaseResult,\n NativeTransaction,\n} from \"../../specs/VoidhashNativeClient.nitro\";\nimport { decodeAppStoreProduct, decodeAppStoreTransaction } from \"../entities/app-store\";\nimport { decodeGooglePlayProduct, decodeGooglePlayTransaction } from \"../entities/google-play\";\nimport type { Product } from \"../entities/product\";\nimport type { Transaction } from \"../entities/transaction\";\n\n/*\n * Reads the native SDK's products and transactions into the facade's types.\n * The generic fields arrive as Nitro structs shaped like the facade's own;\n * the `appStore` and `googlePlay` parts arrive as JSON and are decoded here.\n */\n\n/** Receives what the native client sent that breaks its contract; the facade reports it as a diagnostic. */\nexport type ContractViolation = (message: string) => void;\n\n/** The facade's result of a purchase that went through to the store. */\nexport type StorePurchaseResult =\n | { readonly status: \"purchased\"; readonly transaction: Transaction; readonly synced: boolean }\n | { readonly status: \"pending\" }\n | { readonly status: \"cancelled\" };\n\n/**\n * A store part sent as JSON, decoded. An unreadable part is left out and\n * reported: the product or transaction is still usable through its generic\n * fields.\n */\nconst decodePart = <A>(\n // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the Nitro contract, where an optional is `undefined`.\n json: string | undefined,\n decode: (json: string) => Option.Option<A>,\n onUnreadable: () => void,\n): Option.Option<A> =>\n Option.flatMap(Option.fromUndefinedOr(json), (value) => {\n const decoded = decode(value);\n if (Option.isNone(decoded)) onUnreadable();\n return decoded;\n });\n\n/**\n * A product as the facade types it. A `subscription` without its\n * subscription info breaks the contract and is left out (`None`), reported:\n * the types `voidhash-cli types generate` writes promise that a subscription\n * slug is a `SubscriptionProduct` or missing, never another type.\n */\nexport const toProduct = (\n native: NativeProduct,\n violation: ContractViolation,\n): Option.Option<Product> => {\n const appStore = decodePart(native.appStoreJson, decodeAppStoreProduct, () =>\n violation(`The App Store part of product \"${native.slug}\" could not be read`),\n );\n const googlePlay = decodePart(native.googlePlayJson, decodeGooglePlayProduct, () =>\n violation(`The Google Play part of product \"${native.slug}\" could not be read`),\n );\n const fields = {\n description: native.description,\n displayName: native.displayName,\n name: native.name,\n offers: native.offers,\n price: native.price,\n productId: native.productId,\n slug: native.slug,\n store: native.store,\n storeProductId: native.storeProductId,\n ...Option.match(appStore, { onNone: () => ({}), onSome: (part) => ({ appStore: part }) }),\n ...Option.match(googlePlay, { onNone: () => ({}), onSome: (part) => ({ googlePlay: part }) }),\n };\n return Match.value(native.type).pipe(\n Match.withReturnType<Option.Option<Product>>(),\n Match.when(\"subscription\", () => {\n if (native.subscription !== undefined) {\n return Option.some({ ...fields, subscription: native.subscription, type: \"subscription\" });\n }\n violation(\n `Subscription product \"${native.slug}\" came without its subscription info and is left out`,\n );\n return Option.none();\n }),\n Match.when(\"consumable\", (type) => Option.some({ ...fields, type })),\n Match.when(\"nonConsumable\", (type) => Option.some({ ...fields, type })),\n Match.when(\"nonRenewingSubscription\", (type) => Option.some({ ...fields, type })),\n Match.when(\"unknown\", () =>\n Option.some(\n native.subscription === undefined\n ? { ...fields, type: \"unknown\" }\n : { ...fields, subscription: native.subscription, type: \"unknown\" },\n ),\n ),\n Match.exhaustive,\n );\n};\n\n/** A transaction as the facade types it. */\nexport const toTransaction = (\n native: NativeTransaction,\n violation: ContractViolation,\n): Transaction => {\n const appStore = decodePart(native.appStoreJson, decodeAppStoreTransaction, () =>\n violation(`The App Store part of transaction ${native.id} could not be read`),\n );\n const googlePlay = decodePart(native.googlePlayJson, decodeGooglePlayTransaction, () =>\n violation(`The Google Play part of transaction ${native.id} could not be read`),\n );\n return {\n environment: native.environment,\n id: native.id,\n purchasedAt: native.purchasedAt,\n quantity: native.quantity,\n store: native.store,\n storeProductId: native.storeProductId,\n ...(native.originalId === undefined ? {} : { originalId: native.originalId }),\n ...(native.productSlug === undefined ? {} : { productSlug: native.productSlug }),\n ...(native.expiresAt === undefined ? {} : { expiresAt: native.expiresAt }),\n ...(native.isRenewal === undefined ? {} : { isRenewal: native.isRenewal }),\n ...(native.offer === undefined ? {} : { offer: native.offer }),\n ...Option.match(appStore, { onNone: () => ({}), onSome: (part) => ({ appStore: part }) }),\n ...Option.match(googlePlay, { onNone: () => ({}), onSome: (part) => ({ googlePlay: part }) }),\n };\n};\n\n/**\n * A purchase result as the facade types it. A `purchased` result without its\n * transaction breaks the contract and reads as `None`.\n */\nexport const toPurchaseResult = (\n native: NativePurchaseResult,\n violation: ContractViolation,\n): Option.Option<StorePurchaseResult> =>\n Match.value(native.outcome).pipe(\n Match.withReturnType<Option.Option<StorePurchaseResult>>(),\n Match.when(\"purchased\", () =>\n Option.map(Option.fromUndefinedOr(native.transaction), (transaction) => ({\n status: \"purchased\" as const,\n synced: native.synced ?? false,\n transaction: toTransaction(transaction, violation),\n })),\n ),\n Match.when(\"pending\", () => Option.some({ status: \"pending\" as const })),\n Match.when(\"cancelled\", () => Option.some({ status: \"cancelled\" as const })),\n Match.exhaustive,\n );\n","import * as Effect from \"effect/Effect\";\nimport type * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport { enumOrUnknown, listOrEmpty, optionalNullable, PriceValue } from \"./decoding\";\nimport type { Price } from \"./product\";\n\n/*\n * Google Play's own view of products and purchases, with Play Billing's field\n * names. The native client sends each as JSON; the decoders here read it\n * forward-compatibly.\n */\n\n/** Play Billing's `ProductType`: `subs` for subscriptions, `inapp` for one-time products. */\nexport type GooglePlayProductType = \"subs\" | \"inapp\" | \"unknown\";\n\n/** Play Billing's `RecurrenceMode` of a pricing phase. */\nexport type GooglePlayRecurrenceMode = \"infinite\" | \"finite\" | \"nonRecurring\" | \"unknown\";\n\n/** A Play Billing `PricingPhase`. */\nexport interface GooglePlayPricingPhase {\n readonly formattedPrice: string;\n readonly priceAmountMicros: number;\n readonly priceCurrencyCode: string;\n /** ISO 8601 duration, such as `P1M`. */\n readonly billingPeriod: string;\n readonly billingCycleCount: number;\n readonly recurrenceMode: GooglePlayRecurrenceMode;\n}\n\n/** A Play Billing installment plan of a subscription offer. */\nexport interface GooglePlayInstallmentPlan {\n readonly commitmentPaymentsCount: number;\n readonly subsequentCommitmentPaymentsCount: number;\n}\n\n/** A Play Billing `SubscriptionOfferDetails`: a base plan, or an offer on one. */\nexport interface GooglePlaySubscriptionOffer {\n readonly basePlanId: string;\n /** Absent for the base plan itself. */\n readonly offerId?: string;\n /** Pass it as `googlePlay.offerToken` to buy exactly this offer. */\n readonly offerToken: string;\n readonly offerTags: ReadonlyArray<string>;\n readonly pricingPhases: ReadonlyArray<GooglePlayPricingPhase>;\n readonly installmentPlan?: GooglePlayInstallmentPlan;\n}\n\n/** A Play Billing `OneTimePurchaseOfferDetails`. */\nexport interface GooglePlayOneTimeOffer {\n readonly purchaseOptionId?: string;\n readonly offerId?: string;\n /** Pass it as `googlePlay.offerToken` to buy exactly this offer. */\n readonly offerToken: string;\n readonly offerTags: ReadonlyArray<string>;\n readonly price: Price;\n /** The price before the discount. */\n readonly fullPrice?: Price;\n readonly discountPercentage?: number;\n readonly limitedQuantity?: {\n readonly maximumQuantity: number;\n readonly remainingQuantity: number;\n };\n /** When the offer can be bought; an open end is absent. */\n readonly validTimeWindow?: { readonly startTimeMillis?: number; readonly endTimeMillis?: number };\n readonly preorder?: { readonly releaseTimeMillis: number; readonly presaleEndTimeMillis: number };\n readonly rental?: { readonly rentalPeriod: string; readonly rentalExpirationPeriod?: string };\n}\n\n/** A Play Billing `ProductDetails` as Google Play reports it. */\nexport interface GooglePlayProductInfo {\n /** The Google Play product id. */\n readonly productId: string;\n readonly productType: GooglePlayProductType;\n /** The base plan this product is bound to in Studio. */\n readonly basePlanId?: string;\n /** Every offer Google Play returned, on every base plan. */\n readonly subscriptionOffers: ReadonlyArray<GooglePlaySubscriptionOffer>;\n readonly oneTimeOffers: ReadonlyArray<GooglePlayOneTimeOffer>;\n}\n\n/** Play Billing's `Purchase.PurchaseState`. */\nexport type GooglePlayPurchaseState = \"purchased\" | \"pending\" | \"unknown\";\n\n/** A Play Billing `Purchase` as Google Play reports it. */\nexport interface GooglePlayTransactionInfo {\n readonly orderId?: string;\n readonly purchaseToken: string;\n readonly productIds: ReadonlyArray<string>;\n readonly purchaseState: GooglePlayPurchaseState;\n readonly isAcknowledged: boolean;\n readonly isAutoRenewing?: boolean;\n /** The account id the purchase was made with: the end user's Voidhash identity. */\n readonly obfuscatedAccountId?: string;\n readonly obfuscatedProfileId?: string;\n /**\n * Whether Google Play suspended the subscription (its payment method\n * failed). A suspended purchase grants nothing.\n */\n readonly isSuspended: boolean;\n}\n\n/**\n * How `showInAppMessages()` ended: nothing to do, or the end user fixed their\n * payment method for the subscription whose purchase token it names.\n */\nexport type GooglePlayInAppMessageResult =\n | { readonly status: \"noActionNeeded\" }\n | { readonly status: \"subscriptionStatusUpdated\"; readonly purchaseToken: string };\n\n/** A Play Billing feature `isFeatureSupported()` asks about, by `BillingClient.FeatureType`. */\nexport type GooglePlayBillingFeature =\n | \"subscriptions\"\n | \"subscriptionsUpdate\"\n | \"inAppMessaging\"\n | \"productDetails\"\n | \"billingConfig\"\n | \"alternativeBillingOnly\"\n | \"externalOffer\";\n\nconst GooglePlaySubscriptionOfferValue = Schema.Struct({\n basePlanId: Schema.String,\n offerId: optionalNullable(Schema.String),\n offerToken: Schema.String,\n offerTags: listOrEmpty(Schema.String),\n pricingPhases: listOrEmpty(\n Schema.Struct({\n formattedPrice: Schema.String,\n priceAmountMicros: Schema.Number,\n priceCurrencyCode: Schema.String,\n billingPeriod: Schema.String,\n billingCycleCount: Schema.Number,\n recurrenceMode: enumOrUnknown([\"infinite\", \"finite\", \"nonRecurring\"]),\n }),\n ),\n installmentPlan: optionalNullable(\n Schema.Struct({\n commitmentPaymentsCount: Schema.Number,\n subsequentCommitmentPaymentsCount: Schema.Number,\n }),\n ),\n});\n\nconst GooglePlayOneTimeOfferValue = Schema.Struct({\n purchaseOptionId: optionalNullable(Schema.String),\n offerId: optionalNullable(Schema.String),\n offerToken: Schema.String,\n offerTags: listOrEmpty(Schema.String),\n price: PriceValue,\n fullPrice: optionalNullable(PriceValue),\n discountPercentage: optionalNullable(Schema.Number),\n limitedQuantity: optionalNullable(\n Schema.Struct({ maximumQuantity: Schema.Number, remainingQuantity: Schema.Number }),\n ),\n validTimeWindow: optionalNullable(\n Schema.Struct({\n startTimeMillis: optionalNullable(Schema.Number),\n endTimeMillis: optionalNullable(Schema.Number),\n }),\n ),\n preorder: optionalNullable(\n Schema.Struct({ releaseTimeMillis: Schema.Number, presaleEndTimeMillis: Schema.Number }),\n ),\n rental: optionalNullable(\n Schema.Struct({\n rentalPeriod: Schema.String,\n rentalExpirationPeriod: optionalNullable(Schema.String),\n }),\n ),\n});\n\nconst GooglePlayProductJson = Schema.fromJsonString(\n Schema.Struct({\n productId: Schema.String,\n productType: enumOrUnknown([\"subs\", \"inapp\"]),\n basePlanId: optionalNullable(Schema.String),\n subscriptionOffers: listOrEmpty(GooglePlaySubscriptionOfferValue),\n oneTimeOffers: listOrEmpty(GooglePlayOneTimeOfferValue),\n }),\n);\n\nconst GooglePlayTransactionJson = Schema.fromJsonString(\n Schema.Struct({\n orderId: optionalNullable(Schema.String),\n purchaseToken: Schema.String,\n productIds: listOrEmpty(Schema.String),\n purchaseState: enumOrUnknown([\"purchased\", \"pending\"]),\n isAcknowledged: Schema.Boolean,\n isAutoRenewing: optionalNullable(Schema.Boolean),\n obfuscatedAccountId: optionalNullable(Schema.String),\n obfuscatedProfileId: optionalNullable(Schema.String),\n isSuspended: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(false))),\n }),\n);\n\n/** Reads a product's Google Play part; `None` when it is not one. */\nexport const decodeGooglePlayProduct = (json: string): Option.Option<GooglePlayProductInfo> =>\n Schema.decodeUnknownOption(GooglePlayProductJson)(json);\n\n/** Reads a transaction's Google Play part; `None` when it is not one. */\nexport const decodeGooglePlayTransaction = (\n json: string,\n): Option.Option<GooglePlayTransactionInfo> =>\n Schema.decodeUnknownOption(GooglePlayTransactionJson)(json);\n","import * as Arr from \"effect/Array\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\nimport * as R from \"effect/Record\";\n\nimport { InvalidArgumentError } from \"../errors\";\n\n/** A value a person trait can hold. The person API stores flat scalars only. */\n// oxlint-disable-next-line effect/prefer-option-over-null -- a JSON trait value; `null` clears the trait.\ntype TraitValue = string | number | boolean | null;\n\nconst isTraitValue = (value: unknown): value is TraitValue =>\n value === null || P.isString(value) || P.isNumber(value) || P.isBoolean(value);\n\n/**\n * Why `attributes` can never be written, or `None` when they can. The person\n * API stores flat traits only, so a nested object or an array is refused here,\n * before anything is sent or queued, whether or not the device is online.\n */\nexport const invalidPersonAttributes = (\n attributes: unknown,\n): Option.Option<InvalidArgumentError> => {\n if (!P.isObject(attributes)) {\n return Option.some(new InvalidArgumentError(\"Person attributes must be an object\"));\n }\n const invalidKeys = R.keys(\n R.filter(attributes, (value, key) =>\n key === \"email\" || key === \"name\"\n ? value !== undefined && !P.isString(value)\n : value !== undefined && !isTraitValue(value),\n ),\n );\n return Arr.match(invalidKeys, {\n onEmpty: () => Option.none(),\n onNonEmpty: (keys) =>\n Option.some(\n new InvalidArgumentError(\n `Invalid person attributes (${keys.join(\", \")}): trait values must be strings, numbers, booleans or null, and email and name must be strings`,\n ),\n ),\n });\n};\n","import * as Arr from \"effect/Array\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\nimport * as R from \"effect/Record\";\nimport * as Result from \"effect/Result\";\n\nimport { SCREEN_PROPERTIES } from \"../analytics/constants\";\n\n/** Integration that observed a screen transition. */\nexport type ScreenSource =\n | \"expo-router\"\n | \"react-navigation\"\n | \"nitro-ui-navigation\"\n | \"uikit\"\n | \"swiftui\"\n | \"android-activity\"\n | \"android-fragment\"\n | \"compose-navigation\"\n | \"manual\";\n\n/** One screen the user arrived on, as reported by an integration. */\nexport interface ScreenView {\n /**\n * Router-owned token identifying this screen instance (route key, pathname,\n * controller instance). Two views with the same identity are the same screen\n * and only the first one emits.\n */\n identity: string;\n /** Stable, low-cardinality screen identity. Never contains ids. */\n name: string;\n /** Concrete location, with dynamic segment values filled in. */\n path: string;\n /** Human title when the platform exposes one. */\n title?: string;\n /** Route params. Only forwarded when `includeParams` is on. */\n params?: Record<string, unknown>;\n source: ScreenSource;\n}\n\nexport interface ScreenTrackerOptions {\n /** `false` turns every transition into a no-op. */\n enabled: boolean;\n /** Adds `$screen_params` to the emitted properties. */\n includeParams: boolean;\n /** Rewrites or drops a screen before it reaches the tracker. Return `None` to skip. */\n mapScreen?: (view: ScreenView) => Option.Option<ScreenView>;\n /** Clock used for `$previous_screen_duration_ms`. Defaults to `Date.now`. */\n now?: () => number;\n}\n\nexport interface ScreenTracker {\n /**\n * Feeds one screen arrival through the state machine. Returns the `$screen`\n * properties to capture, or `None` when nothing should be emitted (tracking\n * disabled, same screen instance, or dropped by `mapScreen`).\n */\n transition: (view: ScreenView) => Option.Option<Record<string, unknown>>;\n /** Forgets the current screen so the next transition has `null` previous fields. */\n reset: () => void;\n}\n\n/** Client-side bound on `$screen_name` and `$screen_path`. */\nexport const SCREEN_NAME_MAX_LENGTH = 200;\n/** Client-side bound on the number of `$screen_params` keys. */\nexport const SCREEN_PARAMS_MAX_KEYS = 20;\n\ninterface CurrentScreen {\n identity: string;\n name: string;\n path: string;\n arrivedAt: number;\n}\n\nconst truncate = (value: string) => value.slice(0, SCREEN_NAME_MAX_LENGTH);\n\n/**\n * A route param as text. An object with no text form (one without a\n * prototype, or whose `toString` throws) reads like any other object.\n */\nconst coerceParam = (value: unknown): string =>\n P.isString(value)\n ? value\n : Array.isArray(value)\n ? value.map(coerceParam).join(\",\")\n : Result.getOrElse(\n Result.try(() => String(value)),\n () => \"[object Object]\",\n );\n\nconst coerceParams = (params: Record<string, unknown>): Record<string, string> =>\n R.fromEntries(\n Arr.map(\n Arr.take(R.toEntries(params), SCREEN_PARAMS_MAX_KEYS),\n ([key, value]) => [key, coerceParam(value)] as const,\n ),\n );\n\n/**\n * Creates the pure screen transition state machine shared by every screen\n * tracking integration. It owns only the previous-screen state; capturing the\n * returned properties is the caller's job.\n */\nexport function createScreenTracker(options: ScreenTrackerOptions): ScreenTracker {\n // oxlint-disable-next-line effect/use-clock-service -- synchronous, non-Effect state machine: the `now` option is the injection seam (tests pass a fake clock) and `Date.now` is only the production default.\n const now = options.now ?? Date.now;\n let state = Option.none<CurrentScreen>();\n\n const transition = (input: ScreenView): Option.Option<Record<string, unknown>> => {\n if (!options.enabled) {\n return Option.none();\n }\n const mappedView = options.mapScreen ? options.mapScreen(input) : Option.some(input);\n if (Option.isNone(mappedView)) {\n return Option.none();\n }\n const mapped = mappedView.value;\n if (Option.isSome(state) && state.value.identity === mapped.identity) {\n return Option.none();\n }\n\n const arrivedAt = now();\n const name = truncate(mapped.name);\n const path = truncate(mapped.path);\n const previous = Option.getOrNull(state);\n\n const properties: Record<string, unknown> = {\n [SCREEN_PROPERTIES.NAME]: name,\n [SCREEN_PROPERTIES.PATH]: path,\n [SCREEN_PROPERTIES.SOURCE]: mapped.source,\n [SCREEN_PROPERTIES.PREVIOUS_NAME]: previous?.name ?? null,\n [SCREEN_PROPERTIES.PREVIOUS_PATH]: previous?.path ?? null,\n // A clock set back between two screens must not report a negative stay.\n [SCREEN_PROPERTIES.PREVIOUS_DURATION_MS]: previous\n ? Math.max(arrivedAt - previous.arrivedAt, 0)\n : null,\n };\n if (P.isString(mapped.title) && mapped.title !== \"\") {\n properties[SCREEN_PROPERTIES.TITLE] = mapped.title;\n }\n if (options.includeParams && P.isObject(mapped.params)) {\n properties[SCREEN_PROPERTIES.PARAMS] = coerceParams(mapped.params);\n }\n\n state = Option.some({ identity: mapped.identity, name, path, arrivedAt });\n return Option.some(properties);\n };\n\n return {\n transition,\n reset: () => {\n state = Option.none();\n },\n };\n}\n","/**\n * Prefix of the anonymous ids the SDK creates, `vh_anon_<uuid>`: only letters,\n * digits, `_` and `-`, so the id fits any payment provider's field.\n */\nexport const ANONYMOUS_DISTINCT_ID_PREFIX = \"vh_anon_\";\n\n/** Prefix of the anonymous ids earlier SDK builds created, which a stored id may still carry. */\nexport const LEGACY_ANONYMOUS_DISTINCT_ID_PREFIX = \"vh:anon:\";\n\n/**\n * Whether a distinct id is one the SDK made for an anonymous end user: `vh_anon_<uuid>`, or the\n * `vh:anon:` form a device may still hold from an earlier SDK build. Use it instead of checking a\n * prefix, for example to sign out only an identified person.\n */\nexport const isAnonymousDistinctId = (distinctId: string): boolean =>\n distinctId.startsWith(ANONYMOUS_DISTINCT_ID_PREFIX) ||\n distinctId.startsWith(LEGACY_ANONYMOUS_DISTINCT_ID_PREFIX);\n","export class Perk {}\n","import * as Result from \"effect/Result\";\nimport { Platform } from \"nitro-ui-core\";\n\nimport type { VoidhashClientOptions } from \"../../react-native/src/client\";\nimport { createVoidhashClientOnHost } from \"../../react-native/src/client-host\";\nimport * as NativeClientSpec from \"./specs/VoidhashNativeClient.nitro\";\n\n/**\n * A new native client, one per `VoidhashClient`: it holds a client's state,\n * so it is never shared. NitroUI links this package's native module into\n * every build of an app that depends on it, so the class is looked up and\n * constructed only here, when a client starts: a binary built before the app\n * added the package (a JavaScript update onto an older build) has no such\n * class, and its lookup or construction throws. That yields `None`, so the\n * client fails `init()` with a coded error instead of the app failing to load.\n */\nconst createVoidhashNativeClient = () =>\n Result.getSuccess(Result.try(() => new NativeClientSpec.VoidhashNativeClient()));\n\n/**\n * Bootstrap the Voidhash SDK for a NitroUI app.\n *\n * - There is no schema argument. The schema lives on the server and is\n * fetched on `Provider` mount.\n * - Type safety for product / location / perk slugs comes from the generated\n * `voidhash.gen.d.ts` (run `voidhash-cli types generate`).\n * - No `publishableKey` (`null`, `undefined` or blank), or\n * `options.enabled: false` returns a fully inert client: the provider and\n * every hook still mount (so hook order never changes), but nothing\n * initializes.\n * - An `analyticsConsent` other than `\"granted\"`, `\"denied\"` or `\"pending\"`\n * throws an `INVALID_ARGUMENT` error in development builds; release builds\n * use `\"granted\"` and report `INVALID_CONFIGURATION`.\n * - A `featureFlags.maxWaitMs` that is not zero or a positive integer, or a\n * `featureFlags.defaults` entry that is not a boolean, throws an\n * `INVALID_ARGUMENT` error in development builds; release builds ignore it\n * and report `INVALID_CONFIGURATION`.\n * - A blank `distinctId`, `baseUrl` or `ingestUrl` counts as absent, and\n * whitespace around a `baseUrl` or `ingestUrl` is removed. A\n * `baseUrl` or `ingestUrl` that is not an absolute `http(s)` URL throws an\n * `INVALID_ARGUMENT` error in development builds; release builds use the\n * default origin and report `INVALID_CONFIGURATION` through `onDiagnostic`.\n * - A build without this package's native module (a JavaScript update onto\n * an app binary built before the package was added) loads normally;\n * `init()` then fails with `FAILED_TO_INITIALIZE_VOIDHASH_CLIENT`.\n */\nexport function createVoidhashClient(\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK input from non-Effect app code; an environment without a key naturally holds null or undefined.\n publishableKey: string | null | undefined,\n options: VoidhashClientOptions = {},\n) {\n return createVoidhashClientOnHost(\n {\n createNativeClient: createVoidhashNativeClient,\n packageName: \"@voidhash/nitro-ui\",\n platform: Platform.OS,\n },\n publishableKey,\n options,\n );\n}\n","import * as Arr from \"effect/Array\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\nimport * as R from \"effect/Record\";\nimport { AtomRegistry } from \"effect/reactivity\";\n\nimport { type FeatureFlagsOptions, VoidhashClient, type VoidhashClientOptions } from \"./client\";\nimport { DIAGNOSTIC_CODES, makeDiagnosticEmitter } from \"./core/diagnostics/diagnostics\";\nimport { InvalidArgumentError } from \"./errors\";\nimport { isAnalyticsConsent } from \"./core/sdk-configuration\";\nimport type { NativeClientPort } from \"./core/native/native-client\";\nimport { DEFAULT_FLOW_CAPABILITIES } from \"./core/flows/flows\";\nimport { voidhashProviderFactory } from \"./react/components/provider\";\nimport { currentPersonHookFactory } from \"./react/hooks/use-person\";\nimport { featureFlagsHookFactory } from \"./react/hooks/use-feature-flags\";\nimport { hasPerkHookFactory } from \"./react/hooks/use-has-perk\";\nimport { presentFlowHookFactory } from \"./react/hooks/use-present-flow\";\nimport { productsHookFactory } from \"./react/hooks/use-products\";\nimport { purchaseHookFactory } from \"./react/hooks/use-purchase\";\nimport { restorePurchasesHookFactory } from \"./react/hooks/use-restore-purchases\";\nimport { subscriptionsHookFactory } from \"./react/hooks/use-subscriptions\";\n\nlet nativeEngineWarningShown = false;\n\nconst DEFAULT_BASE_URL = \"https://api.voidhash.com\";\n\n/**\n * An absolute `http(s)` URL with a host. Checked with a pattern rather than\n * `new URL()`: React Native's built-in `URL` accepts any string without\n * validating it, and apps may replace it with a stricter polyfill.\n */\nconst ABSOLUTE_HTTP_URL = /^https?:\\/\\/[^\\s/?#]+(?:[/?#]\\S*)?$/i;\n\n/**\n * Resolves a configured origin, without the whitespace around it: a value read\n * from an environment file often ends with a newline, which the native URL\n * parsers refuse or turn into a host that never resolves. A missing or blank\n * value is absent. Anything else must be an absolute `http(s)` URL: requests\n * to a relative or scheme-less origin fail like an outage forever, so\n * development builds throw and release builds fall back to the default origin\n * and report it once.\n */\nconst resolveOrigin = (\n option: \"baseUrl\" | \"ingestUrl\",\n configured: Option.Option<string>,\n emitDiagnostic: ReturnType<typeof makeDiagnosticEmitter>,\n): Option.Option<string> => {\n const value = Option.filter(\n Option.map(configured, (origin) => origin.trim()),\n (origin) => origin !== \"\",\n );\n if (Option.isNone(value) || ABSOLUTE_HTTP_URL.test(value.value)) return value;\n if (__DEV__) {\n throw new InvalidArgumentError(\n `${option} must be an absolute http(s) URL such as \"https://api.example.com\", got \"${value.value}\"`,\n );\n }\n emitDiagnostic({\n code: DIAGNOSTIC_CODES.INVALID_CONFIGURATION,\n kind: \"configuration\",\n message: `Ignored ${option} \"${value.value}\": it is not an absolute http(s) URL, so the default origin is used`,\n operation: \"createVoidhashClient\",\n retryable: false,\n });\n return Option.none();\n};\n\n/**\n * Validates the `featureFlags` option. A `maxWaitMs` that is not a\n * non-negative integer, or a default that is not a boolean, throws an\n * `INVALID_ARGUMENT` error in development builds; release builds ignore it\n * (the native default wait, or no default for that flag) and report it once.\n */\nconst resolveFeatureFlagOptions = (\n options: FeatureFlagsOptions,\n emitDiagnostic: ReturnType<typeof makeDiagnosticEmitter>,\n) => {\n const refuse = (message: string, fallback: string) => {\n if (__DEV__) throw new InvalidArgumentError(message);\n emitDiagnostic({\n code: DIAGNOSTIC_CODES.INVALID_CONFIGURATION,\n kind: \"configuration\",\n message: `Ignored ${message}; ${fallback}`,\n operation: \"createVoidhashClient\",\n retryable: false,\n });\n };\n const isValidWait = (wait: number) => Number.isInteger(wait) && wait >= 0;\n const maxWaitMs = Option.fromUndefinedOr(options.maxWaitMs);\n if (Option.isSome(maxWaitMs) && !isValidWait(maxWaitMs.value)) {\n refuse(\n `featureFlags.maxWaitMs must be zero or a positive integer, got ${String(maxWaitMs.value)}`,\n \"the default wait is used\",\n );\n }\n const configuredDefaults: Readonly<Record<string, unknown>> = options.defaults ?? {};\n R.toEntries(configuredDefaults).forEach(([key, value]) => {\n if (P.isBoolean(value)) return;\n refuse(\n `featureFlags.defaults[\"${key}\"] must be true or false, got ${String(value)}`,\n \"the flag has no default\",\n );\n });\n const defaults = R.filter(configuredDefaults, P.isBoolean);\n return { defaults, maxWaitMs: Option.filter(maxWaitMs, isValidWait) };\n};\n\n/**\n * What an app framework gives the SDK: the platform the app runs on and how\n * to create the native client there. React Native and NitroUI each supply\n * their own; the option handling and the client are the same for both.\n */\nexport interface VoidhashHost {\n /**\n * The platform the app runs on, as the framework's `Platform.OS` names it.\n * The client is enabled on `\"ios\"` and `\"android\"` only; Android runs one\n * native client per process.\n */\n readonly platform: string;\n /**\n * A new native client, one per `VoidhashClient`, or `None` where the\n * installed binary has none. It must not throw: a creation that fails\n * yields `None`, so `init()` fails with a coded error instead of the bundle\n * failing to load.\n */\n readonly createNativeClient: () => Option.Option<NativeClientPort>;\n /** The npm package the app installs, which a failure that needs a new native build names. */\n readonly packageName: string;\n}\n\n/**\n * Validates the options of `createVoidhashClient` and builds the client, its\n * provider and its hooks on `host`. Each framework's `createVoidhashClient`\n * documents the behaviour for app developers.\n */\nexport function createVoidhashClientOnHost(\n host: VoidhashHost,\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK input from non-Effect app code; an environment without a key naturally holds null or undefined.\n publishableKey: string | null | undefined,\n options: VoidhashClientOptions = {},\n) {\n const key = publishableKey?.trim() ?? \"\";\n const emitDiagnostic = makeDiagnosticEmitter(Option.fromUndefinedOr(options.onDiagnostic));\n const baseUrl = Option.getOrElse(\n resolveOrigin(\"baseUrl\", Option.fromUndefinedOr(options.baseUrl), emitDiagnostic),\n () => DEFAULT_BASE_URL,\n );\n const debug = options.debug ?? false;\n const dev = options.dev ?? false;\n const distinctId = Option.fromUndefinedOr(options.distinctId);\n const enabled =\n (options.enabled ?? true) &&\n key !== \"\" &&\n (host.platform === \"ios\" || host.platform === \"android\");\n const ingestUrl = resolveOrigin(\n \"ingestUrl\",\n Option.fromUndefinedOr(options.ingestUrl),\n emitDiagnostic,\n );\n const readOnly = options.readOnly ?? false;\n const analyticsConsent = options.analyticsConsent ?? \"granted\";\n if (!isAnalyticsConsent(analyticsConsent)) {\n const message = `analyticsConsent must be \"granted\", \"denied\" or \"pending\", got \"${String(analyticsConsent)}\"`;\n if (__DEV__) throw new InvalidArgumentError(message);\n emitDiagnostic({\n code: DIAGNOSTIC_CODES.INVALID_CONFIGURATION,\n kind: \"configuration\",\n message: `Ignored ${message}; \"granted\" is used`,\n operation: \"createVoidhashClient\",\n retryable: false,\n });\n }\n const featureFlags = resolveFeatureFlagOptions(options.featureFlags ?? {}, emitDiagnostic);\n if (options.unstable_nativeEngine === true && __DEV__ && !nativeEngineWarningShown) {\n nativeEngineWarningShown = true;\n // oxlint-disable-next-line effect/use-console-service -- a one-time development notice for the app developer, printed before any SDK runtime exists.\n console.warn(\n \"[voidhash] unstable_nativeEngine no longer has an effect; the SDK always runs on its native client.\",\n );\n }\n\n const client = new VoidhashClient({\n analyticsConsent: isAnalyticsConsent(analyticsConsent) ? analyticsConsent : \"granted\",\n analyticsWhilePending: options.analyticsWhilePending === \"buffer\" ? \"buffer\" : \"drop\",\n appStoreMessages:\n options.appStoreMessages === \"automatic\" ? \"automatic\" : \"deferWhileFlowPresented\",\n atomRegistry: AtomRegistry.make(),\n automaticLifecycleEvents: options.automaticLifecycleEvents ?? true,\n baseUrl,\n createNativeClient: host.createNativeClient,\n debug,\n developmentMode: __DEV__ && dev,\n // A blank configured id counts as absent: the SDK keeps (or mints) the\n // anonymous identity instead of adopting one no request can carry.\n distinctId: Option.filter(distinctId, (id) => P.isString(id) && id.trim() !== \"\"),\n enabled,\n featureFlagDefaults: featureFlags.defaults,\n featureFlagMaxWaitMs: featureFlags.maxWaitMs,\n grantConsentOnIdentify: options.grantConsentOnIdentify ?? false,\n flowCapabilities: Arr.dedupe(options.flowCapabilities ?? DEFAULT_FLOW_CAPABILITIES),\n flowRevisions: options.flowRevisions ?? {},\n flowRuntime: options.flowRuntime === \"module\" ? \"module\" : \"linked\",\n flowLoading: options.flowLoading === \"none\" ? \"none\" : \"standard\",\n ingestUrl,\n installAttribution: options.installAttribution ?? true,\n internalSchema: Option.fromUndefinedOr(options.unstable_internalSchema),\n metaAppId: Option.fromUndefinedOr(options.metaAppId),\n oneNativeClientPerProcess: host.platform === \"android\",\n onDiagnostic: Option.fromUndefinedOr(options.onDiagnostic),\n packageName: host.packageName,\n platform: host.platform,\n preloadLocations: options.preloadLocations ?? [],\n publishableKey: key,\n purchaseIntents: options.purchaseIntents === \"manual\" ? \"manual\" : \"purchaseWhenReady\",\n readOnly,\n scheme: options.scheme ?? \"\",\n screenTracking: options.screenTracking ?? {},\n unstableSwallowErrors: options.unstable_swallowErrors ?? false,\n });\n\n const { provider, context, useVoidhash } = voidhashProviderFactory(client);\n const useCurrentPerson = currentPersonHookFactory(client, context);\n\n return {\n Provider: provider,\n /** App Store actions, as `client.appStore`. */\n appStore: client.appStore,\n client,\n /** Google Play actions, as `client.googlePlay`. */\n googlePlay: client.googlePlay,\n useCurrentPerson,\n useFeatureFlags: featureFlagsHookFactory(client, context),\n useHasPerk: hasPerkHookFactory(client, context),\n usePresentFlow: presentFlowHookFactory(client, context),\n useProducts: productsHookFactory(client, context),\n usePurchase: purchaseHookFactory(client, context),\n useRestorePurchases: restorePurchasesHookFactory(client, context),\n useSubscriptions: subscriptionsHookFactory(\n currentPersonHookFactory(client, context, \"useSubscriptions\"),\n ),\n useVoidhash,\n };\n}\n","import React from \"react\";\nimport * as Option from \"effect/Option\";\n\nimport type { VoidhashClient } from \"../../client\";\nimport type { Person } from \"../../core/entities/person\";\nimport {\n currentPersonAtom,\n currentPersonFreshnessAtom,\n identityEpochAtom,\n} from \"../../core/reactivity/client-state\";\nimport type { VoidhashError } from \"../../errors\";\nimport { type VoidhashContext, useProviderStatus } from \"../components/provider\";\nimport useAsyncFunction from \"./use-async-function\";\nimport { useAtomValue } from \"./use-atom-value\";\n\nexport interface UseCurrentPersonResult {\n /** The person, or `null` until the first snapshot loads and while the client is disabled. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n readonly data: Person | null;\n /** The error that stopped the last read, or `null`. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n readonly error: VoidhashError | null;\n /** `true` while the provider initializes and until this hook's first read has answered. */\n readonly isLoading: boolean;\n /**\n * `true` while the person comes from a snapshot the server has not\n * confirmed recently: a cached one past its refresh window or TTL, or none\n * at all yet. Clears as soon as a refresh lands.\n */\n readonly isStale: boolean;\n readonly refetch: () => Promise<void>;\n}\n\nexport function currentPersonHookFactory(\n client: VoidhashClient,\n vhContext: React.Context<Option.Option<VoidhashContext>>,\n /** The hook's name in the error a development build throws outside a provider. */\n hookName = \"useCurrentPerson\",\n) {\n /**\n * Reads the current person snapshot. Re-renders when a refresh lands and\n * reads again after `identify()` or `reset()` switches the person.\n */\n function useCurrentPerson(): UseCurrentPersonResult {\n const status = useProviderStatus(vhContext, hookName);\n const registry = client.internal.getAtomRegistry();\n const identityEpoch = useAtomValue(registry, identityEpochAtom);\n\n const getPersonCallback = React.useCallback(\n () => client.getCurrentPerson(),\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- identityEpoch is the refetch trigger, not an input of the call.\n [identityEpoch],\n );\n\n const { isLoading, error, refetch } = useAsyncFunction(getPersonCallback, status);\n\n const person = useAtomValue(registry, currentPersonAtom);\n const freshness = useAtomValue(registry, currentPersonFreshnessAtom);\n\n return {\n data: Option.getOrNull(person),\n error,\n isLoading,\n // Staleness travels with the published snapshot, so a refresh that\n // lands in the background clears it.\n isStale: !isLoading && (freshness.isStale || freshness.isExpired),\n refetch,\n };\n }\n return useCurrentPerson;\n}\n","import type { Result } from \"better-result\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as EffectRuntime from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as React from \"react\";\n\nimport type { VoidhashError } from \"../../errors\";\nimport { UnknownVoidhashError } from \"../../errors\";\nimport type { VoidhashInitStatus } from \"../internal/client-lifecycle\";\n\ntype AsyncFunction<T> = () => Promise<Result<T, VoidhashError>>;\n\ninterface State<T> {\n data?: T;\n // oxlint-disable-next-line effect/prefer-option-over-null -- surfaced as-is by the public hooks, whose callers are non-Effect app code.\n error: VoidhashError | null;\n isLoading: boolean;\n /** The function the latest settled call ran; its answer is the one in `data`/`error`. */\n settledFunction?: AsyncFunction<T>;\n}\n\ntype Action<T> =\n | { type: \"loading\" }\n | { type: \"executed\"; fn: AsyncFunction<T>; payload: T }\n | { type: \"error\"; fn: AsyncFunction<T>; payload: VoidhashError };\n\ntype UseAsyncFunctionReturn<T> = Omit<State<T>, \"settledFunction\"> & {\n refetch: () => Promise<void>;\n};\n\n/**\n * Drives a `Promise<Result<T, VoidhashError>>` client call as hook state.\n * The `Err` channel becomes `error`; unexpected exceptions are normalized\n * into an `Err`-shaped state as well.\n *\n * `status` is the provider's lifecycle status (`None` outside a provider): the\n * function runs once the provider is `ready`, and again whenever it changes. `isLoading` is `true`\n * while the provider initializes and until the current function has answered,\n * so a hook never reports a settled empty answer it has not read yet; it is\n * `false` for a disabled or failed provider, where nothing is going to run.\n * A refetch keeps the previous `data` until the new answer arrives.\n */\nfunction useAsyncFunction<T = unknown>(\n asyncFn: AsyncFunction<T>,\n status: Option.Option<VoidhashInitStatus>,\n): UseAsyncFunctionReturn<T> {\n // Each call takes the next id; only the latest call may write its answer,\n // so a slow answer to a superseded or cancelled call never lands.\n const latestCall = React.useRef(0);\n\n const asyncFnReducer = (state: State<T>, action: Action<T>): State<T> => {\n if (action.type === \"loading\") return { data: state.data, error: null, isLoading: true };\n if (action.type === \"executed\") {\n return { data: action.payload, error: null, isLoading: false, settledFunction: action.fn };\n }\n return {\n data: state.data,\n error: action.payload,\n isLoading: false,\n settledFunction: action.fn,\n };\n };\n\n const [state, dispatch] = React.useReducer(asyncFnReducer, { error: null, isLoading: false });\n\n const executeAsyncFunction = React.useCallback(async () => {\n latestCall.current += 1;\n const call = latestCall.current;\n dispatch({ type: \"loading\" });\n\n const exit = await EffectRuntime.runPromise(\n Effect.exit(Effect.tryPromise({ try: () => asyncFn(), catch: (error) => error })),\n );\n\n if (latestCall.current !== call) {\n return;\n }\n\n if (Exit.isSuccess(exit)) {\n const result = exit.value;\n if (result.isOk()) {\n dispatch({ fn: asyncFn, payload: result.value, type: \"executed\" });\n } else {\n dispatch({ fn: asyncFn, payload: result.error, type: \"error\" });\n }\n return;\n }\n\n dispatch({\n fn: asyncFn,\n payload: new UnknownVoidhashError(Cause.squash(exit.cause)),\n type: \"error\",\n });\n }, [asyncFn]);\n\n const refetch = React.useCallback(async () => {\n await executeAsyncFunction();\n }, [executeAsyncFunction]);\n\n const enabled = Option.contains(status, \"ready\");\n React.useEffect(() => {\n if (!enabled) {\n return;\n }\n\n void executeAsyncFunction();\n\n // A call still running when the inputs change or the component unmounts\n // must not write its answer afterwards.\n return () => {\n latestCall.current += 1;\n };\n }, [executeAsyncFunction, enabled]);\n\n return {\n data: state.data,\n error: state.error,\n isLoading:\n Option.contains(status, \"initializing\") ||\n (enabled && (state.isLoading || state.settledFunction !== asyncFn)),\n refetch,\n };\n}\n\nexport default useAsyncFunction;\n","import React from \"react\";\nimport type { Atom, AtomRegistry } from \"effect/reactivity\";\n\ninterface AtomStore<A> {\n readonly subscribe: (notify: () => void) => () => void;\n readonly snapshot: () => A;\n}\n\n/**\n * Reads the value of an Effect `Atom` and re-renders whenever it changes.\n *\n * Internal binding around `React.useSyncExternalStore`, intentionally scoped\n * to the SDK so we don't pull in `@effect/atom-react` (which targets a newer\n * React peer range than this package currently supports).\n */\nexport function useAtomValue<A>(registry: AtomRegistry.AtomRegistry, atom: Atom.Atom<A>): A {\n const store = React.useMemo<AtomStore<A>>(\n () => ({\n subscribe: (notify) => registry.subscribe(atom, notify),\n snapshot: () => registry.get(atom),\n }),\n [registry, atom],\n );\n const value = React.useSyncExternalStore(store.subscribe, store.snapshot);\n\n // Atoms are lazy: without an active mount they may be removed from the\n // registry and lose listeners. Mounting on commit keeps the atom alive for\n // the lifetime of the component subscription.\n React.useEffect(() => registry.mount(atom), [registry, atom]);\n\n return value;\n}\n","import React from \"react\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\n\nimport type { VoidhashClient } from \"../../client\";\nimport type { SdkFeatureFlag } from \"../../core/facade-types\";\nimport type { FeatureFlagKey, FeatureFlagValue } from \"../../core/schema/registry\";\nimport {\n decodeFeatureFlagKeys,\n featureFlagsForKeysAtom,\n identityEpochAtom,\n normalizeFeatureFlagKeys,\n} from \"../../core/reactivity/client-state\";\nimport type { VoidhashError } from \"../../errors\";\nimport { type VoidhashContext, useProviderStatus } from \"../components/provider\";\nimport useAsyncFunction from \"./use-async-function\";\nimport { useAtomValue } from \"./use-atom-value\";\n\n/** One flag's evaluation as {@link UseFeatureFlagsResult.getVariant} reports it. */\nexport interface FeatureFlagVariant {\n enabled: boolean;\n /** The selected variant's key, or `null` for a flag without variants. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n variantKey: string | null;\n /** The selected variant's payload: untyped JSON, `null` when it has none. Validate before use. */\n payload: unknown;\n}\n\nexport interface UseFeatureFlagsResult {\n data: {\n /** Every flag evaluated for the requested keys (all flags when none were passed). */\n flags: ReadonlyArray<SdkFeatureFlag>;\n };\n /** The error that stopped the last evaluation, or `null`. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n error: VoidhashError | null;\n /** The flag's variant, or `null` while it is loading or unknown. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n getVariant: (key: FeatureFlagKey) => FeatureFlagVariant | null;\n /**\n * The value of the variant the flag selected, while the flag is enabled:\n * `null` while loading (`isLoading`), and once loaded when the flag is\n * off, has no variant (or one whose value is not text) or is unknown.\n * Typed by the variant values `voidhash.gen.d.ts` lists for the flag; a\n * variant added since generation is not in that union.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n getVariantValue: <K extends FeatureFlagKey>(key: K) => FeatureFlagValue<K> | null;\n /**\n * Whether the flag is enabled. A flag without an evaluated value (while\n * loading, unknown, or on a disabled client) reads as its\n * `featureFlags.defaults` entry, or `false`.\n */\n isEnabled: (key: FeatureFlagKey) => boolean;\n /** `true` while the provider initializes and until this hook's evaluation has answered. */\n isLoading: boolean;\n refetch: () => Promise<void>;\n}\n\nexport function featureFlagsHookFactory(\n client: VoidhashClient,\n vhContext: React.Context<Option.Option<VoidhashContext>>,\n) {\n /**\n * Evaluates `flagKeys` (every flag when omitted) for the current person and\n * re-renders when a newer evaluation lands, including after `identify()` or\n * `reset()` switches the person.\n */\n function useFeatureFlags(flagKeys?: ReadonlyArray<FeatureFlagKey>): UseFeatureFlagsResult {\n const status = useProviderStatus(vhContext, \"useFeatureFlags\");\n const registry = client.internal.getAtomRegistry();\n const identityEpoch = useAtomValue(registry, identityEpochAtom);\n\n // Callers overwhelmingly pass an inline array literal, which is a fresh\n // identity on every render. Depending on it directly would restart the\n // fetch after every state update, so everything downstream is keyed on\n // the normalized signature and the keys are read back from it.\n const normalizedKeys = normalizeFeatureFlagKeys(flagKeys);\n const stableFlagKeys = React.useMemo(\n () => (normalizedKeys === \"all\" ? undefined : decodeFeatureFlagKeys(normalizedKeys)),\n [normalizedKeys],\n );\n\n // The identity epoch is a dependency so a mounted hook evaluates again\n // for the person an `identify()` or `reset()` switched to.\n const fetchFlags = React.useCallback(\n () => client.getFeatureFlags(stableFlagKeys),\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- identityEpoch is the refetch trigger, not an input of the call.\n [stableFlagKeys, identityEpoch],\n );\n\n const { isLoading, error, refetch } = useAsyncFunction(fetchFlags, status);\n\n // Subscribe to only the slice of flag state matching our request. The\n // `featureFlagsForKeysAtom` family memoizes by normalized key so two\n // hooks asking for the same keys (in any order) share an atom, and hooks\n // asking for different keys can't trample each other.\n const flagsAtom = React.useMemo(\n () => featureFlagsForKeysAtom(stableFlagKeys),\n [stableFlagKeys],\n );\n const flags = useAtomValue(registry, flagsAtom);\n\n const findFlag = React.useCallback(\n (key: string) =>\n Option.flatMap(flags, (result) =>\n Option.fromUndefinedOr(result.flags.find((flag) => flag.key === key)),\n ),\n [flags],\n );\n\n const isEnabled = React.useCallback(\n (key: string) =>\n Option.match(findFlag(key), {\n onNone: () => client.internal.isFeatureEnabledByDefault(key),\n onSome: (flag) => flag.enabled,\n }),\n [findFlag],\n );\n\n const getVariantValue = React.useCallback(\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n <K extends FeatureFlagKey>(key: K): FeatureFlagValue<K> | null => {\n if (isLoading) return null;\n const flag = findFlag(key);\n return Option.isSome(flag) && flag.value.enabled && P.isString(flag.value.payload)\n ? flag.value.payload\n : null;\n },\n [findFlag, isLoading],\n );\n\n const getVariant = React.useCallback(\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n (key: string): FeatureFlagVariant | null =>\n Option.getOrNull(\n Option.map(findFlag(key), (flag) => ({\n enabled: flag.enabled,\n payload: flag.payload,\n variantKey: flag.variantKey,\n })),\n ),\n [findFlag],\n );\n\n const data = React.useMemo(\n () => ({\n flags: Option.match(flags, { onNone: () => [], onSome: (result) => result.flags }),\n }),\n [flags],\n );\n\n return {\n data,\n error,\n getVariant,\n getVariantValue,\n isEnabled,\n isLoading,\n refetch,\n };\n }\n return useFeatureFlags;\n}\n","import React from \"react\";\nimport * as Option from \"effect/Option\";\n\nimport type { VoidhashClient } from \"../../client\";\nimport { type EntitlementGrant, findActiveGrant } from \"../../core/entitlements/find-grant\";\nimport type { VoidhashError } from \"../../errors\";\nimport {\n currentPersonAtom,\n currentPersonFreshnessAtom,\n identityEpochAtom,\n} from \"../../core/reactivity/client-state\";\nimport type { PerkSlug } from \"../../core/schema/registry\";\nimport { type VoidhashContext, useProviderStatus } from \"../components/provider\";\nimport useAsyncFunction from \"./use-async-function\";\nimport { useAtomValue } from \"./use-atom-value\";\n\nexport interface UseHasPerkResult {\n /** The active grant behind `hasAccess`, or `null` when there is none. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n grant: EntitlementGrant | null;\n hasAccess: boolean;\n /**\n * `true` while the provider initializes and until this hook's first check\n * has answered, so `hasAccess: false` is never reported before the SDK has\n * looked. `false` for a disabled client.\n */\n isLoading: boolean;\n /**\n * True while `hasAccess` is answered from a snapshot the server has not\n * confirmed recently: a cached one past its refresh window or TTL, or none\n * at all yet. Clears as soon as a refresh lands, even one that runs in the\n * background. Pair with `error` to decide whether to fail open or closed.\n */\n isStale: boolean;\n /** The error that stopped the last check, or `null`. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n error: VoidhashError | null;\n refetch: () => Promise<void>;\n}\n\nexport function hasPerkHookFactory(\n client: VoidhashClient,\n vhContext: React.Context<Option.Option<VoidhashContext>>,\n) {\n /**\n * Checks whether the current person holds an active grant for `perkSlug`,\n * the perk slug configured in Studio. Re-renders when a refresh lands and\n * checks again after `identify()` or `reset()` switches the person.\n */\n function useHasPerk(perkSlug: PerkSlug): UseHasPerkResult {\n const status = useProviderStatus(vhContext, \"useHasPerk\");\n const registry = client.internal.getAtomRegistry();\n const identityEpoch = useAtomValue(registry, identityEpochAtom);\n\n const getPersonCallback = React.useCallback(\n () => client.getCurrentPerson(),\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- identityEpoch is the refetch trigger, not an input of the call.\n [identityEpoch],\n );\n\n const { isLoading, error, refetch } = useAsyncFunction(getPersonCallback, status);\n\n const person = useAtomValue(registry, currentPersonAtom);\n const freshness = useAtomValue(registry, currentPersonFreshnessAtom);\n\n const grant = React.useMemo(() => findActiveGrant(person, perkSlug), [person, perkSlug]);\n\n // Staleness travels with the published snapshot, not with this hook's\n // own read: a refresh that lands later (in the background, after a\n // purchase or a restore) publishes a fresh snapshot and clears it.\n // Transport failures never surface as errors (the cached snapshot is\n // served instead), so the error fallback only covers the rare failures\n // that do surface while a cached grant is being served.\n const isStale =\n !isLoading &&\n (freshness.isStale ||\n freshness.isExpired ||\n (error !== null && Option.isSome(person) && Option.isSome(grant)));\n\n return {\n error,\n grant: Option.getOrNull(grant),\n hasAccess: Option.isSome(grant),\n isLoading,\n isStale,\n refetch,\n };\n }\n return useHasPerk;\n}\n","import type * as Option from \"effect/Option\";\nimport * as React from \"react\";\n\nimport type { VoidhashClient } from \"../../client\";\nimport type { FlowResult, PresentFlowArguments } from \"../../core/flows/flows\";\nimport type { FlowInput, LocationSlug } from \"../../core/schema/registry\";\nimport { type VoidhashContext, useProviderStatus } from \"../components/provider\";\n\nexport function presentFlowHookFactory(\n client: VoidhashClient,\n vhContext: React.Context<Option.Option<VoidhashContext>>,\n) {\n /**\n * Presents the flow assigned to `location`. `present(options)` resolves with\n * how the flow ended and rejects with a `VoidhashError` when it cannot be\n * shown; `isPresenting` is `true` while a flow started by this hook is on\n * screen. `updateInput(values)` changes inputs of the flow on screen.\n */\n function usePresentFlow<const L extends LocationSlug>(location: L) {\n useProviderStatus(vhContext, \"usePresentFlow\");\n const [isPresenting, setIsPresenting] = React.useState(false);\n\n const present = React.useCallback(\n (...args: PresentFlowArguments<L>): Promise<FlowResult<L>> => {\n setIsPresenting(true);\n return client.presentFlow(location, ...args).finally(() => setIsPresenting(false));\n },\n [location],\n );\n\n const updateInput = React.useCallback(\n (values: Partial<FlowInput<L>>): Promise<void> => client.updateFlowInput<L>(values),\n [],\n );\n\n return { isPresenting, present, updateInput };\n }\n return usePresentFlow;\n}\n","import * as Option from \"effect/Option\";\nimport * as R from \"effect/Record\";\nimport * as Schema from \"effect/Schema\";\nimport React from \"react\";\n\nimport type { VoidhashClient } from \"../../client\";\nimport type { Product, ProductForSlug, ProductsForSlugs } from \"../../core/entities/product\";\nimport { clientRunAtom, productsAtom } from \"../../core/reactivity/client-state\";\nimport type { ProductSlug } from \"../../core/schema/registry\";\nimport type { VoidhashError } from \"../../errors\";\nimport { type VoidhashContext, useProviderStatus } from \"../components/provider\";\nimport { useAtomValue } from \"./use-atom-value\";\n\nconst encodeSlugs = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));\n\n/** How the products load is going, the same for every `useProducts()`. */\ninterface ProductsLoad {\n /** The error that stopped the last load, or `null`. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n readonly error: VoidhashError | null;\n /**\n * `true` while the provider initializes and until the products have\n * loaded; `false` while disabled.\n */\n readonly isLoading: boolean;\n /** Loads the products again. */\n readonly refetch: () => Promise<void>;\n}\n\n/** What `useProducts()` answers: every product. */\nexport interface UseProductsResult extends ProductsLoad {\n /** Every product the store sells this end user, sorted by slug; empty until loaded. */\n readonly products: ReadonlyArray<Product>;\n readonly data: {\n /** Each product by its slug; a slug the store has no product for is absent. */\n readonly bySlug: { readonly [Slug in ProductSlug]?: ProductForSlug<Slug> };\n /** The product a slug names, or `undefined` when the store has none. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n readonly get: <Slug extends ProductSlug>(slug: Slug) => ProductForSlug<Slug> | undefined;\n /** Every product, as `products`. */\n readonly toList: () => ReadonlyArray<Product>;\n };\n}\n\n/** What `useProducts(slugs)` answers: the products those slugs name, in their order. */\nexport interface UseProductsBySlugsResult<\n Slugs extends ReadonlyArray<ProductSlug>,\n> extends ProductsLoad {\n /**\n * The product of each slug, in the order given: `undefined` until loaded\n * and where the store has none. With generated types each is typed by its\n * slug, so a subscription's slug is a `SubscriptionProduct`.\n */\n readonly products: ProductsForSlugs<Slugs>;\n}\n\nexport function productsHookFactory(\n client: VoidhashClient,\n vhContext: React.Context<Option.Option<VoidhashContext>>,\n) {\n /**\n * The store products of the project, loaded once for every mounted hook\n * and loaded again when the identity changes, a purchase or restore\n * completes (in a flow too), the product definitions change, or the client\n * starts again after `end()`. Without arguments, every product; with\n * slugs, the products they name, in that order:\n *\n * ```ts\n * const { products: [yearly, monthly], isLoading } = voidhash.useProducts([\"yearly\", \"monthly\"]);\n * ```\n */\n function useProducts(): UseProductsResult;\n function useProducts<const Slugs extends ReadonlyArray<ProductSlug>>(\n slugs: Slugs,\n ): UseProductsBySlugsResult<Slugs>;\n function useProducts(\n slugs?: ReadonlyArray<ProductSlug>,\n ): UseProductsResult | UseProductsBySlugsResult<ReadonlyArray<ProductSlug>> {\n const status = useProviderStatus(vhContext, \"useProducts\");\n const registry = client.internal.getAtomRegistry();\n const state = useAtomValue(registry, productsAtom);\n const run = useAtomValue(registry, clientRunAtom);\n const ready = Option.contains(status, \"ready\");\n\n // The first hook to mount loads, a mount after a failed load tries again,\n // and so does a new run of the client (`end()` dropped the products); the\n // client keeps the products current from then on.\n React.useEffect(() => {\n if (!ready) return;\n const current = registry.get(productsAtom);\n if (Option.isNone(current.products) && !current.isLoading) void client.getProducts();\n }, [ready, registry, run]);\n\n const refetch = React.useCallback(async () => {\n await client.getProducts();\n }, []);\n\n const products = React.useMemo(\n () => Option.getOrElse(state.products, (): ReadonlyArray<Product> => []),\n [state.products],\n );\n\n // Callers pass an inline array literal, a new identity on every render;\n // the selection follows the slugs it holds.\n const slugsKey = slugs === undefined ? undefined : encodeSlugs(slugs);\n const selected = React.useMemo(\n () => slugs?.map((slug) => products.find((product) => product.slug === slug)),\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- the key is the slugs' content; the array identity changes every render.\n [products, slugsKey],\n );\n\n const data = React.useMemo(() => {\n const bySlug = R.fromIterableWith(products, (product) => [product.slug, product]);\n // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.\n function get<Slug extends ProductSlug>(slug: Slug): ProductForSlug<Slug> | undefined;\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n function get(slug: ProductSlug): Product | undefined {\n return bySlug[slug];\n }\n return { bySlug, get, toList: () => products };\n }, [products]);\n\n const load: ProductsLoad = {\n error: Option.getOrNull(state.error),\n isLoading:\n Option.contains(status, \"initializing\") ||\n (ready &&\n (state.isLoading || (Option.isNone(state.products) && Option.isNone(state.error)))),\n refetch,\n };\n return selected === undefined ? { ...load, data, products } : { ...load, products: selected };\n }\n return useProducts;\n}\n","import { Result } from \"better-result\";\nimport * as Option from \"effect/Option\";\nimport * as React from \"react\";\n\nimport type { PurchaseOptions, PurchaseResult, VoidhashClient } from \"../../client\";\nimport type { Product } from \"../../core/entities/product\";\nimport { PurchaseInProgressError, type VoidhashError } from \"../../errors\";\nimport { type VoidhashContext, useProviderStatus } from \"../components/provider\";\nimport { runHostCallback } from \"../internal/host-callback\";\n\n/** A purchase the store charged for, as `onSuccess` receives it. */\nexport type CompletedPurchase = Extract<PurchaseResult, { status: \"purchased\" }>;\n\n/**\n * Callbacks for a purchase's outcome. An exception a callback throws (or a\n * promise it returns that rejects) is reported through `onDiagnostic` as\n * `HOST_CALLBACK_FAILED` and never affects the purchase or the hook's state.\n */\nexport interface UsePurchaseOptions {\n /**\n * Runs when the store charged (`purchased`), whether or not Voidhash has\n * accepted the receipt yet (`synced`): the purchase is done either way.\n */\n onSuccess?: (result: CompletedPurchase) => void;\n onError?: (error: VoidhashError) => void;\n onSettled?: (result: Result<PurchaseResult, VoidhashError>) => void;\n}\n\n/**\n * What one `purchase()` call of the hook takes: its own callbacks, and the\n * purchase options `client.purchase()` takes.\n */\nexport interface UsePurchaseCallOptions extends UsePurchaseOptions, PurchaseOptions {}\n\nexport function purchaseHookFactory(\n client: VoidhashClient,\n vhContext: React.Context<Option.Option<VoidhashContext>>,\n) {\n /**\n * Buys products, for a Buy button. `purchase(product)` resolves with the\n * result of `client.purchase()` and never rejects; `pendingProduct` is the\n * product a purchase this hook started is buying. Pressing Buy again for\n * the same product with the same purchase options while it runs answers\n * that same purchase (its callbacks, not the second call's, run); a\n * purchase of another product, or of the same product with other options\n * (another offer, say), meanwhile resolves `Err(PURCHASE_IN_PROGRESS)` and\n * leaves the running one alone.\n */\n function usePurchase(hookOptions?: UsePurchaseOptions) {\n useProviderStatus(vhContext, \"usePurchase\");\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n const [pendingProduct, setPendingProduct] = React.useState<Product | undefined>(undefined);\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n const [error, setError] = React.useState<VoidhashError | null>(null);\n const running = React.useRef(\n Option.none<{\n /** What it buys; `None` for options `purchase()` refuses, which match nothing. */\n readonly key: Option.Option<string>;\n readonly settled: Promise<Result<PurchaseResult, VoidhashError>>;\n }>(),\n );\n\n const purchase = React.useCallback(\n (\n product: Product,\n options?: UsePurchaseCallOptions,\n ): Promise<Result<PurchaseResult, VoidhashError>> => {\n const { onError, onSettled, onSuccess, ...purchaseOptions } = {\n ...hookOptions,\n ...options,\n };\n const runCallbacks = (result: Result<PurchaseResult, VoidhashError>) => {\n if (result.isOk() && result.value.status === \"purchased\" && onSuccess) {\n const completed = result.value;\n runHostCallback(client, \"usePurchase.onSuccess\", () => onSuccess(completed));\n }\n if (result.isErr() && onError) {\n runHostCallback(client, \"usePurchase.onError\", () => onError(result.error));\n }\n if (onSettled) runHostCallback(client, \"usePurchase.onSettled\", () => onSettled(result));\n };\n\n const key = client.internal.purchaseKey(product, purchaseOptions);\n const current = running.current;\n if (Option.isSome(current)) {\n if (Option.isSome(key) && Option.contains(current.value.key, key.value)) {\n return current.value.settled;\n }\n const refused = Result.err<PurchaseResult, VoidhashError>(new PurchaseInProgressError());\n runCallbacks(refused);\n return Promise.resolve(refused);\n }\n\n setPendingProduct(product);\n setError(null);\n // `purchase` never rejects — every outcome is a Result — and the hook\n // settles before any callback runs, so a callback that throws cannot\n // leave it loading.\n const settled = client.purchase(product, purchaseOptions).then((result) => {\n running.current = Option.none();\n setPendingProduct(undefined);\n if (result.isErr()) setError(result.error);\n runCallbacks(result);\n return result;\n });\n running.current = Option.some({ key, settled });\n return settled;\n },\n [hookOptions],\n );\n\n return {\n /** The error of the last purchase this hook started, or `null`. */\n error,\n /** Whether a purchase this hook started is running. */\n isLoading: pendingProduct !== undefined,\n /** The product a purchase this hook started is buying, or `undefined`. */\n pendingProduct,\n purchase,\n };\n }\n return usePurchase;\n}\n","import * as P from \"effect/Predicate\";\n\nimport type { VoidhashClient } from \"../../client\";\n\n/**\n * Runs a callback the app passed to a hook. An exception it throws, or a\n * promise it returns that rejects, is reported through `onDiagnostic` as\n * `HOST_CALLBACK_FAILED` under `name`, so a bug in app code never leaves a\n * hook stuck or turns a finished purchase or restore into a failure.\n */\nexport function runHostCallback(\n client: VoidhashClient,\n name: string,\n callback: () => unknown,\n): void {\n const report = (callbackError: unknown) =>\n client.internal.reportHostCallbackFailure(name, callbackError);\n // oxlint-disable-next-line effect/avoid-try-catch -- boundary with host application code: the callback is a plain function the app supplies and may throw anything.\n try {\n const returned = callback();\n if (P.isPromiseLike(returned)) returned.then(undefined, report);\n } catch (callbackError) {\n report(callbackError);\n }\n}\n","import type { Result } from \"better-result\";\nimport type * as Option from \"effect/Option\";\nimport * as React from \"react\";\n\nimport type { VoidhashClient } from \"../../client\";\nimport type { Person } from \"../../core/entities/person\";\nimport type { VoidhashError } from \"../../errors\";\nimport { type VoidhashContext, useProviderStatus } from \"../components/provider\";\nimport { runHostCallback } from \"../internal/host-callback\";\n\n/**\n * Callbacks for a restore's outcome. An exception a callback throws (or a\n * promise it returns that rejects) is reported through `onDiagnostic` as\n * `HOST_CALLBACK_FAILED` and never affects the restore or the hook's state.\n */\nexport interface UseRestorePurchasesOptions {\n /**\n * Runs when the restore finished, with the refreshed person (`null` when\n * there is none). It does not mean the person has access: check their\n * entitlements, which mounted `useHasPerk` hooks already re-render with.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook callback consumed by non-Effect app code.\n onSuccess?: (person: Person | null) => void;\n onError?: (error: VoidhashError) => void;\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook callback consumed by non-Effect app code.\n onSettled?: (result: Result<Person | null, VoidhashError>) => void;\n}\n\nexport function restorePurchasesHookFactory(\n client: VoidhashClient,\n vhContext: React.Context<Option.Option<VoidhashContext>>,\n) {\n /**\n * Restores the current person's purchases, for a Restore button.\n * `restore()` resolves with the result of `client.restorePurchases()`, the\n * refreshed person, and never rejects; `isLoading` is `true` while a\n * restore this hook started runs. `restore` takes no arguments, so it can\n * be passed to `onPress` directly.\n */\n function useRestorePurchases(hookOptions?: UseRestorePurchasesOptions) {\n useProviderStatus(vhContext, \"useRestorePurchases\");\n const [isLoading, setIsLoading] = React.useState(false);\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n const [error, setError] = React.useState<VoidhashError | null>(null);\n\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n const restore = React.useCallback((): Promise<Result<Person | null, VoidhashError>> => {\n setIsLoading(true);\n setError(null);\n\n // `restorePurchases` never rejects — every outcome is a Result — and\n // the hook settles before any callback runs, so a callback that throws\n // cannot leave it loading.\n return client.restorePurchases().then((result) => {\n setIsLoading(false);\n if (result.isErr()) setError(result.error);\n\n const { onError, onSettled, onSuccess } = hookOptions ?? {};\n if (result.isOk() && onSuccess) {\n const person = result.value;\n runHostCallback(client, \"useRestorePurchases.onSuccess\", () => onSuccess(person));\n }\n if (result.isErr() && onError) {\n runHostCallback(client, \"useRestorePurchases.onError\", () => onError(result.error));\n }\n if (onSettled) {\n runHostCallback(client, \"useRestorePurchases.onSettled\", () => onSettled(result));\n }\n return result;\n });\n }, [hookOptions]);\n\n return {\n /** The error of the last restore, or `null`. */\n error,\n isLoading,\n restore,\n };\n }\n return useRestorePurchases;\n}\n","import type { Subscription } from \"../../core/entities/person\";\nimport type { UseCurrentPersonResult } from \"./use-person\";\n\nexport interface UseSubscriptionsResult extends Omit<UseCurrentPersonResult, \"data\"> {\n /**\n * Every subscription of the person that has not ended, including ones in a\n * grace period, in billing retry, on hold or paused: what a \"manage\n * subscription\" screen lists. Empty until the person loads. Access comes\n * from entitlements (`useHasPerk`), never from this list.\n */\n readonly all: ReadonlyArray<Subscription>;\n /** The subscription that matters most now, or `undefined` when there is none. */\n // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.\n readonly current: Subscription | undefined;\n}\n\nconst NO_SUBSCRIPTIONS: ReadonlyArray<Subscription> = [];\n\nexport function subscriptionsHookFactory(useCurrentPerson: () => UseCurrentPersonResult) {\n /**\n * The person's subscriptions as the server knows them across devices and\n * stores: renewal, grace period, billing retry, hold, pause and pending\n * changes. Re-renders with the person, as `useCurrentPerson()` does.\n */\n function useSubscriptions(): UseSubscriptionsResult {\n const { data: person, ...state } = useCurrentPerson();\n return {\n ...state,\n all: person?.subscriptions.all ?? NO_SUBSCRIPTIONS,\n current: person?.subscriptions.current,\n };\n }\n return useSubscriptions;\n}\n","// Generated by `pnpm specs` from the React Native SDK's\n// src/specs/VoidhashNativeClient.nitro.ts. Do not edit: change that spec and\n// run `pnpm specs` again.\nimport { Android, iOS, type HybridObject } from \"nitro-core\";\n\nexport * from \"#nitro/VoidhashNativeClient\";\n\n/*\n * The contract between the React Native facade and the native Voidhash client\n * (the Swift `VoidhashClient` and the Kotlin `com.voidhash.sdk.VoidhashClient`)\n * it is moving onto. The facade keeps its public surface: option validation,\n * the `Result` and `VoidhashError` shapes, the provider and the hooks stay in\n * TypeScript; identity, purchases, analytics, flags, the schema and paywalls\n * are the native client's.\n *\n * Shapes the SDK defines are Nitro structs. Payloads the Voidhash API defines\n * (a person snapshot, a paywall, a schema, a flag payload, event properties)\n * cross as JSON strings, so a server that adds a field needs no new binary.\n *\n * Errors: every promise rejects with an error whose message is\n * `\"<CODE>: <detail>\"`; the detail may be empty. On Android the message\n * reaches JavaScript as the throwable's printed stack trace and on both\n * platforms a synchronous throw gets the method's name in front; the facade\n * reads the code through all of that. Use a facade `VoidhashErrorCode` where\n * one fits (`AUTHENTICATION_FAILED`, `INVALID_ARGUMENT`, `OFFER_UNAVAILABLE`,\n * `PAYWALL_UNAVAILABLE`, `PURCHASE_IN_PROGRESS`,\n * `READ_ONLY_PURCHASE_NOT_ALLOWED`, `REPLACED_SUBSCRIPTION_NOT_OWNED`,\n * `SUBSCRIPTION_REPLACEMENT_REFUSED`, `UNSUPPORTED_PLATFORM`, a `FLOW_*`\n * code), `NOT_INITIALIZED` before `start()`, after `shutdown()` and from a\n * native client the native SDK made inert (nothing was done), and\n * `NOT_IMPLEMENTED` for a member a build does not support yet. A purchase the\n * store refused for a reason it named rejects with that reason's code:\n * `PAYMENT_DECLINED` (Android only: Play\n * `PAYMENT_DECLINED_DUE_TO_INSUFFICIENT_FUNDS`; StoreKit 2 has no declined\n * payment error) or `INELIGIBLE_FOR_OFFER` (Play `USER_INELIGIBLE`, StoreKit\n * `Product.PurchaseError.ineligibleForOffer`); the facade reports both as\n * `FAILED_TO_PURCHASE` with `reason` set. Each facade method keeps the codes it reports today: a code it\n * does not report reaches the app under that method's `FAILED_TO_*` code, its\n * native message kept.\n *\n * Store-specific members (`appStore*`, `googlePlay*`) exist on both\n * platforms, as Nitro requires; on the other platform they reject\n * `UNSUPPORTED_PLATFORM` without doing anything. The facade checks the\n * platform first, so that path is a safety net.\n *\n * Products and transactions: the fields every store has are the structs\n * below, filled from the native SDK's `VoidhashProduct` and\n * `VoidhashTransaction` field for field. Their `appStore` and `googlePlay`\n * parts cross as JSON (`appStoreJson`, `googlePlayJson`), shaped exactly as\n * the facade's `AppStoreProductInfo`, `GooglePlayProductInfo`,\n * `AppStoreTransactionInfo` and `GooglePlayTransactionInfo` types in\n * `src/core/entities/app-store.ts` and `google-play.ts` declare them, with the\n * stores' own field names: dates as milliseconds since the epoch, a `Price`\n * as `{ amount, amountMicros, currencyCode, formatted }`, a `Period` as\n * `{ unit, count, iso8601 }`, an absent value left out or `null`. Every enum\n * here has an `unknown` case: send it for a native case this contract does\n * not list.\n *\n * Rejected publishable key: while API requests are paused because the key\n * was rejected (`401`/`403`), the first `getPersonState`, `getFeatureFlags`\n * or `getPaywall` call that has nothing cached to answer with rejects\n * `AUTHENTICATION_FAILED`. That happens once per pause, shared across the\n * three reads; a request the pause lets through that succeeds, or a new\n * `start()`, ends the pause. Every later read answers as it would offline:\n * from its cache, with an empty answer marked stale, or for a paywall with\n * nothing cached `PAYWALL_UNAVAILABLE`. A read that can answer from its cache\n * never rejects with it. The rejection is reported through the `diagnostic`\n * event either way.\n *\n * Threading and ordering: methods may be called from the JS thread at any\n * time; promises and the event listener settle on the JS thread, in the order\n * the native client produced them. A call that emits events returns a pending\n * promise and settles it only after those events were dispatched to the\n * listener: a promise already settled when it is returned resolves in the\n * JavaScript microtask queue, ahead of any event the call emitted.\n *\n * Identity generations: every identity a client adopts gets the next\n * number of one counter that only grows for the life of the process, across\n * every instance and every `start()`/`shutdown()` (a re-init, another\n * project). Person and flag answers carry the generation they were read\n * under; the facade publishes only the current generation's, so a late answer\n * from an identity switched away from (or from a previous run) is never\n * published, even after a switch back to the same distinct id.\n */\n\n/** The end user's analytics consent, as `setAnalyticsConsent()` takes it. */\nexport type NativeAnalyticsConsent = \"granted\" | \"denied\" | \"pending\";\n\n/** What happens to events captured while analytics consent is `pending`. */\nexport type NativePendingAnalytics = \"drop\" | \"buffer\";\n\n/**\n * Why a person answer has the freshness it has: confirmed by the server just\n * now, served from cache while a refresh still runs, served from cache\n * because the refresh failed, or nothing was ever cached for this identity.\n */\nexport type NativeFreshnessReason = \"fresh\" | \"refreshInFlight\" | \"refreshFailed\" | \"noCache\";\n\n/**\n * How a person write ended: the server confirmed it, it waits in the\n * person-write outbox, or nothing was left to write (`skipped`). Person\n * attributes are written whatever the analytics consent, so `skipped` means\n * one thing only: the write held nothing but an agreement to ad data sharing\n * (`$ad_data_sharing` other than `false`), which is left out while consent is\n * not granted.\n */\nexport type NativeWriteStatus = \"confirmed\" | \"deferred\" | \"skipped\";\n\n/**\n * What Google Play charges when a purchase replaces a subscription; the\n * native SDK's replacement mode and the facade's\n * `SubscriptionReplacementMode`, value for value.\n */\nexport type NativeSubscriptionReplacementMode =\n | \"withTimeProration\"\n | \"chargeProratedPrice\"\n | \"chargeFullPrice\"\n | \"withoutProration\"\n | \"deferred\";\n\n/** The subscription a purchase replaces instead of adding a second one next to it. */\nexport interface NativeSubscriptionReplacement {\n /** Slug of the subscription product the end user has now. */\n readonly productSlug: string;\n readonly mode: NativeSubscriptionReplacementMode;\n}\n\n/** The store a reported transaction comes from. */\nexport type NativeStorePlatform = \"appStore\" | \"googlePlay\";\n\n/** The state another billing integration reported a Google Play purchase in. */\nexport type NativeReportedPurchaseState = \"purchased\" | \"pending\" | \"unspecified\";\n\n/** The interface revision an app was built against at one location. */\nexport interface NativeFlowRevision {\n readonly location: string;\n readonly revision: number;\n}\n\n/** What the app passes to one presentation of a flow. */\nexport interface NativeFlowPresentation {\n /**\n * The interface revision the app was built against; absent to use the one\n * configured for the location, or 0 when there is none.\n */\n readonly revision?: number;\n /** The flow's inputs by name, as a JSON object of strings, numbers and booleans. */\n readonly inputJson: string;\n /** Names of the app actions the app handles. */\n readonly actions: string[];\n}\n\n/**\n * Which flow runtime draws flows, process-wide: the one built into the SDK\n * (`linked`) or the flow runtime modules the server offers (`module`).\n */\nexport type NativeFlowRuntime = \"linked\" | \"module\";\nexport type NativeFlowLoading = \"standard\" | \"none\";\n\n/** What a flow may do beyond purchases, restores, closing and analytics. */\nexport type NativeFlowCapability = \"links\" | \"notifications\" | \"tracking\" | \"attributes\";\n\n/** Which payload a {@link NativeClientEvent} carries. */\nexport type NativeClientEventType =\n | \"person\"\n | \"identity\"\n | \"flags\"\n | \"schema\"\n | \"consent\"\n | \"diagnostic\"\n | \"transaction\"\n | \"purchaseIntent\";\n\n/**\n * When StoreKit shows its messages (price increase consent, billing issues,\n * win-back offers): at once (`automatic`), or held while a Voidhash flow is\n * on screen and shown once it closes (`deferWhileFlowPresented`). Google Play\n * ignores it.\n */\nexport type NativeAppStoreMessages = \"automatic\" | \"deferWhileFlowPresented\";\n\n/**\n * What happens to a purchase the end user started on the App Store (a\n * promoted in-app purchase, a win-back offer): bought through the normal\n * purchase path once `start()` has resolved its identity\n * (`purchaseWhenReady`), never before; or handed to the app as a\n * `purchaseIntent` event (`manual`). Google Play ignores it.\n */\nexport type NativePurchaseIntents = \"purchaseWhenReady\" | \"manual\";\n\n/** Coarse category of a diagnostic, the facade's `VoidhashDiagnosticKind`. */\nexport type NativeDiagnosticKind =\n | \"transport\"\n | \"eviction\"\n | \"breaker\"\n | \"auth\"\n | \"cache\"\n | \"configuration\"\n | \"consent\";\n\n/**\n * The facade's options after validation, as `configure()` receives them.\n * Native automatic screen tracking stays off under React Native: the facade's\n * navigation integrations report screens through `screen()`.\n */\nexport interface NativeClientConfiguration {\n readonly publishableKey: string;\n /** Absolute `http(s)` origin of the API, already validated. */\n readonly baseUrl: string;\n /** Origin of analytics ingest; `baseUrl` when absent. */\n readonly ingestUrl?: string;\n readonly debug: boolean;\n /** Development purchases: `dev: true` in a debug build. Always `false` in release builds. */\n readonly developmentMode: boolean;\n /** Adopted on the first `start()` of the process; later starts resume the stored identity. */\n readonly distinctId?: string;\n /** Observer mode at start; `setReadOnly()` changes it later. */\n readonly readOnly: boolean;\n /**\n * The `analyticsConsent` option: applies when no consent was chosen, in this\n * process or by an earlier `setAnalyticsConsent()` stored on the device.\n */\n readonly analyticsConsent: NativeAnalyticsConsent;\n /**\n * A consent the app chose with `setAnalyticsConsent()` in this process\n * before the client started. It wins over the stored one, is stored in its\n * place, and is in effect before `start()` captures or sends anything.\n */\n readonly chosenAnalyticsConsent?: NativeAnalyticsConsent;\n /**\n * The `analyticsWhilePending` option: `buffer` holds events captured while\n * consent is `pending` in memory and records them when it is granted.\n */\n readonly analyticsWhilePending: NativePendingAnalytics;\n /** The `grantConsentOnIdentify` option: `identify()` grants a `pending` consent. */\n readonly grantConsentOnIdentify: boolean;\n readonly automaticLifecycleEvents: boolean;\n /** Reads which ad brought this install, once per install; see the facade's option. */\n readonly installAttribution: boolean;\n /** The Meta app id to ask Meta's apps about on Android; iOS ignores it. */\n readonly metaAppId?: string;\n /** Locations whose flows are downloaded at start. */\n readonly preloadLocations: string[];\n /**\n * The interface revision the app was built against, per location. Used to\n * preload and as the revision of a presentation that names none.\n */\n readonly flowRevisions: NativeFlowRevision[];\n readonly flowCapabilities: NativeFlowCapability[];\n /**\n * The `flowRuntime` option. `module` switches the linked native renderer to\n * flow runtime modules before anything resolves a flow; set once per\n * process, it stays for the process.\n */\n readonly flowRuntime: NativeFlowRuntime;\n /**\n * The `flowLoading` option: `none` turns the linked native renderer's loading\n * screen off.\n */\n readonly flowLoading: NativeFlowLoading;\n /** `false` turns every `screen()` into a no-op. */\n readonly screenTrackingEnabled: boolean;\n /**\n * The `featureFlags.maxWaitMs` option: how long a flag read with nothing\n * cached waits for Voidhash, in milliseconds, a non-negative integer. The\n * native client's own default (2000) when absent. A binary built before\n * this field ignores it and waits its default.\n */\n readonly featureFlagMaxWaitMs?: number;\n /**\n * The `featureFlags.defaults` option: what each flag reads as while it has\n * no evaluated value. A binary built before this field ignores it; the\n * facade's hooks apply the defaults either way.\n */\n readonly featureFlagDefaults?: Record<string, boolean>;\n /** A runtime schema to use instead of fetching one (tests and previews only). */\n readonly internalSchemaJson?: string;\n /** The `appStoreMessages` option; see {@link NativeAppStoreMessages}. */\n readonly appStoreMessages: NativeAppStoreMessages;\n /** The `purchaseIntents` option; see {@link NativePurchaseIntents}. */\n readonly purchaseIntents: NativePurchaseIntents;\n /** The facade's package version, sent with every request. */\n readonly sdkVersion: string;\n}\n\n/** The identity the client adopted, and the generation it adopted it under. */\nexport interface NativeIdentityChange {\n readonly distinctId: string;\n /** The identity before the change; empty for the identity `start()` loaded. */\n readonly previousDistinctId: string;\n /** The adoption's identity generation; greater than every earlier one. */\n readonly generation: number;\n}\n\n/** A person snapshot with how far it can be trusted. */\nexport interface NativePersonState {\n /** The identity the snapshot belongs to. */\n readonly distinctId: string;\n /** The identity generation the snapshot was read under. */\n readonly generation: number;\n /** The server's person snapshot as JSON; absent when there is none. */\n readonly personJson?: string;\n /** Served from cache past its refresh window. */\n readonly isStale: boolean;\n /** Served from cache past its expiry. */\n readonly isExpired: boolean;\n readonly reason: NativeFreshnessReason;\n}\n\n/** Outcome of `identify()`. */\nexport interface NativeIdentifyResult {\n /** The identity in effect once the call settled: the one `identify()` switched to. */\n readonly identity: NativeIdentityChange;\n /** `confirmed` once the server linked the identities, `deferred` while the link is queued. */\n readonly status: NativeWriteStatus;\n /** The confirmed person, or the last known snapshot for a deferred switch, as JSON. */\n readonly personJson?: string;\n}\n\n/** Outcome of `setPersonAttributesState()`. */\nexport interface NativePersonWriteResult {\n readonly status: NativeWriteStatus;\n /** The confirmed person, or the last known snapshot for a deferred write, as JSON. */\n readonly personJson?: string;\n}\n\n/** One evaluated flag. */\nexport interface NativeFeatureFlag {\n readonly key: string;\n readonly enabled: boolean;\n /** The selected variant's key; absent for a flag without variants. */\n readonly variantKey?: string;\n /** The selected variant's payload as JSON; absent when it has none. */\n readonly payloadJson?: string;\n}\n\n/** A flag evaluation for one request: every flag, or the keys asked for. */\nexport interface NativeFeatureFlagsResult {\n /** The identity the evaluation belongs to. */\n readonly distinctId: string;\n /** The identity generation the evaluation was read under. */\n readonly generation: number;\n /**\n * The keys this evaluation answers; absent for every flag. A `flags` event\n * is stored under these; a read's answer is stored under the keys the\n * caller asked for, whatever comes back here.\n */\n readonly flagKeys?: string[];\n readonly flags: NativeFeatureFlag[];\n /** Served from cache past its refresh window, or no evaluation has ever succeeded. */\n readonly isStale: boolean;\n}\n\n/** The store a product or transaction belongs to; `development` for development-mode purchases. */\nexport type NativeStore = \"appStore\" | \"googlePlay\" | \"development\" | \"unknown\";\n\n/** The native SDK's product type. */\nexport type NativeProductType =\n | \"subscription\"\n | \"consumable\"\n | \"nonConsumable\"\n | \"nonRenewingSubscription\"\n | \"unknown\";\n\n/** The unit of a {@link NativePeriod}. */\nexport type NativePeriodUnit = \"day\" | \"week\" | \"month\" | \"year\" | \"unknown\";\n\n/** How a pricing phase is paid. */\nexport type NativePaymentMode = \"freeTrial\" | \"payAsYouGo\" | \"payUpFront\" | \"unknown\";\n\n/** The native SDK's offer kind. */\nexport type NativeOfferKind = \"introductory\" | \"promotional\" | \"winBack\" | \"oneTime\" | \"unknown\";\n\n/** The native SDK's `Price`. */\nexport interface NativePrice {\n /** The amount in the currency's units (the native `Decimal`/`BigDecimal` as a double). */\n readonly amount: number;\n /** The exact amount × 1,000,000. */\n readonly amountMicros: number;\n /** ISO 4217. */\n readonly currencyCode: string;\n /** The store's localized string, never re-formatted. */\n readonly formatted: string;\n}\n\n/** The native SDK's `Period`, already normalised (7 days are 1 week). */\nexport interface NativePeriod {\n readonly unit: NativePeriodUnit;\n /** At least 1. */\n readonly count: number;\n /** Generated from the normalised value: `P1W`, `P3M`, `P1Y`. */\n readonly iso8601: string;\n}\n\n/** The native SDK's `PricingPhase`. */\nexport interface NativePricingPhase {\n readonly paymentMode: NativePaymentMode;\n /** Per cycle; zero for a free trial. */\n readonly price: NativePrice;\n /** The length of one cycle. */\n readonly period: NativePeriod;\n /** How many cycles the phase lasts, at least 1. */\n readonly cycles: number;\n}\n\n/** The native SDK's `Offer`. */\nexport interface NativeOffer {\n /**\n * Google Play: the Studio offer id when the offer is configured in Studio,\n * else Play's offer id. App Store: a promotional offer's Studio id (only\n * Studio-configured ones are listed), a win-back offer's App Store id, `\"\"`\n * for the introductory offer.\n */\n readonly id: string;\n readonly kind: NativeOfferKind;\n /** Subscription offers: the phases before the regular price, in order. Empty for `oneTime`. */\n readonly phases: NativePricingPhase[];\n /** `oneTime` offers: what the product costs with it. Absent for subscription offers. */\n readonly price?: NativePrice;\n}\n\n/**\n * The native SDK's `SubscriptionInfo`. The four `pricePer*` prices are the\n * native SDK's, computed natively (rounded half-up to the currency's minor\n * units, formatted with the store's locale); never computed in JavaScript.\n */\nexport interface NativeSubscriptionInfo {\n readonly period: NativePeriod;\n /** The App Store subscription group id; on Google Play, the subscription's product id. */\n readonly groupId: string;\n /** The intro offer this end user is eligible for right now; absent otherwise. */\n readonly introOffer?: NativeOffer;\n readonly pricePerDay: NativePrice;\n readonly pricePerWeek: NativePrice;\n readonly pricePerMonth: NativePrice;\n readonly pricePerYear: NativePrice;\n}\n\n/** The native SDK's `VoidhashProduct`, one per Studio product slug. */\nexport interface NativeProduct {\n /** The Voidhash product id (the schema product's `id`). */\n readonly productId: string;\n readonly slug: string;\n readonly store: NativeStore;\n /** The App Store or Google Play product id. */\n readonly storeProductId: string;\n readonly type: NativeProductType;\n /** The Studio name. */\n readonly name: string;\n /** The store's localized title. */\n readonly displayName: string;\n /** The store's localized description. */\n readonly description: string;\n /** The regular price (Google Play: the recurring phase of the pinned base plan). */\n readonly price: NativePrice;\n /** Present exactly when `type` is `subscription`. */\n readonly subscription?: NativeSubscriptionInfo;\n /** The purchasable non-introductory offers for this end user. */\n readonly offers: NativeOffer[];\n /** The product's `appStore` part as JSON (`AppStoreProductInfo`); present exactly when `store` is `appStore`. */\n readonly appStoreJson?: string;\n /** The product's `googlePlay` part as JSON (`GooglePlayProductInfo`); present exactly when `store` is `googlePlay`. */\n readonly googlePlayJson?: string;\n}\n\n/** The kind of offer a transaction was bought with; `code` for a redeemed offer code. */\nexport type NativeTransactionOfferKind =\n | \"introductory\"\n | \"promotional\"\n | \"winBack\"\n | \"oneTime\"\n | \"code\"\n | \"unknown\";\n\n/** Where a transaction was made. */\nexport type NativeEnvironment = \"production\" | \"sandbox\" | \"xcode\" | \"development\" | \"unknown\";\n\n/** The offer of a transaction; every field absent when the store does not say. */\nexport interface NativeTransactionOffer {\n readonly id?: string;\n readonly kind?: NativeTransactionOfferKind;\n readonly paymentMode?: NativePaymentMode;\n}\n\n/** The native SDK's `VoidhashTransaction`. */\nexport interface NativeTransaction {\n /** Apple `transactionId` / Play `purchaseToken`: stable from pending to purchased. */\n readonly id: string;\n /** Apple `originalID`; absent on Google Play. */\n readonly originalId?: string;\n /** Resolved through the schema; absent when no product has the store product. */\n readonly productSlug?: string;\n readonly storeProductId: string;\n readonly store: NativeStore;\n /** Milliseconds since the epoch. */\n readonly purchasedAt: number;\n /** Milliseconds since the epoch. */\n readonly expiresAt?: number;\n /** What the store charged for (`Purchase.getQuantity()` on Google Play). */\n readonly quantity: number;\n /** Apple `reason == .renewal` (iOS 17 and later); absent where unknown (Google Play). */\n readonly isRenewal?: boolean;\n readonly offer?: NativeTransactionOffer;\n readonly environment: NativeEnvironment;\n /** The `appStore` part as JSON (`AppStoreTransactionInfo`); present exactly when `store` is `appStore`. */\n readonly appStoreJson?: string;\n /** The `googlePlay` part as JSON (`GooglePlayTransactionInfo`); present exactly when `store` is `googlePlay`. */\n readonly googlePlayJson?: string;\n}\n\n/**\n * Which offer `purchase()` buys:\n *\n * - `automatic`: a subscription's `introOffer` when it has one, else the\n * regular price. On Google Play this passes the intro offer's token.\n * - `regularPrice`: the regular price (Play: the base plan's token; the App\n * Store may still apply an intro offer the user is eligible for).\n * - `offer`: the offer `offerId` names, resolved against the product's\n * current `offers` and `subscription.introOffer` (of kind `offerKind` when\n * given). `offerKind: introductory` always means the product's current\n * `subscription.introOffer`, whatever `offerId` says (the App Store's has\n * no id of its own, so the app may pass an empty one). None matching\n * rejects `OFFER_UNAVAILABLE`, never buying at the regular price instead.\n */\nexport type NativeOfferSelection = \"automatic\" | \"regularPrice\" | \"offer\";\n\n/** App Store options of a purchase; Google Play ignores them. */\nexport interface NativeAppStorePurchaseOptions {\n /** StoreKit's `simulatesAskToBuyInSandbox` purchase option. */\n readonly simulatesAskToBuyInSandbox?: boolean;\n}\n\n/** Google Play options of a purchase; the App Store ignores them. */\nexport interface NativeGooglePlayPurchaseOptions {\n /** `BillingFlowParams.setIsOfferPersonalized`. */\n readonly isOfferPersonalized?: boolean;\n /** `BillingFlowParams.setObfuscatedProfileId`. */\n readonly obfuscatedProfileId?: string;\n /** Buys exactly this offer token, whatever `offerSelection` says. */\n readonly offerToken?: string;\n}\n\n/** What `purchase()` buys beyond the product. */\nexport interface NativePurchaseOptions {\n readonly offerSelection: NativeOfferSelection;\n /** With `offer`: the offer's id. */\n readonly offerId?: string;\n /** With `offer`: the offer's kind, when the app passed an offer rather than an id. */\n readonly offerKind?: NativeOfferKind;\n /**\n * At least 1. Anything but 1 is honoured for App Store consumables only;\n * elsewhere it rejects `INVALID_ARGUMENT` (the facade checks it first).\n */\n readonly quantity: number;\n readonly replacing?: NativeSubscriptionReplacement;\n readonly appStore?: NativeAppStorePurchaseOptions;\n readonly googlePlay?: NativeGooglePlayPurchaseOptions;\n}\n\n/**\n * How a purchase ended: the store charged (`purchased`), it needs outside\n * action such as Ask to Buy or a pending payment first (`pending`), or the\n * end user dismissed the sheet (`cancelled`).\n */\nexport type NativePurchaseOutcome = \"purchased\" | \"pending\" | \"cancelled\";\n\n/** The native SDK's purchase result. */\nexport interface NativePurchaseResult {\n readonly outcome: NativePurchaseOutcome;\n /** With `purchased`: the transaction. With a Play `deferred` replacement it names the old product. */\n readonly transaction?: NativeTransaction;\n /** With `purchased`: `true` once Voidhash accepted the receipt, `false` while it waits on the device. */\n readonly synced?: boolean;\n}\n\n/** A transaction the native SDK handled outside `purchase()`; its transaction update stream. */\nexport interface NativeTransactionUpdate {\n readonly transaction: NativeTransaction;\n /** `true` once Voidhash accepted the receipt, `false` while it waits on the device. */\n readonly synced: boolean;\n}\n\n/** A purchase the end user started on the App Store, as `purchaseIntents: manual` hands it over. */\nexport interface NativePurchaseIntent {\n readonly productSlug: string;\n /** The offer the end user chose (a win-back offer, iOS 18 and later). */\n readonly offer?: NativeOffer;\n}\n\n/** The storefront the end user buys from. */\nexport interface NativeStorefront {\n /** ISO 3166-1 alpha-2 (StoreKit's alpha-3 converted). */\n readonly countryCode: string;\n /** ISO 4217, when the store says. */\n readonly currencyCode?: string;\n}\n\n/** How a refund request ended. */\nexport type NativeRefundRequestStatus = \"success\" | \"userCancelled\";\n\n/** StoreKit's `RenewalState`. */\nexport type NativeAppStoreSubscriptionState =\n | \"subscribed\"\n | \"expired\"\n | \"inBillingRetryPeriod\"\n | \"inGracePeriod\"\n | \"revoked\"\n | \"unknown\";\n\n/** One StoreKit `Product.SubscriptionInfo.Status`. */\nexport interface NativeAppStoreSubscriptionStatus {\n readonly state: NativeAppStoreSubscriptionState;\n /** The status's verified transaction. */\n readonly transaction: NativeTransaction;\n /**\n * The verified `RenewalInfo` as JSON, shaped as the facade's\n * `AppStoreRenewalInfo`: `{ willAutoRenew, autoRenewProductId?,\n * expirationReason?, gracePeriodExpiresAt?, isInBillingRetry,\n * priceIncreaseStatus?, renewalPrice?, eligibleWinBackOfferIds }`.\n */\n readonly renewalInfoJson: string;\n}\n\n/** Which Google Play in-app message outcome `googlePlayShowInAppMessages()` had. */\nexport type NativeInAppMessageStatus = \"noActionNeeded\" | \"subscriptionStatusUpdated\";\n\n/** The outcome of Play's `showInAppMessages` (TRANSACTIONAL category). */\nexport interface NativeInAppMessageResult {\n readonly status: NativeInAppMessageStatus;\n /** With `subscriptionStatusUpdated`: the purchase token whose status changed. */\n readonly purchaseToken?: string;\n}\n\n/** A purchase another billing integration completed, by its store identifier only. */\nexport interface NativeReportedTransaction {\n readonly platform: NativeStorePlatform;\n /** App Store transaction id; required for `appStore`. */\n readonly transactionId?: string;\n /** Google Play purchase token; required for `googlePlay`. */\n readonly purchaseToken?: string;\n /**\n * Google Play: the state the integration reported. A `pending` or\n * `unspecified` purchase is ignored, as the facade does today; report it\n * again once it is purchased. Absent counts as purchased.\n */\n readonly purchaseState?: NativeReportedPurchaseState;\n /**\n * App Store: the transaction's JWS when the integration handed it over.\n * Sent as the proof a purchase or restore claim needs; without it the\n * native SDK reads it from the device's purchase history.\n */\n readonly signedTransaction?: string;\n}\n\n/** Outcome of a flush or a shutdown. */\nexport interface NativeFlushStatus {\n /** Events the server accepted. */\n readonly flushed: number;\n /** Events still queued. */\n readonly pending: number;\n /** Why delivery stopped, when it did. */\n readonly lastErrorMessage?: string;\n}\n\n/** A non-fatal event the native client handled on its own; the facade's `VoidhashDiagnostic`. */\nexport interface NativeDiagnostic {\n readonly kind: NativeDiagnosticKind;\n /** Stable code, for example `ANALYTICS_EVENT_DROPPED`. */\n readonly code: string;\n readonly operation: string;\n readonly retryable: boolean;\n readonly httpStatus?: number;\n readonly message?: string;\n}\n\n/**\n * One state change, delivered to the listener. `type` names the one payload\n * field that is set:\n *\n * - `identity` → `identity`: the identity `start()` loaded, and every later\n * switch (`identify`, `reset`, `signOut`, and the switch back when the\n * server refused an `identify`), each under a new generation. A switch's\n * event is dispatched before the promise of the call that caused it\n * settles, and before any `person` or `flags` event or read answer of the\n * new generation.\n * - `person` → `person`: the current person or its freshness changed (a\n * refresh, a purchase, a restore, a delivered identity link or attribute\n * write).\n * - `flags` → `flags`: an evaluation was refreshed, keyed by its `flagKeys`.\n * - `schema` → `schemaJson`: a runtime schema was loaded or fetched.\n * - `consent` → `consent`: the analytics consent in effect changed, including\n * the one `start()` settled on.\n * - `diagnostic` → `diagnostic`. Includes `PRODUCT_NOT_FOUND` and\n * `PRODUCT_TYPE_MISMATCH` (kind `configuration`, operation `getProducts`\n * on both platforms), once per slug per products load, its message naming\n * the slug and the store's reason or both types. A product Studio does not\n * sell in this store is not reported by a load of every product.\n * - `transaction` → `transaction`: every element of the native transaction\n * update stream (purchases completed outside `purchase()`: Ask to Buy\n * approvals, pending payments, offer codes, promoted purchases, and on the\n * App Store renewals seen on the device; Google Play reports no renewals),\n * after the native SDK handled it. Never one that `purchase()` itself\n * answers with.\n * - `purchaseIntent` → `purchaseIntent`: with `purchaseIntents: manual`, each\n * App Store purchase intent for a product the schema has; an intent for\n * another product is dropped and reported as `PRODUCT_NOT_FOUND`. Sent\n * from `start()` on, maybe before the app added a listener to the facade,\n * which holds them until it does.\n */\nexport interface NativeClientEvent {\n readonly type: NativeClientEventType;\n readonly identity?: NativeIdentityChange;\n readonly person?: NativePersonState;\n readonly flags?: NativeFeatureFlagsResult;\n readonly schemaJson?: string;\n readonly consent?: NativeAnalyticsConsent;\n readonly diagnostic?: NativeDiagnostic;\n readonly transaction?: NativeTransactionUpdate;\n readonly purchaseIntent?: NativePurchaseIntent;\n}\n\n/**\n * The native Voidhash client behind one React Native `VoidhashClient`: one\n * hybrid object per client, owning the storage namespace of its publishable\n * key and base URL.\n */\n@iOS({ language: \"swift\", implementation: { className: \"HybridVoidhashNativeClient\" } })\n@Android({ language: \"kotlin\", implementation: { className: \"HybridVoidhashNativeClient\" } })\nexport declare class VoidhashNativeClient extends HybridObject {\n public constructor();\n\n // ---- Lifecycle ----\n\n /**\n * The version of this contract the binary implements, the facade's\n * `NATIVE_CONTRACT_VERSION` (`src/core/native/native-client.ts`). The\n * facade reads it before anything else and starts no native client of\n * another version: a JavaScript bundle updated over the air onto a build\n * made for another version fails `init()`, asking for a new build, instead\n * of misreading the answers. A binary whose hybrid has no such member\n * implements version 0. Raise it with every change to this file that a\n * binary built before the change cannot honour. Synchronous; callable\n * before `configure()`.\n */\n contractVersion(): number;\n /**\n * Applies the configuration; touches neither storage nor the network.\n * Called before the first `start()`, and again after `shutdown()` resolved\n * to start once more (a re-init), possibly with other options.\n */\n configure(configuration: NativeClientConfiguration): void;\n /**\n * Starts the client from local state: identity, caches and queues are\n * loaded, store observation and background delivery begin, and the boot\n * refresh starts behind the call. Resolves without waiting for the network\n * (after the device's first unlock).\n *\n * Before it loads anything, it imports what earlier releases of this\n * package (its TypeScript core) stored on the device for this namespace:\n * the identity, the analytics consent and session, queued events, identity\n * links and store receipts, and the cached person, flags, schema and\n * paywalls. A queued receipt is never lost: a store is deleted only once\n * its records are in the native stores, and an import that fails is retried\n * at the next `start()`. The importers live in this module's native code\n * (`ios/` and `android/`), not in the SDKs.\n *\n * The analytics consent it settles on is the one chosen in this process\n * (`chosenAnalyticsConsent`), else the stored one, else the\n * `analyticsConsent` option. Events captured before `start()` are handed to\n * the native SDK, which records them when that consent is `granted`, holds\n * them when it is `pending` and pending events are buffered, and discards\n * them otherwise.\n *\n * Before resolving it dispatches, in this order: the loaded `identity`, the\n * `consent` in effect, the cached or injected `schema` (when there is one),\n * and the cached `person` (when there is one).\n *\n * Another instance that still owns the same storage namespace (a JavaScript\n * reload leaves the previous one running, never shut down) is retired first:\n * it persists its queues as `shutdown()` would, without waiting on the\n * network, and rejects every later call with `NOT_INITIALIZED`. A purchase\n * the retired instance had started is still recorded by it (its receipt in\n * the outbox, its SDK-started marker, on Google Play its unfinished-purchase\n * record), and this instance syncs and finishes it as its own.\n *\n * Android allows one live client per process: configuring a new instance\n * retires the previous one as above, whatever its storage namespace.\n *\n * A `start()` while another is in flight joins it and settles with it; a\n * `start()` on a started client resolves at once and changes nothing. A\n * `shutdown()` that overtakes a start waits for it: the start shuts down\n * whatever it built and rejects with `NOT_INITIALIZED` before `shutdown()`\n * resolves, so nothing it started keeps running.\n */\n start(): Promise<void>;\n /**\n * Flushes for at most about two seconds, persists what is still queued and\n * stops every observer, timer and listener. Every call still pending settles\n * (or rejects with `NOT_INITIALIZED`) before this resolves. Whatever was not\n * delivered goes out after the next `start()`.\n */\n shutdown(): Promise<NativeFlushStatus>;\n /** Registers the one listener for {@link NativeClientEvent}s, replacing any earlier one. */\n setEventListener(listener: (event: NativeClientEvent) => void): void;\n /** Removes the listener; nothing is delivered until the next `setEventListener()`. */\n removeEventListener(): void;\n\n // ---- Identity and person ----\n\n /** The current distinct id. */\n getDistinctId(): Promise<string>;\n /**\n * Switches to `externalUserId` and links the previous anonymous identity\n * onto it. Resolves `confirmed` with the person, or `deferred` with the last\n * known snapshot when the link is queued, together with the identity it\n * switched to. Rejects for an invalid id (`INVALID_ARGUMENT`) without\n * switching, or for a verdict of the API: the client then switches back to\n * the previous identity (a new generation, its `identity` dispatched before\n * the rejection), keeping what it cached for it. The facade puts back the\n * person and flag evaluations it held before the call, so nothing needs to\n * be re-sent for them.\n *\n * Identifying the current identity again adopts nothing: it resolves with\n * the current `NativeIdentityChange` and dispatches no `identity` event. A\n * profile that differs from the one last sent goes out as an identify\n * request, whatever the analytics consent; the same profile sends nothing.\n * Backs both `identify()` and `identifySync()`.\n */\n identify(externalUserId: string, email?: string, name?: string): Promise<NativeIdentifyResult>;\n /**\n * Starts a fresh visitor: a new anonymous identity and analytics session,\n * with what was cached for the previous identity dropped. When someone is\n * signed in this is `signOut()`, `$sign_out` and flush included; for an\n * anonymous identity nothing is captured or sent. Resolves with the\n * identity it switched to.\n */\n reset(): Promise<NativeIdentityChange>;\n /**\n * Signs the user out: captures `$sign_out` under the signing-out identity\n * (with automatic lifecycle events on and consent granted), switches to a\n * fresh anonymous identity, starts a new analytics\n * session, then flushes for at most about two seconds. Resolves with the\n * identity it switched to. Does nothing, and sends nothing, when nobody is\n * signed in: it resolves with the identity in effect.\n */\n signOut(): Promise<NativeIdentityChange>;\n /**\n * Puts the end user in group `groupKey` of `groupType`, which every event\n * captured after it resolves carries in `$groups`, and stores it with the\n * identity. `propertiesJson`, a JSON object of strings, numbers and\n * booleans, sets the group's properties; they go out as a `$groupidentify`\n * event, which is also sent when the group of that type changed. Rejects\n * `INVALID_ARGUMENT` for a type or key the native SDK would refuse. Runs in\n * call order with identity changes.\n */\n group(groupType: string, groupKey: string, propertiesJson?: string): Promise<void>;\n /**\n * Replaces every group the end user is in with the ones in `groupsJson`: an\n * object from group type to `{ id, properties? }`. A type it leaves out is\n * dropped. A `$groupidentify` is sent only for a group whose id or\n * properties changed since they were last sent. A type or id the native\n * SDK finds invalid is left out with a warning. Runs in call order with\n * identity changes; rejects `INVALID_ARGUMENT`, changing nothing, when\n * `groupsJson` is not such an object or an entry has no string `id`.\n */\n setGroups(groupsJson: string): Promise<void>;\n /** Takes the end user out of every group. Runs in call order with identity changes. */\n resetGroups(): Promise<void>;\n /** The groups the end user belongs to, by group type; empty before `start()`. Synchronous. */\n getGroups(): Record<string, string>;\n /**\n * Queues person attributes (`{ email?, name?, …traits }` as JSON, flat\n * values only) without waiting on the network, whatever the analytics\n * consent and in observer mode too. Only an agreement to ad data sharing is\n * left out while consent is not granted.\n */\n setPersonAttributes(attributesJson: string): Promise<void>;\n /**\n * Writes person attributes and reports whether the server confirmed them,\n * whatever the analytics consent and in observer mode too; see\n * {@link NativeWriteStatus} for `skipped`. A confirmed write's `person`\n * event is dispatched before the promise settles.\n */\n setPersonAttributesState(attributesJson: string): Promise<NativePersonWriteResult>;\n /**\n * The current person, cache-first: a fresh entry at once, a stale one after\n * at most 500 ms of waiting for its refresh. `forceFetch` prefers the server.\n * An answer read under an earlier generation still reaches the caller that\n * asked, but the facade does not publish it to the hooks.\n */\n getPersonState(forceFetch: boolean): Promise<NativePersonState>;\n /**\n * Drops the cached person snapshot; the next read asks the server. On both\n * platforms a `person` event with no person (stale, expired, `noCache`) is\n * dispatched before the promise settles.\n */\n resetPersonCache(): Promise<void>;\n\n // ---- Flags, paywalls and products ----\n\n /**\n * Evaluates `flagKeys` (every flag when absent), cache-first. With nothing\n * cached it waits at most `featureFlagMaxWaitMs` (2 s by default), then\n * answers with no flags; the evaluation goes on and lands as a `flags`\n * event. A requested key without an evaluated value is answered with its\n * `featureFlagDefaults` entry, enabled or not and without a variant, when\n * it has one.\n */\n getFeatureFlags(flagKeys?: string[]): Promise<NativeFeatureFlagsResult>;\n /**\n * The paywall assigned to `location` as JSON, `\"null\"` when none is.\n * Rejects `PAYWALL_UNAVAILABLE` when nothing is cached and the server\n * cannot be reached.\n */\n getPaywall(location: string): Promise<string>;\n /**\n * Every product the store returned, one per Studio product slug, sorted by\n * slug: the native SDK's `getProducts()`, one store query per call. A\n * product the store did not return is left out and reported once per load\n * as the `PRODUCT_NOT_FOUND` diagnostic, one it sells as another type than\n * Studio's as `PRODUCT_TYPE_MISMATCH`. Offers and intro eligibility are\n * this end user's: the facade calls it again after an identity change, a\n * completed purchase or restore (a flow's included) and a transaction\n * update other than a renewal. The products it answers are the ones\n * `purchase()` buys until the next call, a completed purchase or a restore.\n */\n getProducts(): Promise<NativeProduct[]>;\n\n // ---- Purchases ----\n\n /**\n * Buys the product with slug `productSlug` through the native SDK's\n * `purchase(product, options)`, with the product the last `getProducts()`\n * answered for that slug; one it does not hold (none loaded yet, or a\n * purchase or restore since) is asked of the store first (an unknown slug\n * rejects `INVALID_ARGUMENT`). Resolves\n * `purchased` with the transaction and whether Voidhash accepted the\n * receipt, `pending`, or `cancelled`: a cancelled sheet and a pending\n * payment are results, not rejections. A purchase in observer mode rejects\n * `READ_ONLY_PURCHASE_NOT_ALLOWED`; a second purchase while one is in\n * flight (including one a flow started) `PURCHASE_IN_PROGRESS`; an offer\n * that cannot be bought `OFFER_UNAVAILABLE`; a store refusal with a reason\n * `PAYMENT_DECLINED` (Android only) or `INELIGIBLE_FOR_OFFER` (both; the\n * products held are dropped then, and nothing is retried at the regular\n * price).\n *\n * When the purchase changed the person, its `person` event is dispatched\n * before the promise settles. A `pending` purchase stays this client's to\n * sync and finish when it completes, also after a relaunch; it later\n * arrives as a `transaction` event.\n *\n * With `replacing`, Google Play replaces that subscription and buys nothing\n * when it cannot: `REPLACED_SUBSCRIPTION_NOT_OWNED` when the account does\n * not own it, `INVALID_ARGUMENT` when either product is not a subscription\n * or both are the same, `SUBSCRIPTION_REPLACEMENT_REFUSED` when Google Play\n * refuses before its sheet opens. A `deferred` replacement resolves\n * `purchased` with the old product's transaction. The App Store ignores\n * `replacing`.\n */\n purchase(productSlug: string, options: NativePurchaseOptions): Promise<NativePurchaseResult>;\n /**\n * Revalidates the store's purchase history for the current identity and\n * resolves with the person the restore refreshed, read from the cache as\n * `getPersonState(false)` reads it: under the current generation, with\n * its real freshness (`fresh` only when the refresh after the restore\n * succeeded); with no person to answer, `personJson` absent. The person's\n * `person` event is dispatched before the promise settles.\n */\n restorePurchases(): Promise<NativePersonState>;\n /** Reports pending purchases and current store entitlements. */\n syncPurchases(): Promise<void>;\n /**\n * Reports a purchase another billing integration completed. Resolves once\n * the receipt is stored; delivery goes on in the background. `isRestore`\n * sends it as an explicit restore for the current identity.\n */\n reportTransaction(transaction: NativeReportedTransaction, isRestore: boolean): Promise<void>;\n\n // ---- Store actions, both stores ----\n\n /**\n * Opens the store's subscription management. App Store:\n * `AppStore.showManageSubscriptions(in:subscriptionGroupID:)` with the\n * group of the product `productSlug` names (iOS 17 and later), else without\n * a group. Google Play: opens\n * `https://play.google.com/store/account/subscriptions?sku=<storeProductId>&package=<package>`,\n * without `sku` when no product is named. Resolves once it was shown.\n */\n showManageSubscriptions(productSlug?: string): Promise<void>;\n /**\n * Opens offer-code redemption. App Store: the newest offer-code sheet the\n * SDK builds against (`presentOfferCodeRedeemSheet(in:)` on iOS 16 and\n * later), `code` ignored; a transaction it returns goes through the normal\n * receipt path and arrives as a `transaction` event. Google Play: opens\n * `https://play.google.com/redeem?code=<code>` (no `code` parameter without one).\n */\n presentCodeRedemption(code?: string): Promise<void>;\n /**\n * The storefront the end user buys from: StoreKit's `Storefront.current`\n * (country converted to alpha-2) or Play's `getBillingConfigAsync`.\n * Resolves `undefined` when the store has none to give; rejects when asking failed.\n */\n // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the Nitro contract, where an optional is `undefined`.\n getStorefront(): Promise<NativeStorefront | undefined>;\n /**\n * App Store: `AppStore.canMakePayments`. Google Play: the billing\n * connection is ready and billing is not unavailable.\n */\n canMakePayments(): Promise<boolean>;\n\n // ---- App Store (Google Play rejects UNSUPPORTED_PLATFORM) ----\n\n /**\n * StoreKit's refund request sheet for the transaction `transactionId`\n * (`Transaction.beginRefundRequest(for:in:)`). Rejects `INVALID_ARGUMENT`\n * for a transaction StoreKit does not know.\n */\n appStoreBeginRefundRequest(transactionId: string): Promise<NativeRefundRequestStatus>;\n /**\n * Every status of subscription group `groupId` the Apple account has\n * (`Product.SubscriptionInfo.status(for:)`), the current end user's first\n * (the one whose transaction carries their app account token), then the\n * others, Family Sharing ones included; verified ones only.\n */\n appStoreSubscriptionStatus(groupId: string): Promise<NativeAppStoreSubscriptionStatus[]>;\n /** The verified transactions of `Transaction.currentEntitlements`. */\n appStoreCurrentEntitlements(): Promise<NativeTransaction[]>;\n /**\n * The verified `AppTransaction.shared` as JSON, shaped as the facade's\n * `AppTransaction`: `{ originalAppVersion, originalPurchaseDate,\n * environment, appTransactionId?, originalPlatform?, jwsRepresentation }`,\n * the date in milliseconds since the epoch, `environment` one of\n * `production`, `sandbox`, `xcode`, `originalPlatform` one of `iOS`,\n * `macOS`, `tvOS`, `visionOS`.\n */\n appStoreAppTransaction(): Promise<string>;\n\n // ---- Google Play (the App Store rejects UNSUPPORTED_PLATFORM) ----\n\n /**\n * Play's `showInAppMessages` for the TRANSACTIONAL category, on the current\n * activity. On `subscriptionStatusUpdated` the native SDK syncs purchases\n * and refreshes the person (its `person` event before the promise settles).\n */\n googlePlayShowInAppMessages(): Promise<NativeInAppMessageResult>;\n /**\n * The account's purchases (subscriptions and one-time), suspended\n * subscriptions included when `includeSuspended`. A suspended purchase is\n * never submitted, acknowledged or consumed.\n */\n googlePlayQueryPurchases(includeSuspended: boolean): Promise<NativeTransaction[]>;\n /**\n * `BillingClient.isFeatureSupported` for the feature `feature` names:\n * `subscriptions`, `subscriptionsUpdate`, `inAppMessaging`,\n * `productDetails`, `billingConfig`, `alternativeBillingOnly`,\n * `externalOffer` (the `FeatureType` constants). Another name rejects\n * `INVALID_ARGUMENT`.\n */\n googlePlayIsFeatureSupported(feature: string): Promise<boolean>;\n\n // ---- Configuration at runtime ----\n\n /**\n * Records analytics consent; it applies at once. Resolves whether it was\n * also stored for later launches.\n *\n * Also accepted before `start()`: a consent other than `granted` then\n * discards the events captured so far, and the consent is stored by\n * `start()` (the facade also passes it as `chosenAnalyticsConsent`). It\n * resolves `false` then, as nothing is stored yet.\n */\n setAnalyticsConsent(consent: NativeAnalyticsConsent): Promise<boolean>;\n /**\n * The analytics consent in effect. Before `start()` the stored consent is\n * not loaded yet, so it answers the consent chosen through\n * `setAnalyticsConsent` or, without one, the configured\n * `analyticsConsent` option.\n */\n getAnalyticsConsent(): NativeAnalyticsConsent;\n /** Switches observer mode; a purchase already in flight keeps its mode. */\n setReadOnly(readOnly: boolean): void;\n isReadOnly(): boolean;\n\n // ---- Analytics ----\n\n /**\n * Queues an event. Synchronous and never throws: the call itself stamps the\n * event with the current identity, session and time and takes its place in\n * the queue, so events keep call order and the identity they were captured\n * under. On iOS this needs an intake outside the client's actor, called\n * synchronously from the bridge. `propertiesJson` is a JSON object the\n * facade already made safe.\n *\n * Allowed before `start()`: such events are kept in memory with their call\n * time and attributed to the identity `start()` loads; past 100 of them the\n * oldest is dropped, reported as `ANALYTICS_EVENT_DROPPED` once the listener\n * is set. What becomes of them depends on the consent `start()` settles on\n * (see `start()`); a `setAnalyticsConsent(\"denied\")` discards them at once.\n */\n capture(eventName: string, propertiesJson: string): void;\n /**\n * Queues a `$screen` event for the screen `name`, stamped and ordered like\n * `capture`. The facade's screen tracker has already applied the app's\n * screen-tracking settings (`mapScreen`, whether route params are kept):\n * `propertiesJson` holds the `$screen_*` properties to record as they are,\n * with nothing stripped again.\n */\n screen(name: string, propertiesJson: string): void;\n /**\n * `capture` for an event the facade held back, which it does while an\n * identity change the app called before the event has not switched the\n * identity yet: recorded under the identity and session now in effect, at\n * `capturedAt` (milliseconds since the epoch), the time the app captured it.\n * A binary built before this member has none; the facade then calls\n * `capture`, and the event takes the time of that call.\n */\n captureAt(eventName: string, propertiesJson: string, capturedAt: number): void;\n /** `screen` for a screen the facade held back; see `captureAt`. */\n screenAt(name: string, propertiesJson: string, capturedAt: number): void;\n /** Sends person writes, receipts and events, waiting at most about two seconds. */\n flush(): Promise<NativeFlushStatus>;\n /** The active analytics session id; empty when there is none. Synchronous. */\n getSessionId(): string;\n\n // ---- Flows ----\n\n /**\n * Presents the flow assigned to `location` and resolves once it ends, as\n * JSON, one of:\n *\n * - `{\"outcome\":\"<outcome>\",\"output\":{…}}`, with `\"productId\":\"<product\n * slug>\"` when the outcome is `purchased`. `purchased`, `restored`\n * and `dismissed` are built in (the last also when the app closed the\n * flow or another replaced it); any other outcome is the one the flow\n * finished with. `output` holds the flow's outputs by name.\n * - `{\"failure\":{\"code\":\"<FLOW_* code>\",\"message\":\"<FLOW_* code>: <detail>\"}}`\n * for a flow that could not be presented, where the code is one of\n * `FLOW_DISABLED`, `FLOW_NOT_ASSIGNED`, `FLOW_UNAVAILABLE`,\n * `FLOW_RENDERER_MISSING`, `FLOW_UNSUPPORTED_PACKAGE`,\n * `FLOW_PRODUCTS_UNAVAILABLE` and `FLOW_PRESENTATION_FAILED`.\n *\n * `onAction` runs an app action the flow calls: it receives the action's\n * name and its arguments as a JSON object, and resolves with the reply as\n * a JSON object or rejects. It is called only for the names in\n * `presentation.actions`; the native side answers every other call itself.\n *\n * Purchases and restores the flow starts go through this client. Never\n * rejects for a flow that cannot be shown: that is a `failure`.\n */\n presentFlow(\n location: string,\n presentation: NativeFlowPresentation,\n onAction: (name: string, argsJson: string) => Promise<string>,\n ): Promise<string>;\n /**\n * Changes inputs of the flow on screen; `valuesJson` is a JSON object of\n * values by input name. Does nothing when no flow is shown.\n */\n updateFlowInput(valuesJson: string): Promise<void>;\n /** Closes the flow on screen, if any; its presentation resolves as dismissed. */\n dismissFlow(): Promise<void>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA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uB,QAAQ,0BAA0B;AAAA,EAC3D,CAAC;AAED,QAAM,EAAE,UAAU,SAAS,YAAY,IAAI,wBAAwB,MAAM;AACzE,QAAM,mBAAmB,yBAAyB,QAAQ,OAAO;AAEjE,SAAO;AAAA,IACL,UAAU;AAAA;AAAA,IAEV,UAAU,OAAO;AAAA,IACjB;AAAA;AAAA,IAEA,YAAY,OAAO;AAAA,IACnB;AAAA,IACA,iBAAiB,wBAAwB,QAAQ,OAAO;AAAA,IACxD,YAAY,mBAAmB,QAAQ,OAAO;AAAA,IAC9C,gBAAgB,uBAAuB,QAAQ,OAAO;AAAA,IACtD,aAAa,oBAAoB,QAAQ,OAAO;AAAA,IAChD,aAAa,oBAAoB,QAAQ,OAAO;AAAA,IAChD,qBAAqB,4BAA4B,QAAQ,OAAO;AAAA,IAChE,kBAAkB;AAAA,MAChB,yBAAyB,QAAQ,SAAS,kBAAkB;AAAA,IAC9D;AAAA,IACA;AAAA,EACF;AACF;;;AYlPA;AAKA;AAAA,2CAAc;;;AbWd,IAAM,6BAA6B,MAC1B,mBAAkB,YAAI,MAAM,IAAqB,wDAAqB,CAAC,CAAC;AA6B1E,SAAS,qBAEd,gBACA,UAAiC,CAAC,GAClC;AACA,SAAO;AAAA,IACL;AAAA,MACE,oBAAoB;AAAA,MACpB,aAAa;AAAA,MACb,UAAU,SAAS;AAAA,IACrB;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["Result","Arr","Option","P","R","EffectResult","Schema","value","Result","Schema","Result","Arr","Effect","Match","Option","P","R","Schema","Atom","Arr","Option","P","Result","value","Arr","Option","Schema","Arr","Option","P","R","Schema","values","value","Effect","Option","Schema","value","Arr","Option","Schema","keys","values","get","Effect","R","Schema","Effect","Option","Schema","value","Option","P","Option","Effect","Schema","value","version","exit","Result","decodeJson","value","isCurrent","Atom","update","options","error","values","Arr","Option","P","R","value","keys","Arr","Option","P","R","Result","value","value","encodeJson","update","Result","values","native","Result","Arr","Option","P","R","React","Option","Cause","Effect","Exit","Option","state","call","exit","React","value","React","React","Option","P","React","React","Option","React","React","values","Option","R","Schema","React","React","get","Result","Option","React","P","Result","React","value"]}
|