import { EmitterSubscription } from 'react-native'; import { LogContext, LogScope, type LoggerConfig } from './logger'; 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 type { AdaptyMockConfig } from './mock/types'; /** * Entry point for the Adapty SDK. * All Adapty methods are available through this class. * @public */ export declare class Adapty { constructor(); private resolveHeldActivation?; private activating; private nonWaitingMethods; /** * 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; handle(method: MethodName, params: string, resultType: AdaptyType, ctx: LogContext, log: LogScope): Promise; /** * 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; /** * Removes all attached event listeners */ removeAllListeners(): void; /** * 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'); * ``` */ enableMock(mockConfig?: AdaptyMockConfig): void; /** * 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. */ activate(apiKey: string, params?: ActivateParamsInput): Promise; /** * 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 */ getFlow(placementId: string, params?: GetPlacementParamsInput): Promise; /** * 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 */ getFlowForDefaultAudience(placementId: string, params?: GetPlacementForDefaultAudienceParamsInput): Promise; /** * 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, * }); * ``` */ preloadFlows(placementIds: string[], params?: PreloadPlacementsParamsInput): Promise; /** * 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']); * ``` */ preloadFlowsForDefaultAudience(placementIds: string[]): Promise; /** * 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} */ getPaywallProducts(flow: Model.AdaptyFlow): Promise; /** * 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} */ getOnboarding(placementId: string, locale?: string, params?: GetPlacementParamsInput): Promise; /** * 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} */ getOnboardingForDefaultAudience(placementId: string, locale?: string, params?: GetPlacementForDefaultAudienceParamsInput): Promise; /** * 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} */ getProfile(): Promise; /** * 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} */ identify(customerUserId: string, params?: IdentifyParamsInput): Promise; /** * 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 */ logShowFlow(flow: Model.AdaptyFlow): Promise; openWebPaywall(paywallOrProduct: Model.AdaptyFlowPaywall | Model.AdaptyPaywallProduct, openIn?: WebPresentation): Promise; createWebPaywallUrl(paywallOrProduct: Model.AdaptyFlowPaywall | Model.AdaptyPaywallProduct): Promise; /** * 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; /** * 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} */ openWebUrl(url: string, openIn?: WebPresentation): Promise; /** * 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} */ requestAppReview(): Promise; /** * Logs out the current user. * You can then login the user using {@link Adapty.identify} method. * * @throws {@link AdaptyError} */ logout(): Promise; /** * 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 * } * ``` */ makePurchase(product: Model.AdaptyPaywallProduct, params?: MakePurchaseParamsInput): Promise; /** * 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. */ makePromotedPurchase(product: Model.AdaptyPromotedProduct): Promise; /** * Opens a native modal screen to redeem Apple Offer Codes. * * @remarks * iOS 14+ only. */ presentCodeRedemptionSheet(): Promise; /** * 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'] } }); * } * ``` */ getPendingStoreMessageTypes(): Promise; /** * 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'] } }); * ``` */ showStoreMessages(params?: { ios?: { filter?: Model.AdaptyStoreMessageType[]; }; }): Promise; /** * 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} */ reportTransaction(transactionId: string, variationId?: string, params?: Pick): Promise; /** * 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 */ restorePurchases(): Promise; /** * 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 */ setFallback(fileLocation: FileLocation): Promise; setIntegrationIdentifier(key: string, value: string): Promise; /** * 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 */ setLogLevel(logLevel: LogLevel, options?: { logger?: LoggerConfig; }): Promise; /** * 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. */ updateExternalAttribution(attribution: Record, provider: AdaptyExternalAttributionProvider): Promise; updateCollectingRefundDataConsent(consent: boolean): Promise; updateRefundPreference(refundPreference: RefundPreference): Promise; /** * 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); * ``` */ updateProfile(params: Partial): Promise; isActivated(): Promise; /** * 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 * } * ``` */ getCurrentInstallationStatus(): Promise; } //# sourceMappingURL=adapty-handler.d.ts.map