import { Platform, EmitterSubscription } from 'react-native'; import { $bridge, initBridge, isBridgeInitialized } from '@/bridge'; import { AdaptyBridgeEventEmitter } from '@/adapty-bridge-event-emitter'; import { LogContext, Log, LogScope, type LoggerConfig } from '@/logger'; import VERSION from '@/version'; import type { Def, Req } from '@/types/schema'; import { coderFactory } from '@/coders/factory'; import { FetchPolicy, GLOBAL_EVENT_TO_NATIVE_EVENT } from '@adapty/core'; import type { ActivateParamsInput, FileLocation, GetPlacementForDefaultAudienceParamsInput, GetPlacementParamsInput, IdentifyParamsInput, LogLevel, MakePurchaseParamsInput, PreloadPlacementsParamsInput, ReportTransactionParamsInput, } from '@adapty/core'; import type * as Model from '@/types'; import { MethodName, GlobalEventName } from '@/types/bridge'; import { AdaptyType } from '@/coders/parse'; import { RefundPreference, AdaptyProfile, AdaptyExternalAttributionProvider, AdaptyInstallationDetails, AdaptyPromotedProduct, WebPresentation, } from '@/types'; import { AdaptyError } from './adapty-error'; import { shouldEnableMock } from '@/utils'; import type { AdaptyMockConfig } from '@/mock/types'; /** * Entry point for the Adapty SDK. * All Adapty methods are available through this class. * @public */ export class Adapty { constructor() { Log.setVersion(VERSION); } private resolveHeldActivation?: (() => Promise) | null = null; private activating: Promise | null = null; private nonWaitingMethods: MethodName[] = [ 'activate', 'is_activated', 'get_flow_for_default_audience', 'get_onboarding_for_default_audience', ]; /** * Promoted purchases, and their default. * * An App Store promoted purchase that nobody completes silently does nothing * - the store hands the product to the app and waits. So the default * listener is a real purchase, not a no-op. Same shape as * DEFAULT_FLOW_EVENT_HANDLERS.onRequestAppReview, which calls the public * requestAppReview() when the app supplies no handler. */ private promotedPurchaseEmitter = new AdaptyBridgeEventEmitter( 'did_receive_promoted_purchase', 'onPromotedPurchaseReceived', product => this.makePromotedPurchase(product).catch(error => Log.warn( 'onPromotedPurchaseReceived', () => `Failed to complete the promoted purchase automatically: ${error}`, ), ), ); // Middleware to call native handle async handle( method: MethodName, params: string, resultType: AdaptyType, ctx: LogContext, log: LogScope, ): Promise { /* * If resolveHeldActivation is defined, * wait until it is resolved before calling native methods * * Not applicable for activate method ofc */ if ( this.resolveHeldActivation && !this.nonWaitingMethods.includes(method) ) { log.wait(() => ({})); await this.resolveHeldActivation(); this.resolveHeldActivation = null; log.waitComplete(() => ({})); } /* * wait until activate call is resolved before calling native methods * Not applicable for activate method ofc */ if ( this.activating && (!this.nonWaitingMethods.includes(method) || method === 'is_activated') ) { log.wait(() => ({})); await this.activating; log.waitComplete(() => ({})); this.activating = null; } try { const result = await $bridge.request(method, params, resultType, ctx); log.success(() => result as Record); return result as T; } catch (error) { /* * Success because error was handled validly * It is a developer task to define which errors must be logged */ log.success(() => ({ error })); throw error; } } /** * Adds an event listener for the latest profile load event. */ addEventListener( event: Extract, callback: (data: AdaptyProfile) => void | Promise, ): EmitterSubscription; /** * Adds an event listener for App Store promoted purchases. * * @remarks * Fires when the user starts a purchase from the App Store product page * rather than from a paywall. * * Registering a listener replaces the SDK's default behaviour, which is to * complete the purchase automatically. While a listener is registered you are * responsible for completing the purchase — call * {@link Adapty.makePromotedPurchase} with the product you receive, or the * purchase never happens. Removing the subscription restores the default. * * The listener is tied to the `Adapty` instance it was registered on — use * the exported singleton so a single set of handlers sees every event. */ addEventListener( event: Extract, callback: (data: AdaptyPromotedProduct) => void | Promise, ): EmitterSubscription; /** * Adds an event listener for successful installation details retrieval. */ addEventListener( event: Extract, callback: (data: AdaptyInstallationDetails) => void | Promise, ): EmitterSubscription; /** * Adds an event listener for installation details retrieval failures. */ addEventListener( event: Extract, callback: (data: AdaptyError) => void | Promise, ): EmitterSubscription; addEventListener( event: GlobalEventName, callback: (data: any) => void | Promise, ): EmitterSubscription { const eventId = GLOBAL_EVENT_TO_NATIVE_EVENT[event]; if (!eventId) { throw new Error(`Unsupported event: ${event}`); } // Promoted purchases go through the emitter rather than straight to the // bridge: the SDK holds its own subscription for them from activation // onward, so that its default can complete a purchase no app handler // claimed. The other three are plain notifications with no SDK-side // default, so the raw bridge subscription is all they need. if (event === 'onPromotedPurchaseReceived') { return this.promotedPurchaseEmitter.addListener(callback); } return $bridge.addEventListener(eventId, callback); } /** * Removes all attached event listeners */ removeAllListeners() { $bridge.removeAllEventListeners(); // Restore SDK's own default promoted-purchase subscription this.promotedPurchaseEmitter.restoreAfterBridgeTeardown(); } /** * Enables mock mode. * * @remarks * This method should be called before activate() if you want to test * SDK methods without full activation (e.g., isActivated()). * If bridge is already initialized, this method does nothing. * * **Important**: Mock mode cannot be disabled at runtime. * To switch back to production mode, you need to restart the app. * * @param {AdaptyMockConfig} [mockConfig] - Optional mock configuration * * @example * ```ts * adapty.enableMock({ profile: { ... } }); * const isActivated = await adapty.isActivated(); // false * await adapty.activate('api_key'); * ``` */ public enableMock(mockConfig?: AdaptyMockConfig): void { if (!isBridgeInitialized()) { initBridge(true, mockConfig); } } /** * Initializes the Adapty SDK. * * @remarks * This method must be called in order for the SDK to work. * It is preffered to call it as early as possible in the app lifecycle, * so background activities can be performed and cache can be updated. * * @example * ## Basic usage in your app's entry point * ```ts * adapty.activate('YOUR_API_KEY'); // <-- pass your API key here (required) * ``` * * ## Usage with your user identifier from your system * ```ts * adapty.activate('YOUR_API_KEY', { // <-- pass your API key here (required) * customerUserId: 'YOUR_USER_ID' // <-- pass your user identifier here (optional) * }); * ``` * * @param {string} apiKey - You can find it in your app settings * in {@link https://app.adapty.io/ | Adapty Dashboard} App settings > General. * @param {ActivateParamsInput} params - Optional parameters of type {@link ActivateParamsInput}. * @returns {Promise} A promise that resolves when the SDK is initialized. * * @throws {@link AdaptyError} * Usually throws if the SDK is already activated or if the API key is invalid. */ public async activate( apiKey: string, params: ActivateParamsInput = {}, ): Promise { // Initialize bridge with mock or native handler based on enableMock flag // If enableMock is not provided, use shouldEnableMock() detection if (!isBridgeInitialized()) { const enableMock = params.enableMock ?? shouldEnableMock(); if (enableMock) { initBridge(enableMock, params.mockConfig); } else { initBridge(false); } } // Subscribe on every activation, including ones the fast-refresh guard (__ignoreActivationOnFastRefresh) skip this.promotedPurchaseEmitter.addNativeEventListenerWithDefault(); // call before log ctx calls, so no logs are lost; keep a level set earlier via setLogLevel if (params.logLevel) { Log.logLevel = params.logLevel; } const ctx = new LogContext(); const log = ctx.call({ methodName: 'activate' }); log.start(() => ({ apiKey, params })); // Skipping activation if SDK is already activated if (params.__ignoreActivationOnFastRefresh) { try { const isAlreadyActivated = await this.isActivated(); if (!!this.activating || isAlreadyActivated) { log.success(() => ({ message: 'SDK already activated, skipping activation because ignoreActivationOnFastRefresh flag is enabled', })); return Promise.resolve(); } } catch (error) { log.waitComplete(() => ({ message: 'Failed to check activation status, proceeding with activation; ignoreActivationOnFastRefresh flag could not be applied', error, })); } } const configurationCoder = coderFactory.createConfigurationCoder(); const config = configurationCoder.encode(apiKey, params); const methodKey = 'activate'; const body = JSON.stringify({ method: methodKey, configuration: config, } satisfies Req['Activate.Request']); const activate = async () => { this.activating = this.handle(methodKey, body, 'Void', ctx, log); await this.activating; }; if (!params.__debugDeferActivation) { return activate(); } /* * Deferring activation solves annoying simulator authentication, * by postponing the moment, when simulator will use StoreKit */ return new Promise(unlock => { // do not resolve promise, only resolveHeldActivation must resolve this.resolveHeldActivation = async () => { const result = await activate(); unlock(result); }; }); } /** * Fetches the flow by the specified placement. * * @remarks * With Adapty, you can remotely configure the products and offers in your app * by simply adding them to paywalls – no need for hardcoding them. * The only thing you hardcode is the placement ID. * This flexibility allows you to easily update paywalls, products, and offers, * or run A/B tests, all without the need for a new app release. * * @param {string} placementId - The identifier of the desired placement. * This is the value you specified when you created the placement * in the Adapty Dashboard. * @param {GetPlacementParamsInput} [params] - Additional parameters for retrieving flow. * @returns {Promise} * A promise that resolves with a requested flow. * * @throws {@link AdaptyError} * Throws an error: * 1. if the flow with the specified ID is not found * 2. if your bundle ID does not match with your Adapty Dashboard setup */ public async getFlow( placementId: string, params: GetPlacementParamsInput = { fetchPolicy: FetchPolicy.ReloadRevalidatingCacheData, loadTimeoutMs: 5000, }, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'getFlow' }); log.start(() => ({ placementId, params })); const methodKey = 'get_flow'; const data: Req['GetFlow.Request'] = { method: methodKey, placement_id: placementId, load_timeout: (params.loadTimeoutMs ?? 5000) / 1000, }; if (params.fetchPolicy !== 'return_cache_data_if_not_expired_else_load') { data['fetch_policy'] = { type: params.fetchPolicy ?? FetchPolicy.ReloadRevalidatingCacheData, } satisfies Def['AdaptyPlacementFetchPolicy']; } else { data['fetch_policy'] = { type: params.fetchPolicy, max_age: params.maxAgeSeconds, } satisfies Def['AdaptyPlacementFetchPolicy']; } const body = JSON.stringify(data); const result = await this.handle( methodKey, body, 'AdaptyFlow', ctx, log, ); return result; } /** * Fetches the flow of the specified placement for the **All Users** audience. * * @remarks * With Adapty, you can remotely configure the products and offers in your app * by simply adding them to paywalls – no need for hardcoding them. * The only thing you hardcode is the placement ID. * This flexibility allows you to easily update paywalls, products, and offers, * or run A/B tests, all without the need for a new app release. * * However, it’s crucial to understand that the recommended approach is to fetch the flow * through the placement ID by the {@link getFlow} method. * The `getFlowForDefaultAudience` method should be a last resort due to its significant drawbacks. * See docs for more details * * @param {string} placementId - The identifier of the desired placement. * This is the value you specified when you created the placement * in the Adapty Dashboard. * @param {GetPlacementForDefaultAudienceParamsInput} [params] - Additional parameters for retrieving flow. * @returns {Promise} * A promise that resolves with a requested flow. * * @throws {@link AdaptyError} * Throws an error: * 1. if the flow with the specified ID is not found * 2. if your bundle ID does not match with your Adapty Dashboard setup */ public async getFlowForDefaultAudience( placementId: string, params: GetPlacementForDefaultAudienceParamsInput = { fetchPolicy: FetchPolicy.ReloadRevalidatingCacheData, }, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'getFlowForDefaultAudience' }); log.start(() => ({ placementId, params })); const methodKey = 'get_flow_for_default_audience'; const data: Req['GetFlowForDefaultAudience.Request'] = { method: methodKey, placement_id: placementId, }; if (params.fetchPolicy !== 'return_cache_data_if_not_expired_else_load') { data['fetch_policy'] = { type: params.fetchPolicy ?? FetchPolicy.ReloadRevalidatingCacheData, } satisfies Def['AdaptyPlacementFetchPolicy']; } else { data['fetch_policy'] = { type: params.fetchPolicy, max_age: params.maxAgeSeconds, } satisfies Def['AdaptyPlacementFetchPolicy']; } const body = JSON.stringify(data); const result = await this.handle( methodKey, body, 'AdaptyFlow', ctx, log, ); return result; } /** * Warms the cache for the given flow placements. * * @remarks * Same request as {@link getFlow}, one per placement, but with less decoding * and all placements fetched in parallel. Nothing is returned; the result * only lands in the cache. * * Useful for cross-placement A/B tests. * * Only the placement JSON is cached — not the UI schema or the paywall * images, so the first flow view creation still goes to the network for those. * * A later {@link getFlow} reads the warmed cache only with * `'return_cache_data_else_load'` (or * `'return_cache_data_if_not_expired_else_load'`); with the default * `'reload_revalidating_cache_data'` it still hits the network and the warmed * copy serves as an offline fallback. Preloading itself always goes to the * network — it has no fetch policy. * * @param {string[]} placementIds - The placements to preload. * @param {PreloadPlacementsParamsInput} [params] - Additional parameters for preloading. * @returns {Promise} A promise that resolves once every placement has been stored. * * @throws {@link AdaptyError} * Throws if any placement failed to load. The error aggregates the failures, * and the placements that did succeed stay in the cache. Requires * {@link activate} to have been called. * * @example * ```ts * await adapty.preloadFlows(['onboarding_flow', 'settings_paywall']); * * const flow = await adapty.getFlow('onboarding_flow', { * fetchPolicy: FetchPolicy.ReturnCacheDataElseLoad, * }); * ``` */ public async preloadFlows( placementIds: string[], params: PreloadPlacementsParamsInput = { loadTimeoutMs: 5000 }, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'preloadFlows' }); log.start(() => ({ placementIds, params })); const methodKey = 'preload_flows'; const body = JSON.stringify({ method: methodKey, placement_ids: placementIds, load_timeout: (params.loadTimeoutMs ?? 5000) / 1000, } satisfies Req['PreloadFlows.Request']); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } /** * Warms the cache for the given flow placements using the **All Users** audience. * * @remarks * The same trade-offs as {@link getFlowForDefaultAudience} apply: faster * fetching, but no targeting by country, attribution or custom attributes. * Unlike {@link preloadFlows} the request carries no timeout. * * See {@link preloadFlows} for what preloading does and does not cover. * * @param {string[]} placementIds - The placements to preload. * @returns {Promise} A promise that resolves once every placement has been stored. * * @throws {@link AdaptyError} * Throws if any placement failed to load. The error aggregates the failures, * and the placements that did succeed stay in the cache. Requires * {@link activate} to have been called. * * @example * ```ts * await adapty.preloadFlowsForDefaultAudience(['onboarding_flow']); * ``` */ public async preloadFlowsForDefaultAudience( placementIds: string[], ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'preloadFlowsForDefaultAudience' }); log.start(() => ({ placementIds })); const methodKey = 'preload_flows_for_default_audience'; const body = JSON.stringify({ method: methodKey, placement_ids: placementIds, } satisfies Req['PreloadFlowsForDefaultAudience.Request']); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } /** * Fetches a list of products associated with a provided flow. * * @example * ```ts * const flow = await adapty.getFlow('placement_id'); * const products = await adapty.getPaywallProducts(flow); * ``` * * @param {Model.AdaptyFlow} flow - a flow to fetch products for. You can get it using {@link Adapty.getFlow} method. * @returns {Promise} A promise that resolves with a list * of {@link Model.AdaptyPaywallProduct} associated with a provided flow. * @throws {@link AdaptyError} */ public async getPaywallProducts( flow: Model.AdaptyFlow, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'getPaywallProducts' }); log.start(() => ({ flow })); const coder = coderFactory.createFlowCoder(); const methodKey = 'get_paywall_products'; const data: Req['GetPaywallProducts.Request'] = { method: methodKey, flow: coder.encode(flow), }; const body = JSON.stringify(data); const result = await this.handle( methodKey, body, 'Array', ctx, log, ); return result; } /** * Fetches the onboarding by the specified placement. * * @deprecated Since 4.0.0. The legacy onboarding API is deprecated — migrate to the Flow * Builder API, which renders onboardings and paywalls natively instead of in a WebView. * This method will be removed in a future version. * * @param {string} placementId - The identifier of the desired placement. * @param {string} [locale] - The locale of the desired onboarding. * @param {GetPlacementParamsInput} [params] - Additional parameters for retrieving the onboarding. * @returns {Promise} A promise that resolves with a requested onboarding. * @throws {@link AdaptyError} */ public async getOnboarding( placementId: string, locale?: string, params: GetPlacementParamsInput = { fetchPolicy: FetchPolicy.ReloadRevalidatingCacheData, loadTimeoutMs: 5000, }, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'getOnboarding' }); log.start(() => ({ placementId, locale, params })); const methodKey = 'get_onboarding'; const data: Req['GetOnboarding.Request'] = { method: methodKey, placement_id: placementId, load_timeout: (params.loadTimeoutMs ?? 5000) / 1000, }; if (locale) { data['locale'] = locale; } if (params.fetchPolicy !== 'return_cache_data_if_not_expired_else_load') { data['fetch_policy'] = { type: params.fetchPolicy ?? FetchPolicy.ReloadRevalidatingCacheData, } satisfies Def['AdaptyPlacementFetchPolicy']; } else { data['fetch_policy'] = { type: params.fetchPolicy, max_age: params.maxAgeSeconds, } satisfies Def['AdaptyPlacementFetchPolicy']; } const body = JSON.stringify(data); const result = await this.handle( methodKey, body, 'AdaptyOnboarding', ctx, log, ); return result; } /** * Fetches the onboarding of the specified placement for the **All Users** audience. * * @deprecated Since 4.0.0. The legacy onboarding API is deprecated — migrate to the Flow * Builder API, which renders onboardings and paywalls natively instead of in a WebView. * This method will be removed in a future version. * * @param {string} placementId - The identifier of the desired placement. * @param {string} [locale] - The locale of the desired onboarding. * @param {GetPlacementForDefaultAudienceParamsInput} [params] - Additional parameters. * @returns {Promise} A promise that resolves with a requested onboarding. * @throws {@link AdaptyError} */ public async getOnboardingForDefaultAudience( placementId: string, locale?: string, params: GetPlacementForDefaultAudienceParamsInput = { fetchPolicy: FetchPolicy.ReloadRevalidatingCacheData, }, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'getOnboardingForDefaultAudience' }); log.start(() => ({ placementId, locale, params })); const methodKey = 'get_onboarding_for_default_audience'; const data: Req['GetOnboardingForDefaultAudience.Request'] = { method: methodKey, placement_id: placementId, }; if (locale) { data['locale'] = locale; } if (params.fetchPolicy !== 'return_cache_data_if_not_expired_else_load') { data['fetch_policy'] = { type: params.fetchPolicy ?? FetchPolicy.ReloadRevalidatingCacheData, } satisfies Def['AdaptyPlacementFetchPolicy']; } else { data['fetch_policy'] = { type: params.fetchPolicy, max_age: params.maxAgeSeconds, } satisfies Def['AdaptyPlacementFetchPolicy']; } const body = JSON.stringify(data); const result = await this.handle( methodKey, body, 'AdaptyOnboarding', ctx, log, ); return result; } /** * Fetches a user profile. * * Allows you to define the level of access, * as well as other parameters. * * @remarks * The getProfile method provides the most up-to-date result * as it always tries to query the API. * If for some reason (e.g. no internet connection), * the Adapty SDK fails to retrieve information from the server, * the data from cache will be returned. * It is also important to note * that the Adapty SDK updates {@link Model.AdaptyProfile} cache * on a regular basis, in order * to keep this information as up-to-date as possible. * * @returns {Promise} * @throws {@link AdaptyError} */ public async getProfile(): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'getProfile' }); log.start(() => ({})); const methodKey = 'get_profile'; const body = JSON.stringify({ method: methodKey, } satisfies Req['GetProfile.Request']); const result = await this.handle( methodKey, body, 'AdaptyProfile', ctx, log, ); return result; } /** * Logs in a user with a provided customerUserId. * * If you don't have a user id on SDK initialization, * you can set it later at any time with this method. * The most common cases are after registration/authorization * when the user switches from being an anonymous user to an authenticated user. * * @param {string} customerUserId - unique user id * @param {IdentifyParamsInput} [params] - Additional parameters for identification * @throws {@link AdaptyError} */ public async identify( customerUserId: string, params?: IdentifyParamsInput, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'identify' }); log.start(() => ({ customerUserId })); const methodKey = 'identify'; const data: Req['Identify.Request'] = { method: methodKey, customer_user_id: customerUserId, }; const identifyParamsCoder = coderFactory.createIdentifyParamsCoder(); const parameters = identifyParamsCoder.encode(params); if (parameters) { data.parameters = parameters; } const body = JSON.stringify(data); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } /** * Logs a flow view event. * * Adapty helps you to measure the performance of your flows. * We automatically collect all the metrics related to purchases except for flow views. * This is because only you know when the flow was shown to a customer. * * @remarks * Whenever you show a flow to your user, * call this function to log the event, * and it will be accumulated in the flow metrics. * * @example * ```ts * const flow = await adapty.getFlow('placement_id'); * // ...after opening the flow * adapty.logShowFlow(flow); * ``` * * @param {Model.AdaptyFlow} flow - object that was shown to the user. * @returns {Promise} resolves when the event is logged */ public async logShowFlow(flow: Model.AdaptyFlow): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'logShowFlow' }); log.start(() => ({ flow })); const coder = coderFactory.createFlowCoder(); const methodKey = 'log_show_flow'; const data: Req['LogShowFlow.Request'] = { method: methodKey, flow: coder.encode(flow), }; const body = JSON.stringify(data); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } public async openWebPaywall( paywallOrProduct: Model.AdaptyFlowPaywall | Model.AdaptyPaywallProduct, openIn: WebPresentation = WebPresentation.BrowserOutApp, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'openWebPaywall' }); log.start(() => ({ paywallOrProduct })); const methodKey = 'open_web_paywall'; const data: Req['OpenWebPaywall.Request'] = { method: methodKey, open_in: openIn, ...this.encodeWebPaywallTarget(paywallOrProduct), }; const body = JSON.stringify(data); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } public async createWebPaywallUrl( paywallOrProduct: Model.AdaptyFlowPaywall | Model.AdaptyPaywallProduct, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'create_web_paywall_url' }); log.start(() => ({ paywallOrProduct })); const methodKey = 'create_web_paywall_url'; const data: Req['CreateWebPaywallUrl.Request'] = { method: methodKey, ...this.encodeWebPaywallTarget(paywallOrProduct), }; const body = JSON.stringify(data); const result = await this.handle( methodKey, body, 'String', ctx, log, ); return result; } /** * Encodes a web paywall target as either a `product` or a `paywall` wire * field. The cross-platform contract accepts exactly one of them; products * are discriminated by the presence of `vendorProductId`. */ private encodeWebPaywallTarget( paywallOrProduct: Model.AdaptyFlowPaywall | Model.AdaptyPaywallProduct, ) { if ('vendorProductId' in paywallOrProduct) { return { product: coderFactory .createPaywallProductCoder() .encode(paywallOrProduct), }; } return { paywall: coderFactory.createFlowPaywallCoder().encode(paywallOrProduct), }; } /** * Opens a URL using the native browser. * * @remarks * This is the native implementation behind the default `onUrlPress` flow * handler. The native side honors `openIn` (`browser_out_app` → external * browser, `browser_in_app` → in-app browser). Call it directly from a custom * `onUrlPress` handler when you want to run your own logic but keep the native * open-URL behavior. * * @param {string} url - The URL to open. * @param {WebPresentation} [openIn] - How to present the URL. When omitted, * the native SDK decides how to present it. * @returns {Promise} resolves when the native call completes. * @throws {@link AdaptyError} */ public async openWebUrl( url: string, openIn?: WebPresentation, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'openWebUrl' }); log.start(() => ({ url, openIn })); const methodKey = 'adapty_ui_open_url'; const data: Req['AdaptyUIOpenUrl.Request'] = { method: methodKey, url, }; if (openIn) { data.open_in = openIn; } const body = JSON.stringify(data); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } /** * Requests the native app-review prompt. * * @remarks * This is the native implementation behind the default `onRequestAppReview` * flow handler (`SKStoreReviewController` on iOS, In-App Review on Android). * Call it directly from a custom `onRequestAppReview` handler when you want to * run your own logic but keep the native prompt. * * @returns {Promise} resolves when the native call completes. * @throws {@link AdaptyError} */ public async requestAppReview(): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'requestAppReview' }); log.start(() => ({})); const methodKey = 'adapty_ui_request_app_review'; const body = JSON.stringify({ method: methodKey, } satisfies Req['AdaptyUIRequestAppReview.Request']); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } /** * Logs out the current user. * You can then login the user using {@link Adapty.identify} method. * * @throws {@link AdaptyError} */ public async logout(): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'logout' }); log.start(() => ({})); const methodKey = 'logout'; const body = JSON.stringify({ method: methodKey, } satisfies Req['Logout.Request']); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } /** * Performs a purchase of the specified product. * * All available promotions will be applied automatically. * * @remarks * Successful purchase will also result in a call to the `'onLatestProfileLoad'` listener. * You can use {@link Adapty.addEventListener} to subscribe to this event and handle * the purchase result outside of this thread. * * @param {Model.AdaptyPaywallProduct} product - The product to be purchased. * You can get the product using {@link Adapty.getPaywallProducts} method. * @param {MakePurchaseParamsInput} [params] - Additional parameters for the purchase. * @returns {Promise} A Promise that resolves to the {@link Model.AdaptyPurchaseResult} object * containing details about the purchase. If the result is `'success'`, it also includes the updated user's profile. * @throws {AdaptyError} If an error occurs during the purchase process * or while decoding the response from the native SDK. * * @example * ```ts * try { * const flow = await adapty.getFlow('onboarding'); * const products = await adapty.getPaywallProducts(flow); * const product = products[0]; * * const profile = await adapty.makePurchase(product); * // successful, canceled, or pending purchase * } catch (error) { * // handle error * } * ``` */ public async makePurchase( product: Model.AdaptyPaywallProduct, params: MakePurchaseParamsInput = {}, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'makePurchase' }); log.start(() => ({ product, params })); const coder = coderFactory.createPaywallProductCoder(); const encoded = coder.encode(product); const productInput = coder.getInput(encoded); const methodKey = 'make_purchase'; const data: Req['MakePurchase.Request'] = { method: methodKey, product: productInput, }; const purchaseParamsCoder = coderFactory.createPurchaseParamsCoder(); const purchaseParams = purchaseParamsCoder.encode(params); if (Object.keys(purchaseParams).length > 0) { data.parameters = purchaseParams; } const body = JSON.stringify(data); const result = await this.handle( methodKey, body, 'AdaptyPurchaseResult', ctx, log, ); return result; } /** * Purchases a product promoted in the App Store. * * @remarks * Use this with the product delivered by the * `'onPromotedPurchaseReceived'` event. Unlike {@link Adapty.makePurchase}, * a promoted product carries no paywall context, so no purchase parameters * are accepted. * * Pass the event's product object as is: on iOS it carries the StoreKit * purchase intent required to complete the purchase, so a hand-built * product fails. * * @example * ```ts * adapty.addEventListener('onPromotedPurchaseReceived', async product => { * await adapty.makePromotedPurchase(product); * }); * ``` * * @param {Model.AdaptyPromotedProduct} product - The promoted product to purchase. * @returns {Promise} The result of the purchase. * * @throws {@link AdaptyError} Throws if the purchase fails. */ public async makePromotedPurchase( product: Model.AdaptyPromotedProduct, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'makePromotedPurchase' }); log.start(() => ({ product })); const coder = coderFactory.createPromotedProductCoder(); const encoded = coder.encode(product); const productInput = coder.getInput(encoded); const methodKey = 'make_promoted_purchase'; const data: Req['MakePromotedPurchase.Request'] = { method: methodKey, product: productInput, }; const body = JSON.stringify(data); const result = await this.handle( methodKey, body, 'AdaptyPurchaseResult', ctx, log, ); return result; } /** * Opens a native modal screen to redeem Apple Offer Codes. * * @remarks * iOS 14+ only. */ public async presentCodeRedemptionSheet(): Promise { if (Platform.OS === 'android') { return Promise.resolve(); } const ctx = new LogContext(); const log = ctx.call({ methodName: 'presentCodeRedemptionSheet' }); log.start(() => ({})); const methodKey = 'present_code_redemption_sheet'; const body = JSON.stringify({ method: methodKey, } satisfies Req['PresentCodeRedemptionSheet.Request']); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } /** * Gets the types of store messages currently waiting in the SDK queue. * * @platform ios * @remarks * iOS 16+ only. The queue is kept only when the SDK is activated with * `storeMessagesHandling: 'manual'`; in `'auto'` mode and before activation * the result is always empty. The result is a snapshot of unique types in * no particular order — there is no event for newly arrived messages. * * `[]` means `showStoreMessages()` has nothing to show right now. `null` means the * store cannot report pending messages: on Android Google Play decides on show, so * this resolves `null` without calling native — call `showStoreMessages()` there. * Below iOS 16 the native method is unavailable and the call rejects. * * @returns {Promise} A promise that resolves with the pending types, or `null` where the store cannot report them (Android). * @throws {@link AdaptyError} If an error occurs on iOS. * * @example * ```ts * const types = await adapty.getPendingStoreMessageTypes(); * if (types === null) { * // The store can't report pending messages (Android): let it decide * await adapty.showStoreMessages(); * } else if (types.includes('billing_issue')) { * // Explain the billing issue in your own UI first, then show the system message * await adapty.showStoreMessages({ ios: { filter: ['billing_issue'] } }); * } * ``` */ public async getPendingStoreMessageTypes(): Promise< Model.AdaptyStoreMessageType[] | null > { if (Platform.OS === 'android') { return null; } const ctx = new LogContext(); const log = ctx.call({ methodName: 'getPendingStoreMessageTypes' }); log.start(() => ({})); const methodKey = 'get_pending_store_message_types'; const body = JSON.stringify({ method: methodKey, } satisfies Req['GetPendingStoreMessageTypes.Request']); const result = await this.handle( methodKey, body, 'Array', ctx, log, ); return result; } /** * Shows pending store messages: App Store messages on iOS, Google Play in-app messages on Android. * * @remarks * Intended for `storeMessagesHandling: 'manual'`, but works in both modes. * * iOS 16+: messages are shown one by one; a successfully shown message leaves * the queue, a message that failed to show stays for a retry. Omit `ios.filter` to * show every pending message, pass `[]` to show none. * * Android: shows every applicable message; Google Play decides whether one exists. * * @param {object} [params] - Optional parameters. * @param {object} [params.ios] - iOS-only parameters, ignored on Android. * @param {Model.AdaptyStoreMessageType[]} [params.ios.filter] - The message types to show. * @returns {Promise} A promise that resolves once the messages have been processed. * @throws {@link AdaptyError} with code `operationInProgress` (3201) if another show is running, * or `resolverFailure` (3202) if no foreground window scene is available (iOS). * * @example * ```ts * // Show everything that is pending, e.g. after onboarding is finished * await adapty.showStoreMessages(); * * // iOS: show just the price increase consent; Android shows everything * await adapty.showStoreMessages({ ios: { filter: ['price_increase_consent'] } }); * ``` */ public async showStoreMessages(params?: { ios?: { filter?: Model.AdaptyStoreMessageType[] }; }): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'showStoreMessages' }); log.start(() => ({ params })); const methodKey = 'show_store_messages'; const body = JSON.stringify({ method: methodKey, filter: Platform.OS === 'ios' ? params?.ios?.filter : undefined, } satisfies Req['ShowStoreMessage.Request']); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } /** * Sets the variation ID of the purchase. * * In Observer mode, Adapty SDK doesn't know, where the purchase was made from. * If you display products using our Paywalls or A/B Tests, * you can manually assign variation to the purchase. * After doing this, you'll be able to see metrics in Adapty Dashboard. * * @param {string} transactionId - `transactionId` property of {@link Model.AdaptySubscription} * @param {string} variationId - `variationId` property of {@link Model.AdaptyFlow} * @param params - Optional platform-specific parameters. * @param {string} [params.ios.jwsTransaction] - iOS only. StoreKit 2 JWS representation of the transaction. * @throws {@link AdaptyError} */ public async reportTransaction( transactionId: string, variationId?: string, params?: Pick, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'reportTransaction' }); log.start(() => ({ variationId, transactionId, params })); const methodKey = 'report_transaction'; const coder = coderFactory.createReportTransactionParamsCoder(); const data: Req['ReportTransaction.Request'] = { method: methodKey, ...coder.encode({ transactionId, variationId, ios: params?.ios }), }; const body = JSON.stringify(data); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } /** * Restores user purchases and updates the profile. * * @returns {Promise} resolves with the updated profile * @throws {@link AdaptyError} if an error occurs during the restore process or while decoding the response */ public async restorePurchases(): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'restorePurchases' }); log.start(() => ({})); const methodKey = 'restore_purchases'; const body = JSON.stringify({ method: methodKey, } satisfies Req['RestorePurchases.Request']); const result = await this.handle( methodKey, body, 'AdaptyProfile', ctx, log, ); return result; } /** * Sets the fallback paywalls. * * Fallback file will be used if the SDK fails * to fetch the paywalls or onboardings from the dashboard. * It is not designed to be used for the offline flow, * as products are not cached in Adapty. * * @returns {Promise} resolves when fallback placements are saved */ public async setFallback(fileLocation: FileLocation): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'setFallback' }); const fileLocationJson = Platform.select({ ios: fileLocation.ios.fileName, android: 'relativeAssetPath' in fileLocation.android ? `${fileLocation.android.relativeAssetPath}a` : `${fileLocation.android.rawResName}r`, }); log.start(() => ({ fileLocationJson })); const methodKey = 'set_fallback'; const data: Req['SetFallback.Request'] = { method: methodKey, asset_id: fileLocationJson ?? '', }; const body = JSON.stringify(data); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } public async setIntegrationIdentifier( key: string, value: string, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'setIntegrationIdentifier' }); log.start(() => ({ key })); const methodKey = 'set_integration_identifiers'; const data: Req['SetIntegrationIdentifier.Request'] = { method: methodKey, key_values: { [key]: value }, }; const body = JSON.stringify(data); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } /** * Sets the preferred log level and, optionally, a custom JS logger configuration. * * By default, JS-side SDK logs are disabled until a log level is set here or via `logLevel` in `activate`. * The native level stays at the native SDK default until then. * * @remarks * There are four levels available: * `error`: only errors will be logged * `warn`: messages from the SDK that do not cause critical errors, but are worth paying attention to * `info`: various information messages, such as those that log the lifecycle of various modules * `verbose`: any additional information that may be useful during debugging, such as function calls, API queries, etc. * * `options.logger.sinks` replaces all current sinks and calls `destroy()` on them, so include `consoleLogSink` to keep console output. * Any `options.logger` also resets `defaultMeta`, so pass it again each time. * To change only the level, omit `options.logger`; the current sinks are kept. * The new level and sinks apply to this call's own logs too, and stay applied even if the native call then rejects. * * @example * ```ts * import { adapty, consoleLogSink } from 'react-native-adapty'; * * await adapty.setLogLevel('verbose'); * * await adapty.setLogLevel('verbose', { * logger: { * sinks: [ * consoleLogSink, * { id: 'my-sink', handle: event => sendToServer(event.level, event.message, event.params) }, * ], * }, * }); * ``` * * @param {LogLevel} logLevel - new preferred log level * @param options - optional settings * @param options.logger - JS logger configuration: sinks and default metadata * @returns {Promise} resolves when the log level is set * @throws {@link AdaptyError} if the log level is invalid */ public async setLogLevel( logLevel: LogLevel, options?: { logger?: LoggerConfig }, ): Promise { // apply sinks and level before the first log, as activate does, so this call is logged under the new config if (options?.logger) { Log.configure(options.logger); } Log.logLevel = logLevel; const ctx = new LogContext(); const log = ctx.call({ methodName: 'setLogLevel' }); log.start(() => ({ logLevel })); const methodKey = 'set_log_level'; const data: Req['SetLogLevel.Request'] = { method: methodKey, value: logLevel, }; const body = JSON.stringify(data); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } /** * Updates attribution data from an external attribution provider * for the current user. * * @example * ```ts * const attribution = { * 'Adjust Adid': 'adjust_adid', * 'Adjust Network': 'adjust_network', * 'Adjust Campaign': 'adjust_campaign', * 'Adjust Adgroup': 'adjust_adgroup', * }; * * adapty.updateExternalAttribution(attribution, 'adjust'); * ``` * * @param {Record} attribution - An object containing attribution data. * @param {AdaptyExternalAttributionProvider} provider - The attribution provider the data came from. Any string is accepted. * @returns {Promise} A promise that resolves when the attribution data is updated. * * @throws {@link AdaptyError} Throws if parameters are invalid or not provided. */ public async updateExternalAttribution( attribution: Record, provider: AdaptyExternalAttributionProvider, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'updateExternalAttribution' }); log.start(() => ({ attribution, provider })); const methodKey = 'update_external_attribution_data'; const data: Req['UpdateExternalAttributionData.Request'] = { method: methodKey, attribution: JSON.stringify(attribution), provider: provider, }; const body = JSON.stringify(data); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } public async updateCollectingRefundDataConsent( consent: boolean, ): Promise { if (Platform.OS === 'android') { return Promise.resolve(); } const ctx = new LogContext(); const log = ctx.call({ methodName: 'update_collecting_refund_data_consent', }); log.start(() => ({ consent })); const methodKey = 'update_collecting_refund_data_consent'; const data: Req['UpdateCollectingRefundDataConsent.Request'] = { method: methodKey, consent: consent, }; const body = JSON.stringify(data); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } public async updateRefundPreference( refundPreference: RefundPreference, ): Promise { if (Platform.OS === 'android') { return Promise.resolve(); } const ctx = new LogContext(); const log = ctx.call({ methodName: 'update_refund_preference' }); log.start(() => ({ refundPreference })); const methodKey = 'update_refund_preference'; const data: Req['UpdateRefundPreference.Request'] = { method: methodKey, refund_preference: refundPreference, }; const body = JSON.stringify(data); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } /** * Updates a profile for the current user. * * @param {Model.AdaptyProfileParameters} params — an object of parameters to update * @throws {@link AdaptyError} If parameters are invalid or there is a network error. * * @example * ```ts * const profile = { * email: 'foo@example.com', * phone: '+1234567890', * }; * * await adapty.updateProfile(profile); * ``` */ public async updateProfile( params: Partial, ): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'updateProfile' }); log.start(() => ({ params })); const coder = coderFactory.createProfileParametersCoder(); const methodKey = 'update_profile'; const data: Req['UpdateProfile.Request'] = { method: methodKey, params: coder.encode(params), }; const body = JSON.stringify(data); const result = await this.handle(methodKey, body, 'Void', ctx, log); return result; } public async isActivated(): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'isActivated' }); log.start(() => ({})); const methodKey = 'is_activated'; const body = JSON.stringify({ method: methodKey, } satisfies Req['IsActivated.Request']); const result = await this.handle( methodKey, body, 'Boolean', ctx, log, ); return result; } /** * Gets the current installation status. * * @remarks * Installation status provides information about when the app was installed, * how many times it has been launched, and other installation-related details. * The status can be "not_available", "not_determined", or "determined" with details. * * @returns {Promise} A promise that resolves with the installation status. * @throws {@link AdaptyError} If an error occurs while retrieving the installation status. * * @example * ```ts * try { * const status = await adapty.getCurrentInstallationStatus(); * if (status.status === 'determined') { * console.log('Install time:', status.details.installTime); * console.log('Launch count:', status.details.appLaunchCount); * } * } catch (error) { * // handle error * } * ``` */ public async getCurrentInstallationStatus(): Promise { const ctx = new LogContext(); const log = ctx.call({ methodName: 'getCurrentInstallationStatus' }); log.start(() => ({})); const methodKey = 'get_current_installation_status'; const body = JSON.stringify({ method: methodKey, } satisfies Req['GetCurrentInstallationStatus.Request']); const result = await this.handle( methodKey, body, 'AdaptyInstallationStatus', ctx, log, ); return result; } }