diff --git a/AGENTS.md b/AGENTS.md index 9f9c5bc..e1a1a89 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -87,11 +87,13 @@ This repo uses platform dependency injection to keep `@adapty/core` platform-agn - `ILoggerAdapter` for logging - **Instantiation rule:** do not instantiate `*Coder` via `new` outside `src/coders/**`. In SDK / bridge / feature code, use `CoderFactory` as the single entry point. - **When adding a new coder:** add a corresponding `create*Coder()` method to `CoderFactory` and use it instead of direct construction. +- **Platform propagation:** `Coder` requires an `IPlatformAdapter` in its constructor. A coder that nests another coder (in `properties`, fields, methods, `ArrayCoder`/`HashmapCoder`) must pass `this.platform`; otherwise platform-gated `required` checks inside `ios`/`android` blocks of the nested coder never fire. ### Testing Guidance - Tests should create coders with mock adapters, not mutate `Platform` globals. - Prefer inline adapters: `{ OS: 'ios' }` / `{ OS: 'android' }`. +- Coder tests that do not care about the platform pass `new DefaultPlatformAdapter()` (OS `'unknown'`, platform-gated checks off). `src/coders/nested-platform.test.ts` verifies that every coder reachable from `CoderFactory` shares the factory's adapter. ### Usage in Downstream SDKs diff --git a/README.md b/README.md index 0aab768..8db8fee 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ > > This package is an internal dependency of Adapty JavaScript SDKs. It is not intended for direct installation. -This package contains the shared TypeScript foundation used by Adapty JavaScript SDKs, like React Native and Capacitor. +This package contains the shared TypeScript foundation used by Adapty JavaScript SDKs: React Native and Capacitor. ## Documentation diff --git a/cross_platform.yaml b/cross_platform.yaml index bdd79cb..e070b5d 100644 --- a/cross_platform.yaml +++ b/cross_platform.yaml @@ -1,5 +1,5 @@ $schema: "https://json-schema.org/draft/2020-12/schema" -$id: "https://adapty.io/crossPlatform/4.2.0/schema" +$id: "https://adapty.io/crossPlatform/4.3.2/schema" title: "Cross Platform Format" $requests: @@ -117,6 +117,24 @@ $requests: properties: success: { const: true } + ### destroyFlowView ### + AdaptyUIDestroyFlowView.Request: #request + type: object + required: [method, id] + properties: + method: { const: "adapty_ui_destroy_flow_view" } + id: { type: string, description: "View Id" } + + AdaptyUIDestroyFlowView.Response: #response + type: object + oneOf: + - required: [error] + properties: + error: { $ref: "#/$defs/AdaptyError" } + - required: [success] + properties: + success: { const: true } + ### presentOnboardingView ### AdaptyUIPresentOnboardingView.Request: #request type: object @@ -291,6 +309,47 @@ $requests: properties: success: { $ref: "#/$defs/AdaptyFlow" } + ### preloadFlows ### + PreloadFlows.Request: #request + type: object + required: [method, placement_ids] + properties: + method: { const: "preload_flows" } + placement_ids: + type: array + items: { type: string } + load_timeout: { type: number, description: "seconds" } + + PreloadFlows.Response: #response + type: object + oneOf: + - required: [error] + properties: + error: { $ref: "#/$defs/AdaptyError" } + - required: [success] + properties: + success: { const: true } + + ### preloadFlowsForDefaultAudience ### + PreloadFlowsForDefaultAudience.Request: #request + type: object + required: [method, placement_ids] + properties: + method: { const: "preload_flows_for_default_audience" } + placement_ids: + type: array + items: { type: string } + + PreloadFlowsForDefaultAudience.Response: #response + type: object + oneOf: + - required: [error] + properties: + error: { $ref: "#/$defs/AdaptyError" } + - required: [success] + properties: + success: { const: true } + ### getPaywallProducts ### GetPaywallProducts.Request: #request type: object @@ -308,10 +367,10 @@ $requests: - required: [success] properties: success: - { - type: array, - items: { $ref: "#/$defs/AdaptyPaywallProduct.Response" }, - } + type: array + items: { $ref: "#/$defs/AdaptyPaywallProduct.Response" } + + ### getProfile ### GetProfile.Request: #request @@ -465,6 +524,46 @@ $requests: properties: success: { $ref: "#/$defs/AdaptyPurchaseResult" } + ### getPendingStoreMessageTypes ### + GetPendingStoreMessageTypes.Request: #request + type: object + description: "iOS Only. Requires iOS 16+" + required: [method] + properties: + method: { const: "get_pending_store_message_types" } + + GetPendingStoreMessageTypes.Response: #response + type: object + oneOf: + - required: [error] + properties: + error: { $ref: "#/$defs/AdaptyError" } + - required: [success] + properties: + success: + type: array + items: { $ref: "#/$defs/AdaptyStoreMessageType" } + + ### showStoreMessage ### + ShowStoreMessage.Request: #request + type: object + description: "Requires iOS 16+ on iOS" + required: [method] + properties: + method: { const: "show_store_messages" } + filter: + type: array + items: { $ref: "#/$defs/AdaptyStoreMessageType" } + + ShowStoreMessage.Response: #response + type: object + oneOf: + - required: [error] + properties: + error: { $ref: "#/$defs/AdaptyError" } + - required: [success] + properties: + success: { const: true } OpenWebPaywall.Request: #request type: object required: [method] @@ -547,6 +646,7 @@ $requests: method: { const: "report_transaction" } variation_id: { type: string } transaction_id: { type: string } + apple_jws_transaction: { type: string } ReportTransaction.Response: #response type: object @@ -1162,6 +1262,11 @@ $defs: customer_identity_parameters: { $ref: "#/$defs/CustomerIdentityParameters" } observer_mode: { type: boolean, default: false } + store_messages_handling: + { + $ref: "#/$defs/StoreMessagesHandling", + description: "Requires iOS 16+ on iOS", + } apple_idfa_collection_disabled: { type: boolean, default: false } google_adid_collection_disabled: { type: boolean, default: false } google_enable_pending_prepaid_plans: { type: boolean, default: false } @@ -1184,6 +1289,20 @@ $defs: memory_storage_count_limit: { type: integer } disk_storage_size_limit: { type: integer, description: "bytes" } + StoreMessagesHandling: #request + type: string + enum: ["auto", "manual", "default"] + + AdaptyStoreMessageType: #request #response + type: string + anyOf: + - enum: + - generic + - price_increase_consent + - billing_issue + - win_back_offer + - pattern: "^storekit_-?[0-9]+$" + CustomerIdentityParameters: #request type: object properties: @@ -1228,7 +1347,10 @@ $defs: AdaptyPrice: #response type: object - required: [amount] + required: + - amount + - currency_code # iOS Only + - localized_string # iOS Only properties: amount: { type: number } currency_code: { type: string } @@ -1238,12 +1360,19 @@ $defs: AdaptyPromotedProduct.Request: #request type: object required: + - purchase_intent_id # iOS Only - vendor_product_id properties: + purchase_intent_id: { type: string } # iOS Only vendor_product_id: { type: string } subscription: type: object properties: + pricing_terms: # iOS Only + type: object + required: [billing_plan_id] + properties: + billing_plan_id: { type: string } offer: type: object required: [offer_identifier] @@ -1255,12 +1384,14 @@ $defs: AdaptyPromotedProduct.Response: #event type: object required: + - purchase_intent_id # iOS Only - vendor_product_id - localized_description - localized_title - is_family_shareable # iOS Only - price properties: + purchase_intent_id: { type: string } # iOS Only vendor_product_id: { type: string } localized_description: { type: string } localized_title: { type: string } @@ -1271,17 +1402,41 @@ $defs: subscription: { $ref: "#/$defs/AdaptyProduct.Subscription" } payload_data: { type: string } + AdaptySubscriptionPricingTerms: #event #response + type: object + required: + - billing_plan_id + - billing_price + - billing_period + - commitment_info + properties: + billing_plan_id: { type: string } + billing_price: { $ref: "#/$defs/AdaptyPrice" } + billing_period: { $ref: "#/$defs/AdaptySubscriptionPeriod" } + commitment_info: { $ref: "#/$defs/AdaptySubscriptionCommitmentInfo" } + + AdaptySubscriptionCommitmentInfo: #event #response + type: object + required: + - price + - period + properties: + price: { $ref: "#/$defs/AdaptyPrice" } + period: { $ref: "#/$defs/AdaptySubscriptionPeriod" } + AdaptyProduct.Subscription: #event #response type: object required: - group_identifier # iOS Only - period + - pricing_terms # iOS Only - renewal_type # Android Only - base_plan_id # Android Only properties: group_identifier: { type: string, description: "iOS Only" } period: { $ref: "#/$defs/AdaptySubscriptionPeriod" } localized_period: { type: string } + pricing_terms: { $ref: "#/$defs/AdaptySubscriptionPricingTerms" } offer: { $ref: "#/$defs/AdaptySubscriptionOffer" } renewal_type: # Android Only type: string @@ -1312,6 +1467,11 @@ $defs: subscription: type: object properties: + pricing_terms: # iOS Only + type: object + required: [billing_plan_id] + properties: + billing_plan_id: { type: string } offer: type: object required: [offer_identifier] @@ -1519,10 +1679,18 @@ $defs: adapty_product_id: { type: string } access_level_id: { type: string } product_type: { type: string } - promotional_offer_id: { type: string, description: "iOS Only" } - win_back_offer_id: { type: string, description: "iOS Only" } base_plan_id: { type: string, description: "Android Only" } offer_id: { type: string, description: "Android Only" } + pricing_terms: # iOS only + type: array + items: + type: object + required: + - billing_plan_id # iOS only + properties: + billing_plan_id: { type: string } # iOS only + promotional_offer_id: { type: string } # iOS only + win_back_offer_id: { type: string } # iOS only AdaptySubscriptionPeriod: #response type: object @@ -1600,6 +1768,8 @@ $defs: billing_issue_detected_at: { $ref: "#/$defs/Date" } starts_at: { $ref: "#/$defs/Date" } cancellation_reason: { type: string } + billing_plan_id: { type: string, description: "iOS Only" } + commitment: { $ref: "#/$defs/AdaptyProfile.SubscriptionCommitmentInfo" } is_refund: { type: boolean } AdaptyProfile.NonSubscription: #response @@ -1636,6 +1806,7 @@ $defs: - is_refund - is_sandbox - will_renew + - billing_plan_id # iOS Only properties: store: { type: string } vendor_product_id: { type: string } @@ -1658,6 +1829,16 @@ $defs: active_promotional_offer_id: { type: string } offer_id: { type: string } cancellation_reason: { type: string } + billing_plan_id: { type: string, description: "iOS Only" } + commitment: { $ref: "#/$defs/AdaptyProfile.SubscriptionCommitmentInfo" } + + AdaptyProfile.SubscriptionCommitmentInfo: #response + type: object + required: [billing_period_number, total_billing_periods, expires_at] + properties: + billing_period_number: { type: integer, minimum: 0 } + total_billing_periods: { type: integer, minimum: 0 } + expires_at: { $ref: "#/$defs/Date" } AdaptyProfile.CustomAttributes: type: object @@ -1694,7 +1875,7 @@ $defs: analytics_disabled: { type: boolean } AdaptySubscriptionOffer.Identifier: #request #response - type: string + type: object oneOf: - required: [type] properties: diff --git a/package.json b/package.json index 1259920..0ebddff 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package", "name": "@adapty/core", - "version": "4.2.0", + "version": "4.3.2", "description": "Platform-agnostic core for Adapty JS SDKs", "license": "MIT", "author": "Adapty team ", diff --git a/scripts/generate-api-types.ts b/scripts/generate-api-types.ts index e0e7c8a..48c25e1 100644 --- a/scripts/generate-api-types.ts +++ b/scripts/generate-api-types.ts @@ -212,13 +212,21 @@ function isPrimitiveOneOf(variants: SchemaNode[]): boolean { if (v.type === 'integer' && !v.properties && !v.oneOf) return true; if (v.type === 'boolean' && !v.properties && !v.oneOf) return true; if (v.enum) return true; + // A branch that only narrows the parent `type: string` with a regex, + // e.g. `- pattern: "^storekit_-?[0-9]+$"`. TS cannot express the pattern, + // so the branch contributes an open `string`. + if (v.pattern && !v.type && !v.properties && !v.oneOf) return true; return false; }); } /** * Renders a union of primitive types and enums. - * E.g., oneOf: [{type: string}, {enum: [a, b, c]}] → 'a' | 'b' | 'c' | string + * E.g., oneOf: [{type: string}, {enum: [a, b, c]}] → 'a' | 'b' | 'c' | (string & {}) + * + * An open `string` next to enum literals is emitted as `(string & {})`: a bare + * `string` would swallow them, since TS collapses `'a' | string` to `string`, + * and the documented values would be lost from both the type and autocomplete. */ function renderPrimitiveUnion(variants: SchemaNode[]): string { const parts: string[] = []; @@ -230,10 +238,14 @@ function renderPrimitiveUnion(variants: SchemaNode[]): string { ); } } + const hasEnumLiterals = parts.length > 0; for (const v of variants) { - if (!v.enum) { - parts.push(resolvePrimitive(v.type)); - } + if (v.enum) continue; + // A `pattern`-only branch inherits `string` from the parent node. + const rendered = !v.type && v.pattern ? 'string' : resolvePrimitive(v.type); + parts.push( + hasEnumLiterals && rendered === 'string' ? '(string & {})' : rendered, + ); } return parts.join(' | '); } @@ -522,6 +534,14 @@ function resolveTopLevelType(node: SchemaNode, depth: number): string { return renderOneOf(node.oneOf, depth); } + // type: string + anyOf → open enum union, e.g. 'a' | 'b' | (string & {}) + if (node.type === 'string' && node.anyOf) { + if (isPrimitiveOneOf(node.anyOf)) { + return renderPrimitiveUnion(node.anyOf); + } + return renderAnyOf(node.anyOf, depth); + } + // type: object with oneOf and no properties → OneOf or discriminated union if (node.type === 'object' && node.oneOf && !node.properties) { if (node.required) { @@ -536,7 +556,7 @@ function resolveTopLevelType(node: SchemaNode, depth: number): string { } // Simple string aliases - if (node.type === 'string' && !node.enum && !node.oneOf) { + if (node.type === 'string' && !node.enum && !node.oneOf && !node.anyOf) { return 'string'; } diff --git a/src/coders/adapty-access-level.test.ts b/src/coders/adapty-access-level.test.ts index 1895e74..6539053 100644 --- a/src/coders/adapty-access-level.test.ts +++ b/src/coders/adapty-access-level.test.ts @@ -1,7 +1,9 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import type { AdaptyAccessLevel, CancellationReason, OfferType, + SubscriptionBillingPlan, VendorStore, } from '@/types'; import type { Def } from '@/types/schema'; @@ -15,6 +17,12 @@ const mocks: Def['AdaptyProfile.AccessLevel'][] = [ active_promotional_offer_id: 'iosOffer1', active_promotional_offer_type: 'promo1', billing_issue_detected_at: '2023-08-08T12:00:00.000Z', + billing_plan_id: 'monthly', + commitment: { + billing_period_number: 3, + total_billing_periods: 12, + expires_at: '2024-08-08T12:00:00.000Z', + }, cancellation_reason: 'user_cancelled', expires_at: '2023-10-08T12:00:00.000Z', id: 'accessLevel1', @@ -77,6 +85,17 @@ function toModel(mock: (typeof mocks)[number]): Model { activePromotionalOfferType: mock.active_promotional_offer_type as OfferType, }), + ...(mock.billing_plan_id && { + billingPlan: mock.billing_plan_id as SubscriptionBillingPlan, + }), + ...(mock.commitment && { + commitmentInfo: { + billingPeriodNumber: mock.commitment.billing_period_number, + totalBillingPeriods: mock.commitment.total_billing_periods, + expiresAt: new Date(mock.commitment.expires_at), + }, + }), + ...(mock.offer_id && { offerId: mock.offer_id }), android: { ...(mock.offer_id && { offerId: mock.offer_id, @@ -89,7 +108,7 @@ describe('AdaptyAccessLevelCoder', () => { let coder: AdaptyAccessLevelCoder; beforeEach(() => { - coder = new AdaptyAccessLevelCoder(); + coder = new AdaptyAccessLevelCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-access-level.ts b/src/coders/adapty-access-level.ts index 5291e13..b607bb4 100644 --- a/src/coders/adapty-access-level.ts +++ b/src/coders/adapty-access-level.ts @@ -3,6 +3,7 @@ import type { AdaptyAccessLevel } from '../types'; import type { Properties } from './types'; import { SimpleCoder } from './coder'; import { DateCoder } from './date'; +import { AdaptyProfileSubscriptionCommitmentInfoCoder } from './adapty-profile-subscription-commitment-info'; type Model = AdaptyAccessLevel; type Serializable = Def['AdaptyProfile.AccessLevel']; @@ -105,6 +106,25 @@ export class AdaptyAccessLevelCoder extends SimpleCoder { required: true, type: 'boolean', }, + billingPlan: { + key: 'billing_plan_id', + required: false, + type: 'string', + }, + commitmentInfo: { + key: 'commitment', + required: false, + type: 'object', + converter: new AdaptyProfileSubscriptionCommitmentInfoCoder( + this.platform, + ), + }, + offerId: { + key: 'offer_id', + required: false, + type: 'string', + }, + // Deprecated alias of the top-level offerId android: { offerId: { key: 'offer_id', diff --git a/src/coders/adapty-configuration.test.ts b/src/coders/adapty-configuration.test.ts index 2a5bc19..b1657c9 100644 --- a/src/coders/adapty-configuration.test.ts +++ b/src/coders/adapty-configuration.test.ts @@ -210,6 +210,24 @@ describe('AdaptyConfigurationCoder', () => { expect(resultWithTrue.clear_data_on_backup).toBe(true); }); + it.each(['ios', 'android'] as const)( + 'should encode storeMessagesHandling on %s only when set', + os => { + const platformCoder = createCoder(os); + expect( + platformCoder.encode(apiKey, {}).store_messages_handling, + ).toBeUndefined(); + expect( + platformCoder.encode(apiKey, { storeMessagesHandling: 'manual' }) + .store_messages_handling, + ).toBe('manual'); + expect( + platformCoder.encode(apiKey, { storeMessagesHandling: 'auto' }) + .store_messages_handling, + ).toBe('auto'); + }, + ); + it('should default adaptyAttributionEnabled to false', () => { expect(coder.encode(apiKey, {}).adapty_attribution_enabled).toBe(false); expect( diff --git a/src/coders/adapty-configuration.ts b/src/coders/adapty-configuration.ts index 10d2fcd..8df357e 100644 --- a/src/coders/adapty-configuration.ts +++ b/src/coders/adapty-configuration.ts @@ -32,6 +32,10 @@ export class AdaptyConfigurationCoder { config['adapty_attribution_enabled'] = params.adaptyAttributionEnabled ?? false; + if (params.storeMessagesHandling) { + config['store_messages_handling'] = params.storeMessagesHandling; + } + if (params.logLevel) { config['log_level'] = params.logLevel; } @@ -48,7 +52,7 @@ export class AdaptyConfigurationCoder { config['activate_ui'] = params.activateUi ?? true; - const mediaCacheCoder = new AdaptyUiMediaCacheCoder(); + const mediaCacheCoder = new AdaptyUiMediaCacheCoder(this.platform); config['media_cache'] = mediaCacheCoder.encode( params.mediaCache ?? { memoryStorageTotalCostLimit: 100 * 1024 * 1024, diff --git a/src/coders/adapty-discount-phase.test.ts b/src/coders/adapty-discount-phase.test.ts index 971514b..87578d8 100644 --- a/src/coders/adapty-discount-phase.test.ts +++ b/src/coders/adapty-discount-phase.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import type { AdaptyDiscountPhase, OfferType } from '@/types'; import type { Def } from '@/types/schema'; import { AdaptyDiscountPhaseCoder } from './adapty-discount-phase'; @@ -33,8 +34,10 @@ const mocks: Def['AdaptySubscriptionOffer.Phase'][] = [ ]; function toModel(mock: (typeof mocks)[number]): Model { - const _price = new AdaptyPriceCoder(); - const _subscription = new AdaptySubscriptionPeriodCoder(); + const _price = new AdaptyPriceCoder(new DefaultPlatformAdapter()); + const _subscription = new AdaptySubscriptionPeriodCoder( + new DefaultPlatformAdapter(), + ); return { numberOfPeriods: mock.number_of_periods, @@ -54,7 +57,7 @@ describe('AdaptyDiscountPhaseCoder', () => { let coder: AdaptyDiscountPhaseCoder; beforeEach(() => { - coder = new AdaptyDiscountPhaseCoder(); + coder = new AdaptyDiscountPhaseCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-discount-phase.ts b/src/coders/adapty-discount-phase.ts index 5d7b092..80b4013 100644 --- a/src/coders/adapty-discount-phase.ts +++ b/src/coders/adapty-discount-phase.ts @@ -30,13 +30,13 @@ export class AdaptyDiscountPhaseCoder extends SimpleCoder { key: 'price', required: true, type: 'object', - converter: new AdaptyPriceCoder(), + converter: new AdaptyPriceCoder(this.platform), }, subscriptionPeriod: { key: 'subscription_period', required: true, type: 'object', - converter: new AdaptySubscriptionPeriodCoder(), + converter: new AdaptySubscriptionPeriodCoder(this.platform), }, }; } diff --git a/src/coders/adapty-flow-paywall.test.ts b/src/coders/adapty-flow-paywall.test.ts index f952c2b..2f1b7f4 100644 --- a/src/coders/adapty-flow-paywall.test.ts +++ b/src/coders/adapty-flow-paywall.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import type { AdaptyFlowPaywall } from '@/types'; import type { Def } from '@/types/schema'; import { AdaptyFlowPaywallCoder } from './adapty-flow-paywall'; @@ -28,8 +29,13 @@ const mocks: Def['AdaptyFlowPaywall'][] = [ adapty_product_id: 'adaptyProduct1', access_level_id: 'premium', product_type: 'subscription', - promotional_offer_id: 'offer1', - win_back_offer_id: 'offer2', + pricing_terms: [ + { + billing_plan_id: 'up_front', + promotional_offer_id: 'offer1', + win_back_offer_id: 'offer2', + }, + ], base_plan_id: 'base1', offer_id: 'androidOffer1', }, @@ -59,7 +65,9 @@ const mocks: Def['AdaptyFlowPaywall'][] = [ ]; function toModel(mock: (typeof mocks)[number]): Model { - const _products = new ArrayCoder(() => new ProductReferenceCoder()); + const _products = new ArrayCoder( + () => new ProductReferenceCoder(new DefaultPlatformAdapter()), + ); // `products` is kept on the runtime object (matching the coder's decode // output) but is not part of the public `Model` type — hence the cast. @@ -91,7 +99,7 @@ describe('AdaptyFlowPaywallCoder', () => { let coder: AdaptyFlowPaywallCoder; beforeEach(() => { - coder = new AdaptyFlowPaywallCoder(); + coder = new AdaptyFlowPaywallCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-flow-paywall.ts b/src/coders/adapty-flow-paywall.ts index 4caf356..6508100 100644 --- a/src/coders/adapty-flow-paywall.ts +++ b/src/coders/adapty-flow-paywall.ts @@ -16,45 +16,43 @@ type CodableModel = Omit & { }; type Serializable = Def['AdaptyFlowPaywall']; -// Wire-level properties including the internal `products` field. -// The `as unknown as` cast is intentional: `products` is required on the wire -// but optional in CodableModel (so that Model extends CodableModel for -// override compatibility). The cast bridges the required/optional mismatch. -const PROPERTIES = { - placement: { - key: 'placement', - required: true, - type: 'object', - converter: new AdaptyPlacementCoder(), - }, - id: { key: 'paywall_id', required: true, type: 'string' }, - name: { key: 'paywall_name', required: true, type: 'string' }, - products: { - key: 'products', - required: true, - type: 'array', - converter: new ArrayCoder(() => new ProductReferenceCoder()), - }, - variationId: { key: 'variation_id', required: true, type: 'string' }, - webPurchaseUrl: { - key: 'web_purchase_url', - required: false, - type: 'string', - }, -} as unknown as Properties; - export class AdaptyFlowPaywallCoder extends Coder< Model, CodableModel, Serializable > { - protected properties: Properties = PROPERTIES; + // Wire-level properties including the internal `products` field. + // The `as unknown as` cast is intentional: `products` is required on the wire + // but optional in CodableModel (so that Model extends CodableModel for + // override compatibility). The cast bridges the required/optional mismatch. + protected properties: Properties = { + placement: { + key: 'placement', + required: true, + type: 'object', + converter: new AdaptyPlacementCoder(this.platform), + }, + id: { key: 'paywall_id', required: true, type: 'string' }, + name: { key: 'paywall_name', required: true, type: 'string' }, + products: { + key: 'products', + required: true, + type: 'array', + converter: new ArrayCoder(() => new ProductReferenceCoder(this.platform)), + }, + variationId: { key: 'variation_id', required: true, type: 'string' }, + webPurchaseUrl: { + key: 'web_purchase_url', + required: false, + type: 'string', + }, + } as unknown as Properties; override decode(data: Serializable): Model { const codablePart = super.decode(data); // Keep `products` on the runtime object (for encode round-trip) while // exposing only `productIdentifiers` on the public type. - // products is always present on the wire (required: true in PROPERTIES). + // products is always present on the wire (required: true in properties). return { ...codablePart, productIdentifiers: codablePart.products!.map(product => ({ diff --git a/src/coders/adapty-flow.test.ts b/src/coders/adapty-flow.test.ts index 430a193..25b7091 100644 --- a/src/coders/adapty-flow.test.ts +++ b/src/coders/adapty-flow.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import type { AdaptyFlow } from '@/types'; import type { Def } from '@/types/schema'; import { AdaptyFlowCoder } from './adapty-flow'; @@ -91,8 +92,12 @@ const mocks: Def['AdaptyFlow'][] = [ ]; function toModel(mock: (typeof mocks)[number]): Model { - const _remoteConfigs = new ArrayCoder(() => new AdaptyRemoteConfigCoder()); - const _paywalls = new ArrayCoder(() => new AdaptyFlowPaywallCoder()); + const _remoteConfigs = new ArrayCoder( + () => new AdaptyRemoteConfigCoder(new DefaultPlatformAdapter()), + ); + const _paywalls = new ArrayCoder( + () => new AdaptyFlowPaywallCoder(new DefaultPlatformAdapter()), + ); const decodedPlacement = { abTestName: mock.placement.ab_test_name, @@ -131,7 +136,7 @@ describe('AdaptyFlowCoder', () => { let coder: AdaptyFlowCoder; beforeEach(() => { - coder = new AdaptyFlowCoder(); + coder = new AdaptyFlowCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-flow.ts b/src/coders/adapty-flow.ts index 2968e3c..3c35623 100644 --- a/src/coders/adapty-flow.ts +++ b/src/coders/adapty-flow.ts @@ -20,7 +20,7 @@ export class AdaptyFlowCoder extends Coder { key: 'placement', required: true, type: 'object', - converter: new AdaptyPlacementCoder(), + converter: new AdaptyPlacementCoder(this.platform), }, id: { key: 'flow_id', required: true, type: 'string' }, name: { key: 'flow_name', required: true, type: 'string' }, @@ -30,7 +30,9 @@ export class AdaptyFlowCoder extends Coder { key: 'remote_configs', required: false, type: 'array', - converter: new ArrayCoder(() => new AdaptyRemoteConfigCoder()), + converter: new ArrayCoder( + () => new AdaptyRemoteConfigCoder(this.platform), + ), }, flowVersionId: { key: 'flow_version_id', @@ -41,7 +43,9 @@ export class AdaptyFlowCoder extends Coder { key: 'variations', required: true, type: 'array', - converter: new ArrayCoder(() => new AdaptyFlowPaywallCoder()), + converter: new ArrayCoder( + () => new AdaptyFlowPaywallCoder(this.platform), + ), }, uiSchema: { key: 'ui_schema', diff --git a/src/coders/adapty-native-error.test.ts b/src/coders/adapty-native-error.test.ts index 8c25da2..269fd90 100644 --- a/src/coders/adapty-native-error.test.ts +++ b/src/coders/adapty-native-error.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import { AdaptyNativeErrorCoder } from './adapty-native-error'; import { AdaptyError } from '@/adapty-error'; import type { AdaptyNativeError } from '@/types/bridge'; @@ -30,7 +31,7 @@ describe('AdaptyNativeErrorCoder', () => { let coder: AdaptyNativeErrorCoder; beforeEach(() => { - coder = new AdaptyNativeErrorCoder(); + coder = new AdaptyNativeErrorCoder(new DefaultPlatformAdapter()); }); // Important for analytics systems, etc. diff --git a/src/coders/adapty-non-subscription.test.ts b/src/coders/adapty-non-subscription.test.ts index c23e82c..55ce658 100644 --- a/src/coders/adapty-non-subscription.test.ts +++ b/src/coders/adapty-non-subscription.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import type { Def } from '@/types/schema'; import type { AdaptyNonSubscription, VendorStore } from '@/types'; import { AdaptyNonSubscriptionCoder } from './adapty-non-subscription'; @@ -44,7 +45,7 @@ describe('AdaptyNonSubscriptionCoder', () => { let coder: AdaptyNonSubscriptionCoder; beforeEach(() => { - coder = new AdaptyNonSubscriptionCoder(); + coder = new AdaptyNonSubscriptionCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-onboarding-builder.test.ts b/src/coders/adapty-onboarding-builder.test.ts index fcd129f..4902e57 100644 --- a/src/coders/adapty-onboarding-builder.test.ts +++ b/src/coders/adapty-onboarding-builder.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import { AdaptyOnboardingBuilderCoder } from './adapty-onboarding-builder'; import type { AdaptyOnboardingBuilder } from '@/types'; import type { Def } from '@/types/schema'; @@ -24,7 +25,7 @@ describe('AdaptyOnboardingBuilderCoder', () => { let coder: AdaptyOnboardingBuilderCoder; beforeEach(() => { - coder = new AdaptyOnboardingBuilderCoder(); + coder = new AdaptyOnboardingBuilderCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-onboarding.test.ts b/src/coders/adapty-onboarding.test.ts index e3bcf9b..8bd1cd7 100644 --- a/src/coders/adapty-onboarding.test.ts +++ b/src/coders/adapty-onboarding.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import { AdaptyOnboardingCoder } from './adapty-onboarding'; import type { AdaptyOnboarding } from '@/types'; import type { Def } from '@/types/schema'; @@ -84,7 +85,7 @@ describe('AdaptyOnboardingCoder', () => { let coder: AdaptyOnboardingCoder; beforeEach(() => { - coder = new AdaptyOnboardingCoder(); + coder = new AdaptyOnboardingCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-onboarding.ts b/src/coders/adapty-onboarding.ts index 6bace95..79707fd 100644 --- a/src/coders/adapty-onboarding.ts +++ b/src/coders/adapty-onboarding.ts @@ -20,7 +20,7 @@ export class AdaptyOnboardingCoder extends Coder< key: 'placement', required: true, type: 'object', - converter: new AdaptyPlacementCoder(), + converter: new AdaptyPlacementCoder(this.platform), }, id: { key: 'onboarding_id', required: true, type: 'string' }, name: { key: 'onboarding_name', required: true, type: 'string' }, @@ -28,7 +28,7 @@ export class AdaptyOnboardingCoder extends Coder< key: 'remote_config', required: false, type: 'object', - converter: new AdaptyRemoteConfigCoder(), + converter: new AdaptyRemoteConfigCoder(this.platform), }, variationId: { key: 'variation_id', required: true, type: 'string' }, version: { key: 'response_created_at', required: false, type: 'number' }, @@ -36,7 +36,7 @@ export class AdaptyOnboardingCoder extends Coder< key: 'onboarding_builder', required: true, type: 'object', - converter: new AdaptyOnboardingBuilderCoder(), + converter: new AdaptyOnboardingBuilderCoder(this.platform), }, payloadData: { key: 'payload_data', required: false, type: 'string' }, requestLocale: { key: 'request_locale', required: true, type: 'string' }, diff --git a/src/coders/adapty-paywall-product.test.ts b/src/coders/adapty-paywall-product.test.ts index 5b4a900..f81f6a1 100644 --- a/src/coders/adapty-paywall-product.test.ts +++ b/src/coders/adapty-paywall-product.test.ts @@ -1,5 +1,7 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import type { AdaptyPaywallProduct } from '@/types'; import type { Def } from '@/types/schema'; +import type { IPlatformAdapter } from '@/adapters/interfaces'; import { AdaptyPriceCoder } from './adapty-price'; import { AdaptyPaywallProductCoder } from './adapty-paywall-product'; import { AdaptySubscriptionDetailsCoder } from './adapty-subscription-details'; @@ -89,6 +91,15 @@ const mocks: Def['AdaptyPaywallProduct.Response'][] = [ number_of_units: 1, }, localized_period: '1 year', + pricing_terms: { + billing_plan_id: 'monthly', + billing_price: { amount: 6.99, localized_string: '$6.99' }, + billing_period: { unit: 'month', number_of_units: 1 }, + commitment_info: { + price: { amount: 83.88, localized_string: '$83.88' }, + period: { unit: 'year', number_of_units: 1 }, + }, + }, offer: { offer_identifier: { type: 'promotional', @@ -118,8 +129,10 @@ const mocks: Def['AdaptyPaywallProduct.Response'][] = [ ]; function toModel(mock: (typeof mocks)[number]): Model { - const _price = new AdaptyPriceCoder(); - const _details = new AdaptySubscriptionDetailsCoder(); + const _price = new AdaptyPriceCoder(new DefaultPlatformAdapter()); + const _details = new AdaptySubscriptionDetailsCoder( + new DefaultPlatformAdapter(), + ); return { ios: { @@ -151,7 +164,7 @@ describe('AdaptyPaywallProductCoder', () => { let coder: AdaptyPaywallProductCoder; beforeEach(() => { - coder = new AdaptyPaywallProductCoder(); + coder = new AdaptyPaywallProductCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { @@ -166,4 +179,50 @@ describe('AdaptyPaywallProductCoder', () => { expect(encoded).toStrictEqual(mock); }); + + describe('getInput', () => { + it('should map the billing plan and the offer identifier', () => { + expect(coder.getInput(mocks[1]!).subscription).toStrictEqual({ + pricing_terms: { billing_plan_id: 'monthly' }, + offer: { + offer_identifier: { type: 'promotional', id: 'test_promo_offer' }, + }, + }); + }); + + it('should omit pricing terms when the product has none', () => { + expect(coder.getInput(mocks[0]!).subscription).toStrictEqual({ + offer: { + offer_identifier: { type: 'introductory', id: 'test_intro_offer' }, + }, + }); + }); + }); + + describe('getInput after a model round-trip', () => { + const ios = new AdaptyPaywallProductCoder({ + OS: 'ios', + } as IPlatformAdapter); + + it('should send the billing plan when there is no offer', () => { + const { offer: _offer, ...subscription } = mocks[1]!.subscription!; + const model = ios.decode({ ...mocks[1]!, subscription }); + + expect(ios.getInput(ios.encode(model)).subscription).toStrictEqual({ + pricing_terms: { billing_plan_id: 'monthly' }, + }); + }); + + it('should omit the subscription for Android products without an offer', () => { + const android = new AdaptyPaywallProductCoder({ + OS: 'android', + } as IPlatformAdapter); + const { offer: _offer, ...subscription } = mocks[0]!.subscription!; + const model = android.decode({ ...mocks[0]!, subscription }); + + expect(android.getInput(android.encode(model)).subscription).toBe( + undefined, + ); + }); + }); }); diff --git a/src/coders/adapty-paywall-product.ts b/src/coders/adapty-paywall-product.ts index c00bc0e..5f03b18 100644 --- a/src/coders/adapty-paywall-product.ts +++ b/src/coders/adapty-paywall-product.ts @@ -3,7 +3,10 @@ import type { Def } from '@/types/schema'; import type { Properties } from './types'; import { SimpleCoder } from './coder'; import { AdaptyPriceCoder } from './adapty-price'; -import { AdaptySubscriptionDetailsCoder } from './adapty-subscription-details'; +import { + AdaptySubscriptionDetailsCoder, + getSubscriptionInput, +} from './adapty-subscription-details'; type Model = AdaptyPaywallProduct; type Serializable = Def['AdaptyPaywallProduct.Response']; @@ -52,7 +55,7 @@ export class AdaptyPaywallProductCoder extends SimpleCoder< key: 'price', required: false, // Native SDKs require this type: 'object', - converter: new AdaptyPriceCoder(), + converter: new AdaptyPriceCoder(this.platform), }, webPurchaseUrl: { key: 'web_purchase_url', @@ -64,7 +67,7 @@ export class AdaptyPaywallProductCoder extends SimpleCoder< key: 'subscription', required: false, type: 'object', - converter: new AdaptySubscriptionDetailsCoder(), + converter: new AdaptySubscriptionDetailsCoder(this.platform), }, ios: { isFamilyShareable: { @@ -85,13 +88,7 @@ export class AdaptyPaywallProductCoder extends SimpleCoder< payload_data: data.payload_data, paywall_name: data.paywall_name, paywall_variation_id: data.paywall_variation_id, - subscription: data.subscription?.offer - ? { - offer: { - offer_identifier: data.subscription.offer.offer_identifier, - }, - } - : undefined, + subscription: getSubscriptionInput(data.subscription), vendor_product_id: data.vendor_product_id, }; } diff --git a/src/coders/adapty-placement.test.ts b/src/coders/adapty-placement.test.ts index c52008b..651b593 100644 --- a/src/coders/adapty-placement.test.ts +++ b/src/coders/adapty-placement.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import { AdaptyPlacementCoder } from './adapty-placement'; import type { AdaptyPlacement } from '@/types'; import type { Def } from '@/types/schema'; @@ -38,7 +39,7 @@ describe('AdaptyPlacementCoder', () => { let coder: AdaptyPlacementCoder; beforeEach(() => { - coder = new AdaptyPlacementCoder(); + coder = new AdaptyPlacementCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-price.test.ts b/src/coders/adapty-price.test.ts index a899bdb..763568b 100644 --- a/src/coders/adapty-price.test.ts +++ b/src/coders/adapty-price.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import { AdaptyPriceCoder } from './adapty-price'; import type { AdaptyPrice } from '@/types'; import type { Def } from '@/types/schema'; @@ -26,7 +27,7 @@ describe('AdaptyPriceCoder', () => { let coder: AdaptyPriceCoder; beforeEach(() => { - coder = new AdaptyPriceCoder(); + coder = new AdaptyPriceCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-profile-parameters.test.ts b/src/coders/adapty-profile-parameters.test.ts index c6d49fb..609e192 100644 --- a/src/coders/adapty-profile-parameters.test.ts +++ b/src/coders/adapty-profile-parameters.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import { Def } from '@/types/schema'; import { AdaptyProfileParametersCoder } from './adapty-profile-parameters'; @@ -16,7 +17,7 @@ const mocks: Def['AdaptyProfileParameters'][] = [ ]; describe('AdaptyProfileParametersCoder', () => { - const coder = new AdaptyProfileParametersCoder(); + const coder = new AdaptyProfileParametersCoder(new DefaultPlatformAdapter()); it.each(mocks)('should encode/decode', mock => { const decoded = coder.decode(mock); diff --git a/src/coders/adapty-profile-subscription-commitment-info.test.ts b/src/coders/adapty-profile-subscription-commitment-info.test.ts new file mode 100644 index 0000000..b6386d0 --- /dev/null +++ b/src/coders/adapty-profile-subscription-commitment-info.test.ts @@ -0,0 +1,44 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; +import type { AdaptyProfileSubscriptionCommitmentInfo } from '@/types'; +import type { Def } from '@/types/schema'; +import { AdaptyProfileSubscriptionCommitmentInfoCoder } from './adapty-profile-subscription-commitment-info'; + +type Model = AdaptyProfileSubscriptionCommitmentInfo; +const mocks: Def['AdaptyProfile.SubscriptionCommitmentInfo'][] = [ + { + billing_period_number: 3, + total_billing_periods: 12, + expires_at: '2024-08-08T12:00:00.000Z', + }, + { + billing_period_number: 0, + total_billing_periods: 12, + expires_at: '2025-01-01T00:00:00.000Z', + }, +]; + +function toModel(mock: (typeof mocks)[number]): Model { + return { + billingPeriodNumber: mock.billing_period_number, + totalBillingPeriods: mock.total_billing_periods, + expiresAt: new Date(mock.expires_at), + }; +} + +describe('AdaptyProfileSubscriptionCommitmentInfoCoder', () => { + let coder: AdaptyProfileSubscriptionCommitmentInfoCoder; + + beforeEach(() => { + coder = new AdaptyProfileSubscriptionCommitmentInfoCoder( + new DefaultPlatformAdapter(), + ); + }); + + it.each(mocks)('should decode to expected result', mock => { + expect(coder.decode(mock)).toStrictEqual(toModel(mock)); + }); + + it.each(mocks)('should decode/encode', mock => { + expect(coder.encode(coder.decode(mock))).toStrictEqual(mock); + }); +}); diff --git a/src/coders/adapty-profile-subscription-commitment-info.ts b/src/coders/adapty-profile-subscription-commitment-info.ts new file mode 100644 index 0000000..e302235 --- /dev/null +++ b/src/coders/adapty-profile-subscription-commitment-info.ts @@ -0,0 +1,32 @@ +import type { AdaptyProfileSubscriptionCommitmentInfo } from '@/types'; +import type { Def } from '@/types/schema'; +import type { Properties } from './types'; +import { SimpleCoder } from './coder'; +import { DateCoder } from './date'; + +type Model = AdaptyProfileSubscriptionCommitmentInfo; +type Serializable = Def['AdaptyProfile.SubscriptionCommitmentInfo']; + +export class AdaptyProfileSubscriptionCommitmentInfoCoder extends SimpleCoder< + Model, + Serializable +> { + protected properties: Properties = { + billingPeriodNumber: { + key: 'billing_period_number', + required: true, + type: 'number', + }, + totalBillingPeriods: { + key: 'total_billing_periods', + required: true, + type: 'number', + }, + expiresAt: { + key: 'expires_at', + required: true, + type: 'string', + converter: new DateCoder(), + }, + }; +} diff --git a/src/coders/adapty-profile.test.ts b/src/coders/adapty-profile.test.ts index c998797..fccce59 100644 --- a/src/coders/adapty-profile.test.ts +++ b/src/coders/adapty-profile.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import type { Def } from '@/types/schema'; import type { AdaptyProfile } from '@/types'; import { AdaptyProfileCoder } from './adapty-profile'; @@ -185,10 +186,16 @@ const mocks: Omit< ]; function toModel(mock: (typeof mocks)[number]): Model { - const _levels = new HashmapCoder(new AdaptyAccessLevelCoder()); - const _subs = new HashmapCoder(new AdaptySubscriptionCoder()); + const _levels = new HashmapCoder( + new AdaptyAccessLevelCoder(new DefaultPlatformAdapter()), + ); + const _subs = new HashmapCoder( + new AdaptySubscriptionCoder(new DefaultPlatformAdapter()), + ); const _nonsubs = new HashmapCoder( - new ArrayCoder(() => new AdaptyNonSubscriptionCoder()), + new ArrayCoder( + () => new AdaptyNonSubscriptionCoder(new DefaultPlatformAdapter()), + ), ); return { @@ -214,7 +221,7 @@ describe('AdaptyProfileCoder', () => { let coder: AdaptyProfileCoder; beforeEach(() => { - coder = new AdaptyProfileCoder(); + coder = new AdaptyProfileCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-profile.ts b/src/coders/adapty-profile.ts index 8744a9f..c2b6f81 100644 --- a/src/coders/adapty-profile.ts +++ b/src/coders/adapty-profile.ts @@ -17,7 +17,7 @@ export class AdaptyProfileCoder extends SimpleCoder { key: 'paid_access_levels', required: false, type: 'object', - converter: new HashmapCoder(new AdaptyAccessLevelCoder()), + converter: new HashmapCoder(new AdaptyAccessLevelCoder(this.platform)), }, appliedExternalAttributionProviders: { key: 'applied_attribution_sources', @@ -39,7 +39,7 @@ export class AdaptyProfileCoder extends SimpleCoder { required: false, type: 'object', converter: new HashmapCoder( - new ArrayCoder(() => new AdaptyNonSubscriptionCoder()), + new ArrayCoder(() => new AdaptyNonSubscriptionCoder(this.platform)), ), }, profileId: { @@ -51,7 +51,7 @@ export class AdaptyProfileCoder extends SimpleCoder { key: 'subscriptions', required: false, type: 'object', - converter: new HashmapCoder(new AdaptySubscriptionCoder()), + converter: new HashmapCoder(new AdaptySubscriptionCoder(this.platform)), }, }; } diff --git a/src/coders/adapty-promoted-product.test.ts b/src/coders/adapty-promoted-product.test.ts index ff46116..3f9ef57 100644 --- a/src/coders/adapty-promoted-product.test.ts +++ b/src/coders/adapty-promoted-product.test.ts @@ -1,5 +1,7 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import type { AdaptyPromotedProduct } from '@/types'; import type { Def } from '@/types/schema'; +import type { IPlatformAdapter } from '@/adapters/interfaces'; import { AdaptyPriceCoder } from './adapty-price'; import { AdaptyPromotedProductCoder } from './adapty-promoted-product'; import { AdaptySubscriptionDetailsCoder } from './adapty-subscription-details'; @@ -7,6 +9,7 @@ import { AdaptySubscriptionDetailsCoder } from './adapty-subscription-details'; type Model = AdaptyPromotedProduct; const mocks: Def['AdaptyPromotedProduct.Response'][] = [ { + purchase_intent_id: 'intent-1', is_family_shareable: false, localized_description: 'Get premium features with this plan', localized_title: 'Yearly Premium Plan', @@ -55,6 +58,7 @@ const mocks: Def['AdaptyPromotedProduct.Response'][] = [ }, }, { + purchase_intent_id: 'intent-2', is_family_shareable: true, localized_description: 'Get premium features with this plan', localized_title: 'Yearly Premium Plan', @@ -73,6 +77,31 @@ const mocks: Def['AdaptyPromotedProduct.Response'][] = [ number_of_units: 1, }, localized_period: '1 year', + pricing_terms: { + billing_plan_id: 'monthly', + billing_price: { + amount: 6.99, + currency_code: 'USD', + currency_symbol: '$', + localized_string: '$6.99', + }, + billing_period: { + unit: 'month', + number_of_units: 1, + }, + commitment_info: { + price: { + amount: 83.88, + currency_code: 'USD', + currency_symbol: '$', + localized_string: '$83.88', + }, + period: { + unit: 'year', + number_of_units: 1, + }, + }, + }, offer: { offer_identifier: { type: 'promotional', @@ -101,6 +130,7 @@ const mocks: Def['AdaptyPromotedProduct.Response'][] = [ }, { // Non-subscription product: no subscription, no optional fields + purchase_intent_id: 'intent-3', is_family_shareable: false, localized_description: 'Unlock all the things, once', localized_title: 'Lifetime Access', @@ -115,12 +145,15 @@ const mocks: Def['AdaptyPromotedProduct.Response'][] = [ ]; function toModel(mock: (typeof mocks)[number]): Model { - const _price = new AdaptyPriceCoder(); - const _details = new AdaptySubscriptionDetailsCoder(); + const _price = new AdaptyPriceCoder(new DefaultPlatformAdapter()); + const _details = new AdaptySubscriptionDetailsCoder( + new DefaultPlatformAdapter(), + ); return { ios: { isFamilyShareable: mock.is_family_shareable as boolean, + purchaseIntentId: mock.purchase_intent_id as string, }, localizedDescription: mock.localized_description, localizedTitle: mock.localized_title, @@ -140,7 +173,7 @@ describe('AdaptyPromotedProductCoder', () => { let coder: AdaptyPromotedProductCoder; beforeEach(() => { - coder = new AdaptyPromotedProductCoder(); + coder = new AdaptyPromotedProductCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { @@ -159,6 +192,7 @@ describe('AdaptyPromotedProductCoder', () => { describe('getInput', () => { it('should map the nested subscription offer identifier', () => { expect(coder.getInput(mocks[0]!)).toStrictEqual({ + purchase_intent_id: 'intent-1', vendor_product_id: 'yearly.premium.6999', payload_data: 'examplePayloadData', subscription: { @@ -169,12 +203,77 @@ describe('AdaptyPromotedProductCoder', () => { }); }); + it('should map the billing plan alongside the offer identifier', () => { + expect(coder.getInput(mocks[1]!)).toStrictEqual({ + purchase_intent_id: 'intent-2', + vendor_product_id: 'yearly.premium.6999', + payload_data: undefined, + subscription: { + pricing_terms: { billing_plan_id: 'monthly' }, + offer: { + offer_identifier: { type: 'promotional', id: 'test_promo_offer' }, + }, + }, + }); + }); + it('should omit the subscription when the product has no offer', () => { expect(coder.getInput(mocks[2]!)).toStrictEqual({ + purchase_intent_id: 'intent-3', vendor_product_id: 'lifetime.access.9999', payload_data: undefined, subscription: undefined, }); }); }); + + describe('platform', () => { + const ios = new AdaptyPromotedProductCoder({ + OS: 'ios', + } as IPlatformAdapter); + const android = new AdaptyPromotedProductCoder({ + OS: 'android', + } as IPlatformAdapter); + const { purchase_intent_id: _, ...withoutIntent } = mocks[1]!; + // Android products always carry base_plan_id, so the Android case uses the Android-shaped mock + const { purchase_intent_id: _androidIntent, ...androidWithoutIntent } = + mocks[0]!; + + it('should require purchase_intent_id on iOS', () => { + expect(() => ios.decode(withoutIntent)).toThrow(/purchaseIntentId/); + }); + + it('should not require purchase_intent_id on Android', () => { + expect(android.decode(mocks[0]!).ios).toStrictEqual({ + isFamilyShareable: false, + purchaseIntentId: 'intent-1', + }); + expect(() => android.decode(androidWithoutIntent)).not.toThrow(); + }); + + it('should send purchase intent and billing plan after a model round-trip', () => { + const model = ios.decode(mocks[1]!); + + expect(ios.getInput(ios.encode(model))).toStrictEqual({ + purchase_intent_id: 'intent-2', + vendor_product_id: 'yearly.premium.6999', + payload_data: undefined, + subscription: { + pricing_terms: { billing_plan_id: 'monthly' }, + offer: { + offer_identifier: { type: 'promotional', id: 'test_promo_offer' }, + }, + }, + }); + }); + + it('should send the billing plan when there is no offer', () => { + const { offer: _offer, ...subscription } = mocks[1]!.subscription!; + const model = ios.decode({ ...mocks[1]!, subscription }); + + expect(ios.getInput(ios.encode(model)).subscription).toStrictEqual({ + pricing_terms: { billing_plan_id: 'monthly' }, + }); + }); + }); }); diff --git a/src/coders/adapty-promoted-product.ts b/src/coders/adapty-promoted-product.ts index 63ec0ba..91bc494 100644 --- a/src/coders/adapty-promoted-product.ts +++ b/src/coders/adapty-promoted-product.ts @@ -3,7 +3,10 @@ import type { Def } from '@/types/schema'; import type { Properties } from './types'; import { SimpleCoder } from './coder'; import { AdaptyPriceCoder } from './adapty-price'; -import { AdaptySubscriptionDetailsCoder } from './adapty-subscription-details'; +import { + AdaptySubscriptionDetailsCoder, + getSubscriptionInput, +} from './adapty-subscription-details'; type Model = AdaptyPromotedProduct; type Serializable = Def['AdaptyPromotedProduct.Response']; @@ -29,14 +32,14 @@ export class AdaptyPromotedProductCoder extends SimpleCoder< key: 'price', required: false, // Native SDKs require this type: 'object', - converter: new AdaptyPriceCoder(), + converter: new AdaptyPriceCoder(this.platform), }, payloadData: { key: 'payload_data', required: false, type: 'string' }, subscription: { key: 'subscription', required: false, type: 'object', - converter: new AdaptySubscriptionDetailsCoder(), + converter: new AdaptySubscriptionDetailsCoder(this.platform), }, ios: { isFamilyShareable: { @@ -44,20 +47,20 @@ export class AdaptyPromotedProductCoder extends SimpleCoder< required: true, type: 'boolean', }, + purchaseIntentId: { + key: 'purchase_intent_id', + required: true, + type: 'string', + }, }, }; public getInput(data: Serializable): Def['AdaptyPromotedProduct.Request'] { return { + purchase_intent_id: data.purchase_intent_id, vendor_product_id: data.vendor_product_id, payload_data: data.payload_data, - subscription: data.subscription?.offer - ? { - offer: { - offer_identifier: data.subscription.offer.offer_identifier, - }, - } - : undefined, + subscription: getSubscriptionInput(data.subscription), }; } } diff --git a/src/coders/adapty-remote-config.test.ts b/src/coders/adapty-remote-config.test.ts index cc25802..c8794a4 100644 --- a/src/coders/adapty-remote-config.test.ts +++ b/src/coders/adapty-remote-config.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import { AdaptyRemoteConfigCoder } from './adapty-remote-config'; import type { AdaptyRemoteConfig } from '@/types'; import type { Def } from '@/types/schema'; @@ -26,7 +27,7 @@ describe('AdaptyRemoteConfigCoder', () => { let coder: AdaptyRemoteConfigCoder; beforeEach(() => { - coder = new AdaptyRemoteConfigCoder(); + coder = new AdaptyRemoteConfigCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-report-transaction-params.test.ts b/src/coders/adapty-report-transaction-params.test.ts new file mode 100644 index 0000000..0e2a287 --- /dev/null +++ b/src/coders/adapty-report-transaction-params.test.ts @@ -0,0 +1,54 @@ +import type { IPlatformAdapter, PlatformOS } from '@/adapters/interfaces'; +import { AdaptyReportTransactionParamsCoder } from '@/coders/adapty-report-transaction-params'; + +describe('AdaptyReportTransactionParamsCoder', () => { + const createCoder = (OS: PlatformOS = 'ios') => + new AdaptyReportTransactionParamsCoder({ OS } as IPlatformAdapter); + + const fullParams = { + transactionId: 'transaction_12345', + variationId: 'variation_abc', + ios: { jwsTransaction: 'jws_transaction_abc' }, + }; + + it('should encode only transaction_id when nothing else is set', () => { + const result = createCoder().encode({ transactionId: 'transaction_12345' }); + expect(result).toEqual({ transaction_id: 'transaction_12345' }); + }); + + it('should omit empty variation_id', () => { + const result = createCoder().encode({ + transactionId: 'transaction_12345', + variationId: '', + }); + expect(result).toEqual({ transaction_id: 'transaction_12345' }); + }); + + it('should encode all fields on iOS', () => { + const result = createCoder('ios').encode(fullParams); + expect(result).toEqual({ + transaction_id: 'transaction_12345', + variation_id: 'variation_abc', + apple_jws_transaction: 'jws_transaction_abc', + }); + }); + + it.each(['android', 'unknown'] as const)( + 'should omit apple_jws_transaction on %s', + OS => { + const result = createCoder(OS).encode(fullParams); + expect(result).toEqual({ + transaction_id: 'transaction_12345', + variation_id: 'variation_abc', + }); + }, + ); + + it('should omit empty jwsTransaction on iOS', () => { + const result = createCoder('ios').encode({ + transactionId: 'transaction_12345', + ios: { jwsTransaction: '' }, + }); + expect(result).toEqual({ transaction_id: 'transaction_12345' }); + }); +}); diff --git a/src/coders/adapty-report-transaction-params.ts b/src/coders/adapty-report-transaction-params.ts new file mode 100644 index 0000000..43cc092 --- /dev/null +++ b/src/coders/adapty-report-transaction-params.ts @@ -0,0 +1,26 @@ +import type { IPlatformAdapter } from '@/adapters/interfaces'; +import type { Req } from '@/types/schema'; +import * as Input from '@/types/inputs'; + +type Model = Input.ReportTransactionParamsInput; +type Serializable = Omit; + +export class AdaptyReportTransactionParamsCoder { + constructor(private readonly platform: IPlatformAdapter) {} + + encode(params: Model): Serializable { + const result: Serializable = { + transaction_id: params.transactionId, + }; + + if (params.variationId) { + result.variation_id = params.variationId; + } + + if (this.platform.OS === 'ios' && params.ios?.jwsTransaction) { + result.apple_jws_transaction = params.ios.jwsTransaction; + } + + return result; + } +} diff --git a/src/coders/adapty-subscription-commitment-info.test.ts b/src/coders/adapty-subscription-commitment-info.test.ts new file mode 100644 index 0000000..5b6ff5b --- /dev/null +++ b/src/coders/adapty-subscription-commitment-info.test.ts @@ -0,0 +1,50 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; +import type { AdaptySubscriptionCommitmentInfo, ProductPeriod } from '@/types'; +import type { Def } from '@/types/schema'; +import { AdaptySubscriptionCommitmentInfoCoder } from './adapty-subscription-commitment-info'; + +type Model = AdaptySubscriptionCommitmentInfo; +const mocks: Def['AdaptySubscriptionCommitmentInfo'][] = [ + { + price: { + amount: 83.88, + currency_code: 'USD', + currency_symbol: '$', + localized_string: '$83.88', + }, + period: { unit: 'year', number_of_units: 1 }, + }, +]; + +function toModel(mock: (typeof mocks)[number]): Model { + return { + price: { + amount: mock.price.amount, + currencyCode: mock.price.currency_code, + currencySymbol: mock.price.currency_symbol, + localizedString: mock.price.localized_string, + }, + period: { + unit: mock.period.unit as ProductPeriod, + numberOfUnits: mock.period.number_of_units, + }, + }; +} + +describe('AdaptySubscriptionCommitmentInfoCoder', () => { + let coder: AdaptySubscriptionCommitmentInfoCoder; + + beforeEach(() => { + coder = new AdaptySubscriptionCommitmentInfoCoder( + new DefaultPlatformAdapter(), + ); + }); + + it.each(mocks)('should decode to expected result', mock => { + expect(coder.decode(mock)).toStrictEqual(toModel(mock)); + }); + + it.each(mocks)('should decode/encode', mock => { + expect(coder.encode(coder.decode(mock))).toStrictEqual(mock); + }); +}); diff --git a/src/coders/adapty-subscription-commitment-info.ts b/src/coders/adapty-subscription-commitment-info.ts new file mode 100644 index 0000000..53d9e70 --- /dev/null +++ b/src/coders/adapty-subscription-commitment-info.ts @@ -0,0 +1,29 @@ +import type { AdaptySubscriptionCommitmentInfo } from '@/types'; +import type { Def } from '@/types/schema'; +import type { Properties } from './types'; +import { SimpleCoder } from './coder'; +import { AdaptyPriceCoder } from './adapty-price'; +import { AdaptySubscriptionPeriodCoder } from './adapty-subscription-period'; + +type Model = AdaptySubscriptionCommitmentInfo; +type Serializable = Def['AdaptySubscriptionCommitmentInfo']; + +export class AdaptySubscriptionCommitmentInfoCoder extends SimpleCoder< + Model, + Serializable +> { + protected properties: Properties = { + price: { + key: 'price', + required: true, + type: 'object', + converter: new AdaptyPriceCoder(this.platform), + }, + period: { + key: 'period', + required: true, + type: 'object', + converter: new AdaptySubscriptionPeriodCoder(this.platform), + }, + }; +} diff --git a/src/coders/adapty-subscription-details.test.ts b/src/coders/adapty-subscription-details.test.ts index da5882b..1058dfc 100644 --- a/src/coders/adapty-subscription-details.test.ts +++ b/src/coders/adapty-subscription-details.test.ts @@ -1,8 +1,11 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import type { AdaptySubscriptionDetails } from '@/types'; import type { Def } from '@/types/schema'; +import type { IPlatformAdapter } from '@/adapters/interfaces'; import { AdaptySubscriptionDetailsCoder } from './adapty-subscription-details'; import { AdaptySubscriptionPeriodCoder } from './adapty-subscription-period'; import { AdaptySubscriptionOfferCoder } from '@/coders/adapty-subscription-offer'; +import { AdaptySubscriptionPricingTermsCoder } from './adapty-subscription-pricing-terms'; type Model = AdaptySubscriptionDetails; const mocks: Def['AdaptyProduct.Subscription'][] = [ @@ -47,6 +50,31 @@ const mocks: Def['AdaptyProduct.Subscription'][] = [ number_of_units: 1, }, localized_period: '1 year', + pricing_terms: { + billing_plan_id: 'monthly', + billing_price: { + amount: 6.99, + currency_code: 'USD', + currency_symbol: '$', + localized_string: '$6.99', + }, + billing_period: { + unit: 'month', + number_of_units: 1, + }, + commitment_info: { + price: { + amount: 83.88, + currency_code: 'USD', + currency_symbol: '$', + localized_string: '$83.88', + }, + period: { + unit: 'year', + number_of_units: 1, + }, + }, + }, offer: { offer_identifier: { type: 'promotional', @@ -75,8 +103,13 @@ const mocks: Def['AdaptyProduct.Subscription'][] = [ ]; function toModel(mock: (typeof mocks)[number]): Model { - const _period = new AdaptySubscriptionPeriodCoder(); - const _offer = new AdaptySubscriptionOfferCoder(); + const _period = new AdaptySubscriptionPeriodCoder( + new DefaultPlatformAdapter(), + ); + const _offer = new AdaptySubscriptionOfferCoder(new DefaultPlatformAdapter()); + const _pricingTerms = new AdaptySubscriptionPricingTermsCoder( + new DefaultPlatformAdapter(), + ); return { subscriptionPeriod: _period.decode(mock.period), @@ -96,6 +129,9 @@ function toModel(mock: (typeof mocks)[number]): Model { : { ios: { subscriptionGroupIdentifier: mock.group_identifier, + ...(mock.pricing_terms && { + pricingTerms: _pricingTerms.decode(mock.pricing_terms), + }), }, }), }; @@ -105,7 +141,7 @@ describe('AdaptySubscriptionDetailsCoder', () => { let coder: AdaptySubscriptionDetailsCoder; beforeEach(() => { - coder = new AdaptySubscriptionDetailsCoder(); + coder = new AdaptySubscriptionDetailsCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { @@ -120,4 +156,54 @@ describe('AdaptySubscriptionDetailsCoder', () => { expect(encoded).toStrictEqual(mock); }); + + it('should decode iOS pricing terms', () => { + const decoded = coder.decode(mocks[1]!); + + expect(decoded.ios?.pricingTerms).toStrictEqual({ + billingPlan: 'monthly', + billingPrice: { + amount: 6.99, + currencyCode: 'USD', + currencySymbol: '$', + localizedString: '$6.99', + }, + billingPeriod: { unit: 'month', numberOfUnits: 1 }, + commitmentInfo: { + price: { + amount: 83.88, + currencyCode: 'USD', + currencySymbol: '$', + localizedString: '$83.88', + }, + period: { unit: 'year', numberOfUnits: 1 }, + }, + }); + }); + + it('should drop iOS pricing terms from Android subscriptions', () => { + const android = new AdaptySubscriptionDetailsCoder({ + OS: 'android', + } as IPlatformAdapter); + const decoded = android.decode({ + ...mocks[0]!, + pricing_terms: mocks[1]!.pricing_terms, + }); + + expect(decoded.ios).toBeUndefined(); + expect(decoded.android).toStrictEqual({ + basePlanId: 'androidPlan1', + renewalType: 'prepaid', + }); + }); + + it('should keep iOS pricing terms on iOS', () => { + const ios = new AdaptySubscriptionDetailsCoder({ + OS: 'ios', + } as IPlatformAdapter); + + expect(ios.decode(mocks[1]!).ios?.pricingTerms?.billingPlan).toBe( + 'monthly', + ); + }); }); diff --git a/src/coders/adapty-subscription-details.ts b/src/coders/adapty-subscription-details.ts index 662529b..a13d9a6 100644 --- a/src/coders/adapty-subscription-details.ts +++ b/src/coders/adapty-subscription-details.ts @@ -4,9 +4,14 @@ import type { Properties } from './types'; import { SimpleCoder } from './coder'; import { AdaptySubscriptionPeriodCoder } from './adapty-subscription-period'; import { AdaptySubscriptionOfferCoder } from '@/coders/adapty-subscription-offer'; +import { AdaptySubscriptionPricingTermsCoder } from './adapty-subscription-pricing-terms'; type Model = AdaptySubscriptionDetails; type Serializable = Def['AdaptyProduct.Subscription']; +// Same shape for paywall and promoted product requests +type SubscriptionInput = NonNullable< + Def['AdaptyPaywallProduct.Request']['subscription'] +>; export class AdaptySubscriptionDetailsCoder extends SimpleCoder< Model, @@ -17,7 +22,7 @@ export class AdaptySubscriptionDetailsCoder extends SimpleCoder< key: 'period', required: true, type: 'object', - converter: new AdaptySubscriptionPeriodCoder(), + converter: new AdaptySubscriptionPeriodCoder(this.platform), }, localizedSubscriptionPeriod: { key: 'localized_period', @@ -28,7 +33,7 @@ export class AdaptySubscriptionDetailsCoder extends SimpleCoder< key: 'offer', required: false, type: 'object', - converter: new AdaptySubscriptionOfferCoder(), + converter: new AdaptySubscriptionOfferCoder(this.platform), }, ios: { subscriptionGroupIdentifier: { @@ -36,6 +41,12 @@ export class AdaptySubscriptionDetailsCoder extends SimpleCoder< required: false, type: 'string', }, + pricingTerms: { + key: 'pricing_terms', + required: false, + type: 'object', + converter: new AdaptySubscriptionPricingTermsCoder(this.platform), + }, }, android: { basePlanId: { @@ -58,3 +69,17 @@ export class AdaptySubscriptionDetailsCoder extends SimpleCoder< return partialData; } } + +// Picks the purchase-relevant subset of subscription details for native requests +export function getSubscriptionInput( + data: Serializable | undefined, +): SubscriptionInput | undefined { + const billingPlanId = data?.pricing_terms?.billing_plan_id; + const offerIdentifier = data?.offer?.offer_identifier; + if (!billingPlanId && !offerIdentifier) return undefined; + + return { + ...(billingPlanId && { pricing_terms: { billing_plan_id: billingPlanId } }), + ...(offerIdentifier && { offer: { offer_identifier: offerIdentifier } }), + }; +} diff --git a/src/coders/adapty-subscription-offer-identifier.test.ts b/src/coders/adapty-subscription-offer-identifier.test.ts index 8473106..21621c2 100644 --- a/src/coders/adapty-subscription-offer-identifier.test.ts +++ b/src/coders/adapty-subscription-offer-identifier.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import type { AdaptySubscriptionOfferId } from '@/types'; import type { Def } from '@/types/schema'; import { AdaptySubscriptionOfferIdCoder } from '@/coders/adapty-subscription-offer-identifier'; @@ -48,7 +49,7 @@ describe('AdaptySubscriptionOfferIdCoder', () => { let coder: AdaptySubscriptionOfferIdCoder; beforeEach(() => { - coder = new AdaptySubscriptionOfferIdCoder(); + coder = new AdaptySubscriptionOfferIdCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-subscription-offer.test.ts b/src/coders/adapty-subscription-offer.test.ts index f955ded..13791c5 100644 --- a/src/coders/adapty-subscription-offer.test.ts +++ b/src/coders/adapty-subscription-offer.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import type { AdaptySubscriptionOffer } from '@/types'; import type { Def } from '@/types/schema'; import { AdaptyDiscountPhaseCoder } from './adapty-discount-phase'; @@ -59,8 +60,12 @@ const mocks: Def['AdaptySubscriptionOffer'][] = [ ]; function toModel(mock: (typeof mocks)[number]): Model { - const _offerId = new AdaptySubscriptionOfferIdCoder(); - const _discounts = new ArrayCoder(() => new AdaptyDiscountPhaseCoder()); + const _offerId = new AdaptySubscriptionOfferIdCoder( + new DefaultPlatformAdapter(), + ); + const _discounts = new ArrayCoder( + () => new AdaptyDiscountPhaseCoder(new DefaultPlatformAdapter()), + ); return { identifier: _offerId.decode(mock.offer_identifier), @@ -77,7 +82,7 @@ describe('AdaptySubscriptionOfferCoder', () => { let coder: AdaptySubscriptionOfferCoder; beforeEach(() => { - coder = new AdaptySubscriptionOfferCoder(); + coder = new AdaptySubscriptionOfferCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-subscription-offer.ts b/src/coders/adapty-subscription-offer.ts index 0b9e3a3..8a4d089 100644 --- a/src/coders/adapty-subscription-offer.ts +++ b/src/coders/adapty-subscription-offer.ts @@ -18,13 +18,15 @@ export class AdaptySubscriptionOfferCoder extends SimpleCoder< key: 'offer_identifier', required: true, type: 'object', - converter: new AdaptySubscriptionOfferIdCoder(), + converter: new AdaptySubscriptionOfferIdCoder(this.platform), }, phases: { key: 'phases', required: true, type: 'array', - converter: new ArrayCoder(() => new AdaptyDiscountPhaseCoder()), + converter: new ArrayCoder( + () => new AdaptyDiscountPhaseCoder(this.platform), + ), }, android: { offerTags: { diff --git a/src/coders/adapty-subscription-period.test.ts b/src/coders/adapty-subscription-period.test.ts index d69982c..97c6299 100644 --- a/src/coders/adapty-subscription-period.test.ts +++ b/src/coders/adapty-subscription-period.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import type { AdaptySubscriptionPeriod, ProductPeriod } from '@/types'; import type { Def } from '@/types/schema'; import { AdaptySubscriptionPeriodCoder } from './adapty-subscription-period'; @@ -22,7 +23,7 @@ describe('AdaptySubscriptionPeriodCoder', () => { let coder: AdaptySubscriptionPeriodCoder; beforeEach(() => { - coder = new AdaptySubscriptionPeriodCoder(); + coder = new AdaptySubscriptionPeriodCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-subscription-pricing-terms.test.ts b/src/coders/adapty-subscription-pricing-terms.test.ts new file mode 100644 index 0000000..1a53808 --- /dev/null +++ b/src/coders/adapty-subscription-pricing-terms.test.ts @@ -0,0 +1,66 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; +import type { AdaptySubscriptionPricingTerms, ProductPeriod } from '@/types'; +import type { Def } from '@/types/schema'; +import { AdaptySubscriptionPricingTermsCoder } from './adapty-subscription-pricing-terms'; + +type Model = AdaptySubscriptionPricingTerms; +const mocks: Def['AdaptySubscriptionPricingTerms'][] = [ + { + billing_plan_id: 'monthly', + billing_price: { amount: 6.99, localized_string: '$6.99' }, + billing_period: { unit: 'month', number_of_units: 1 }, + commitment_info: { + price: { amount: 83.88, localized_string: '$83.88' }, + period: { unit: 'year', number_of_units: 1 }, + }, + }, + { + // Unknown plans are passed through as is + billing_plan_id: 'quarterly', + billing_price: { amount: 59.99 }, + billing_period: { unit: 'year', number_of_units: 1 }, + commitment_info: { + price: { amount: 59.99 }, + period: { unit: 'year', number_of_units: 1 }, + }, + }, +]; + +function toModel(mock: (typeof mocks)[number]): Model { + const price = (p: Def['AdaptyPrice']) => ({ + amount: p.amount, + ...(p.localized_string && { localizedString: p.localized_string }), + }); + const period = (p: Def['AdaptySubscriptionPeriod']) => ({ + unit: p.unit as ProductPeriod, + numberOfUnits: p.number_of_units, + }); + + return { + billingPlan: mock.billing_plan_id, + billingPrice: price(mock.billing_price), + billingPeriod: period(mock.billing_period), + commitmentInfo: { + price: price(mock.commitment_info.price), + period: period(mock.commitment_info.period), + }, + }; +} + +describe('AdaptySubscriptionPricingTermsCoder', () => { + let coder: AdaptySubscriptionPricingTermsCoder; + + beforeEach(() => { + coder = new AdaptySubscriptionPricingTermsCoder( + new DefaultPlatformAdapter(), + ); + }); + + it.each(mocks)('should decode to expected result', mock => { + expect(coder.decode(mock)).toStrictEqual(toModel(mock)); + }); + + it.each(mocks)('should decode/encode', mock => { + expect(coder.encode(coder.decode(mock))).toStrictEqual(mock); + }); +}); diff --git a/src/coders/adapty-subscription-pricing-terms.ts b/src/coders/adapty-subscription-pricing-terms.ts new file mode 100644 index 0000000..7e7c973 --- /dev/null +++ b/src/coders/adapty-subscription-pricing-terms.ts @@ -0,0 +1,41 @@ +import type { AdaptySubscriptionPricingTerms } from '@/types'; +import type { Def } from '@/types/schema'; +import type { Properties } from './types'; +import { SimpleCoder } from './coder'; +import { AdaptyPriceCoder } from './adapty-price'; +import { AdaptySubscriptionPeriodCoder } from './adapty-subscription-period'; +import { AdaptySubscriptionCommitmentInfoCoder } from './adapty-subscription-commitment-info'; + +type Model = AdaptySubscriptionPricingTerms; +type Serializable = Def['AdaptySubscriptionPricingTerms']; + +export class AdaptySubscriptionPricingTermsCoder extends SimpleCoder< + Model, + Serializable +> { + protected properties: Properties = { + billingPlan: { + key: 'billing_plan_id', + required: true, + type: 'string', + }, + billingPrice: { + key: 'billing_price', + required: true, + type: 'object', + converter: new AdaptyPriceCoder(this.platform), + }, + billingPeriod: { + key: 'billing_period', + required: true, + type: 'object', + converter: new AdaptySubscriptionPeriodCoder(this.platform), + }, + commitmentInfo: { + key: 'commitment_info', + required: true, + type: 'object', + converter: new AdaptySubscriptionCommitmentInfoCoder(this.platform), + }, + }; +} diff --git a/src/coders/adapty-subscription.test.ts b/src/coders/adapty-subscription.test.ts index 5a5af95..b3c7465 100644 --- a/src/coders/adapty-subscription.test.ts +++ b/src/coders/adapty-subscription.test.ts @@ -1,6 +1,8 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import type { AdaptySubscription, CancellationReason, + SubscriptionBillingPlan, VendorStore, } from '@/types'; import type { Def } from '@/types/schema'; @@ -10,6 +12,12 @@ type Model = AdaptySubscription; const mocks: Def['AdaptyProfile.Subscription'][] = [ { activated_at: '2023-08-09T12:34:56.789Z', + billing_plan_id: 'monthly', + commitment: { + billing_period_number: 3, + total_billing_periods: 12, + expires_at: '2024-08-08T12:00:00.000Z', + }, is_active: true, is_in_grace_period: false, is_lifetime: false, @@ -34,6 +42,7 @@ const mocks: Def['AdaptyProfile.Subscription'][] = [ renewed_at: '2023-07-09T12:34:56.789Z', starts_at: '2023-08-09T12:34:56.789Z', store: 'Google Play', + offer_id: 'androidOffer1', unsubscribed_at: '2023-08-09T12:34:56.789Z', vendor_original_transaction_id: 'originalTransaction456', vendor_product_id: 'product456', @@ -73,6 +82,17 @@ function toModel(mock: (typeof mocks)[number]): Model { vendorProductId: mock.vendor_product_id, vendorTransactionId: mock.vendor_transaction_id, willRenew: mock.will_renew, + ...(mock.offer_id && { offerId: mock.offer_id }), + ...(mock.billing_plan_id && { + billingPlan: mock.billing_plan_id as SubscriptionBillingPlan, + }), + ...(mock.commitment && { + commitmentInfo: { + billingPeriodNumber: mock.commitment.billing_period_number, + totalBillingPeriods: mock.commitment.total_billing_periods, + expiresAt: new Date(mock.commitment.expires_at), + }, + }), }; } @@ -80,7 +100,7 @@ describe('AdaptySubscriptionCoder', () => { let coder: AdaptySubscriptionCoder; beforeEach(() => { - coder = new AdaptySubscriptionCoder(); + coder = new AdaptySubscriptionCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-subscription.ts b/src/coders/adapty-subscription.ts index 1d85d2d..01133ab 100644 --- a/src/coders/adapty-subscription.ts +++ b/src/coders/adapty-subscription.ts @@ -3,6 +3,7 @@ import type { Def } from '@/types/schema'; import type { Properties } from './types'; import { SimpleCoder } from './coder'; import { DateCoder } from './date'; +import { AdaptyProfileSubscriptionCommitmentInfoCoder } from './adapty-profile-subscription-commitment-info'; type Model = AdaptySubscription; type Serializable = Def['AdaptyProfile.Subscription']; @@ -115,5 +116,23 @@ export class AdaptySubscriptionCoder extends SimpleCoder { required: false, type: 'string', }, + billingPlan: { + key: 'billing_plan_id', + required: false, + type: 'string', + }, + commitmentInfo: { + key: 'commitment', + required: false, + type: 'object', + converter: new AdaptyProfileSubscriptionCommitmentInfoCoder( + this.platform, + ), + }, + offerId: { + key: 'offer_id', + required: false, + type: 'string', + }, }; } diff --git a/src/coders/adapty-ui-dialog-config.test.ts b/src/coders/adapty-ui-dialog-config.test.ts index 3eb3b3c..49ecb37 100644 --- a/src/coders/adapty-ui-dialog-config.test.ts +++ b/src/coders/adapty-ui-dialog-config.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import { Def } from '@/types/schema'; import { AdaptyUiDialogConfigCoder } from '@/coders/adapty-ui-dialog-config'; @@ -14,7 +15,7 @@ const mocks: Def['AdaptyUI.DialogConfiguration'][] = [ ]; describe('AdaptyUiDialogConfigCoder', () => { - const coder = new AdaptyUiDialogConfigCoder(); + const coder = new AdaptyUiDialogConfigCoder(new DefaultPlatformAdapter()); it.each(mocks)('should encode/decode', mock => { const decoded = coder.decode(mock); diff --git a/src/coders/adapty-ui-media-cache.test.ts b/src/coders/adapty-ui-media-cache.test.ts index e908119..59ca5ce 100644 --- a/src/coders/adapty-ui-media-cache.test.ts +++ b/src/coders/adapty-ui-media-cache.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import { Def } from '@/types/schema'; import { AdaptyUiMediaCacheCoder } from '@/coders/adapty-ui-media-cache'; @@ -10,7 +11,7 @@ const mocks: Required['media_cache'][] = [ ]; describe('AdaptyUiMediaCacheCoder', () => { - const coder = new AdaptyUiMediaCacheCoder(); + const coder = new AdaptyUiMediaCacheCoder(new DefaultPlatformAdapter()); it.each(mocks)('should encode/decode', mock => { const decoded = coder.decode(mock); diff --git a/src/coders/adapty-ui-onboarding-meta.test.ts b/src/coders/adapty-ui-onboarding-meta.test.ts index 1a844ba..5d87a6d 100644 --- a/src/coders/adapty-ui-onboarding-meta.test.ts +++ b/src/coders/adapty-ui-onboarding-meta.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import { AdaptyUiOnboardingMetaCoder } from './adapty-ui-onboarding-meta'; import type { AdaptyUiOnboardingMeta } from '@/ui-builder/types'; import type { Def } from '@/types/schema'; @@ -31,7 +32,7 @@ describe('AdaptyUiOnboardingMetaCoder', () => { let coder: AdaptyUiOnboardingMetaCoder; beforeEach(() => { - coder = new AdaptyUiOnboardingMetaCoder(); + coder = new AdaptyUiOnboardingMetaCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-ui-onboarding-state-params.test.ts b/src/coders/adapty-ui-onboarding-state-params.test.ts index 6df65d5..8ed525c 100644 --- a/src/coders/adapty-ui-onboarding-state-params.test.ts +++ b/src/coders/adapty-ui-onboarding-state-params.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import { AdaptyUiOnboardingStateParamsCoder } from './adapty-ui-onboarding-state-params'; import type { AdaptyUiOnboardingStateParams } from '@/ui-builder/types'; import type { Def } from '@/types/schema'; @@ -28,7 +29,9 @@ describe('AdaptyUiOnboardingStateParamsCoder', () => { let coder: AdaptyUiOnboardingStateParamsCoder; beforeEach(() => { - coder = new AdaptyUiOnboardingStateParamsCoder(); + coder = new AdaptyUiOnboardingStateParamsCoder( + new DefaultPlatformAdapter(), + ); }); it.each(mocks)('should decode to expected result', mock => { diff --git a/src/coders/adapty-ui-onboarding-state-updated-action.test.ts b/src/coders/adapty-ui-onboarding-state-updated-action.test.ts index 8f9c519..edc66c3 100644 --- a/src/coders/adapty-ui-onboarding-state-updated-action.test.ts +++ b/src/coders/adapty-ui-onboarding-state-updated-action.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import { AdaptyUiOnboardingStateUpdatedActionCoder } from './adapty-ui-onboarding-state-updated-action'; import type { OnboardingStateUpdatedAction } from '@/ui-builder/types'; import type { Event } from '@/types/schema'; @@ -95,7 +96,9 @@ describe('AdaptyUiOnboardingStateUpdatedActionCoder', () => { let coder: AdaptyUiOnboardingStateUpdatedActionCoder; beforeEach(() => { - coder = new AdaptyUiOnboardingStateUpdatedActionCoder(); + coder = new AdaptyUiOnboardingStateUpdatedActionCoder( + new DefaultPlatformAdapter(), + ); }); it.each(mocks.map((mock, idx) => ({ mock, expected: expectedResults[idx] })))( diff --git a/src/coders/adapty-ui-onboarding-state-updated-action.ts b/src/coders/adapty-ui-onboarding-state-updated-action.ts index 1f74633..001a42e 100644 --- a/src/coders/adapty-ui-onboarding-state-updated-action.ts +++ b/src/coders/adapty-ui-onboarding-state-updated-action.ts @@ -13,7 +13,9 @@ export class AdaptyUiOnboardingStateUpdatedActionCoder extends SimpleCoder< BaseModel, Serializable > { - private readonly paramCoder = new AdaptyUiOnboardingStateParamsCoder(); + private readonly paramCoder = new AdaptyUiOnboardingStateParamsCoder( + this.platform, + ); protected properties: Properties = { elementId: { diff --git a/src/coders/bridge-error.test.ts b/src/coders/bridge-error.test.ts index a57fea7..7a68e8f 100644 --- a/src/coders/bridge-error.test.ts +++ b/src/coders/bridge-error.test.ts @@ -1,3 +1,4 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; import { AdaptyBridgeError } from '@/types/bridge'; import { BridgeErrorCoder } from './bridge-error'; import { AdaptyError } from '@/adapty-error'; @@ -12,7 +13,7 @@ describe('BridgeErrorCoder', () => { }; beforeEach(() => { - coder = new BridgeErrorCoder(); + coder = new BridgeErrorCoder(new DefaultPlatformAdapter()); }); it('should be Error', () => { diff --git a/src/coders/coder.ts b/src/coders/coder.ts index 0001fd3..c433b14 100644 --- a/src/coders/coder.ts +++ b/src/coders/coder.ts @@ -1,5 +1,4 @@ import { AdaptyError } from '@/adapty-error'; -import { DefaultPlatformAdapter } from '@/adapters/defaults'; import type { IPlatformAdapter } from '@/adapters/interfaces'; import { Converter, Properties, StrType } from './types'; @@ -11,7 +10,7 @@ export abstract class Coder< protected readonly platform: IPlatformAdapter; protected abstract properties: Properties; - constructor(platform: IPlatformAdapter = new DefaultPlatformAdapter()) { + constructor(platform: IPlatformAdapter) { this.platform = platform; } diff --git a/src/coders/factory.ts b/src/coders/factory.ts index 95cbb15..ef90205 100644 --- a/src/coders/factory.ts +++ b/src/coders/factory.ts @@ -21,14 +21,18 @@ import { AdaptyPlacementCoder } from './adapty-placement'; import { AdaptyPriceCoder } from './adapty-price'; import { AdaptyPromotedProductCoder } from './adapty-promoted-product'; import { AdaptyProfileParametersCoder } from './adapty-profile-parameters'; +import { AdaptyProfileSubscriptionCommitmentInfoCoder } from './adapty-profile-subscription-commitment-info'; import { AdaptyProfileCoder } from './adapty-profile'; import { AdaptyPurchaseParamsCoder } from './adapty-purchase-params'; import { AdaptyPurchaseResultCoder } from './adapty-purchase-result'; +import { AdaptyReportTransactionParamsCoder } from './adapty-report-transaction-params'; import { AdaptyRemoteConfigCoder } from './adapty-remote-config'; +import { AdaptySubscriptionCommitmentInfoCoder } from './adapty-subscription-commitment-info'; import { AdaptySubscriptionDetailsCoder } from './adapty-subscription-details'; import { AdaptySubscriptionOfferIdCoder } from './adapty-subscription-offer-identifier'; import { AdaptySubscriptionOfferCoder } from './adapty-subscription-offer'; import { AdaptySubscriptionPeriodCoder } from './adapty-subscription-period'; +import { AdaptySubscriptionPricingTermsCoder } from './adapty-subscription-pricing-terms'; import { AdaptySubscriptionCoder } from './adapty-subscription'; import { AdaptyUiDialogConfigCoder } from './adapty-ui-dialog-config'; import { AdaptyUICreateOnboardingViewParamsCoder } from './adapty-ui-create-onboarding-view-params'; @@ -43,6 +47,7 @@ import { DateCoder } from './date'; import { HashmapCoder } from './hashmap'; import { JSONCoder } from './json'; import { ProductReferenceCoder } from './product-reference'; +import { ProductReferencePricingTermsCoder } from './product-reference-pricing-terms'; import type { Converter } from './types'; /** @@ -147,6 +152,10 @@ export class CoderFactory { return new ProductReferenceCoder(this.deps.platform); } + createProductReferencePricingTermsCoder(): ProductReferencePricingTermsCoder { + return new ProductReferencePricingTermsCoder(this.deps.platform); + } + createProfileCoder(): AdaptyProfileCoder { return new AdaptyProfileCoder(this.deps.platform); } @@ -155,6 +164,10 @@ export class CoderFactory { return new AdaptyProfileParametersCoder(this.deps.platform); } + createProfileSubscriptionCommitmentInfoCoder(): AdaptyProfileSubscriptionCommitmentInfoCoder { + return new AdaptyProfileSubscriptionCommitmentInfoCoder(this.deps.platform); + } + createPromotedProductCoder(): AdaptyPromotedProductCoder { return new AdaptyPromotedProductCoder(this.deps.platform); } @@ -163,10 +176,18 @@ export class CoderFactory { return new AdaptyRemoteConfigCoder(this.deps.platform); } + createReportTransactionParamsCoder(): AdaptyReportTransactionParamsCoder { + return new AdaptyReportTransactionParamsCoder(this.deps.platform); + } + createSubscriptionCoder(): AdaptySubscriptionCoder { return new AdaptySubscriptionCoder(this.deps.platform); } + createSubscriptionCommitmentInfoCoder(): AdaptySubscriptionCommitmentInfoCoder { + return new AdaptySubscriptionCommitmentInfoCoder(this.deps.platform); + } + createSubscriptionDetailsCoder(): AdaptySubscriptionDetailsCoder { return new AdaptySubscriptionDetailsCoder(this.deps.platform); } @@ -183,6 +204,10 @@ export class CoderFactory { return new AdaptySubscriptionPeriodCoder(this.deps.platform); } + createSubscriptionPricingTermsCoder(): AdaptySubscriptionPricingTermsCoder { + return new AdaptySubscriptionPricingTermsCoder(this.deps.platform); + } + createUiCreateOnboardingViewParamsCoder(): AdaptyUICreateOnboardingViewParamsCoder { return new AdaptyUICreateOnboardingViewParamsCoder(); } diff --git a/src/coders/nested-platform.test.ts b/src/coders/nested-platform.test.ts new file mode 100644 index 0000000..a1a0933 --- /dev/null +++ b/src/coders/nested-platform.test.ts @@ -0,0 +1,160 @@ +import type { + IPlatformAdapter, + ISdkMetadataAdapter, +} from '@/adapters/interfaces'; +import type { Def } from '@/types/schema'; +import { ArrayCoder } from './array'; +import { CoderFactory } from './factory'; + +const sdkMetadata: ISdkMetadataAdapter = { + sdkName: 'test', + sdkVersion: '0.0.0', +}; + +function createFactory(platform: IPlatformAdapter): CoderFactory { + return new CoderFactory({ platform, sdkMetadata }); +} + +const androidProduct: Def['AdaptyPaywallProduct.Response'] = { + vendor_product_id: 'yearly.premium', + adapty_product_id: 'adapty_yearly', + access_level_id: 'premium', + product_type: 'subscription', + paywall_product_index: 0, + paywall_variation_id: 'variation1', + paywall_ab_test_name: 'abTest1', + paywall_name: 'Paywall', + localized_description: 'Premium', + localized_title: 'Premium Yearly', + price: { amount: 69.99, localized_string: '$69.99' }, + subscription: { + base_plan_id: 'yearly-base', + renewal_type: 'autorenewable', + period: { unit: 'year', number_of_units: 1 }, + }, +}; + +const { base_plan_id: _basePlanId, ...subscriptionWithoutBasePlan } = + androidProduct.subscription!; +const androidProductWithoutBasePlan: Def['AdaptyPaywallProduct.Response'] = { + ...androidProduct, + subscription: subscriptionWithoutBasePlan, +}; + +const iosProduct: Def['AdaptyPaywallProduct.Response'] = { + ...androidProduct, + is_family_shareable: false, + subscription: { + group_identifier: 'group1', + period: { unit: 'year', number_of_units: 1 }, + }, +}; + +describe('nested coders and the platform adapter', () => { + describe('android.basePlanId in nested subscription details', () => { + const android = createFactory({ OS: 'android' }); + + it('should reject an Android product without base_plan_id', () => { + expect(() => + android + .createPaywallProductCoder() + .decode(androidProductWithoutBasePlan), + ).toThrow(/basePlanId/); + }); + + it('should reject the whole products array on Android', () => { + expect(() => + android + .createPaywallProductArrayCoder() + .decode([androidProduct, androidProductWithoutBasePlan]), + ).toThrow(/basePlanId/); + }); + + it('should decode an Android product with base_plan_id', () => { + const decoded = android + .createPaywallProductCoder() + .decode(androidProduct); + + expect(decoded.subscription?.android).toStrictEqual({ + basePlanId: 'yearly-base', + renewalType: 'autorenewable', + }); + }); + + it('should not require base_plan_id for iOS products on iOS', () => { + const ios = createFactory({ OS: 'ios' }); + + expect(() => + ios.createPaywallProductCoder().decode(iosProduct), + ).not.toThrow(); + }); + + it.each(['web', 'unknown'] as const)( + 'should keep platform checks off on %s', + OS => { + expect(() => + createFactory({ OS }) + .createPaywallProductCoder() + .decode(androidProductWithoutBasePlan), + ).not.toThrow(); + }, + ); + }); + + describe('platform adapter sharing', () => { + const platform: IPlatformAdapter = { OS: 'android' }; + const factory = createFactory(platform); + const proto = CoderFactory.prototype as unknown as Record< + string, + (this: CoderFactory) => unknown + >; + const methods = Object.getOwnPropertyNames(CoderFactory.prototype).filter( + name => name.startsWith('create') && proto[name]?.length === 0, + ); + + // Walks the object graph and returns every object that holds a `platform` field. + // Coders created inside methods are not reachable here; the required constructor parameter covers them. + function collectPlatformHolders(root: unknown): { platform: unknown }[] { + const holders: { platform: unknown }[] = []; + const seen = new Set(); + const visit = (value: unknown): void => { + if (value === null || typeof value !== 'object' || seen.has(value)) { + return; + } + seen.add(value); + if (value instanceof ArrayCoder) { + const inner = value as unknown as { coderFactory: () => unknown }; + visit(inner.coderFactory()); + } + if ('platform' in value) { + holders.push(value as { platform: unknown }); + } + Object.values(value).forEach(visit); + }; + visit(root); + return holders; + } + + it('should find factory methods to check', () => { + expect(methods.length).toBeGreaterThan(30); + }); + + it.each(methods)( + '%s should pass the factory platform to every nested coder', + name => { + const holders = collectPlatformHolders(proto[name]!.call(factory)); + + holders.forEach(holder => expect(holder.platform).toBe(platform)); + }, + ); + + it('should reach nested coders of the paywall product', () => { + const holders = collectPlatformHolders( + factory.createPaywallProductCoder(), + ); + + // product, price, subscription details and their nested coders + expect(holders.length).toBeGreaterThan(5); + }); + }); +}); diff --git a/src/coders/parse.test.ts b/src/coders/parse.test.ts index 2e38127..bb096dc 100644 --- a/src/coders/parse.test.ts +++ b/src/coders/parse.test.ts @@ -116,6 +116,16 @@ describe('parseMethodResult', () => { ); expect(result).toBe('primary'); }); + + it('returns Array payload without decoding', () => { + const types = ['billing_issue', 'storekit_-42']; + const result = parseMethodResult( + factory, + JSON.stringify({ success: types }), + 'Array', + ); + expect(result).toEqual(types); + }); }); describe('success is routed to the matching coder', () => { diff --git a/src/coders/parse.ts b/src/coders/parse.ts index 165b9ed..fd19812 100644 --- a/src/coders/parse.ts +++ b/src/coders/parse.ts @@ -21,6 +21,7 @@ const AdaptyTypes = [ 'AdaptyUiOnboardingStateParams', 'AdaptyUiOnboardingStateUpdatedAction', 'Array', + 'Array', 'BridgeError', 'String', 'Boolean', @@ -73,6 +74,7 @@ export function parseMethodResult( 'Void', 'AdaptyUiView', 'AdaptyUiDialogActionType', + 'Array', ].includes(resultType) ) { return obj.success as T; diff --git a/src/coders/product-reference-pricing-terms.test.ts b/src/coders/product-reference-pricing-terms.test.ts new file mode 100644 index 0000000..7ec646c --- /dev/null +++ b/src/coders/product-reference-pricing-terms.test.ts @@ -0,0 +1,42 @@ +import { DefaultPlatformAdapter } from '@/adapters/defaults'; +import type { ProductReferencePricingTerms } from '@/types'; +import type { Def } from '@/types/schema'; +import { ProductReferencePricingTermsCoder } from './product-reference-pricing-terms'; + +type Model = ProductReferencePricingTerms; +const mocks: NonNullable< + Def['AdaptyFlowPaywall.ProductReference']['pricing_terms'] +> = [ + { billing_plan_id: 'up_front' }, + { + billing_plan_id: 'monthly', + promotional_offer_id: 'promo1', + win_back_offer_id: 'winBack1', + }, +]; + +function toModel(mock: (typeof mocks)[number]): Model { + return { + billingPlan: mock.billing_plan_id, + ...(mock.promotional_offer_id && { + promotionalOfferId: mock.promotional_offer_id, + }), + ...(mock.win_back_offer_id && { winBackOfferId: mock.win_back_offer_id }), + }; +} + +describe('ProductReferencePricingTermsCoder', () => { + let coder: ProductReferencePricingTermsCoder; + + beforeEach(() => { + coder = new ProductReferencePricingTermsCoder(new DefaultPlatformAdapter()); + }); + + it.each(mocks)('should decode to expected result', mock => { + expect(coder.decode(mock)).toStrictEqual(toModel(mock)); + }); + + it.each(mocks)('should decode/encode', mock => { + expect(coder.encode(coder.decode(mock))).toStrictEqual(mock); + }); +}); diff --git a/src/coders/product-reference-pricing-terms.ts b/src/coders/product-reference-pricing-terms.ts new file mode 100644 index 0000000..7110ac3 --- /dev/null +++ b/src/coders/product-reference-pricing-terms.ts @@ -0,0 +1,32 @@ +import type { ProductReferencePricingTerms } from '@/types'; +import type { Def } from '@/types/schema'; +import type { Properties } from './types'; +import { SimpleCoder } from './coder'; + +type Model = ProductReferencePricingTerms; +type Serializable = NonNullable< + Def['AdaptyFlowPaywall.ProductReference']['pricing_terms'] +>[number]; + +export class ProductReferencePricingTermsCoder extends SimpleCoder< + Model, + Serializable +> { + protected properties: Properties = { + billingPlan: { + key: 'billing_plan_id', + required: true, + type: 'string', + }, + promotionalOfferId: { + key: 'promotional_offer_id', + required: false, + type: 'string', + }, + winBackOfferId: { + key: 'win_back_offer_id', + required: false, + type: 'string', + }, + }; +} diff --git a/src/coders/product-reference.test.ts b/src/coders/product-reference.test.ts index a716978..57ad125 100644 --- a/src/coders/product-reference.test.ts +++ b/src/coders/product-reference.test.ts @@ -1,5 +1,7 @@ -import type { ProductReference } from '@/types'; +import { DefaultPlatformAdapter } from '@/adapters/defaults'; +import type { ProductReference, SubscriptionBillingPlan } from '@/types'; import type { Def } from '@/types/schema'; +import type { IPlatformAdapter } from '@/adapters/interfaces'; import { ProductReferenceCoder } from './product-reference'; type Model = ProductReference; @@ -16,8 +18,14 @@ const mocks: Def['AdaptyFlowPaywall.ProductReference'][] = [ adapty_product_id: 'adaptyProduct456', access_level_id: 'premium', product_type: 'subscription', - promotional_offer_id: 'offer789', - win_back_offer_id: 'offer456', + pricing_terms: [ + { billing_plan_id: 'monthly', promotional_offer_id: 'offer789' }, + { + billing_plan_id: 'up_front', + promotional_offer_id: 'offer789', + win_back_offer_id: 'offer456', + }, + ], }, { vendor_product_id: 'product111', @@ -33,8 +41,7 @@ const mocks: Def['AdaptyFlowPaywall.ProductReference'][] = [ adapty_product_id: 'adaptyProductXYZ', access_level_id: 'premium', product_type: 'non_subscription', - promotional_offer_id: 'promoOfferIOS', - win_back_offer_id: 'winBackOfferIOS', + pricing_terms: [{ billing_plan_id: 'up_front' }], base_plan_id: 'baseAndroid', offer_id: 'offerAndroid', }, @@ -48,11 +55,16 @@ function toModel(mock: (typeof mocks)[number]): Model { accessLevelId: mock.access_level_id, productType: mock.product_type, ios: { - ...(mock.promotional_offer_id && { - promotionalOfferId: mock.promotional_offer_id, - }), - ...(mock.win_back_offer_id && { - winBackOfferId: mock.win_back_offer_id, + ...(mock.pricing_terms && { + pricingTerms: mock.pricing_terms.map(terms => ({ + billingPlan: terms.billing_plan_id as SubscriptionBillingPlan, + ...(terms.promotional_offer_id && { + promotionalOfferId: terms.promotional_offer_id, + }), + ...(terms.win_back_offer_id && { + winBackOfferId: terms.win_back_offer_id, + }), + })), }), }, android: { @@ -66,7 +78,7 @@ describe('ProductReferenceCoder', () => { let coder: ProductReferenceCoder; beforeEach(() => { - coder = new ProductReferenceCoder(); + coder = new ProductReferenceCoder(new DefaultPlatformAdapter()); }); it.each(mocks)('should decode to expected result', mock => { @@ -81,4 +93,15 @@ describe('ProductReferenceCoder', () => { expect(encoded).toStrictEqual(mock); }); + + it.each(['ios', 'android'] as const)( + 'should decode a reference without pricing terms on %s', + OS => { + const platformCoder = new ProductReferenceCoder({ + OS, + } as IPlatformAdapter); + + expect(platformCoder.decode(mocks[0]!).ios).toStrictEqual({}); + }, + ); }); diff --git a/src/coders/product-reference.ts b/src/coders/product-reference.ts index bfeed97..49e8ce8 100644 --- a/src/coders/product-reference.ts +++ b/src/coders/product-reference.ts @@ -2,6 +2,8 @@ import type { Properties } from './types'; import type { ProductReference } from '@/types'; import type { Def } from '@/types/schema'; import { SimpleCoder } from './coder'; +import { ArrayCoder } from './array'; +import { ProductReferencePricingTermsCoder } from './product-reference-pricing-terms'; type Model = ProductReference; type Serializable = Def['AdaptyFlowPaywall.ProductReference']; @@ -34,15 +36,13 @@ export class ProductReferenceCoder extends SimpleCoder { type: 'string', }, ios: { - promotionalOfferId: { - key: 'promotional_offer_id', + pricingTerms: { + key: 'pricing_terms', required: false, - type: 'string', - }, - winBackOfferId: { - key: 'win_back_offer_id', - required: false, - type: 'string', + type: 'array', + converter: new ArrayCoder( + () => new ProductReferencePricingTermsCoder(this.platform), + ), }, }, android: { diff --git a/src/logger/console-sink.ts b/src/logger/console-sink.ts index 96f2585..483afed 100644 --- a/src/logger/console-sink.ts +++ b/src/logger/console-sink.ts @@ -11,6 +11,7 @@ function getConsoleForLevel( case 'warn': return console.warn; case 'verbose': + case 'debug': return console.debug; case 'info': default: diff --git a/src/logger/log.ts b/src/logger/log.ts index 15a0887..d445758 100644 --- a/src/logger/log.ts +++ b/src/logger/log.ts @@ -69,6 +69,8 @@ export class Log { return 2; case LogLevel.VERBOSE: return 3; + case LogLevel.DEBUG: + return 4; } } diff --git a/src/types/api.d.ts b/src/types/api.d.ts index 71892ff..fc85e76 100644 --- a/src/types/api.d.ts +++ b/src/types/api.d.ts @@ -78,6 +78,15 @@ export interface components { [{ error: components['defs']['AdaptyError'] }, { success: true }] >; + 'AdaptyUIDestroyFlowView.Request': { + method: 'adapty_ui_destroy_flow_view'; + id: string; + }; + + 'AdaptyUIDestroyFlowView.Response': OneOf< + [{ error: components['defs']['AdaptyError'] }, { success: true }] + >; + 'AdaptyUIPresentOnboardingView.Request': { method: 'adapty_ui_present_onboarding_view'; id: string; @@ -185,6 +194,25 @@ export interface components { ] >; + 'PreloadFlows.Request': { + method: 'preload_flows'; + placement_ids: string[]; + load_timeout?: number; + }; + + 'PreloadFlows.Response': OneOf< + [{ error: components['defs']['AdaptyError'] }, { success: true }] + >; + + 'PreloadFlowsForDefaultAudience.Request': { + method: 'preload_flows_for_default_audience'; + placement_ids: string[]; + }; + + 'PreloadFlowsForDefaultAudience.Response': OneOf< + [{ error: components['defs']['AdaptyError'] }, { success: true }] + >; + 'GetPaywallProducts.Request': { method: 'get_paywall_products'; flow: components['defs']['AdaptyFlow']; @@ -285,6 +313,26 @@ export interface components { ] >; + 'GetPendingStoreMessageTypes.Request': { + method: 'get_pending_store_message_types'; + }; + + 'GetPendingStoreMessageTypes.Response': OneOf< + [ + { error: components['defs']['AdaptyError'] }, + { success: components['defs']['AdaptyStoreMessageType'][] }, + ] + >; + + 'ShowStoreMessage.Request': { + method: 'show_store_messages'; + filter?: components['defs']['AdaptyStoreMessageType'][]; + }; + + 'ShowStoreMessage.Response': OneOf< + [{ error: components['defs']['AdaptyError'] }, { success: true }] + >; + 'OpenWebPaywall.Request': { method: 'open_web_paywall'; open_in?: components['defs']['AdaptyWebPresentation']; @@ -335,6 +383,7 @@ export interface components { method: 'report_transaction'; variation_id?: string; transaction_id: string; + apple_jws_transaction?: string; }; 'ReportTransaction.Response': OneOf< @@ -617,7 +666,7 @@ export interface components { | 'products_screen_presented' | 'user_email_collected' | 'onboarding_completed' - | string; + | (string & {}); element_id?: string; reply?: string; }; @@ -707,6 +756,7 @@ export interface components { customer_user_id?: string; customer_identity_parameters?: components['defs']['CustomerIdentityParameters']; observer_mode?: boolean; + store_messages_handling?: components['defs']['StoreMessagesHandling']; apple_idfa_collection_disabled?: boolean; google_adid_collection_disabled?: boolean; google_enable_pending_prepaid_plans?: boolean; @@ -728,6 +778,15 @@ export interface components { }; }; + StoreMessagesHandling: 'auto' | 'manual' | 'default'; + + AdaptyStoreMessageType: + | 'generic' + | 'price_increase_consent' + | 'billing_issue' + | 'win_back_offer' + | (string & {}); + CustomerIdentityParameters: { app_account_token?: string; obfuscated_account_id?: string; @@ -762,8 +821,12 @@ export interface components { }; 'AdaptyPromotedProduct.Request': { + purchase_intent_id?: string; vendor_product_id: string; subscription?: { + pricing_terms?: { + billing_plan_id: string; + }; offer?: { offer_identifier: components['defs']['AdaptySubscriptionOffer.Identifier']; }; @@ -772,6 +835,7 @@ export interface components { }; 'AdaptyPromotedProduct.Response': { + purchase_intent_id?: string; vendor_product_id: string; localized_description: string; localized_title: string; @@ -782,10 +846,23 @@ export interface components { payload_data?: string; }; + AdaptySubscriptionPricingTerms: { + billing_plan_id: string; + billing_price: components['defs']['AdaptyPrice']; + billing_period: components['defs']['AdaptySubscriptionPeriod']; + commitment_info: components['defs']['AdaptySubscriptionCommitmentInfo']; + }; + + AdaptySubscriptionCommitmentInfo: { + price: components['defs']['AdaptyPrice']; + period: components['defs']['AdaptySubscriptionPeriod']; + }; + 'AdaptyProduct.Subscription': { group_identifier?: string; period: components['defs']['AdaptySubscriptionPeriod']; localized_period?: string; + pricing_terms?: components['defs']['AdaptySubscriptionPricingTerms']; offer?: components['defs']['AdaptySubscriptionOffer']; renewal_type?: 'prepaid' | 'autorenewable'; base_plan_id?: string; @@ -798,6 +875,9 @@ export interface components { product_type: string; paywall_product_index: number; subscription?: { + pricing_terms?: { + billing_plan_id: string; + }; offer?: { offer_identifier: components['defs']['AdaptySubscriptionOffer.Identifier']; }; @@ -904,10 +984,13 @@ export interface components { adapty_product_id: string; access_level_id: string; product_type: string; - promotional_offer_id?: string; - win_back_offer_id?: string; base_plan_id?: string; offer_id?: string; + pricing_terms?: { + billing_plan_id: string; + promotional_offer_id?: string; + win_back_offer_id?: string; + }[]; }; AdaptySubscriptionPeriod: { @@ -960,6 +1043,8 @@ export interface components { billing_issue_detected_at?: components['defs']['Date']; starts_at?: components['defs']['Date']; cancellation_reason?: string; + billing_plan_id?: string; + commitment?: components['defs']['AdaptyProfile.SubscriptionCommitmentInfo']; is_refund: boolean; }; @@ -996,6 +1081,14 @@ export interface components { active_promotional_offer_id?: string; offer_id?: string; cancellation_reason?: string; + billing_plan_id?: string; + commitment?: components['defs']['AdaptyProfile.SubscriptionCommitmentInfo']; + }; + + 'AdaptyProfile.SubscriptionCommitmentInfo': { + billing_period_number: number; + total_billing_periods: number; + expires_at: components['defs']['Date']; }; 'AdaptyProfile.CustomAttributes': { @@ -1120,7 +1213,7 @@ export interface components { | 'health' | 'siri' | 'music' - | string; + | (string & {}); 'AdaptyUI.CustomTagsValues': { [key: string]: string; diff --git a/src/types/bridge.ts b/src/types/bridge.ts index 963e211..3b29b4f 100644 --- a/src/types/bridge.ts +++ b/src/types/bridge.ts @@ -11,6 +11,7 @@ import type { Event } from './schema'; export const MethodNames = [ 'activate', 'adapty_ui_create_flow_view', + 'adapty_ui_destroy_flow_view', 'adapty_ui_dismiss_flow_view', 'adapty_ui_present_flow_view', 'adapty_ui_show_dialog', @@ -23,6 +24,7 @@ export const MethodNames = [ 'get_flow', 'get_flow_for_default_audience', 'get_paywall_products', + 'get_pending_store_message_types', 'get_onboarding', 'get_onboarding_for_default_audience', 'get_profile', @@ -34,12 +36,15 @@ export const MethodNames = [ 'make_promoted_purchase', 'make_purchase', 'open_web_paywall', + 'preload_flows', + 'preload_flows_for_default_audience', 'present_code_redemption_sheet', 'report_transaction', 'restore_purchases', 'set_fallback', 'set_integration_identifiers', 'set_log_level', + 'show_store_messages', 'update_collecting_refund_data_consent', 'update_external_attribution_data', 'update_profile', diff --git a/src/types/error.ts b/src/types/error.ts index bb0513d..28e91b7 100644 --- a/src/types/error.ts +++ b/src/types/error.ts @@ -122,6 +122,16 @@ const ErrorCodeMapping = Object.freeze({ 3007: 'unsupportedData', 3100: 'persistingDataError', 3101: 'fetchTimeoutError', + /** + * Another operation of the same kind is already in progress + * (e.g. a store message show). + */ + 3201: 'operationInProgress', + /** + * A required resource could not be resolved + * (e.g. no foreground-active window scene to show store messages). + */ + 3202: 'resolverFailure', 9000: 'operationInterrupted', }); @@ -177,6 +187,8 @@ export const ErrorCodeName = Object.freeze({ unsupportedData: 3007, persistingDataError: 3100, fetchTimeoutError: 3101, + operationInProgress: 3201, + resolverFailure: 3202, operationInterrupted: 9000, } as const); export type ErrorCodeName = keyof typeof ErrorCodeName; diff --git a/src/types/index.ts b/src/types/index.ts index 918d665..1038c73 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -51,6 +51,18 @@ export const ProductPeriod = Object.freeze({ }); export type ProductPeriod = (typeof ProductPeriod)[keyof typeof ProductPeriod]; +export const SubscriptionBillingPlan = Object.freeze({ + UpFront: 'up_front', + Monthly: 'monthly', +}); +/** + * Billing plan of a subscription. + * Open-ended: native SDKs may pass through plans unknown to this version. + */ +export type SubscriptionBillingPlan = + | (typeof SubscriptionBillingPlan)[keyof typeof SubscriptionBillingPlan] + | (string & {}); + export interface AdaptyPrice { /** * Price as number @@ -339,6 +351,22 @@ export type AdaptyExternalAttributionProvider = | 'custom' | (string & {}); +/** + * Reason StoreKit wants to show an App Store message. + * + * @remarks + * Reasons unknown to the SDK arrive as `storekit_`, + * so any string is accepted. + * Requires iOS 16+. + * @public + */ +export type AdaptyStoreMessageType = + | 'generic' + | 'price_increase_consent' + | 'billing_issue' + | 'win_back_offer' + | (string & {}); + /** * Interface representing a user profile in Adapty, * including details about the user's subscriptions and consumable products. @@ -508,7 +536,31 @@ export interface AdaptyAccessLevel { */ readonly willRenew: boolean; + /** + * Billing plan of the subscription. Set for App Store purchases only, see {@link store}. + * @readonly + */ + readonly billingPlan?: SubscriptionBillingPlan; + + /** + * Commitment progress of a subscription bought with a commitment billing plan. + * Set for App Store purchases only, see {@link store}. + * @readonly + */ + readonly commitmentInfo?: AdaptyProfileSubscriptionCommitmentInfo; + + /** + * Identifier of the Google Play offer the subscription was bought with. + * Set for Play Store purchases only, see {@link store}. + * @readonly + */ + readonly offerId?: string; + android?: { + /** + * @deprecated Use the top-level {@link AdaptyAccessLevel.offerId}: + * the value depends on the purchase store, not on the device OS. + */ offerId?: string; }; } @@ -691,6 +743,48 @@ export interface AdaptySubscription { * @readonly */ readonly willRenew: boolean; + + /** + * Billing plan of the subscription. Set for App Store purchases only, see {@link store}. + * @readonly + */ + readonly billingPlan?: SubscriptionBillingPlan; + + /** + * Commitment progress of a subscription bought with a commitment billing plan. + * Set for App Store purchases only, see {@link store}. + * @readonly + */ + readonly commitmentInfo?: AdaptyProfileSubscriptionCommitmentInfo; + + /** + * Identifier of the Google Play offer the subscription was bought with. + * Set for Play Store purchases only, see {@link store}. + * @readonly + */ + readonly offerId?: string; +} + +/** + * Commitment progress of a subscription purchased with a commitment billing plan. + * @public + */ +export interface AdaptyProfileSubscriptionCommitmentInfo { + /** + * Number of the current billing period within the commitment. + * @readonly + */ + readonly billingPeriodNumber: number; + /** + * Total number of billing periods in the commitment. + * @readonly + */ + readonly totalBillingPeriods: number; + /** + * The date and time when the commitment expires. + * @readonly + */ + readonly expiresAt: Date; } /** @@ -807,6 +901,11 @@ export interface AdaptyPromotedProduct { * @see {@link https://developer.apple.com/documentation/storekit/skproduct/3564805-isfamilyshareable} */ readonly isFamilyShareable: boolean; + /** + * StoreKit purchase intent identifier, passed back to native on purchase. + * @internal + */ + readonly purchaseIntentId: string; }; } @@ -833,6 +932,11 @@ export interface AdaptySubscriptionDetails { * Will be `null` for iOS version below 12.0 and macOS version below 10.14. */ subscriptionGroupIdentifier?: string; + /** + * Billing terms of the subscription: billing plan, price per billing period + * and the total commitment. + */ + pricingTerms?: AdaptySubscriptionPricingTerms; }; android?: { @@ -841,6 +945,52 @@ export interface AdaptySubscriptionDetails { }; } +/** + * Billing terms of a subscription product. + * iOS only. + * @public + */ +export interface AdaptySubscriptionPricingTerms { + /** + * Billing plan of the subscription. + * @readonly + */ + readonly billingPlan: SubscriptionBillingPlan; + /** + * Price charged for each billing period. + * @readonly + */ + readonly billingPrice: AdaptyPrice; + /** + * Period between charges. + * @readonly + */ + readonly billingPeriod: AdaptySubscriptionPeriod; + /** + * Total price and period the user commits to. + * @readonly + */ + readonly commitmentInfo: AdaptySubscriptionCommitmentInfo; +} + +/** + * Total price and period of a subscription commitment. + * iOS only. + * @public + */ +export interface AdaptySubscriptionCommitmentInfo { + /** + * Total price of the commitment. + * @readonly + */ + readonly price: AdaptyPrice; + /** + * Total period of the commitment. + * @readonly + */ + readonly period: AdaptySubscriptionPeriod; +} + /** * Subscription offer model to products * @see {@link https://doc.adapty.io/docs/rn-api-reference#adaptysubscriptionoffer} @@ -935,8 +1085,7 @@ export interface ProductReference { productType: string; ios?: { - promotionalOfferId?: string; - winBackOfferId?: string; + pricingTerms?: ProductReferencePricingTerms[]; }; android?: { @@ -945,6 +1094,16 @@ export interface ProductReference { }; } +/** + * Billing plan with the offers available for it, as configured for a paywall product. + * @internal + */ +export interface ProductReferencePricingTerms { + billingPlan: SubscriptionBillingPlan; + promotionalOfferId?: string; + winBackOfferId?: string; +} + /** * Interface representing a product identifier with vendor and platform-specific information. * @public diff --git a/src/types/inputs.ts b/src/types/inputs.ts index c01e4b8..e0d953d 100644 --- a/src/types/inputs.ts +++ b/src/types/inputs.ts @@ -1,33 +1,40 @@ import { AdaptyUiMediaCache } from '@/ui-builder/types'; import type { AdaptyMockConfig } from '@/mock/types'; /** - * Log levels for the SDK + * Log levels for the SDK, ordered from the least to the most verbose: + * `ERROR` < `WARN` < `INFO` < `VERBOSE` < `DEBUG`. * * @remarks + * Setting a level enables it and all the levels above it in the list. * Logging is performed on a native side. * So you are expected to watch logs in Xcode or Android Studio. */ export const LogLevel = Object.freeze({ /** - * Logs any additional information that may be useful during debugging, - * such as function calls, API queries, etc. - */ - VERBOSE: 'verbose', - /** - * Logs only errors + * Level 0 — logs only errors. */ ERROR: 'error', /** - * Logs messages from the SDK + * Level 1 — logs errors and messages from the SDK * that do not cause critical errors, - * but are worth paying attention to + * but are worth paying attention to. */ WARN: 'warn', /** - * Logs various information messages, - * such as those that log the lifecycle of various modules + * Level 2 — additionally logs various information messages, + * such as those that log the lifecycle of various modules. */ INFO: 'info', + /** + * Level 3 — additionally logs any information that may be useful + * during debugging, such as function calls, API queries, etc. + */ + VERBOSE: 'verbose', + /** + * Level 4 — the most detailed level, additionally logs + * low-level internal details of the native SDK. + */ + DEBUG: 'debug', }); export type LogLevel = (typeof LogLevel)[keyof typeof LogLevel]; @@ -86,6 +93,26 @@ export type GetPlacementForDefaultAudienceParamsInput = maxAgeSeconds: number; }; +/** + * Describes optional parameters for the placement preload methods. + * + * @remarks + * Preloading has no fetch policy: it always goes to the network and only warms + * the placement cache, so unlike {@link GetPlacementParamsInput} the only knob + * is the timeout. + */ +export interface PreloadPlacementsParamsInput { + /** + * This value limits the timeout (in milliseconds) for this method. + * + * @remarks + * The native SDKs clamp anything below 1000 ms up to 1000 ms. Reaching the + * timeout is not an error by itself — the affected placements are retried + * against the default audience source. + */ + loadTimeoutMs?: number; +} + /** * Describes optional parameters for the {@link activate} method. */ @@ -172,6 +199,21 @@ export interface ActivateParamsInput { * @defaultValue `false` */ adaptyAttributionEnabled?: boolean; + /** + * Controls who decides when store messages are shown: App Store messages + * (price increase consent, billing issue, win-back offer, etc.) on iOS, + * Google Play in-app messages (e.g. a declined payment) on Android. + * + * @remarks + * - `'auto'` — iOS: StoreKit presents them automatically. Android: the SDK + * requests them on every `Activity.onResume`. + * - `'manual'` — messages are shown only when the app calls `showStoreMessages`. + * On iOS the SDK also keeps them in a queue readable via `getPendingStoreMessageTypes`. + * + * Has no effect below iOS 16. + * @defaultValue `'auto'` + */ + storeMessagesHandling?: 'auto' | 'manual'; ios?: { /** * Disables IDFA collection @@ -206,6 +248,15 @@ export interface IdentifyParamsInput { }; } +export interface ReportTransactionParamsInput { + transactionId: string; + variationId?: string; + ios?: { + /** StoreKit 2 JWS representation of the transaction */ + jwsTransaction?: string; + }; +} + export interface GetPaywallProductsParamsInput {} export const AdaptyAndroidSubscriptionUpdateReplacementMode = Object.freeze({