expo-iap 4.7.0 → 4.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.prettierignore +0 -1
- package/CLAUDE.md +1 -1
- package/CONTRIBUTING.md +6 -6
- package/android/src/main/java/expo/modules/iap/ExpoIapHelper.kt +78 -7
- package/android/src/main/java/expo/modules/iap/ExpoIapLog.kt +46 -28
- package/android/src/main/java/expo/modules/iap/ExpoIapModule.kt +3 -2
- package/build/ExpoIapModule.d.ts.map +1 -1
- package/build/ExpoIapModule.js +8 -22
- package/build/ExpoIapModule.js.map +1 -1
- package/build/index.d.ts +4 -7
- package/build/index.d.ts.map +1 -1
- package/build/index.js +23 -13
- package/build/index.js.map +1 -1
- package/build/index.kepler.d.ts +39 -4
- package/build/index.kepler.d.ts.map +1 -1
- package/build/index.kepler.js +45 -2
- package/build/index.kepler.js.map +1 -1
- package/build/kit-api.d.ts +18 -8
- package/build/kit-api.d.ts.map +1 -1
- package/build/kit-api.js +90 -3
- package/build/kit-api.js.map +1 -1
- package/build/modules/android.d.ts +9 -1
- package/build/modules/android.d.ts.map +1 -1
- package/build/modules/android.js +9 -1
- package/build/modules/android.js.map +1 -1
- package/build/modules/ios.d.ts +27 -5
- package/build/modules/ios.d.ts.map +1 -1
- package/build/modules/ios.js +20 -16
- package/build/modules/ios.js.map +1 -1
- package/build/types.d.ts +105 -176
- package/build/types.d.ts.map +1 -1
- package/build/types.js +4 -1
- package/build/types.js.map +1 -1
- package/build/useIAP.d.ts +19 -4
- package/build/useIAP.d.ts.map +1 -1
- package/build/useIAP.js +2 -1
- package/build/useIAP.js.map +1 -1
- package/build/utils/deprecation.d.ts +3 -0
- package/build/utils/deprecation.d.ts.map +1 -0
- package/build/utils/deprecation.js +13 -0
- package/build/utils/deprecation.js.map +1 -0
- package/build/vega-adapter.d.ts +1 -0
- package/build/vega-adapter.d.ts.map +1 -1
- package/build/vega-adapter.js +20 -13
- package/build/vega-adapter.js.map +1 -1
- package/ios/ExpoIapHelper.swift +42 -7
- package/ios/ExpoIapLog.swift +15 -0
- package/ios/onside/OnsideIapModule.swift +127 -16
- package/openiap-versions.json +3 -3
- package/package.json +1 -1
- package/plugin/build/onsidePodfile.d.ts +1 -0
- package/plugin/build/onsidePodfile.js +16 -0
- package/plugin/build/withIAP.d.ts +12 -2
- package/plugin/build/withIAP.js +124 -59
- package/plugin/build/withLocalOpenIAP.d.ts +2 -0
- package/plugin/build/withLocalOpenIAP.js +18 -0
- package/plugin/src/expoConfig.augmentation.d.ts +16 -5
- package/plugin/src/onsidePodfile.ts +15 -0
- package/plugin/src/withIAP.ts +195 -77
- package/plugin/src/withLocalOpenIAP.ts +23 -0
- package/scripts/update-types.mjs +112 -81
- package/src/ExpoIapModule.ts +19 -23
- package/src/index.kepler.ts +72 -3
- package/src/index.ts +34 -30
- package/src/kit-api.ts +136 -13
- package/src/modules/android.ts +9 -1
- package/src/modules/ios.ts +26 -22
- package/src/types.ts +116 -204
- package/src/useIAP.ts +21 -5
- package/src/utils/deprecation.ts +16 -0
- package/src/vega-adapter.ts +23 -12
- package/build/useWebhookEvents.d.ts +0 -26
- package/build/useWebhookEvents.d.ts.map +0 -1
- package/build/useWebhookEvents.js +0 -105
- package/build/useWebhookEvents.js.map +0 -1
- package/build/webhook-client.d.ts +0 -82
- package/build/webhook-client.d.ts.map +0 -1
- package/build/webhook-client.js +0 -176
- package/build/webhook-client.js.map +0 -1
- package/src/useWebhookEvents.ts +0 -155
- package/src/webhook-client.ts +0 -312
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.kepler.js","sourceRoot":"","sources":["../src/index.kepler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,gBAAgB,EAAC,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAC,SAAS,EAAC,MAAM,SAAS,CAAC;AAalC,cAAc,SAAS,CAAC;AACxB,cAAc,QAAQ,CAAC;AACvB,cAAc,UAAU,CAAC;AACzB,OAAO,EA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0CAA0C,GAEnD,KAAK,IAAI,EAAE,CAAC,WAAW,CAAC,4CAA4C,CAAC,CAAC;AAC1E,MAAM,CAAC,MAAM,wBAAwB,GAEjC,KAAK,IAAI,EAAE,CAAC,WAAW,CAAC,0BAA0B,CAAC,CAAC","sourcesContent":["import {getVegaIapModule} from './vega';\nimport {ErrorCode} from './types';\nimport type {\n MutationField,\n ProductQueryType,\n Purchase,\n PurchaseError,\n PurchaseOptions,\n PurchaseUpdatedListenerOptions,\n QueryField,\n RequestPurchasePropsByPlatforms,\n RequestSubscriptionPropsByPlatforms,\n} from './types';\n\nexport * from './types';\nexport * from './vega';\nexport * from './useIAP';\nexport {kitApi, KitApiError} from './kit-api';\nexport type {\n EntitlementsResponse,\n KitApiOptions,\n KitClientPayloadResponse,\n KitProduct,\n KitProductClientPayload,\n KitProductOffer,\n KitProductPlatform,\n KitProductsOptions,\n KitProductsResponse,\n KitSubscription,\n StatusResponse,\n} from './kit-api';\nexport {connectWebhookStream, parseWebhookEventData} from './webhook-client';\n\nexport enum OpenIapEvent {\n PurchaseUpdated = 'purchase-updated',\n PurchaseError = 'purchase-error',\n PromotedProductIOS = 'promoted-product-ios',\n UserChoiceBillingAndroid = 'user-choice-billing-android',\n DeveloperProvidedBillingAndroid = 'developer-provided-billing-android',\n SubscriptionBillingIssue = 'subscription-billing-issue',\n}\n\nexport type ProductTypeInput = ProductQueryType | 'inapp';\n\nexport interface EventSubscription {\n remove(): void;\n}\n\nconst getModule = () => {\n const module = getVegaIapModule();\n if (!module) {\n throw new Error(\n 'Amazon Vega IAP module is unavailable. Install @amazon-devices/keplerscript-appstore-iap-lib in the Vega app target and build with the React Native for Vega kepler platform.',\n );\n }\n return module;\n};\n\nconst unsupported = (feature: string): never => {\n throw new Error(`${feature} is not supported on Amazon Vega.`);\n};\n\nconst normalizeProductType = (\n type?: ProductTypeInput | null,\n): ProductQueryType => {\n if (type === 'subs' || type === 'all') return type;\n return 'in-app';\n};\n\nconst normalizePurchaseArray = (purchases: Purchase[]): Purchase[] =>\n purchases.map((purchase) => {\n const platform = String(purchase.platform).toLowerCase();\n if (platform === purchase.platform) return purchase;\n if (platform === 'android' || platform === 'ios') {\n return {...purchase, platform};\n }\n return purchase;\n });\n\nconst getAndroidRequest = (\n request?:\n | RequestPurchasePropsByPlatforms\n | RequestSubscriptionPropsByPlatforms\n | null,\n) => request?.google ?? request?.android;\n\nconst createPurchaseTokenError = (purchase: Purchase): Error => {\n const error = new Error(\n 'Purchase token is required to finish Amazon Vega transaction',\n ) as Error & PurchaseError;\n error.code = ErrorCode.DeveloperError;\n error.productId = purchase.productId;\n return error;\n};\n\nexport const emitter = {\n addListener(\n eventName: OpenIapEvent,\n listener: (payload: Purchase | PurchaseError) => void,\n ): EventSubscription {\n return getModule().addListener(eventName, listener);\n },\n removeListener(\n eventName: OpenIapEvent,\n listener: (payload: Purchase | PurchaseError) => void,\n ): void {\n return getModule().removeListener(eventName, listener);\n },\n};\n\nexport const purchaseUpdatedListener = (\n listener: (event: Purchase) => void,\n options?: PurchaseUpdatedListenerOptions | null,\n): EventSubscription => {\n return getModule().addListener(OpenIapEvent.PurchaseUpdated, (purchase) => {\n listener(purchase as Purchase);\n });\n};\n\nexport const purchaseErrorListener = (\n listener: (error: PurchaseError) => void,\n): EventSubscription => {\n return getModule().addListener(OpenIapEvent.PurchaseError, (error) => {\n listener(error as PurchaseError);\n });\n};\n\nexport const initConnection: MutationField<'initConnection'> = async (\n config,\n) => {\n return getModule().initConnection(config ?? null);\n};\n\nexport const endConnection: MutationField<'endConnection'> = async () => {\n return getModule().endConnection();\n};\n\nexport const fetchProducts: QueryField<'fetchProducts'> = async (request) => {\n const {skus, type} = request;\n return getModule().fetchProducts(normalizeProductType(type), skus);\n};\n\nexport const requestPurchase: MutationField<'requestPurchase'> = async (\n args,\n) => {\n const androidRequest = getAndroidRequest(args.request);\n if (!androidRequest?.skus?.length) {\n throw new Error(\n 'Invalid request for Amazon Vega. The `request.google.skus` or `request.android.skus` property is required and must be a non-empty array.',\n );\n }\n\n return normalizePurchaseArray(\n await getModule().requestPurchase({\n skuArr: androidRequest.skus,\n type: normalizeProductType(args.type),\n }),\n );\n};\n\nexport const getAvailablePurchases: QueryField<\n 'getAvailablePurchases'\n> = async (options) => {\n return normalizePurchaseArray(\n await getModule().getAvailableItems((options ?? {}) as PurchaseOptions),\n );\n};\n\nexport const finishTransaction: MutationField<'finishTransaction'> = async ({\n purchase,\n isConsumable = false,\n}) => {\n const token = purchase.purchaseToken ?? undefined;\n if (!token) {\n throw createPurchaseTokenError(purchase);\n }\n\n if (isConsumable) {\n await getModule().consumePurchaseAndroid(token);\n return;\n }\n\n await getModule().acknowledgePurchaseAndroid(token);\n};\n\nexport const restorePurchases: MutationField<'restorePurchases'> = async () => {\n await getAvailablePurchases({\n includeSuspendedAndroid: false,\n });\n};\n\nexport const getActiveSubscriptions: QueryField<\n 'getActiveSubscriptions'\n> = async (subscriptionIds) => {\n return getModule().getActiveSubscriptions(subscriptionIds ?? null);\n};\n\nexport const hasActiveSubscriptions: QueryField<\n 'hasActiveSubscriptions'\n> = async (subscriptionIds) => {\n return getModule().hasActiveSubscriptions(subscriptionIds ?? null);\n};\n\nexport const getStorefront: QueryField<'getStorefront'> = async () => {\n return getModule().getStorefront();\n};\n\nexport const verifyPurchaseWithProvider: MutationField<\n 'verifyPurchaseWithProvider'\n> = async (options) => {\n return getModule().verifyPurchaseWithProvider(options);\n};\n\nexport const validateReceipt: MutationField<'validateReceipt'> = async () =>\n unsupported('validateReceipt');\n\nexport const verifyPurchase: MutationField<'verifyPurchase'> = validateReceipt;\n\nexport const acknowledgePurchaseAndroid: MutationField<\n 'acknowledgePurchaseAndroid'\n> = async (purchaseToken) => {\n await getModule().acknowledgePurchaseAndroid(purchaseToken);\n return true;\n};\n\nexport const consumePurchaseAndroid: MutationField<\n 'consumePurchaseAndroid'\n> = async (purchaseToken) => {\n await getModule().consumePurchaseAndroid(purchaseToken);\n return true;\n};\n\nexport const acknowledgePurchase = acknowledgePurchaseAndroid;\nexport const consumePurchase = consumePurchaseAndroid;\n\nexport const syncIOS: MutationField<'syncIOS'> = async () =>\n unsupported('syncIOS');\nexport const getAppTransactionIOS: QueryField<\n 'getAppTransactionIOS'\n> = async () => null;\nexport const getPromotedProductIOS: QueryField<\n 'getPromotedProductIOS'\n> = async () => null;\nexport const requestPurchaseOnPromotedProductIOS = async (): Promise<boolean> =>\n unsupported('requestPurchaseOnPromotedProductIOS');\nexport const showManageSubscriptionsIOS: MutationField<\n 'showManageSubscriptionsIOS'\n> = async () => [];\nexport const presentCodeRedemptionSheetIOS: MutationField<\n 'presentCodeRedemptionSheetIOS'\n> = async () => false;\nexport const presentExternalPurchaseLinkIOS: MutationField<\n 'presentExternalPurchaseLinkIOS'\n> = async () => unsupported('presentExternalPurchaseLinkIOS');\n\nexport const deepLinkToSubscriptions: MutationField<\n 'deepLinkToSubscriptions'\n> = async () => unsupported('deepLinkToSubscriptions');\nexport const openRedeemOfferCodeAndroid: MutationField<\n 'openRedeemOfferCodeAndroid'\n> = async () => false;\n\nexport const promotedProductListenerIOS = (): EventSubscription => ({\n remove: () => {},\n});\nexport const userChoiceBillingListenerAndroid = (): EventSubscription => ({\n remove: () => {},\n});\nexport const developerProvidedBillingListenerAndroid =\n (): EventSubscription => ({\n remove: () => {},\n });\nexport const subscriptionBillingIssueListener = (): EventSubscription => ({\n remove: () => {},\n});\n\nexport const checkAlternativeBillingAvailabilityAndroid: MutationField<\n 'checkAlternativeBillingAvailabilityAndroid'\n> = async () => unsupported('checkAlternativeBillingAvailabilityAndroid');\nexport const showAlternativeBillingDialogAndroid: MutationField<\n 'showAlternativeBillingDialogAndroid'\n> = async () => unsupported('showAlternativeBillingDialogAndroid');\nexport const createAlternativeBillingTokenAndroid: MutationField<\n 'createAlternativeBillingTokenAndroid'\n> = async () => unsupported('createAlternativeBillingTokenAndroid');\nexport const isBillingProgramAvailableAndroid: MutationField<\n 'isBillingProgramAvailableAndroid'\n> = async () => unsupported('isBillingProgramAvailableAndroid');\nexport const getBillingChoiceInfoAndroid: QueryField<\n 'getBillingChoiceInfoAndroid'\n> = async () => unsupported('getBillingChoiceInfoAndroid');\nexport const launchExternalLinkAndroid: MutationField<\n 'launchExternalLinkAndroid'\n> = async () => unsupported('launchExternalLinkAndroid');\nexport const createBillingProgramReportingDetailsAndroid: MutationField<\n 'createBillingProgramReportingDetailsAndroid'\n> = async () => unsupported('createBillingProgramReportingDetailsAndroid');\nexport const showBillingProgramInformationDialogAndroid: MutationField<\n 'showBillingProgramInformationDialogAndroid'\n> = async () => unsupported('showBillingProgramInformationDialogAndroid');\nexport const showInAppMessagesAndroid: MutationField<\n 'showInAppMessagesAndroid'\n> = async () => unsupported('showInAppMessagesAndroid');\n"]}
|
|
1
|
+
{"version":3,"file":"index.kepler.js","sourceRoot":"","sources":["../src/index.kepler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,gBAAgB,EAAC,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAC,SAAS,EAAC,MAAM,SAAS,CAAC;AAalC,OAAO,EAAC,cAAc,EAAC,MAAM,qBAAqB,CAAC;AAEnD,cAAc,SAAS,CAAC;AACxB,cAAc,QAAQ,CAAC;AACvB,cAAc,UAAU,CAAC;AACzB,OAAO,EAAC,MAAM,EAAE,WAAW,EAAC,MAAM,WAAW,CAAC;AAiB9C,MAAM,CAAN,IAAY,YAOX;AAPD,WAAY,YAAY;IACtB,oDAAoC,CAAA;IACpC,gDAAgC,CAAA;IAChC,2DAA2C,CAAA;IAC3C,wEAAwD,CAAA;IACxD,sFAAsE,CAAA;IACtE,uEAAuD,CAAA;AACzD,CAAC,EAPW,YAAY,KAAZ,YAAY,QAOvB;AAUD,MAAM,oBAAoB,GACxB,iGAAiG,CAAC;AAMpG,MAAM,SAAS,GAAG,GAAG,EAAE;IACrB,MAAM,MAAM,GAAG,gBAAgB,EAAE,CAAC;IAClC,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CACb,+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AEpD,KAAK,IAAI,EAAE,CAAC,WAAW,CAAC,6CAA6C,CAAC,CAAC;AAC3E,MAAM,CAAC,MAAM,0CAA0C,GAEnD,KAAK,IAAI,EAAE,CAAC,WAAW,CAAC,4CAA4C,CAAC,CAAC;AAC1E,MAAM,CAAC,MAAM,wBAAwB,GAEjC,KAAK,IAAI,EAAE,CAAC,WAAW,CAAC,0BAA0B,CAAC,CAAC","sourcesContent":["import {getVegaIapModule} from './vega';\nimport {ErrorCode} from './types';\nimport type {\n MutationField,\n ProductQueryType,\n ProductRequest,\n Purchase,\n PurchaseError,\n PurchaseOptions,\n PurchaseUpdatedListenerOptions,\n QueryField,\n RequestPurchasePropsByPlatforms,\n RequestSubscriptionPropsByPlatforms,\n} from './types';\nimport {warnLegacyOnce} from './utils/deprecation';\n\nexport * from './types';\nexport * from './vega';\nexport * from './useIAP';\nexport {kitApi, KitApiError} from './kit-api';\nexport type {\n EntitlementsResponse,\n KitApiOptions,\n KitClientPayloadCache,\n KitClientPayloadOptions,\n KitClientPayloadResponse,\n KitProduct,\n KitProductClientPayload,\n KitProductOffer,\n KitProductPlatform,\n KitProductsOptions,\n KitProductsResponse,\n KitSubscription,\n StatusResponse,\n} from './kit-api';\n\nexport enum OpenIapEvent {\n PurchaseUpdated = 'purchase-updated',\n PurchaseError = 'purchase-error',\n PromotedProductIOS = 'promoted-product-ios',\n UserChoiceBillingAndroid = 'user-choice-billing-android',\n DeveloperProvidedBillingAndroid = 'developer-provided-billing-android',\n SubscriptionBillingIssue = 'subscription-billing-issue',\n}\n\n/**\n * Product type accepted by the Amazon Vega entry point.\n *\n * Compatibility note: the `'inapp'` member is deprecated. Use `'in-app'`\n * instead; the alias will be removed in expo-iap 5.0.0.\n */\nexport type ProductTypeInput = ProductQueryType | 'inapp';\n\nconst LEGACY_INAPP_WARNING =\n \"'inapp' product type is deprecated and will be removed in expo-iap 5.0.0. Use 'in-app' instead.\";\n\nexport interface EventSubscription {\n remove(): void;\n}\n\nconst getModule = () => {\n const module = getVegaIapModule();\n if (!module) {\n throw new Error(\n 'Amazon Vega IAP module is unavailable. Install @amazon-devices/keplerscript-appstore-iap-lib in the Vega app target and build with the React Native for Vega kepler platform.',\n );\n }\n return module;\n};\n\nconst unsupported = (feature: string): never => {\n throw new Error(`${feature} is not supported on Amazon Vega.`);\n};\n\nconst normalizeProductType = (\n type?: ProductTypeInput | null,\n): ProductQueryType => {\n if (type === 'subs' || type === 'all') return type;\n if (type === 'inapp') {\n warnLegacyOnce('product-type.inapp', LEGACY_INAPP_WARNING);\n }\n return 'in-app';\n};\n\nconst normalizePurchaseArray = (purchases: Purchase[]): Purchase[] =>\n purchases.map((purchase) => {\n const platform = String(purchase.platform).toLowerCase();\n if (platform === purchase.platform) return purchase;\n if (platform === 'android' || platform === 'ios') {\n return {...purchase, platform};\n }\n return purchase;\n });\n\nconst getAndroidRequest = (\n request?:\n | RequestPurchasePropsByPlatforms\n | RequestSubscriptionPropsByPlatforms\n | null,\n) => {\n if (\n request != null &&\n Object.prototype.hasOwnProperty.call(request, 'google')\n ) {\n return request.google;\n }\n if (\n request != null &&\n Object.prototype.hasOwnProperty.call(request, 'android')\n ) {\n warnLegacyOnce(\n 'request-purchase.android',\n '`request.android` is deprecated and will be removed in expo-iap 5.0.0. Use `request.google` instead.',\n );\n return request.android;\n }\n return undefined;\n};\n\nconst createPurchaseTokenError = (purchase: Purchase): Error => {\n const error = new Error(\n 'Purchase token is required to finish Amazon Vega transaction',\n ) as Error & PurchaseError;\n error.code = ErrorCode.DeveloperError;\n error.productId = purchase.productId;\n return error;\n};\n\nexport const emitter = {\n addListener(\n eventName: OpenIapEvent,\n listener: (payload: Purchase | PurchaseError) => void,\n ): EventSubscription {\n return getModule().addListener(eventName, listener);\n },\n removeListener(\n eventName: OpenIapEvent,\n listener: (payload: Purchase | PurchaseError) => void,\n ): void {\n return getModule().removeListener(eventName, listener);\n },\n};\n\nexport const purchaseUpdatedListener = (\n listener: (event: Purchase) => void,\n options?: PurchaseUpdatedListenerOptions | null,\n): EventSubscription => {\n return getModule().addListener(OpenIapEvent.PurchaseUpdated, (purchase) => {\n listener(purchase as Purchase);\n });\n};\n\nexport const purchaseErrorListener = (\n listener: (error: PurchaseError) => void,\n): EventSubscription => {\n return getModule().addListener(OpenIapEvent.PurchaseError, (error) => {\n listener(error as PurchaseError);\n });\n};\n\nexport const initConnection: MutationField<'initConnection'> = async (\n config,\n) => {\n return getModule().initConnection(config ?? null);\n};\n\nexport const endConnection: MutationField<'endConnection'> = async () => {\n return getModule().endConnection();\n};\n\nexport const fetchProducts = async (\n request: Omit<ProductRequest, 'type'> & {\n type?: ProductTypeInput | null;\n },\n): ReturnType<QueryField<'fetchProducts'>> => {\n const {skus, type} = request;\n return getModule().fetchProducts(normalizeProductType(type), skus);\n};\n\nexport const requestPurchase: MutationField<'requestPurchase'> = async (\n args,\n) => {\n const androidRequest = getAndroidRequest(args.request);\n if (!androidRequest?.skus?.length) {\n throw new Error(\n 'Invalid request for Amazon Vega. The `request.google.skus` or `request.android.skus` property is required and must be a non-empty array.',\n );\n }\n\n return normalizePurchaseArray(\n await getModule().requestPurchase({\n skuArr: androidRequest.skus,\n type: normalizeProductType(args.type),\n }),\n );\n};\n\nexport const getAvailablePurchases: QueryField<\n 'getAvailablePurchases'\n> = async (options) => {\n return normalizePurchaseArray(\n await getModule().getAvailableItems((options ?? {}) as PurchaseOptions),\n );\n};\n\nexport const finishTransaction: MutationField<'finishTransaction'> = async ({\n purchase,\n isConsumable = false,\n}) => {\n const token = purchase.purchaseToken ?? undefined;\n if (!token) {\n throw createPurchaseTokenError(purchase);\n }\n\n if (isConsumable) {\n await getModule().consumePurchaseAndroid(token);\n return;\n }\n\n await getModule().acknowledgePurchaseAndroid(token);\n};\n\nexport const restorePurchases: MutationField<'restorePurchases'> = async () => {\n await getAvailablePurchases({\n includeSuspendedAndroid: false,\n });\n};\n\nexport const getActiveSubscriptions: QueryField<\n 'getActiveSubscriptions'\n> = async (subscriptionIds) => {\n return getModule().getActiveSubscriptions(subscriptionIds ?? null);\n};\n\nexport const hasActiveSubscriptions: QueryField<\n 'hasActiveSubscriptions'\n> = async (subscriptionIds) => {\n return getModule().hasActiveSubscriptions(subscriptionIds ?? null);\n};\n\nexport const getStorefront: QueryField<'getStorefront'> = async () => {\n return getModule().getStorefront();\n};\n\nexport const verifyPurchaseWithProvider: MutationField<\n 'verifyPurchaseWithProvider'\n> = async (options) => {\n return getModule().verifyPurchaseWithProvider(options);\n};\n\n/**\n * @deprecated Use `verifyPurchase` instead. This compatibility operation will\n * be removed in expo-iap 5.0.0.\n */\nexport const validateReceipt: MutationField<'validateReceipt'> = async () =>\n unsupported('validateReceipt');\n\nexport const verifyPurchase: MutationField<'verifyPurchase'> = validateReceipt;\n\nexport const acknowledgePurchaseAndroid: MutationField<\n 'acknowledgePurchaseAndroid'\n> = async (purchaseToken) => {\n await getModule().acknowledgePurchaseAndroid(purchaseToken);\n return true;\n};\n\nexport const consumePurchaseAndroid: MutationField<\n 'consumePurchaseAndroid'\n> = async (purchaseToken) => {\n await getModule().consumePurchaseAndroid(purchaseToken);\n return true;\n};\n\n/**\n * @deprecated Use `acknowledgePurchaseAndroid` instead. This alias will be\n * removed in expo-iap 5.0.0.\n */\nexport const acknowledgePurchase = acknowledgePurchaseAndroid;\n\n/**\n * @deprecated Use `consumePurchaseAndroid` instead. This alias will be removed\n * in expo-iap 5.0.0.\n */\nexport const consumePurchase = consumePurchaseAndroid;\n\nexport const syncIOS: MutationField<'syncIOS'> = async () =>\n unsupported('syncIOS');\nexport const getAppTransactionIOS: QueryField<\n 'getAppTransactionIOS'\n> = async () => null;\nexport const getPromotedProductIOS: QueryField<\n 'getPromotedProductIOS'\n> = async () => null;\n\n/**\n * @deprecated Use `promotedProductListenerIOS` followed by `requestPurchase`\n * instead. This compatibility operation will be removed in expo-iap 5.0.0.\n */\nexport const requestPurchaseOnPromotedProductIOS = async (): Promise<boolean> =>\n unsupported('requestPurchaseOnPromotedProductIOS');\nexport const showManageSubscriptionsIOS: MutationField<\n 'showManageSubscriptionsIOS'\n> = async () => [];\nexport const presentCodeRedemptionSheetIOS: MutationField<\n 'presentCodeRedemptionSheetIOS'\n> = async () => false;\nexport const presentExternalPurchaseLinkIOS: MutationField<\n 'presentExternalPurchaseLinkIOS'\n> = async () => unsupported('presentExternalPurchaseLinkIOS');\n\nexport const deepLinkToSubscriptions: MutationField<\n 'deepLinkToSubscriptions'\n> = async () => unsupported('deepLinkToSubscriptions');\nexport const openRedeemOfferCodeAndroid: MutationField<\n 'openRedeemOfferCodeAndroid'\n> = async () => false;\n\nexport const promotedProductListenerIOS = (): EventSubscription => ({\n remove: () => {},\n});\nexport const userChoiceBillingListenerAndroid = (): EventSubscription => ({\n remove: () => {},\n});\nexport const developerProvidedBillingListenerAndroid =\n (): EventSubscription => ({\n remove: () => {},\n });\nexport const subscriptionBillingIssueListener = (): EventSubscription => ({\n remove: () => {},\n});\n\n/**\n * @deprecated Use `isBillingProgramAvailableAndroid('external-offer')`\n * instead. Scheduled for removal in expo-iap 5.0.0.\n */\nexport const checkAlternativeBillingAvailabilityAndroid: MutationField<\n 'checkAlternativeBillingAvailabilityAndroid'\n> = async () => unsupported('checkAlternativeBillingAvailabilityAndroid');\n\n/**\n * @deprecated Use `launchExternalLinkAndroid` instead. Scheduled for removal\n * in expo-iap 5.0.0.\n */\nexport const showAlternativeBillingDialogAndroid: MutationField<\n 'showAlternativeBillingDialogAndroid'\n> = async () => unsupported('showAlternativeBillingDialogAndroid');\n\n/**\n * @deprecated Use `createBillingProgramReportingDetailsAndroid` with the\n * external-offer program instead. Scheduled for removal in expo-iap 5.0.0.\n */\nexport const createAlternativeBillingTokenAndroid: MutationField<\n 'createAlternativeBillingTokenAndroid'\n> = async () => unsupported('createAlternativeBillingTokenAndroid');\nexport const isBillingProgramAvailableAndroid: MutationField<\n 'isBillingProgramAvailableAndroid'\n> = async () => unsupported('isBillingProgramAvailableAndroid');\nexport const getBillingChoiceInfoAndroid: QueryField<\n 'getBillingChoiceInfoAndroid'\n> = async () => unsupported('getBillingChoiceInfoAndroid');\nexport const launchExternalLinkAndroid: MutationField<\n 'launchExternalLinkAndroid'\n> = async () => unsupported('launchExternalLinkAndroid');\nexport const createBillingProgramReportingDetailsAndroid: MutationField<\n 'createBillingProgramReportingDetailsAndroid'\n> = async () => unsupported('createBillingProgramReportingDetailsAndroid');\nexport const showBillingProgramInformationDialogAndroid: MutationField<\n 'showBillingProgramInformationDialogAndroid'\n> = async () => unsupported('showBillingProgramInformationDialogAndroid');\nexport const showInAppMessagesAndroid: MutationField<\n 'showInAppMessagesAndroid'\n> = async () => unsupported('showInAppMessagesAndroid');\n"]}
|
package/build/kit-api.d.ts
CHANGED
|
@@ -2,6 +2,19 @@ export type KitApiOptions = {
|
|
|
2
2
|
apiKey: string;
|
|
3
3
|
baseUrl?: string;
|
|
4
4
|
fetchImpl?: (input: string, init?: RequestInit) => Promise<Response>;
|
|
5
|
+
/** Optional AsyncStorage-compatible persistent cache for direct client
|
|
6
|
+
* payload reads. Cache failures never change a successful API result. */
|
|
7
|
+
clientPayloadCache?: KitClientPayloadCache;
|
|
8
|
+
};
|
|
9
|
+
export type KitClientPayloadCache = {
|
|
10
|
+
getItem: (key: string) => Promise<string | null> | string | null;
|
|
11
|
+
setItem: (key: string, value: string) => Promise<void> | void;
|
|
12
|
+
removeItem?: (key: string) => Promise<void> | void;
|
|
13
|
+
};
|
|
14
|
+
export type KitClientPayloadOptions = {
|
|
15
|
+
/** Revalidate a cached payload with its scoped ETag. Without this flag,
|
|
16
|
+
* a valid persistent entry is returned without a network request. */
|
|
17
|
+
refresh?: boolean;
|
|
5
18
|
};
|
|
6
19
|
export type KitSubscription = {
|
|
7
20
|
id: string;
|
|
@@ -64,18 +77,15 @@ export type KitProductsOptions = {
|
|
|
64
77
|
platform?: KitProductPlatform;
|
|
65
78
|
/** Include public client payload bodies in a bounded platform page. */
|
|
66
79
|
includeClientPayload?: boolean;
|
|
67
|
-
/** Page size for
|
|
68
|
-
* Ignored by the legacy non-payload catalog path. */
|
|
80
|
+
/** Page size for every catalog read (default 25, maximum 50). */
|
|
69
81
|
limit?: number;
|
|
70
|
-
/** Opaque cursor returned as `nextCursor` by the previous
|
|
71
|
-
* Ignored by the legacy non-payload catalog path. */
|
|
82
|
+
/** Opaque cursor returned as `nextCursor` by the previous page. */
|
|
72
83
|
cursor?: string;
|
|
73
84
|
};
|
|
74
85
|
export type KitProductsResponse = {
|
|
75
86
|
products: KitProduct[];
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
/** Present when a payload-inclusive catalog page has another page. */
|
|
87
|
+
hasMore: boolean;
|
|
88
|
+
/** Present when a catalog page has another page. */
|
|
79
89
|
nextCursor?: string;
|
|
80
90
|
};
|
|
81
91
|
export type KitClientPayloadResponse = {
|
|
@@ -102,7 +112,7 @@ export declare function kitApi(options: KitApiOptions): {
|
|
|
102
112
|
products: (productOptions?: KitProductsOptions) => Promise<KitProductsResponse>;
|
|
103
113
|
/** GET one public client payload by its store-specific natural key.
|
|
104
114
|
* Payloads are app-facing data; never store secrets in them. */
|
|
105
|
-
clientPayload: (productId: string, platform: KitProductPlatform) => Promise<KitClientPayloadResponse>;
|
|
115
|
+
clientPayload: (productId: string, platform: KitProductPlatform, payloadOptions?: KitClientPayloadOptions) => Promise<KitClientPayloadResponse>;
|
|
106
116
|
/** POST /v1/subscriptions/bind-user — call after a successful
|
|
107
117
|
* verifyReceipt so kit knows which userId owns the verified
|
|
108
118
|
* `purchaseToken`. Idempotent. */
|
package/build/kit-api.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kit-api.d.ts","sourceRoot":"","sources":["../src/kit-api.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,aAAa,GAAG;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IAGjB,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WA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,kBAAkB;IAgC7C;oEACgE;+BAEnD,MAAM,YACP,kBAAkB,mBACZ,uBAAuB;IAkCzC;;sCAEkC;8BACR,MAAM,UAAU,MAAM;YACnC,OAAO;eAAS,OAAO;;EAQvC"}
|
package/build/kit-api.js
CHANGED
|
@@ -84,7 +84,7 @@ export function kitApi(options) {
|
|
|
84
84
|
}
|
|
85
85
|
throw new Error("kitApi requires a fetch implementation. Pass `fetchImpl` for runtimes without a global fetch.");
|
|
86
86
|
})();
|
|
87
|
-
async function
|
|
87
|
+
async function request(path, init) {
|
|
88
88
|
// Normalize headers without depending on a global `Headers`
|
|
89
89
|
// constructor: older React Native runtimes ship `fetch` (or a
|
|
90
90
|
// polyfill via `fetchImpl`) without exposing `Headers` globally.
|
|
@@ -101,10 +101,12 @@ export function kitApi(options) {
|
|
|
101
101
|
// already-stripped `baseUrl` (PR #124
|
|
102
102
|
// (https://github.com/hyodotdev/openiap/pull/124) review).
|
|
103
103
|
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
104
|
-
|
|
104
|
+
return fetchImpl(`${baseUrl}${normalizedPath}`, {
|
|
105
105
|
...init,
|
|
106
106
|
headers,
|
|
107
107
|
});
|
|
108
|
+
}
|
|
109
|
+
async function parseResponse(response, path) {
|
|
108
110
|
const text = await response.text();
|
|
109
111
|
// Empty body normalizes to null so callers expecting JSON
|
|
110
112
|
// (status / entitlements / list*) don't get a truthy ""
|
|
@@ -134,6 +136,62 @@ export function kitApi(options) {
|
|
|
134
136
|
}
|
|
135
137
|
return parsed;
|
|
136
138
|
}
|
|
139
|
+
async function call(path, init) {
|
|
140
|
+
return parseResponse(await request(path, init), path);
|
|
141
|
+
}
|
|
142
|
+
function clientPayloadCacheKey(productId, platform) {
|
|
143
|
+
return [
|
|
144
|
+
"iapkit-client-payload-v1",
|
|
145
|
+
baseUrl,
|
|
146
|
+
options.apiKey,
|
|
147
|
+
platform,
|
|
148
|
+
productId,
|
|
149
|
+
]
|
|
150
|
+
.map(encodeURIComponent)
|
|
151
|
+
.join(":");
|
|
152
|
+
}
|
|
153
|
+
async function readCachedClientPayload(cacheKey) {
|
|
154
|
+
if (!options.clientPayloadCache)
|
|
155
|
+
return null;
|
|
156
|
+
try {
|
|
157
|
+
const raw = await options.clientPayloadCache.getItem(cacheKey);
|
|
158
|
+
if (!raw)
|
|
159
|
+
return null;
|
|
160
|
+
const candidate = JSON.parse(raw);
|
|
161
|
+
const payload = candidate.clientPayload;
|
|
162
|
+
if (!payload ||
|
|
163
|
+
!["toml", "json", "text"].includes(payload.format) ||
|
|
164
|
+
typeof payload.body !== "string" ||
|
|
165
|
+
!Number.isSafeInteger(payload.version) ||
|
|
166
|
+
payload.version < 1 ||
|
|
167
|
+
typeof payload.updatedAt !== "number" ||
|
|
168
|
+
(candidate.etag !== undefined && typeof candidate.etag !== "string")) {
|
|
169
|
+
await options.clientPayloadCache.removeItem?.(cacheKey);
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
return candidate;
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async function writeCachedClientPayload(cacheKey, value) {
|
|
179
|
+
try {
|
|
180
|
+
await options.clientPayloadCache?.setItem(cacheKey, JSON.stringify(value));
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
// Persistence is an optimization. A device storage failure must not
|
|
184
|
+
// turn a successful IAPKit read into an application error.
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
async function removeCachedClientPayload(cacheKey) {
|
|
188
|
+
try {
|
|
189
|
+
await options.clientPayloadCache?.removeItem?.(cacheKey);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
// See writeCachedClientPayload: cache maintenance is best effort.
|
|
193
|
+
}
|
|
194
|
+
}
|
|
137
195
|
return {
|
|
138
196
|
apiKey: options.apiKey,
|
|
139
197
|
baseUrl,
|
|
@@ -171,7 +229,36 @@ export function kitApi(options) {
|
|
|
171
229
|
},
|
|
172
230
|
/** GET one public client payload by its store-specific natural key.
|
|
173
231
|
* Payloads are app-facing data; never store secrets in them. */
|
|
174
|
-
clientPayload: (productId, platform
|
|
232
|
+
clientPayload: async (productId, platform, payloadOptions = {}) => {
|
|
233
|
+
const path = `/v1/products/${encodeURIComponent(options.apiKey)}/${encodeURIComponent(productId)}/client-payload?platform=${encodeURIComponent(platform)}`;
|
|
234
|
+
const cacheKey = clientPayloadCacheKey(productId, platform);
|
|
235
|
+
const cached = await readCachedClientPayload(cacheKey);
|
|
236
|
+
if (cached && payloadOptions.refresh !== true) {
|
|
237
|
+
return { clientPayload: cached.clientPayload };
|
|
238
|
+
}
|
|
239
|
+
const response = await request(path, {
|
|
240
|
+
...(cached?.etag ? { headers: { "If-None-Match": cached.etag } } : {}),
|
|
241
|
+
});
|
|
242
|
+
if (response.status === 304 && cached) {
|
|
243
|
+
return { clientPayload: cached.clientPayload };
|
|
244
|
+
}
|
|
245
|
+
try {
|
|
246
|
+
const result = await parseResponse(response, path);
|
|
247
|
+
await writeCachedClientPayload(cacheKey, {
|
|
248
|
+
...result,
|
|
249
|
+
...(response.headers.get("etag")
|
|
250
|
+
? { etag: response.headers.get("etag") }
|
|
251
|
+
: {}),
|
|
252
|
+
});
|
|
253
|
+
return result;
|
|
254
|
+
}
|
|
255
|
+
catch (error) {
|
|
256
|
+
if (error instanceof KitApiError && error.status === 404) {
|
|
257
|
+
await removeCachedClientPayload(cacheKey);
|
|
258
|
+
}
|
|
259
|
+
throw error;
|
|
260
|
+
}
|
|
261
|
+
},
|
|
175
262
|
/** POST /v1/subscriptions/bind-user — call after a successful
|
|
176
263
|
* verifyReceipt so kit knows which userId owns the verified
|
|
177
264
|
* `purchaseToken`. Idempotent. */
|
package/build/kit-api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kit-api.js","sourceRoot":"","sources":["../src/kit-api.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,oEAAoE;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Aa,EAAE,CAAC,SAAiB,EAAE,QAA4B,EAAE,EAAE,CACjE,IAAI,CACF,gBAAgB,kBAAkB,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,kBAAkB,CAAC,SAAS,CAAC,4BAA4B,kBAAkB,CAAC,QAAQ,CAAC,EAAE,CAC9I;QAEH;;0CAEkC;QAClC,QAAQ,EAAE,CAAC,aAAqB,EAAE,MAAc,EAAE,EAAE,CAClD,IAAI,CACF,+BAA+B,kBAAkB,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,EACnE;YACE,MAAM,EAAE,MAAM;YACd,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,aAAa,EAAE,MAAM,EAAE,CAAC;SAChD,CACF;KACJ,CAAC;AACJ,CAAC","sourcesContent":["// Tiny fetch wrapper around kit's `/v1` HTTP surface for use by the JS\n// SDK consumers (react-native-iap + expo-iap). Mirrors the shape of\n// `packages/mcp-server/src/kit-client.ts` so the same operations are\n// reachable from both LLM tools and end-user apps without each\n// duplicating the URL layout.\n\nexport type KitApiOptions = {\n apiKey: string;\n baseUrl?: string;\n // Optional fetch override for runtimes without a global (older RN\n // builds) or for injection in tests.\n fetchImpl?: (input: string, init?: RequestInit) => Promise<Response>;\n};\n\nexport type KitSubscription = {\n id: string;\n productId: string;\n platform: \"IOS\" | \"Android\";\n state: string;\n expiresAt?: number;\n renewsAt?: number;\n willRenew?: boolean;\n cancellationReason?: string;\n currency?: string;\n priceAmountMicros?: number;\n startedAt: number;\n updatedAt: number;\n purchaseToken: string;\n userId?: string;\n};\n\nexport type EntitlementsResponse = {\n userId: string;\n productIds: string[];\n subscriptions: KitSubscription[];\n};\n\nexport type StatusResponse = {\n active: boolean;\n subscription: KitSubscription | null;\n};\n\nexport type KitProductPlatform = \"IOS\" | \"Android\";\n\nexport type KitProductClientPayload = {\n format: \"toml\" | \"json\" | \"text\";\n body: string;\n version: number;\n updatedAt: number;\n};\n\nexport type KitProductOffer = {\n id: string;\n kind:\n | \"FreeTrial\"\n | \"IntroPayUpFront\"\n | \"IntroPayAsYouGo\"\n | \"PromotionalOffer\"\n | \"BasePlan\";\n duration?: string;\n numberOfPeriods?: number;\n priceAmountMicros?: number;\n currency?: string;\n};\n\nexport type KitProduct = {\n productId: string;\n platform: KitProductPlatform;\n type: \"Subscription\" | \"NonConsumable\" | \"Consumable\";\n title: string;\n description?: string;\n priceAmountMicros?: number;\n currency?: string;\n state: \"Draft\" | \"Ready\" | \"Active\" | \"Removed\";\n storeRef?: string;\n subscriptionGroupId?: string;\n subscriptionGroupName?: string;\n billingPeriod?: \"P1W\" | \"P1M\" | \"P2M\" | \"P3M\" | \"P6M\" | \"P1Y\";\n offers?: KitProductOffer[];\n updatedAt: number;\n clientPayload?: KitProductClientPayload;\n};\n\nexport type KitProductsOptions = {\n platform?: KitProductPlatform;\n /** Include public client payload bodies in a bounded platform page. */\n includeClientPayload?: boolean;\n /** Page size for payload-inclusive reads (default 25, maximum 50).\n * Ignored by the legacy non-payload catalog path. */\n limit?: number;\n /** Opaque cursor returned as `nextCursor` by the previous payload page.\n * Ignored by the legacy non-payload catalog path. */\n cursor?: string;\n};\n\nexport type KitProductsResponse = {\n products: KitProduct[];\n /** Present on payload-inclusive catalog pages. */\n hasMore?: boolean;\n /** Present when a payload-inclusive catalog page has another page. */\n nextCursor?: string;\n};\n\nexport type KitClientPayloadResponse = {\n clientPayload: KitProductClientPayload;\n};\n\nconst DEFAULT_BASE_URL = \"https://kit.openiap.dev\";\n\n// Merge caller-supplied headers with kit defaults (`accept`,\n// optionally `content-type`). When the runtime exposes a global\n// `Headers` constructor we use it directly so callers passing a\n// `Headers` instance (a `HeadersInit`) keep that exact instance's\n// values. When `Headers` is missing — older React Native builds where\n// the operator wires up `fetchImpl` without a `Headers` polyfill —\n// we fall back to a case-insensitive merge into a plain record so\n// the request still goes through. Either way, caller-set values take\n// precedence over kit defaults.\nfunction mergeHeaders(\n callerHeaders: HeadersInit | undefined,\n hasBody: boolean,\n): HeadersInit {\n if (typeof Headers === \"function\") {\n const merged = new Headers(callerHeaders);\n if (!merged.has(\"accept\")) merged.set(\"accept\", \"application/json\");\n if (hasBody && !merged.has(\"content-type\")) {\n merged.set(\"content-type\", \"application/json\");\n }\n return merged;\n }\n // Plain-object fallback path. Build a case-insensitive name map\n // from whatever the caller passed (Headers-shaped, array-of-pairs,\n // or plain record) and re-emit as a record `fetchImpl` accepts.\n const lower = new Map<string, { name: string; value: string }>();\n const setIfAbsent = (name: string, value: string) => {\n const key = name.toLowerCase();\n if (!lower.has(key)) lower.set(key, { name, value });\n };\n const setForce = (name: string, value: string) => {\n const key = name.toLowerCase();\n lower.set(key, { name, value });\n };\n if (callerHeaders) {\n if (Array.isArray(callerHeaders)) {\n for (const [name, value] of callerHeaders) setForce(name, value);\n } else if (\n typeof (callerHeaders as { forEach?: unknown }).forEach === \"function\"\n ) {\n // `Headers`-like (without being our `typeof Headers === \"function\"`\n // global). RN polyfills sometimes attach `Headers` only to\n // request/response instances rather than the global scope.\n // Standard signature is `forEach((value, key, parent))`; we\n // bind the first two positionally so a polyfill that omits\n // the third argument still works. `key` is the header name.\n (\n callerHeaders as {\n forEach: (cb: (value: string, key: string) => void) => void;\n }\n ).forEach((value, key) => setForce(key, value));\n } else {\n for (const [name, value] of Object.entries(\n callerHeaders as Record<string, string>,\n )) {\n setForce(name, value);\n }\n }\n }\n setIfAbsent(\"accept\", \"application/json\");\n if (hasBody) setIfAbsent(\"content-type\", \"application/json\");\n const out: Record<string, string> = {};\n for (const { name, value } of lower.values()) out[name] = value;\n return out;\n}\n\nexport class KitApiError extends Error {\n constructor(\n readonly status: number,\n readonly body: unknown,\n message: string,\n ) {\n super(message);\n this.name = \"KitApiError\";\n }\n}\n\nexport function kitApi(options: KitApiOptions) {\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\");\n const fetchImpl: (input: string, init?: RequestInit) => Promise<Response> =\n (() => {\n if (options.fetchImpl) return options.fetchImpl;\n if (typeof fetch === \"function\") {\n return (input: string, init?: RequestInit) => fetch(input, init);\n }\n throw new Error(\n \"kitApi requires a fetch implementation. Pass `fetchImpl` for runtimes without a global fetch.\",\n );\n })();\n\n async function call<T>(path: string, init?: RequestInit): Promise<T> {\n // Normalize headers without depending on a global `Headers`\n // constructor: older React Native runtimes ship `fetch` (or a\n // polyfill via `fetchImpl`) without exposing `Headers` globally.\n // The prior implementation crashed before the first request on\n // those runtimes. We use `new Headers()` when available (preserves\n // caller-supplied `Headers` instances exactly), and otherwise fall\n // back to a small case-insensitive merge into a plain record.\n // Either way, kit defaults only apply when the caller hasn't set\n // the same name.\n const headers = mergeHeaders(init?.headers, init?.body != null);\n // Prepend a leading slash if `path` is missing one. Today's\n // call sites all hard-code the leading \"/\", but normalizing here\n // makes the helper safe for future additions and matches the\n // already-stripped `baseUrl` (PR #124\n // (https://github.com/hyodotdev/openiap/pull/124) review).\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n const response = await fetchImpl(`${baseUrl}${normalizedPath}`, {\n ...init,\n headers,\n });\n const text = await response.text();\n // Empty body normalizes to null so callers expecting JSON\n // (status / entitlements / list*) don't get a truthy \"\"\n // and crash on property access.\n let parsed: unknown = null;\n let parseError: unknown = null;\n if (text) {\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n // Non-JSON body (a misconfigured proxy returning HTML, a\n // CDN-injected error page, etc.) on a 2xx response would\n // otherwise reach the caller as `parsed = text` and crash\n // on property access via `parsed as T`. Throw a structured\n // KitApiError instead so callers see a typed failure.\n parseError = error;\n }\n }\n if (!response.ok) {\n // Surface the raw body (text or parsed) on the error path so\n // operators can read the upstream error message verbatim.\n throw new KitApiError(\n response.status,\n parsed ?? text,\n `kit ${path} returned ${response.status}`,\n );\n }\n if (parseError) {\n throw new KitApiError(\n response.status,\n text,\n `kit ${path} returned a non-JSON ${response.status} body (${\n parseError instanceof Error ? parseError.message : String(parseError)\n })`,\n );\n }\n return parsed as T;\n }\n\n return {\n apiKey: options.apiKey,\n baseUrl,\n\n /** GET /v1/subscriptions/status — the `active` boolean is the\n * fastest gate for \"is this user paying?\". */\n status: (userId: string) =>\n call<StatusResponse>(\n `/v1/subscriptions/status/${encodeURIComponent(options.apiKey)}?userId=${encodeURIComponent(userId)}`,\n ),\n\n /** GET /v1/subscriptions/entitlements — every productId the user\n * is entitled to. Use this when feature gating depends on which\n * specific tier the user owns. */\n entitlements: (userId: string) =>\n call<EntitlementsResponse>(\n `/v1/subscriptions/entitlements/${encodeURIComponent(options.apiKey)}?userId=${encodeURIComponent(userId)}`,\n ),\n\n /** GET /v1/products — read the store-synced catalog. Client payloads\n * are excluded unless explicitly requested because they may add up to\n * 16 KiB per product. */\n products: (productOptions: KitProductsOptions = {}) => {\n if (\n productOptions.includeClientPayload === true &&\n !productOptions.platform\n ) {\n throw new Error(\n \"kitApi.products requires platform when includeClientPayload is true\",\n );\n }\n const query = new URLSearchParams();\n if (productOptions.platform) {\n query.set(\"platform\", productOptions.platform);\n }\n if (productOptions.includeClientPayload !== undefined) {\n query.set(\n \"includeClientPayload\",\n String(productOptions.includeClientPayload),\n );\n }\n if (productOptions.limit !== undefined) {\n query.set(\"limit\", String(productOptions.limit));\n }\n if (productOptions.cursor !== undefined) {\n query.set(\"cursor\", productOptions.cursor);\n }\n const encodedQuery = query.toString();\n const suffix = encodedQuery ? `?${encodedQuery}` : \"\";\n return call<KitProductsResponse>(\n `/v1/products/${encodeURIComponent(options.apiKey)}${suffix}`,\n );\n },\n\n /** GET one public client payload by its store-specific natural key.\n * Payloads are app-facing data; never store secrets in them. */\n clientPayload: (productId: string, platform: KitProductPlatform) =>\n call<KitClientPayloadResponse>(\n `/v1/products/${encodeURIComponent(options.apiKey)}/${encodeURIComponent(productId)}/client-payload?platform=${encodeURIComponent(platform)}`,\n ),\n\n /** POST /v1/subscriptions/bind-user — call after a successful\n * verifyReceipt so kit knows which userId owns the verified\n * `purchaseToken`. Idempotent. */\n bindUser: (purchaseToken: string, userId: string) =>\n call<{ ok: boolean; bound: boolean }>(\n `/v1/subscriptions/bind-user/${encodeURIComponent(options.apiKey)}`,\n {\n method: \"POST\",\n body: JSON.stringify({ purchaseToken, userId }),\n },\n ),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"kit-api.js","sourceRoot":"","sources":["../src/kit-api.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,oEAAoE;AACpE,qEAAqE;AACrE,+DAA+D;AAC/D,8BAA8B;AAuH9B,MAAM,gBAAgB,GAAG,yBAAyB,CAAC;AAEnD,6DAA6D;AAC7D,gEAAgE;AAChE,gEAAgE;AAChE,kEAAkE;AAClE,sEAAsE;AACtE,mEAAmE;AACnE,kEAAkE;AAClE,qEAAqE;AACrE,gCAAgC;AAChC,SAAS,YAAY,CACnB,aAAsC,EACtC,OAAgB;IAEhB,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE,CAAC;QAClC,MAAM,MAAM,GAAG,IAAI,OAAO,CAAC,aAAa,CAAC,CAAC;QAC1C,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;YAAE,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,kBAAkB,CAAC,CAAC;QACpE,IAAI,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,EAAE,CAAC;YAC3C,MAAM,CAAC,GAAG,CAAC,cAAc,EAAE,kBAAkB,CAAC,CAAC;QACjD,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,gEAAgE;IAChE,mEAAmE;IACnE,gEAAgE;IAChE,MAAM,KAAK,GAAG,IAAI,GAAG,EAA2C,CAAC;IACjE,MAAM,WAAW,GAAG,CAAC,IAAY,EAAE,KAAa,EAAE,EAAE;QAClD,MAAM,GAAG,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QAC/B,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC;YAAE,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,IAAI,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,CAAC,MAAM,CAAC,EAAE,EACnE;YACE,MAAM,EAAE,MAAM;YACd,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,aAAa,EAAE,MAAM,EAAE,CAAC;SAChD,CACF;KACJ,CAAC;AACJ,CAAC","sourcesContent":["// Tiny fetch wrapper around kit's `/v1` HTTP surface for use by the JS\n// SDK consumers (react-native-iap + expo-iap). Mirrors the shape of\n// `packages/mcp-server/src/kit-client.ts` so the same operations are\n// reachable from both LLM tools and end-user apps without each\n// duplicating the URL layout.\n\nexport type KitApiOptions = {\n apiKey: string;\n baseUrl?: string;\n // Optional fetch override for runtimes without a global (older RN\n // builds) or for injection in tests.\n fetchImpl?: (input: string, init?: RequestInit) => Promise<Response>;\n /** Optional AsyncStorage-compatible persistent cache for direct client\n * payload reads. Cache failures never change a successful API result. */\n clientPayloadCache?: KitClientPayloadCache;\n};\n\nexport type KitClientPayloadCache = {\n getItem: (key: string) => Promise<string | null> | string | null;\n setItem: (key: string, value: string) => Promise<void> | void;\n removeItem?: (key: string) => Promise<void> | void;\n};\n\nexport type KitClientPayloadOptions = {\n /** Revalidate a cached payload with its scoped ETag. Without this flag,\n * a valid persistent entry is returned without a network request. */\n refresh?: boolean;\n};\n\nexport type KitSubscription = {\n id: string;\n productId: string;\n platform: \"IOS\" | \"Android\";\n state: string;\n expiresAt?: number;\n renewsAt?: number;\n willRenew?: boolean;\n cancellationReason?: string;\n currency?: string;\n priceAmountMicros?: number;\n startedAt: number;\n updatedAt: number;\n purchaseToken: string;\n userId?: string;\n};\n\nexport type EntitlementsResponse = {\n userId: string;\n productIds: string[];\n subscriptions: KitSubscription[];\n};\n\nexport type StatusResponse = {\n active: boolean;\n subscription: KitSubscription | null;\n};\n\nexport type KitProductPlatform = \"IOS\" | \"Android\";\n\nexport type KitProductClientPayload = {\n format: \"toml\" | \"json\" | \"text\";\n body: string;\n version: number;\n updatedAt: number;\n};\n\nexport type KitProductOffer = {\n id: string;\n kind:\n | \"FreeTrial\"\n | \"IntroPayUpFront\"\n | \"IntroPayAsYouGo\"\n | \"PromotionalOffer\"\n | \"BasePlan\";\n duration?: string;\n numberOfPeriods?: number;\n priceAmountMicros?: number;\n currency?: string;\n};\n\nexport type KitProduct = {\n productId: string;\n platform: KitProductPlatform;\n type: \"Subscription\" | \"NonConsumable\" | \"Consumable\";\n title: string;\n description?: string;\n priceAmountMicros?: number;\n currency?: string;\n state: \"Draft\" | \"Ready\" | \"Active\" | \"Removed\";\n storeRef?: string;\n subscriptionGroupId?: string;\n subscriptionGroupName?: string;\n billingPeriod?: \"P1W\" | \"P1M\" | \"P2M\" | \"P3M\" | \"P6M\" | \"P1Y\";\n offers?: KitProductOffer[];\n updatedAt: number;\n clientPayload?: KitProductClientPayload;\n};\n\nexport type KitProductsOptions = {\n platform?: KitProductPlatform;\n /** Include public client payload bodies in a bounded platform page. */\n includeClientPayload?: boolean;\n /** Page size for every catalog read (default 25, maximum 50). */\n limit?: number;\n /** Opaque cursor returned as `nextCursor` by the previous page. */\n cursor?: string;\n};\n\nexport type KitProductsResponse = {\n products: KitProduct[];\n hasMore: boolean;\n /** Present when a catalog page has another page. */\n nextCursor?: string;\n};\n\nexport type KitClientPayloadResponse = {\n clientPayload: KitProductClientPayload;\n};\n\ntype CachedClientPayload = KitClientPayloadResponse & {\n etag?: string;\n};\n\nconst DEFAULT_BASE_URL = \"https://kit.openiap.dev\";\n\n// Merge caller-supplied headers with kit defaults (`accept`,\n// optionally `content-type`). When the runtime exposes a global\n// `Headers` constructor we use it directly so callers passing a\n// `Headers` instance (a `HeadersInit`) keep that exact instance's\n// values. When `Headers` is missing — older React Native builds where\n// the operator wires up `fetchImpl` without a `Headers` polyfill —\n// we fall back to a case-insensitive merge into a plain record so\n// the request still goes through. Either way, caller-set values take\n// precedence over kit defaults.\nfunction mergeHeaders(\n callerHeaders: HeadersInit | undefined,\n hasBody: boolean,\n): HeadersInit {\n if (typeof Headers === \"function\") {\n const merged = new Headers(callerHeaders);\n if (!merged.has(\"accept\")) merged.set(\"accept\", \"application/json\");\n if (hasBody && !merged.has(\"content-type\")) {\n merged.set(\"content-type\", \"application/json\");\n }\n return merged;\n }\n // Plain-object fallback path. Build a case-insensitive name map\n // from whatever the caller passed (Headers-shaped, array-of-pairs,\n // or plain record) and re-emit as a record `fetchImpl` accepts.\n const lower = new Map<string, { name: string; value: string }>();\n const setIfAbsent = (name: string, value: string) => {\n const key = name.toLowerCase();\n if (!lower.has(key)) lower.set(key, { name, value });\n };\n const setForce = (name: string, value: string) => {\n const key = name.toLowerCase();\n lower.set(key, { name, value });\n };\n if (callerHeaders) {\n if (Array.isArray(callerHeaders)) {\n for (const [name, value] of callerHeaders) setForce(name, value);\n } else if (\n typeof (callerHeaders as { forEach?: unknown }).forEach === \"function\"\n ) {\n // `Headers`-like (without being our `typeof Headers === \"function\"`\n // global). RN polyfills sometimes attach `Headers` only to\n // request/response instances rather than the global scope.\n // Standard signature is `forEach((value, key, parent))`; we\n // bind the first two positionally so a polyfill that omits\n // the third argument still works. `key` is the header name.\n (\n callerHeaders as {\n forEach: (cb: (value: string, key: string) => void) => void;\n }\n ).forEach((value, key) => setForce(key, value));\n } else {\n for (const [name, value] of Object.entries(\n callerHeaders as Record<string, string>,\n )) {\n setForce(name, value);\n }\n }\n }\n setIfAbsent(\"accept\", \"application/json\");\n if (hasBody) setIfAbsent(\"content-type\", \"application/json\");\n const out: Record<string, string> = {};\n for (const { name, value } of lower.values()) out[name] = value;\n return out;\n}\n\nexport class KitApiError extends Error {\n constructor(\n readonly status: number,\n readonly body: unknown,\n message: string,\n ) {\n super(message);\n this.name = \"KitApiError\";\n }\n}\n\nexport function kitApi(options: KitApiOptions) {\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\");\n const fetchImpl: (input: string, init?: RequestInit) => Promise<Response> =\n (() => {\n if (options.fetchImpl) return options.fetchImpl;\n if (typeof fetch === \"function\") {\n return (input: string, init?: RequestInit) => fetch(input, init);\n }\n throw new Error(\n \"kitApi requires a fetch implementation. Pass `fetchImpl` for runtimes without a global fetch.\",\n );\n })();\n\n async function request(path: string, init?: RequestInit): Promise<Response> {\n // Normalize headers without depending on a global `Headers`\n // constructor: older React Native runtimes ship `fetch` (or a\n // polyfill via `fetchImpl`) without exposing `Headers` globally.\n // The prior implementation crashed before the first request on\n // those runtimes. We use `new Headers()` when available (preserves\n // caller-supplied `Headers` instances exactly), and otherwise fall\n // back to a small case-insensitive merge into a plain record.\n // Either way, kit defaults only apply when the caller hasn't set\n // the same name.\n const headers = mergeHeaders(init?.headers, init?.body != null);\n // Prepend a leading slash if `path` is missing one. Today's\n // call sites all hard-code the leading \"/\", but normalizing here\n // makes the helper safe for future additions and matches the\n // already-stripped `baseUrl` (PR #124\n // (https://github.com/hyodotdev/openiap/pull/124) review).\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n return fetchImpl(`${baseUrl}${normalizedPath}`, {\n ...init,\n headers,\n });\n }\n\n async function parseResponse<T>(\n response: Response,\n path: string,\n ): Promise<T> {\n const text = await response.text();\n // Empty body normalizes to null so callers expecting JSON\n // (status / entitlements / list*) don't get a truthy \"\"\n // and crash on property access.\n let parsed: unknown = null;\n let parseError: unknown = null;\n if (text) {\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n // Non-JSON body (a misconfigured proxy returning HTML, a\n // CDN-injected error page, etc.) on a 2xx response would\n // otherwise reach the caller as `parsed = text` and crash\n // on property access via `parsed as T`. Throw a structured\n // KitApiError instead so callers see a typed failure.\n parseError = error;\n }\n }\n if (!response.ok) {\n // Surface the raw body (text or parsed) on the error path so\n // operators can read the upstream error message verbatim.\n throw new KitApiError(\n response.status,\n parsed ?? text,\n `kit ${path} returned ${response.status}`,\n );\n }\n if (parseError) {\n throw new KitApiError(\n response.status,\n text,\n `kit ${path} returned a non-JSON ${response.status} body (${\n parseError instanceof Error ? parseError.message : String(parseError)\n })`,\n );\n }\n return parsed as T;\n }\n\n async function call<T>(path: string, init?: RequestInit): Promise<T> {\n return parseResponse<T>(await request(path, init), path);\n }\n\n function clientPayloadCacheKey(\n productId: string,\n platform: KitProductPlatform,\n ): string {\n return [\n \"iapkit-client-payload-v1\",\n baseUrl,\n options.apiKey,\n platform,\n productId,\n ]\n .map(encodeURIComponent)\n .join(\":\");\n }\n\n async function readCachedClientPayload(\n cacheKey: string,\n ): Promise<CachedClientPayload | null> {\n if (!options.clientPayloadCache) return null;\n try {\n const raw = await options.clientPayloadCache.getItem(cacheKey);\n if (!raw) return null;\n const candidate = JSON.parse(raw) as Partial<CachedClientPayload>;\n const payload = candidate.clientPayload;\n if (\n !payload ||\n ![\"toml\", \"json\", \"text\"].includes(payload.format) ||\n typeof payload.body !== \"string\" ||\n !Number.isSafeInteger(payload.version) ||\n payload.version < 1 ||\n typeof payload.updatedAt !== \"number\" ||\n (candidate.etag !== undefined && typeof candidate.etag !== \"string\")\n ) {\n await options.clientPayloadCache.removeItem?.(cacheKey);\n return null;\n }\n return candidate as CachedClientPayload;\n } catch {\n return null;\n }\n }\n\n async function writeCachedClientPayload(\n cacheKey: string,\n value: CachedClientPayload,\n ): Promise<void> {\n try {\n await options.clientPayloadCache?.setItem(\n cacheKey,\n JSON.stringify(value),\n );\n } catch {\n // Persistence is an optimization. A device storage failure must not\n // turn a successful IAPKit read into an application error.\n }\n }\n\n async function removeCachedClientPayload(cacheKey: string): Promise<void> {\n try {\n await options.clientPayloadCache?.removeItem?.(cacheKey);\n } catch {\n // See writeCachedClientPayload: cache maintenance is best effort.\n }\n }\n\n return {\n apiKey: options.apiKey,\n baseUrl,\n\n /** GET /v1/subscriptions/status — the `active` boolean is the\n * fastest gate for \"is this user paying?\". */\n status: (userId: string) =>\n call<StatusResponse>(\n `/v1/subscriptions/status/${encodeURIComponent(options.apiKey)}?userId=${encodeURIComponent(userId)}`,\n ),\n\n /** GET /v1/subscriptions/entitlements — every productId the user\n * is entitled to. Use this when feature gating depends on which\n * specific tier the user owns. */\n entitlements: (userId: string) =>\n call<EntitlementsResponse>(\n `/v1/subscriptions/entitlements/${encodeURIComponent(options.apiKey)}?userId=${encodeURIComponent(userId)}`,\n ),\n\n /** GET /v1/products — read the store-synced catalog. Client payloads\n * are excluded unless explicitly requested because they may add up to\n * 16 KiB per product. */\n products: (productOptions: KitProductsOptions = {}) => {\n if (\n productOptions.includeClientPayload === true &&\n !productOptions.platform\n ) {\n throw new Error(\n \"kitApi.products requires platform when includeClientPayload is true\",\n );\n }\n const query = new URLSearchParams();\n if (productOptions.platform) {\n query.set(\"platform\", productOptions.platform);\n }\n if (productOptions.includeClientPayload !== undefined) {\n query.set(\n \"includeClientPayload\",\n String(productOptions.includeClientPayload),\n );\n }\n if (productOptions.limit !== undefined) {\n query.set(\"limit\", String(productOptions.limit));\n }\n if (productOptions.cursor !== undefined) {\n query.set(\"cursor\", productOptions.cursor);\n }\n const encodedQuery = query.toString();\n const suffix = encodedQuery ? `?${encodedQuery}` : \"\";\n return call<KitProductsResponse>(\n `/v1/products/${encodeURIComponent(options.apiKey)}${suffix}`,\n );\n },\n\n /** GET one public client payload by its store-specific natural key.\n * Payloads are app-facing data; never store secrets in them. */\n clientPayload: async (\n productId: string,\n platform: KitProductPlatform,\n payloadOptions: KitClientPayloadOptions = {},\n ) => {\n const path = `/v1/products/${encodeURIComponent(options.apiKey)}/${encodeURIComponent(productId)}/client-payload?platform=${encodeURIComponent(platform)}`;\n const cacheKey = clientPayloadCacheKey(productId, platform);\n const cached = await readCachedClientPayload(cacheKey);\n if (cached && payloadOptions.refresh !== true) {\n return { clientPayload: cached.clientPayload };\n }\n const response = await request(path, {\n ...(cached?.etag ? { headers: { \"If-None-Match\": cached.etag } } : {}),\n });\n if (response.status === 304 && cached) {\n return { clientPayload: cached.clientPayload };\n }\n try {\n const result = await parseResponse<KitClientPayloadResponse>(\n response,\n path,\n );\n await writeCachedClientPayload(cacheKey, {\n ...result,\n ...(response.headers.get(\"etag\")\n ? { etag: response.headers.get(\"etag\")! }\n : {}),\n });\n return result;\n } catch (error) {\n if (error instanceof KitApiError && error.status === 404) {\n await removeCachedClientPayload(cacheKey);\n }\n throw error;\n }\n },\n\n /** POST /v1/subscriptions/bind-user — call after a successful\n * verifyReceipt so kit knows which userId owns the verified\n * `purchaseToken`. Idempotent. */\n bindUser: (purchaseToken: string, userId: string) =>\n call<{ ok: boolean; bound: boolean }>(\n `/v1/subscriptions/bind-user/${encodeURIComponent(options.apiKey)}`,\n {\n method: \"POST\",\n body: JSON.stringify({ purchaseToken, userId }),\n },\n ),\n };\n}\n"]}
|
|
@@ -25,7 +25,8 @@ export declare const deepLinkToSubscriptionsAndroid: (options?: DeepLinkOptions
|
|
|
25
25
|
* your access token in the binary you ship to users is potentially dangerous.
|
|
26
26
|
* Use server side validation instead for your production builds
|
|
27
27
|
*
|
|
28
|
-
* @deprecated Use verifyPurchase instead
|
|
28
|
+
* @deprecated Use verifyPurchase instead. This function will be removed in
|
|
29
|
+
* expo-iap 5.0.0.
|
|
29
30
|
* @param {Object} params - The parameters object
|
|
30
31
|
* @param {string} params.packageName - package name of your app.
|
|
31
32
|
* @param {string} params.productId - product id for your in app product.
|
|
@@ -90,6 +91,8 @@ export declare const openRedeemOfferCodeAndroid: MutationField<'openRedeemOfferC
|
|
|
90
91
|
* ```
|
|
91
92
|
*
|
|
92
93
|
* @see {@link https://openiap.dev/docs/apis/android/check-alternative-billing-availability-android}
|
|
94
|
+
* @deprecated Use `isBillingProgramAvailableAndroid('external-offer')`
|
|
95
|
+
* instead. Scheduled for removal in expo-iap 5.0.0.
|
|
93
96
|
*/
|
|
94
97
|
export declare const checkAlternativeBillingAvailabilityAndroid: MutationField<'checkAlternativeBillingAvailabilityAndroid'>;
|
|
95
98
|
/**
|
|
@@ -117,6 +120,8 @@ export declare const checkAlternativeBillingAvailabilityAndroid: MutationField<'
|
|
|
117
120
|
* ```
|
|
118
121
|
*
|
|
119
122
|
* @see {@link https://openiap.dev/docs/apis/android/show-alternative-billing-dialog-android}
|
|
123
|
+
* @deprecated Use `launchExternalLinkAndroid` instead. Scheduled for removal
|
|
124
|
+
* in expo-iap 5.0.0.
|
|
120
125
|
*/
|
|
121
126
|
export declare const showAlternativeBillingDialogAndroid: MutationField<'showAlternativeBillingDialogAndroid'>;
|
|
122
127
|
/**
|
|
@@ -144,6 +149,9 @@ export declare const showAlternativeBillingDialogAndroid: MutationField<'showAlt
|
|
|
144
149
|
* ```
|
|
145
150
|
*
|
|
146
151
|
* @see {@link https://openiap.dev/docs/apis/android/create-alternative-billing-token-android}
|
|
152
|
+
* @deprecated Use
|
|
153
|
+
* `createBillingProgramReportingDetailsAndroid('external-offer')` instead.
|
|
154
|
+
* Scheduled for removal in expo-iap 5.0.0.
|
|
147
155
|
*/
|
|
148
156
|
export declare const createAlternativeBillingTokenAndroid: MutationField<'createAlternativeBillingTokenAndroid'>;
|
|
149
157
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"android.d.ts","sourceRoot":"","sources":["../../src/modules/android.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAEV,qBAAqB,EAErB,qCAAqC,EAErC,eAAe,EACf,2BAA2B,EAI3B,uDAAuD,EACvD,aAAa,EACb,UAAU,EACV,2BAA2B,EAC5B,MAAM,UAAU,CAAC;AA2BlB,wBAAgB,gBAAgB,CAAC,CAAC,SAAS;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAC,EAC5D,IAAI,EAAE,OAAO,GACZ,IAAI,IAAI,CAAC,GAAG;IAAC,QAAQ,EAAE,SAAS,CAAA;CAAC,CAQnC;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,8BAA8B,GACzC,UAAU,eAAe,GAAG,IAAI,KAC/B,OAAO,CAAC,IAAI,CAuBd,CAAC;AAEF
|
|
1
|
+
{"version":3,"file":"android.d.ts","sourceRoot":"","sources":["../../src/modules/android.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAEV,qBAAqB,EAErB,qCAAqC,EAErC,eAAe,EACf,2BAA2B,EAI3B,u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;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,gCAAgC,EAAE,aAAa,CAC1D,kCAAkC,CAInC,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,2BAA2B,EAAE,UAAU,CAClD,6BAA6B,CAW9B,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,yBAAyB,EAAE,aAAa,CACnD,2BAA2B,CAI5B,CAAC;AAiCF,wBAAgB,2CAA2C,CACzD,IAAI,EAAE,uDAAuD,GAC5D,OAAO,CAAC,qCAAqC,CAAC,CAAC;AAClD,wBAAgB,2CAA2C,CACzD,OAAO,EAAE,qBAAqB,EAC9B,oBAAoB,CAAC,EAAE,2BAA2B,GAAG,IAAI,GACxD,OAAO,CAAC,qCAAqC,CAAC,CAAC;AAclD;;;;;;;;;GASG;AACH,eAAO,MAAM,0CAA0C,EAAE,aAAa,CACpE,4CAA4C,CAS7C,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,wBAAwB,EAAE,aAAa,CAClD,0BAA0B,CAM3B,CAAC"}
|
package/build/modules/android.js
CHANGED
|
@@ -63,7 +63,8 @@ export const deepLinkToSubscriptionsAndroid = async (options) => {
|
|
|
63
63
|
* your access token in the binary you ship to users is potentially dangerous.
|
|
64
64
|
* Use server side validation instead for your production builds
|
|
65
65
|
*
|
|
66
|
-
* @deprecated Use verifyPurchase instead
|
|
66
|
+
* @deprecated Use verifyPurchase instead. This function will be removed in
|
|
67
|
+
* expo-iap 5.0.0.
|
|
67
68
|
* @param {Object} params - The parameters object
|
|
68
69
|
* @param {string} params.packageName - package name of your app.
|
|
69
70
|
* @param {string} params.productId - product id for your in app product.
|
|
@@ -178,6 +179,8 @@ export const openRedeemOfferCodeAndroid = async () => {
|
|
|
178
179
|
* ```
|
|
179
180
|
*
|
|
180
181
|
* @see {@link https://openiap.dev/docs/apis/android/check-alternative-billing-availability-android}
|
|
182
|
+
* @deprecated Use `isBillingProgramAvailableAndroid('external-offer')`
|
|
183
|
+
* instead. Scheduled for removal in expo-iap 5.0.0.
|
|
181
184
|
*/
|
|
182
185
|
export const checkAlternativeBillingAvailabilityAndroid = async () => {
|
|
183
186
|
requireAndroidPlatform('checkAlternativeBillingAvailabilityAndroid');
|
|
@@ -208,6 +211,8 @@ export const checkAlternativeBillingAvailabilityAndroid = async () => {
|
|
|
208
211
|
* ```
|
|
209
212
|
*
|
|
210
213
|
* @see {@link https://openiap.dev/docs/apis/android/show-alternative-billing-dialog-android}
|
|
214
|
+
* @deprecated Use `launchExternalLinkAndroid` instead. Scheduled for removal
|
|
215
|
+
* in expo-iap 5.0.0.
|
|
211
216
|
*/
|
|
212
217
|
export const showAlternativeBillingDialogAndroid = async () => {
|
|
213
218
|
requireAndroidPlatform('showAlternativeBillingDialogAndroid');
|
|
@@ -238,6 +243,9 @@ export const showAlternativeBillingDialogAndroid = async () => {
|
|
|
238
243
|
* ```
|
|
239
244
|
*
|
|
240
245
|
* @see {@link https://openiap.dev/docs/apis/android/create-alternative-billing-token-android}
|
|
246
|
+
* @deprecated Use
|
|
247
|
+
* `createBillingProgramReportingDetailsAndroid('external-offer')` instead.
|
|
248
|
+
* Scheduled for removal in expo-iap 5.0.0.
|
|
241
249
|
*/
|
|
242
250
|
export const createAlternativeBillingTokenAndroid = async (sku) => {
|
|
243
251
|
requireAndroidPlatform('createAlternativeBillingTokenAndroid');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"android.js","sourceRoot":"","sources":["../../src/modules/android.ts"],"names":[],"mappings":"AAAA,wBAAwB;AACxB,OAAO,EAAC,OAAO,EAAE,QAAQ,EAAC,MAAM,cAAc,CAAC;AAE/C,mBAAmB;AACnB,OAAO,aAAa,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAC,QAAQ,EAAC,MAAM,SAAS,CAAC;AA4BjC,MAAM,mBAAmB,GAAG,aAAoC,CAAC;AAEjE;;;;;;;GAOG;AACH,MAAM,sBAAsB,GAAG,CA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I,CAAC,CAAC;AAChE,CAAC,CAAC","sourcesContent":["// External dependencies\nimport {Linking, Platform} from 'react-native';\n\n// Internal modules\nimport ExpoIapModule from '../ExpoIapModule';\nimport {isVegaOS} from '../vega';\n\n// Types\nimport type {\n BillingChoiceInfoAndroid,\n BillingProgramAndroid,\n BillingProgramInformationDialogParamsAndroid,\n BillingProgramReportingDetailsAndroid,\n BillingResultAndroid,\n DeepLinkOptions,\n DeveloperBillingTypeAndroid,\n GetBillingChoiceInfoParamsAndroid,\n InAppMessageParamsAndroid,\n InAppMessageResultAndroid,\n MutationCreateBillingProgramReportingDetailsAndroidArgs,\n MutationField,\n QueryField,\n VerifyPurchaseResultAndroid,\n} from '../types';\n\ntype NativeAndroidModule = {\n deepLinkToSubscriptionsAndroid?: (params: {\n skuAndroid?: string;\n packageNameAndroid?: string;\n }) => Promise<void> | void;\n getStorefront?: () => Promise<string> | string;\n};\n\nconst nativeAndroidModule = ExpoIapModule as NativeAndroidModule;\n\n/**\n * Enforce the documented Android-only contract. Vega OS is treated as an\n * Android store runtime (matching `isAndroidStoreRuntime` in src/index.ts),\n * so it passes through. Without this guard, calling a suffixed wrapper on\n * another platform falls through to the native proxy and surfaces as an\n * opaque `TypeError: ExpoIapModule.<name> is not a function` instead of the\n * promised platform error.\n */\nconst requireAndroidPlatform = (methodName: string): void => {\n if (Platform.OS !== 'android' && !isVegaOS()) {\n throw new Error(`${methodName} is only available on Android and Vega OS`);\n }\n};\n\n// Type guards\nexport function isProductAndroid<T extends {platform?: string}>(\n item: unknown,\n): item is T & {platform: 'android'} {\n return (\n item != null &&\n typeof item === 'object' &&\n 'platform' in item &&\n typeof (item as any).platform === 'string' &&\n (item as any).platform.toLowerCase() === 'android'\n );\n}\n\n/**\n * Deep link to subscriptions screen on Android.\n * @param {Object} params - The parameters object\n * @param {string} params.skuAndroid - The product's SKU (on Android)\n * @param {string} params.packageNameAndroid - The package name of your Android app (e.g., 'com.example.app')\n * @returns {Promise<void>}\n *\n * @example\n * ```typescript\n * await deepLinkToSubscriptionsAndroid({\n * skuAndroid: 'subscription_id',\n * packageNameAndroid: 'com.example.app'\n * });\n * ```\n */\nexport const deepLinkToSubscriptionsAndroid = async (\n options?: DeepLinkOptions | null,\n): Promise<void> => {\n const sku = options?.skuAndroid ?? undefined;\n const packageName = options?.packageNameAndroid ?? undefined;\n\n // Prefer native deep link implementation via OpenIAP module\n if (nativeAndroidModule?.deepLinkToSubscriptionsAndroid) {\n return nativeAndroidModule.deepLinkToSubscriptionsAndroid({\n skuAndroid: sku,\n packageNameAndroid: packageName,\n });\n }\n\n // Fallback to Linking if native method unavailable\n if (!packageName) {\n throw new Error(\n 'packageName is required for deepLinkToSubscriptionsAndroid',\n );\n }\n const base = `https://play.google.com/store/account/subscriptions?package=${encodeURIComponent(\n packageName,\n )}`;\n const url = sku ? `${base}&sku=${encodeURIComponent(sku)}` : base;\n return Linking.openURL(url);\n};\n\n/**\n * Validate receipt for Android. NOTE: This method is here for debugging purposes only. Including\n * your access token in the binary you ship to users is potentially dangerous.\n * Use server side validation instead for your production builds\n *\n * @deprecated Use verifyPurchase instead\n * @param {Object} params - The parameters object\n * @param {string} params.packageName - package name of your app.\n * @param {string} params.productId - product id for your in app product.\n * @param {string} params.productToken - token for your purchase (called 'token' in the API documentation).\n * @param {string} params.accessToken - OAuth access token with androidpublisher scope. Required for authentication.\n * @param {boolean} params.isSub - whether this is subscription or in-app. `true` for subscription.\n * @returns {Promise<ReceiptAndroid>}\n */\nexport const validateReceiptAndroid = async ({\n packageName,\n productId,\n productToken,\n accessToken,\n isSub,\n}: {\n packageName: string;\n productId: string;\n productToken: string;\n accessToken: string;\n isSub?: boolean;\n}): Promise<VerifyPurchaseResultAndroid> => {\n const type = isSub ? 'subscriptions' : 'products';\n\n const url =\n 'https://androidpublisher.googleapis.com/androidpublisher/v3/applications' +\n `/${packageName}/purchases/${type}/${productId}` +\n `/tokens/${productToken}`;\n\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n });\n\n if (!response.ok) {\n throw Object.assign(new Error(response.statusText), {\n statusCode: response.status,\n });\n }\n\n return response.json();\n};\n\n/**\n * Consume a purchase token so the user can purchase the same product again\n * (Android consumable products). Prefer using `finishTransaction` with\n * `isConsumable: true`, which dispatches to this under the hood.\n *\n * @see {@link https://openiap.dev/docs/apis/android/consume-purchase-android}\n */\nexport const consumePurchaseAndroid: MutationField<\n 'consumePurchaseAndroid'\n> = async (purchaseToken) => {\n requireAndroidPlatform('consumePurchaseAndroid');\n const result = await ExpoIapModule.consumePurchaseAndroid(purchaseToken);\n\n if (typeof result === 'boolean') {\n return result;\n }\n\n if (result && typeof result === 'object') {\n const record = result as Record<string, unknown>;\n if (typeof record.success === 'boolean') {\n return record.success;\n }\n if (typeof record.responseCode === 'number') {\n return record.responseCode === 0;\n }\n }\n\n throw new Error(\n `consumePurchaseAndroid returned an unexpected response payload: ${JSON.stringify(\n result,\n )}`,\n );\n};\n\n/**\n * Acknowledge a non-consumable purchase or subscription (Android only).\n * @param {Object} params - The parameters object\n * @param {string} params.token - The product's token (on Android)\n * @returns {Promise<VoidResult | void>}\n * @throws Error if called on a non-Android platform\n *\n * @see {@link https://openiap.dev/docs/apis/android/acknowledge-purchase-android}\n */\nexport const acknowledgePurchaseAndroid: MutationField<\n 'acknowledgePurchaseAndroid'\n> = async (purchaseToken) => {\n requireAndroidPlatform('acknowledgePurchaseAndroid');\n const result = await ExpoIapModule.acknowledgePurchaseAndroid(purchaseToken);\n\n if (typeof result === 'boolean') {\n return result;\n }\n\n if (result && typeof result === 'object') {\n const record = result as Record<string, unknown>;\n if (typeof record.success === 'boolean') {\n return record.success;\n }\n if (typeof record.responseCode === 'number') {\n return record.responseCode === 0;\n }\n }\n\n return true;\n};\n\n/**\n * Open the Google Play offer/promo code redemption flow so the user can enter a code (Android only).\n * On Play builds, launches the Play Store redeem page. A listener can receive\n * the purchase while the app has an active billing connection; reconcile\n * available purchases when the app resumes. Unsupported store flavors return false.\n * Does not require the billing client to be initialized (no Play Billing version requirement).\n * Android counterpart of presentCodeRedemptionSheetIOS.\n *\n * @returns Promise resolving to true when launched, or false when unsupported\n *\n * @see {@link https://openiap.dev/docs/apis/android/open-redeem-offer-code-android}\n */\nexport const openRedeemOfferCodeAndroid: MutationField<\n 'openRedeemOfferCodeAndroid'\n> = async () => {\n requireAndroidPlatform('openRedeemOfferCodeAndroid');\n if (isVegaOS()) {\n return false;\n }\n return ExpoIapModule.openRedeemOfferCodeAndroid();\n};\n\n/**\n * Check if alternative billing is available for this user/device (Android only).\n * Step 1 of alternative billing flow.\n *\n * Returns true if available, false otherwise.\n * Throws OpenIapError.NotPrepared if billing client not ready.\n *\n * @returns {Promise<boolean>}\n *\n * @example\n * ```typescript\n * const isAvailable = await checkAlternativeBillingAvailabilityAndroid();\n * if (isAvailable) {\n * // Proceed with alternative billing flow\n * }\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/android/check-alternative-billing-availability-android}\n */\nexport const checkAlternativeBillingAvailabilityAndroid: MutationField<\n 'checkAlternativeBillingAvailabilityAndroid'\n> = async () => {\n requireAndroidPlatform('checkAlternativeBillingAvailabilityAndroid');\n return ExpoIapModule.checkAlternativeBillingAvailabilityAndroid();\n};\n\n/**\n * Show alternative billing information dialog to user (Android only).\n * Step 2 of alternative billing flow.\n * Must be called BEFORE processing payment in your payment system.\n *\n * Returns true if user accepted, false if user canceled.\n * Throws OpenIapError.NotPrepared if billing client not ready.\n *\n * @returns {Promise<boolean>}\n *\n * @example\n * ```typescript\n * const userAccepted = await showAlternativeBillingDialogAndroid();\n * if (userAccepted) {\n * // Process payment in your payment system\n * const success = await processCustomPayment();\n * if (success) {\n * // Create reporting token\n * const token = await createAlternativeBillingTokenAndroid();\n * // Send token to your backend for Google Play reporting\n * }\n * }\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/android/show-alternative-billing-dialog-android}\n */\nexport const showAlternativeBillingDialogAndroid: MutationField<\n 'showAlternativeBillingDialogAndroid'\n> = async () => {\n requireAndroidPlatform('showAlternativeBillingDialogAndroid');\n return ExpoIapModule.showAlternativeBillingDialogAndroid();\n};\n\n/**\n * Create external transaction token for Google Play reporting (Android only).\n * Step 3 of alternative billing flow.\n * Must be called AFTER successful payment in your payment system.\n * Token must be reported to Google Play backend within 24 hours.\n *\n * Returns token string, or null if creation failed.\n * Throws OpenIapError.NotPrepared if billing client not ready.\n *\n * @param {string} sku - The product SKU that was purchased\n * @returns {Promise<string | null>}\n *\n * @example\n * ```typescript\n * const token = await createAlternativeBillingTokenAndroid('premium_subscription');\n * if (token) {\n * // Send token to your backend\n * await fetch('/api/report-transaction', {\n * method: 'POST',\n * body: JSON.stringify({ token, sku: 'premium_subscription' })\n * });\n * }\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/android/create-alternative-billing-token-android}\n */\nexport const createAlternativeBillingTokenAndroid: MutationField<\n 'createAlternativeBillingTokenAndroid'\n> = async (sku?: string) => {\n requireAndroidPlatform('createAlternativeBillingTokenAndroid');\n return ExpoIapModule.createAlternativeBillingTokenAndroid(sku);\n};\n\n// ============================================================================\n// Billing Programs API (Google Play Billing Library 8.2.0+)\n// ============================================================================\n\n/**\n * Check if a specific billing program is available for this user/device (Android only).\n * Available in Google Play Billing Library 8.2.0+. Billing Choice availability\n * details, including the configured renderer and external-link support, require 9.1.0+.\n *\n * @param program - The billing program to check\n * @returns Promise resolving to availability result\n *\n * @example\n * ```typescript\n * const result = await isBillingProgramAvailableAndroid('external-offer');\n * if (result.isAvailable) {\n * // Proceed with billing program flow\n * }\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/android/is-billing-program-available-android}\n */\nexport const isBillingProgramAvailableAndroid: MutationField<\n 'isBillingProgramAvailableAndroid'\n> = async (program) => {\n requireAndroidPlatform('isBillingProgramAvailableAndroid');\n return ExpoIapModule.isBillingProgramAvailableAndroid(program);\n};\n\n/**\n * Fetch Play Billing assets and loyalty text for developer-rendered Billing Choice screens.\n * Available in Google Play Billing Library 9.1.0+.\n *\n * @param params - Billing Choice info request parameters\n * @returns Promise resolving to Play Billing Choice display information\n *\n * @see {@link https://openiap.dev/docs/apis/android/get-billing-choice-info-android}\n */\nexport const getBillingChoiceInfoAndroid: QueryField<\n 'getBillingChoiceInfoAndroid'\n> = async (\n params: GetBillingChoiceInfoParamsAndroid = {},\n): Promise<BillingChoiceInfoAndroid> => {\n requireAndroidPlatform('getBillingChoiceInfoAndroid');\n return ExpoIapModule.getBillingChoiceInfoAndroid({\n billingProgram: params.billingProgram ?? 'billing-choice',\n playBillingChoiceImageLayout:\n params.playBillingChoiceImageLayout ?? 'rectangular-four-by-one',\n userLocale: params.userLocale ?? null,\n });\n};\n\n/**\n * Launch an external link for the specified billing program (Android only).\n * Available in Google Play Billing Library 8.2.0+; developer-rendered Billing\n * Choice external-link flows require 9.1.0+ and `externalTransactionToken`.\n *\n * @param params - The external link parameters\n * @returns Promise resolving to true if the link was launched successfully\n *\n * @example\n * ```typescript\n * await launchExternalLinkAndroid({\n * billingProgram: 'billing-choice',\n * externalTransactionToken: 'pre-generated-token',\n * launchMode: 'launch-in-external-browser-or-app',\n * linkType: 'link-to-digital-content-offer',\n * linkUri: 'https://your-payment-site.com',\n * });\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/android/launch-external-link-android}\n */\nexport const launchExternalLinkAndroid: MutationField<\n 'launchExternalLinkAndroid'\n> = async (params) => {\n requireAndroidPlatform('launchExternalLinkAndroid');\n return ExpoIapModule.launchExternalLinkAndroid(params);\n};\n\n/**\n * Create billing program reporting details for Google Play reporting (Android only).\n * Available in Google Play Billing Library 8.2.0+.\n *\n * Must be called AFTER successful payment in your payment system.\n * Token must be reported to Google Play backend within 24 hours.\n *\n * @param program - The billing program type\n * @returns Promise resolving to reporting details including the external transaction token\n *\n * @example\n * ```typescript\n * const details = await createBillingProgramReportingDetailsAndroid('external-offer');\n * // Report details.externalTransactionToken to Google Play within 24 hours\n * await reportToGooglePlay(details.externalTransactionToken);\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/android/create-billing-program-reporting-details-android}\n */\nconst createBillingProgramReportingDetailsAndroidField: MutationField<\n 'createBillingProgramReportingDetailsAndroid'\n> = async (\n args: MutationCreateBillingProgramReportingDetailsAndroidArgs,\n): Promise<BillingProgramReportingDetailsAndroid> => {\n requireAndroidPlatform('createBillingProgramReportingDetailsAndroid');\n return ExpoIapModule.createBillingProgramReportingDetailsAndroid(\n args.program,\n args.developerBillingType ?? null,\n );\n};\n\nexport function createBillingProgramReportingDetailsAndroid(\n args: MutationCreateBillingProgramReportingDetailsAndroidArgs,\n): Promise<BillingProgramReportingDetailsAndroid>;\nexport function createBillingProgramReportingDetailsAndroid(\n program: BillingProgramAndroid,\n developerBillingType?: DeveloperBillingTypeAndroid | null,\n): Promise<BillingProgramReportingDetailsAndroid>;\nexport function createBillingProgramReportingDetailsAndroid(\n programOrArgs:\n | BillingProgramAndroid\n | MutationCreateBillingProgramReportingDetailsAndroidArgs,\n developerBillingType?: DeveloperBillingTypeAndroid | null,\n): Promise<BillingProgramReportingDetailsAndroid> {\n const args =\n typeof programOrArgs === 'string'\n ? {program: programOrArgs, developerBillingType}\n : programOrArgs;\n return createBillingProgramReportingDetailsAndroidField(args);\n}\n\n/**\n * Show Google's mandatory information dialog before a developer-rendered,\n * in-app Billing Choice screen.\n * Available in Google Play Billing Library 9.1.0+.\n *\n * @param params - Dialog parameters with the external transaction token\n * @returns Promise resolving to BillingResult\n *\n * @see {@link https://openiap.dev/docs/apis/android/show-billing-program-information-dialog-android}\n */\nexport const showBillingProgramInformationDialogAndroid: MutationField<\n 'showBillingProgramInformationDialogAndroid'\n> = async (\n params: BillingProgramInformationDialogParamsAndroid,\n): Promise<BillingResultAndroid> => {\n requireAndroidPlatform('showBillingProgramInformationDialogAndroid');\n return ExpoIapModule.showBillingProgramInformationDialogAndroid({\n billingProgram: params.billingProgram ?? 'billing-choice',\n externalTransactionToken: params.externalTransactionToken,\n });\n};\n\n/**\n * Show Play Billing in-app messages, such as transactional subscription updates.\n * Available in Google Play Billing Library 4.1.0+.\n *\n * @param params - Optional in-app message categories\n * @returns Promise resolving to in-app message result\n *\n * @see {@link https://openiap.dev/docs/apis/android/show-in-app-messages-android}\n */\nexport const showInAppMessagesAndroid: MutationField<\n 'showInAppMessagesAndroid'\n> = async (\n params?: InAppMessageParamsAndroid | null,\n): Promise<InAppMessageResultAndroid> => {\n requireAndroidPlatform('showInAppMessagesAndroid');\n return ExpoIapModule.showInAppMessagesAndroid(params ?? null);\n};\n"]}
|
|
1
|
+
{"version":3,"file":"android.js","sourceRoot":"","sources":["../../src/modules/android.ts"],"names":[],"mappings":"AAAA,wBAAwB;AACxB,OAAO,EAAC,OAAO,EAAE,QAAQ,EAAC,MAAM,cAAc,CAAC;AAE/C,mBAAmB;AACnB,OAAO,aAAa,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAC,QAAQ,EAAC,MAAM,SAAS,CAAC;AA4BjC,MAAM,mBAAmB,GAAG,aAAoC,CAAC;AAEjE;;;;;;;GAOG;AACH,MAAM,sBAAsB,GAAG,CAAC,UAAkB,EAAQ,EAAE;IAC1D,IAAI,QAAQ,CAAC,EAAE,KAAK,SAAS,IAAI,CAAC,QAAQ,EAAE,EAAE,CAAC;QAC7C,MAAM,IAAI,KAAK,CAAC,GAAG,UAAU,2CAA2C,CAAC,CAAC;IAC5E,CAAC;AACH,CAAC,CAAC;AAEF,cAAc;AACd,MAAM,UAAU,gBAAgB,CAC9B,IAAa;IAEb,OAAO,CACL,IAAI,IAAI,IAAI;QACZ,OAAO,IAAI,KAAK,QAAQ;QACxB,UAAU,IAAI,IAAI;QAClB,OAAQ,IAAY,CAAC,QAAQ,KAAK,QAAQ;QACzC,IAAY,CAAC,QAAQ,CAAC,WAAW,EAAE,KAAK,SAAS,CACnD,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,KAAK,EACjD,OA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2D,EAC3D,oBAAyD;IAEzD,MAAM,IAAI,GACR,OAAO,aAAa,KAAK,QAAQ;QAC/B,CAAC,CAAC,EAAC,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAAC;QAChD,CAAC,CAAC,aAAa,CAAC;IACpB,OAAO,gDAAgD,CAAC,IAAI,CAAC,CAAC;AAChE,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,0CAA0C,GAEnD,KAAK,EACP,MAAoD,EACrB,EAAE;IACjC,sBAAsB,CAAC,4CAA4C,CAAC,CAAC;IACrE,OAAO,aAAa,CAAC,0CAA0C,CAAC;QAC9D,cAAc,EAAE,MAAM,CAAC,cAAc,IAAI,gBAAgB;QACzD,wBAAwB,EAAE,MAAM,CAAC,wBAAwB;KAC1D,CAAC,CAAC;AACL,CAAC,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAEjC,KAAK,EACP,MAAyC,EACL,EAAE;IACtC,sBAAsB,CAAC,0BAA0B,CAAC,CAAC;IACnD,OAAO,aAAa,CAAC,wBAAwB,CAAC,MAAM,IAAI,IAAI,CAAC,CAAC;AAChE,CAAC,CAAC","sourcesContent":["// External dependencies\nimport {Linking, Platform} from 'react-native';\n\n// Internal modules\nimport ExpoIapModule from '../ExpoIapModule';\nimport {isVegaOS} from '../vega';\n\n// Types\nimport type {\n BillingChoiceInfoAndroid,\n BillingProgramAndroid,\n BillingProgramInformationDialogParamsAndroid,\n BillingProgramReportingDetailsAndroid,\n BillingResultAndroid,\n DeepLinkOptions,\n DeveloperBillingTypeAndroid,\n GetBillingChoiceInfoParamsAndroid,\n InAppMessageParamsAndroid,\n InAppMessageResultAndroid,\n MutationCreateBillingProgramReportingDetailsAndroidArgs,\n MutationField,\n QueryField,\n VerifyPurchaseResultAndroid,\n} from '../types';\n\ntype NativeAndroidModule = {\n deepLinkToSubscriptionsAndroid?: (params: {\n skuAndroid?: string;\n packageNameAndroid?: string;\n }) => Promise<void> | void;\n getStorefront?: () => Promise<string> | string;\n};\n\nconst nativeAndroidModule = ExpoIapModule as NativeAndroidModule;\n\n/**\n * Enforce the documented Android-only contract. Vega OS is treated as an\n * Android store runtime (matching `isAndroidStoreRuntime` in src/index.ts),\n * so it passes through. Without this guard, calling a suffixed wrapper on\n * another platform falls through to the native proxy and surfaces as an\n * opaque `TypeError: ExpoIapModule.<name> is not a function` instead of the\n * promised platform error.\n */\nconst requireAndroidPlatform = (methodName: string): void => {\n if (Platform.OS !== 'android' && !isVegaOS()) {\n throw new Error(`${methodName} is only available on Android and Vega OS`);\n }\n};\n\n// Type guards\nexport function isProductAndroid<T extends {platform?: string}>(\n item: unknown,\n): item is T & {platform: 'android'} {\n return (\n item != null &&\n typeof item === 'object' &&\n 'platform' in item &&\n typeof (item as any).platform === 'string' &&\n (item as any).platform.toLowerCase() === 'android'\n );\n}\n\n/**\n * Deep link to subscriptions screen on Android.\n * @param {Object} params - The parameters object\n * @param {string} params.skuAndroid - The product's SKU (on Android)\n * @param {string} params.packageNameAndroid - The package name of your Android app (e.g., 'com.example.app')\n * @returns {Promise<void>}\n *\n * @example\n * ```typescript\n * await deepLinkToSubscriptionsAndroid({\n * skuAndroid: 'subscription_id',\n * packageNameAndroid: 'com.example.app'\n * });\n * ```\n */\nexport const deepLinkToSubscriptionsAndroid = async (\n options?: DeepLinkOptions | null,\n): Promise<void> => {\n const sku = options?.skuAndroid ?? undefined;\n const packageName = options?.packageNameAndroid ?? undefined;\n\n // Prefer native deep link implementation via OpenIAP module\n if (nativeAndroidModule?.deepLinkToSubscriptionsAndroid) {\n return nativeAndroidModule.deepLinkToSubscriptionsAndroid({\n skuAndroid: sku,\n packageNameAndroid: packageName,\n });\n }\n\n // Fallback to Linking if native method unavailable\n if (!packageName) {\n throw new Error(\n 'packageName is required for deepLinkToSubscriptionsAndroid',\n );\n }\n const base = `https://play.google.com/store/account/subscriptions?package=${encodeURIComponent(\n packageName,\n )}`;\n const url = sku ? `${base}&sku=${encodeURIComponent(sku)}` : base;\n return Linking.openURL(url);\n};\n\n/**\n * Validate receipt for Android. NOTE: This method is here for debugging purposes only. Including\n * your access token in the binary you ship to users is potentially dangerous.\n * Use server side validation instead for your production builds\n *\n * @deprecated Use verifyPurchase instead. This function will be removed in\n * expo-iap 5.0.0.\n * @param {Object} params - The parameters object\n * @param {string} params.packageName - package name of your app.\n * @param {string} params.productId - product id for your in app product.\n * @param {string} params.productToken - token for your purchase (called 'token' in the API documentation).\n * @param {string} params.accessToken - OAuth access token with androidpublisher scope. Required for authentication.\n * @param {boolean} params.isSub - whether this is subscription or in-app. `true` for subscription.\n * @returns {Promise<ReceiptAndroid>}\n */\nexport const validateReceiptAndroid = async ({\n packageName,\n productId,\n productToken,\n accessToken,\n isSub,\n}: {\n packageName: string;\n productId: string;\n productToken: string;\n accessToken: string;\n isSub?: boolean;\n}): Promise<VerifyPurchaseResultAndroid> => {\n const type = isSub ? 'subscriptions' : 'products';\n\n const url =\n 'https://androidpublisher.googleapis.com/androidpublisher/v3/applications' +\n `/${packageName}/purchases/${type}/${productId}` +\n `/tokens/${productToken}`;\n\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n });\n\n if (!response.ok) {\n throw Object.assign(new Error(response.statusText), {\n statusCode: response.status,\n });\n }\n\n return response.json();\n};\n\n/**\n * Consume a purchase token so the user can purchase the same product again\n * (Android consumable products). Prefer using `finishTransaction` with\n * `isConsumable: true`, which dispatches to this under the hood.\n *\n * @see {@link https://openiap.dev/docs/apis/android/consume-purchase-android}\n */\nexport const consumePurchaseAndroid: MutationField<\n 'consumePurchaseAndroid'\n> = async (purchaseToken) => {\n requireAndroidPlatform('consumePurchaseAndroid');\n const result = await ExpoIapModule.consumePurchaseAndroid(purchaseToken);\n\n if (typeof result === 'boolean') {\n return result;\n }\n\n if (result && typeof result === 'object') {\n const record = result as Record<string, unknown>;\n if (typeof record.success === 'boolean') {\n return record.success;\n }\n if (typeof record.responseCode === 'number') {\n return record.responseCode === 0;\n }\n }\n\n throw new Error(\n `consumePurchaseAndroid returned an unexpected response payload: ${JSON.stringify(\n result,\n )}`,\n );\n};\n\n/**\n * Acknowledge a non-consumable purchase or subscription (Android only).\n * @param {Object} params - The parameters object\n * @param {string} params.token - The product's token (on Android)\n * @returns {Promise<VoidResult | void>}\n * @throws Error if called on a non-Android platform\n *\n * @see {@link https://openiap.dev/docs/apis/android/acknowledge-purchase-android}\n */\nexport const acknowledgePurchaseAndroid: MutationField<\n 'acknowledgePurchaseAndroid'\n> = async (purchaseToken) => {\n requireAndroidPlatform('acknowledgePurchaseAndroid');\n const result = await ExpoIapModule.acknowledgePurchaseAndroid(purchaseToken);\n\n if (typeof result === 'boolean') {\n return result;\n }\n\n if (result && typeof result === 'object') {\n const record = result as Record<string, unknown>;\n if (typeof record.success === 'boolean') {\n return record.success;\n }\n if (typeof record.responseCode === 'number') {\n return record.responseCode === 0;\n }\n }\n\n return true;\n};\n\n/**\n * Open the Google Play offer/promo code redemption flow so the user can enter a code (Android only).\n * On Play builds, launches the Play Store redeem page. A listener can receive\n * the purchase while the app has an active billing connection; reconcile\n * available purchases when the app resumes. Unsupported store flavors return false.\n * Does not require the billing client to be initialized (no Play Billing version requirement).\n * Android counterpart of presentCodeRedemptionSheetIOS.\n *\n * @returns Promise resolving to true when launched, or false when unsupported\n *\n * @see {@link https://openiap.dev/docs/apis/android/open-redeem-offer-code-android}\n */\nexport const openRedeemOfferCodeAndroid: MutationField<\n 'openRedeemOfferCodeAndroid'\n> = async () => {\n requireAndroidPlatform('openRedeemOfferCodeAndroid');\n if (isVegaOS()) {\n return false;\n }\n return ExpoIapModule.openRedeemOfferCodeAndroid();\n};\n\n/**\n * Check if alternative billing is available for this user/device (Android only).\n * Step 1 of alternative billing flow.\n *\n * Returns true if available, false otherwise.\n * Throws OpenIapError.NotPrepared if billing client not ready.\n *\n * @returns {Promise<boolean>}\n *\n * @example\n * ```typescript\n * const isAvailable = await checkAlternativeBillingAvailabilityAndroid();\n * if (isAvailable) {\n * // Proceed with alternative billing flow\n * }\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/android/check-alternative-billing-availability-android}\n * @deprecated Use `isBillingProgramAvailableAndroid('external-offer')`\n * instead. Scheduled for removal in expo-iap 5.0.0.\n */\nexport const checkAlternativeBillingAvailabilityAndroid: MutationField<\n 'checkAlternativeBillingAvailabilityAndroid'\n> = async () => {\n requireAndroidPlatform('checkAlternativeBillingAvailabilityAndroid');\n return ExpoIapModule.checkAlternativeBillingAvailabilityAndroid();\n};\n\n/**\n * Show alternative billing information dialog to user (Android only).\n * Step 2 of alternative billing flow.\n * Must be called BEFORE processing payment in your payment system.\n *\n * Returns true if user accepted, false if user canceled.\n * Throws OpenIapError.NotPrepared if billing client not ready.\n *\n * @returns {Promise<boolean>}\n *\n * @example\n * ```typescript\n * const userAccepted = await showAlternativeBillingDialogAndroid();\n * if (userAccepted) {\n * // Process payment in your payment system\n * const success = await processCustomPayment();\n * if (success) {\n * // Create reporting token\n * const token = await createAlternativeBillingTokenAndroid();\n * // Send token to your backend for Google Play reporting\n * }\n * }\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/android/show-alternative-billing-dialog-android}\n * @deprecated Use `launchExternalLinkAndroid` instead. Scheduled for removal\n * in expo-iap 5.0.0.\n */\nexport const showAlternativeBillingDialogAndroid: MutationField<\n 'showAlternativeBillingDialogAndroid'\n> = async () => {\n requireAndroidPlatform('showAlternativeBillingDialogAndroid');\n return ExpoIapModule.showAlternativeBillingDialogAndroid();\n};\n\n/**\n * Create external transaction token for Google Play reporting (Android only).\n * Step 3 of alternative billing flow.\n * Must be called AFTER successful payment in your payment system.\n * Token must be reported to Google Play backend within 24 hours.\n *\n * Returns token string, or null if creation failed.\n * Throws OpenIapError.NotPrepared if billing client not ready.\n *\n * @param {string} sku - The product SKU that was purchased\n * @returns {Promise<string | null>}\n *\n * @example\n * ```typescript\n * const token = await createAlternativeBillingTokenAndroid('premium_subscription');\n * if (token) {\n * // Send token to your backend\n * await fetch('/api/report-transaction', {\n * method: 'POST',\n * body: JSON.stringify({ token, sku: 'premium_subscription' })\n * });\n * }\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/android/create-alternative-billing-token-android}\n * @deprecated Use\n * `createBillingProgramReportingDetailsAndroid('external-offer')` instead.\n * Scheduled for removal in expo-iap 5.0.0.\n */\nexport const createAlternativeBillingTokenAndroid: MutationField<\n 'createAlternativeBillingTokenAndroid'\n> = async (sku?: string) => {\n requireAndroidPlatform('createAlternativeBillingTokenAndroid');\n return ExpoIapModule.createAlternativeBillingTokenAndroid(sku);\n};\n\n// ============================================================================\n// Billing Programs API (Google Play Billing Library 8.2.0+)\n// ============================================================================\n\n/**\n * Check if a specific billing program is available for this user/device (Android only).\n * Available in Google Play Billing Library 8.2.0+. Billing Choice availability\n * details, including the configured renderer and external-link support, require 9.1.0+.\n *\n * @param program - The billing program to check\n * @returns Promise resolving to availability result\n *\n * @example\n * ```typescript\n * const result = await isBillingProgramAvailableAndroid('external-offer');\n * if (result.isAvailable) {\n * // Proceed with billing program flow\n * }\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/android/is-billing-program-available-android}\n */\nexport const isBillingProgramAvailableAndroid: MutationField<\n 'isBillingProgramAvailableAndroid'\n> = async (program) => {\n requireAndroidPlatform('isBillingProgramAvailableAndroid');\n return ExpoIapModule.isBillingProgramAvailableAndroid(program);\n};\n\n/**\n * Fetch Play Billing assets and loyalty text for developer-rendered Billing Choice screens.\n * Available in Google Play Billing Library 9.1.0+.\n *\n * @param params - Billing Choice info request parameters\n * @returns Promise resolving to Play Billing Choice display information\n *\n * @see {@link https://openiap.dev/docs/apis/android/get-billing-choice-info-android}\n */\nexport const getBillingChoiceInfoAndroid: QueryField<\n 'getBillingChoiceInfoAndroid'\n> = async (\n params: GetBillingChoiceInfoParamsAndroid = {},\n): Promise<BillingChoiceInfoAndroid> => {\n requireAndroidPlatform('getBillingChoiceInfoAndroid');\n return ExpoIapModule.getBillingChoiceInfoAndroid({\n billingProgram: params.billingProgram ?? 'billing-choice',\n playBillingChoiceImageLayout:\n params.playBillingChoiceImageLayout ?? 'rectangular-four-by-one',\n userLocale: params.userLocale ?? null,\n });\n};\n\n/**\n * Launch an external link for the specified billing program (Android only).\n * Available in Google Play Billing Library 8.2.0+; developer-rendered Billing\n * Choice external-link flows require 9.1.0+ and `externalTransactionToken`.\n *\n * @param params - The external link parameters\n * @returns Promise resolving to true if the link was launched successfully\n *\n * @example\n * ```typescript\n * await launchExternalLinkAndroid({\n * billingProgram: 'billing-choice',\n * externalTransactionToken: 'pre-generated-token',\n * launchMode: 'launch-in-external-browser-or-app',\n * linkType: 'link-to-digital-content-offer',\n * linkUri: 'https://your-payment-site.com',\n * });\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/android/launch-external-link-android}\n */\nexport const launchExternalLinkAndroid: MutationField<\n 'launchExternalLinkAndroid'\n> = async (params) => {\n requireAndroidPlatform('launchExternalLinkAndroid');\n return ExpoIapModule.launchExternalLinkAndroid(params);\n};\n\n/**\n * Create billing program reporting details for Google Play reporting (Android only).\n * Available in Google Play Billing Library 8.2.0+.\n *\n * Must be called AFTER successful payment in your payment system.\n * Token must be reported to Google Play backend within 24 hours.\n *\n * @param program - The billing program type\n * @returns Promise resolving to reporting details including the external transaction token\n *\n * @example\n * ```typescript\n * const details = await createBillingProgramReportingDetailsAndroid('external-offer');\n * // Report details.externalTransactionToken to Google Play within 24 hours\n * await reportToGooglePlay(details.externalTransactionToken);\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/android/create-billing-program-reporting-details-android}\n */\nconst createBillingProgramReportingDetailsAndroidField: MutationField<\n 'createBillingProgramReportingDetailsAndroid'\n> = async (\n args: MutationCreateBillingProgramReportingDetailsAndroidArgs,\n): Promise<BillingProgramReportingDetailsAndroid> => {\n requireAndroidPlatform('createBillingProgramReportingDetailsAndroid');\n return ExpoIapModule.createBillingProgramReportingDetailsAndroid(\n args.program,\n args.developerBillingType ?? null,\n );\n};\n\nexport function createBillingProgramReportingDetailsAndroid(\n args: MutationCreateBillingProgramReportingDetailsAndroidArgs,\n): Promise<BillingProgramReportingDetailsAndroid>;\nexport function createBillingProgramReportingDetailsAndroid(\n program: BillingProgramAndroid,\n developerBillingType?: DeveloperBillingTypeAndroid | null,\n): Promise<BillingProgramReportingDetailsAndroid>;\nexport function createBillingProgramReportingDetailsAndroid(\n programOrArgs:\n | BillingProgramAndroid\n | MutationCreateBillingProgramReportingDetailsAndroidArgs,\n developerBillingType?: DeveloperBillingTypeAndroid | null,\n): Promise<BillingProgramReportingDetailsAndroid> {\n const args =\n typeof programOrArgs === 'string'\n ? {program: programOrArgs, developerBillingType}\n : programOrArgs;\n return createBillingProgramReportingDetailsAndroidField(args);\n}\n\n/**\n * Show Google's mandatory information dialog before a developer-rendered,\n * in-app Billing Choice screen.\n * Available in Google Play Billing Library 9.1.0+.\n *\n * @param params - Dialog parameters with the external transaction token\n * @returns Promise resolving to BillingResult\n *\n * @see {@link https://openiap.dev/docs/apis/android/show-billing-program-information-dialog-android}\n */\nexport const showBillingProgramInformationDialogAndroid: MutationField<\n 'showBillingProgramInformationDialogAndroid'\n> = async (\n params: BillingProgramInformationDialogParamsAndroid,\n): Promise<BillingResultAndroid> => {\n requireAndroidPlatform('showBillingProgramInformationDialogAndroid');\n return ExpoIapModule.showBillingProgramInformationDialogAndroid({\n billingProgram: params.billingProgram ?? 'billing-choice',\n externalTransactionToken: params.externalTransactionToken,\n });\n};\n\n/**\n * Show Play Billing in-app messages, such as transactional subscription updates.\n * Available in Google Play Billing Library 4.1.0+.\n *\n * @param params - Optional in-app message categories\n * @returns Promise resolving to in-app message result\n *\n * @see {@link https://openiap.dev/docs/apis/android/show-in-app-messages-android}\n */\nexport const showInAppMessagesAndroid: MutationField<\n 'showInAppMessagesAndroid'\n> = async (\n params?: InAppMessageParamsAndroid | null,\n): Promise<InAppMessageResultAndroid> => {\n requireAndroidPlatform('showInAppMessagesAndroid');\n return ExpoIapModule.showInAppMessagesAndroid(params ?? null);\n};\n"]}
|