@rocapine/react-native-onboarding 1.75.0 → 1.76.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/index.d.ts +5 -3
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +16 -2
  4. package/dist/index.js.map +1 -1
  5. package/dist/onboarding-example.d.ts +140 -0
  6. package/dist/onboarding-example.d.ts.map +1 -1
  7. package/dist/onboarding-example.js +41 -1
  8. package/dist/onboarding-example.js.map +1 -1
  9. package/dist/paywalls/PaywallProvider.d.ts +71 -5
  10. package/dist/paywalls/PaywallProvider.d.ts.map +1 -1
  11. package/dist/paywalls/PaywallProvider.js +237 -57
  12. package/dist/paywalls/PaywallProvider.js.map +1 -1
  13. package/dist/paywalls/customScreens.d.ts +31 -0
  14. package/dist/paywalls/customScreens.d.ts.map +1 -1
  15. package/dist/paywalls/observer.d.ts +129 -0
  16. package/dist/paywalls/observer.d.ts.map +1 -0
  17. package/dist/paywalls/observer.js +211 -0
  18. package/dist/paywalls/observer.js.map +1 -0
  19. package/dist/paywalls/present.d.ts +19 -15
  20. package/dist/paywalls/present.d.ts.map +1 -1
  21. package/dist/paywalls/present.js +21 -17
  22. package/dist/paywalls/present.js.map +1 -1
  23. package/dist/paywalls/types.d.ts +3 -1
  24. package/dist/paywalls/types.d.ts.map +1 -1
  25. package/dist/products/adapters/expoIap.d.ts +38 -1
  26. package/dist/products/adapters/expoIap.d.ts.map +1 -1
  27. package/dist/products/adapters/expoIap.js +509 -75
  28. package/dist/products/adapters/expoIap.js.map +1 -1
  29. package/dist/products/index.d.ts +1 -0
  30. package/dist/products/index.d.ts.map +1 -1
  31. package/dist/products/index.js.map +1 -1
  32. package/dist/products/types.d.ts +13 -0
  33. package/dist/products/types.d.ts.map +1 -1
  34. package/dist/screens/completingActions.d.ts +55 -3
  35. package/dist/screens/completingActions.d.ts.map +1 -1
  36. package/dist/screens/completingActions.js +209 -15
  37. package/dist/screens/completingActions.js.map +1 -1
  38. package/dist/screens/elementTypeRegistry.d.ts +14 -0
  39. package/dist/screens/elementTypeRegistry.d.ts.map +1 -1
  40. package/dist/screens/elementTypeRegistry.js +38 -1
  41. package/dist/screens/elementTypeRegistry.js.map +1 -1
  42. package/dist/screens/elements/ButtonElement.d.ts +3 -2
  43. package/dist/screens/elements/ButtonElement.d.ts.map +1 -1
  44. package/dist/screens/elements/ButtonElement.js +5 -1
  45. package/dist/screens/elements/ButtonElement.js.map +1 -1
  46. package/dist/screens/types.d.ts +2 -2
  47. package/dist/screens/types.d.ts.map +1 -1
  48. package/dist/screens/types.js +5 -1
  49. package/dist/screens/types.js.map +1 -1
  50. package/dist/screens/unknownKeys.d.ts +25 -4
  51. package/dist/screens/unknownKeys.d.ts.map +1 -1
  52. package/dist/screens/unknownKeys.js +81 -2
  53. package/dist/screens/unknownKeys.js.map +1 -1
  54. package/dist/steps/common.types.d.ts +178 -6
  55. package/dist/steps/common.types.d.ts.map +1 -1
  56. package/dist/steps/common.types.js +64 -3
  57. package/dist/steps/common.types.js.map +1 -1
  58. package/package.json +1 -1
  59. package/src/__tests__/authoringDocEscapes.test.ts +59 -0
  60. package/src/__tests__/completingActions.test.ts +371 -1
  61. package/src/__tests__/customActionHooks.test.ts +224 -0
  62. package/src/__tests__/onboardingExampleElements.test.ts +47 -0
  63. package/src/__tests__/requestPermissionAction.test.ts +138 -0
  64. package/src/__tests__/retryIdempotencyDocs.test.ts +57 -0
  65. package/src/__tests__/unknownKeys.test.ts +110 -0
  66. package/src/index.ts +33 -1
  67. package/src/onboarding-example.ts +41 -1
  68. package/src/paywalls/PaywallProvider.tsx +370 -66
  69. package/src/paywalls/__tests__/PaywallProvider.observer.test.tsx +866 -0
  70. package/src/paywalls/__tests__/observer.test.ts +401 -0
  71. package/src/paywalls/__tests__/present.test.ts +0 -18
  72. package/src/paywalls/customScreens.ts +34 -1
  73. package/src/paywalls/observer.ts +308 -0
  74. package/src/paywalls/present.ts +24 -18
  75. package/src/paywalls/types.ts +3 -1
  76. package/src/products/adapters/__tests__/expoIap.contract.test.ts +648 -0
  77. package/src/products/adapters/__tests__/expoIap.test.ts +25 -11
  78. package/src/products/adapters/__tests__/expoIap5Fake.ts +288 -0
  79. package/src/products/adapters/expoIap.ts +609 -78
  80. package/src/products/index.ts +1 -0
  81. package/src/products/types.ts +13 -0
  82. package/src/screens/completingActions.ts +223 -15
  83. package/src/screens/elementTypeRegistry.ts +34 -0
  84. package/src/screens/elements/ButtonElement.ts +9 -1
  85. package/src/screens/types.ts +2 -2
  86. package/src/screens/unknownKeys.ts +113 -7
  87. package/src/steps/common.types.ts +213 -6
@@ -1,5 +1,11 @@
1
1
  import { Platform } from "react-native";
2
- import type { ProductProvider, ProductRef, ProductPeriod, ResolvedProduct } from "../types";
2
+ import type {
3
+ ProductProvider,
4
+ ProductRef,
5
+ ProductPeriod,
6
+ PurchaseResult,
7
+ ResolvedProduct,
8
+ } from "../types";
3
9
 
4
10
  // Optional peer: expo-iap. Same dynamic-require pattern as elements/haptics.ts.
5
11
  let IAP: any;
@@ -13,17 +19,115 @@ const toPeriod = (iso: string | null | undefined): { period: ProductPeriod | nul
13
19
  if (!iso) return { period: null, count: 0 };
14
20
  const m = /^P(\d+)([DWMY])$/.exec(iso);
15
21
  if (!m) return { period: null, count: 0 };
22
+ // `D: "week"` is wrong for a daily plan and is deliberately left alone here:
23
+ // `ProductPeriod` has no "day" member, all three adapters share the same
24
+ // mapping, and widening a published union is a release-visible change rather
25
+ // than part of this fix. Tracked in #258. Only `period` is affected —
26
+ // `periodIso` is what `deriveProductFields` divides by, and it is exact.
16
27
  const map: Record<string, ProductPeriod> = { D: "week", W: "week", M: "month", Y: "year" };
17
28
  return { period: map[m[2]] ?? null, count: Number(m[1]) };
18
29
  };
19
30
 
20
- // expo-iap surfaces a user cancellation as a code rather than a typed error.
31
+ /**
32
+ * A user cancellation, across every code shape expo-iap has used.
33
+ *
34
+ * 5.x normalized every code to openiap kebab-case (`ErrorCode.UserCancelled
35
+ * === "user-cancelled"`, `types.js:41`) and dropped the `userCancelled`
36
+ * boolean, so testing only the pre-5.x screaming-snake codes turned a dismissed
37
+ * StoreKit sheet into `onError` on the paywall. All shapes are accepted: an
38
+ * older peer is still a supported peer.
39
+ */
21
40
  const isCancellation = (e: any): boolean =>
22
- e?.code === "E_USER_CANCELLED" || e?.code === "USER_CANCELED" || e?.userCancelled === true;
41
+ e?.code === "user-cancelled" ||
42
+ e?.code === "E_USER_CANCELLED" ||
43
+ e?.code === "USER_CANCELED" ||
44
+ e?.userCancelled === true;
45
+
46
+ /**
47
+ * Codes that mean the store connection is gone, so a READ is worth retrying
48
+ * after reopening it.
49
+ *
50
+ * `endConnection` is process-wide: any other `useIAP` in the host unmounting,
51
+ * or an Android `ServiceDisconnected`, closes the connection this adapter
52
+ * opened. Caching a RESOLVED connect promise then made every later call fail
53
+ * for the life of the process.
54
+ *
55
+ * **Reads only.** `requestPurchase` is never retried on these — see the comment
56
+ * on `withConnection`.
57
+ */
58
+ const CONNECTION_LOST = new Set([
59
+ "not-prepared",
60
+ "connection-closed",
61
+ "service-disconnected",
62
+ "init-connection",
63
+ "E_NOT_PREPARED",
64
+ "E_SERVICE_DISCONNECTED",
65
+ ]);
23
66
 
24
67
  const idFor = (ref: ProductRef): string | undefined =>
25
68
  Platform.OS === "ios" ? ref.ios : ref.android;
26
69
 
70
+ /**
71
+ * Play refs are authored `productId:basePlanId` (see `ProductRef.android`) —
72
+ * RevenueCat's convention, which the studio writes for every platform.
73
+ *
74
+ * expo-iap is not RevenueCat: `fetchProducts` filters the store's answer by the
75
+ * BARE `item.id` (`build/index.js:471-477`), so passing the composite id
76
+ * through matched nothing and the product was skipped — a blank Android paywall
77
+ * reporting `status: "ready"`. The base plan half is not noise either: it is
78
+ * what selects the offer, and therefore the offer token Play needs.
79
+ */
80
+ const splitAndroidRef = (id: string): { productId: string; basePlanId?: string } => {
81
+ const at = id.indexOf(":");
82
+ return at < 0
83
+ ? { productId: id }
84
+ : { productId: id.slice(0, at), basePlanId: id.slice(at + 1) };
85
+ };
86
+
87
+ /** Play's `RecurrenceMode.INFINITE_RECURRING` — the ongoing phase of a base plan. */
88
+ const RECURRENCE_INFINITE = 1;
89
+
90
+ /**
91
+ * The subscription offer for the base plan the ref names.
92
+ *
93
+ * With no base plan authored there is nothing to disambiguate, so the first
94
+ * offer stands. With one authored and no offer carrying it, the ref points at a
95
+ * base plan this product does not have — worth saying out loud, because the
96
+ * purchase will be for a different plan than the price shown.
97
+ */
98
+ const offerFor = (s: any, basePlanId: string | undefined, productId: string): any | undefined => {
99
+ const offers: any[] = Array.isArray(s?.subscriptionOffers) ? s.subscriptionOffers : [];
100
+ if (offers.length === 0) return undefined;
101
+ if (!basePlanId) return offers[0];
102
+ const matched = offers.find((o) => o?.basePlanIdAndroid === basePlanId);
103
+ if (matched) return matched;
104
+ console.warn(
105
+ `expoIapProductProvider: "${productId}" has no base plan "${basePlanId}" — ` +
106
+ `offers are [${offers.map((o) => o?.basePlanIdAndroid ?? "?").join(", ")}]. ` +
107
+ `Falling back to the first offer; the authored ref is probably stale.`
108
+ );
109
+ return offers[0];
110
+ };
111
+
112
+ /**
113
+ * The phase of an Android offer that the subscriber actually recurs on.
114
+ *
115
+ * `pricingPhaseList[0]` is the TRIAL or intro phase whenever one exists, so
116
+ * reading it gave a $59.99/year plan with a one-week trial `periodIso: "P1W"` —
117
+ * and a `pricePerYear` near $3,130, because `deriveProductFields` divides the
118
+ * price by the period it is told. Prefer the infinite-recurring phase; failing
119
+ * that the last priced phase, since intro phases come first.
120
+ */
121
+ const recurringPhase = (offer: any): any | undefined => {
122
+ const phases: any[] = offer?.pricingPhasesAndroid?.pricingPhaseList ?? [];
123
+ if (phases.length === 0) return undefined;
124
+ return (
125
+ phases.find((p) => Number(p?.recurrenceMode) === RECURRENCE_INFINITE) ??
126
+ [...phases].reverse().find((p) => Number(p?.priceAmountMicros ?? 0) > 0) ??
127
+ phases[phases.length - 1]
128
+ );
129
+ };
130
+
27
131
  const ISO_UNIT: Record<string, string> = { day: "D", week: "W", month: "M", year: "Y" };
28
132
 
29
133
  /**
@@ -39,11 +143,11 @@ const ISO_UNIT: Record<string, string> = { day: "D", week: "W", month: "M", year
39
143
  * expo-iap has never exposed one ready-made, and the shape has moved:
40
144
  * - ≤4.x published `subscriptionPeriodISO` / `subscriptionPeriod` on the product
41
145
  * - 5.x publishes the iOS period SPLIT in two (`subscriptionPeriodUnitIOS`,
42
- * `subscriptionPeriodNumberIOS`) and the Android one buried in the first
43
- * pricing phase of the first subscription offer
146
+ * `subscriptionPeriodNumberIOS`) and the Android one in the pricing phases
147
+ * of a subscription offer
44
148
  * All three are read, newest-shape-last so an older peer keeps working.
45
149
  */
46
- const periodIsoFrom = (s: any): string | null => {
150
+ const periodIsoFrom = (s: any, phase: any): string | null => {
47
151
  const direct = s?.subscriptionPeriodISO ?? s?.subscriptionPeriod;
48
152
  if (typeof direct === "string" && direct) return direct;
49
153
 
@@ -56,13 +160,124 @@ const periodIsoFrom = (s: any): string | null => {
56
160
  return `P${Number.isFinite(n) && n > 0 ? n : 1}${unit}`;
57
161
  }
58
162
 
59
- const androidPeriod =
60
- s?.subscriptionOffers?.[0]?.pricingPhasesAndroid?.pricingPhaseList?.[0]?.billingPeriod;
163
+ const androidPeriod = phase?.billingPeriod;
61
164
  return typeof androidPeriod === "string" && androidPeriod ? androidPeriod : null;
62
165
  };
63
166
 
167
+ /** Does this delivered transaction belong to the sku we asked for? */
168
+ const deliversFor = (purchase: any, sku: string): boolean =>
169
+ purchase?.productId === sku ||
170
+ (Array.isArray(purchase?.ids) && purchase.ids.includes(sku));
171
+
172
+ /** The products a `PurchaseError` names, if it names any (`types.d.ts:1164-1174`). */
173
+ const errorSkus = (e: any): string[] =>
174
+ [e?.productId, ...(Array.isArray(e?.productIds) ? e.productIds : [])].filter(
175
+ (s): s is string => typeof s === "string" && s.length > 0
176
+ );
177
+
178
+ /** A transaction id, which is what `Purchase.id` carries (`types.d.ts:1151`). */
179
+ const txIdOf = (purchase: any): string | null =>
180
+ typeof purchase?.id === "string" && purchase.id ? purchase.id : null;
181
+
182
+ /**
183
+ * `purchaseState` is `'pending' | 'purchased' | 'unknown'` (`types.d.ts:1264`).
184
+ *
185
+ * `getAvailablePurchases` reports UNFINISHED purchases too, so an Android
186
+ * slow-payment purchase used to entitle the user before the money moved. Grant
187
+ * only on an explicit "purchased" — with one exception, a peer that reports no
188
+ * state at all predates the field, and rejecting its silence would break every
189
+ * restore on that peer rather than tightening anything.
190
+ */
191
+ const isPaid = (p: any): boolean => p?.purchaseState == null || p.purchaseState === "purchased";
192
+
193
+ /**
194
+ * expo-iap reports a purchase failure two different ways, and only one of them
195
+ * is an `Error`.
196
+ *
197
+ * A rejection from `requestPurchase` is a real `Error` (`createPurchaseError`,
198
+ * `utils/errorMapping.d.ts:19` — `PurchaseError extends Error`). What arrives
199
+ * on `purchaseErrorListener` is the OTHER `PurchaseError`: the plain
200
+ * `{ code, message }` shape from `types.d.ts:1164`, straight off the native
201
+ * emitter. `new Error(String(plainObject))` turns that into
202
+ * "[object Object]" — the store's diagnosis, thrown away at the one point a
203
+ * host would read it.
204
+ */
205
+ const asError = (e: unknown): Error => {
206
+ if (e instanceof Error) return e;
207
+ const message =
208
+ typeof (e as any)?.message === "string" && (e as any).message ? (e as any).message : String(e);
209
+ const code = (e as any)?.code;
210
+ const error = new Error(code ? `${message} (${code})` : message);
211
+ if (code) (error as any).code = code;
212
+ return error;
213
+ };
214
+
215
+ const failureFor = (e: any): PurchaseResult =>
216
+ isCancellation(e) ? { status: "cancelled" } : { status: "error", error: asError(e) };
217
+
218
+ /** What `getProducts` remembers per ref so `purchase` can dispatch correctly. */
219
+ type ResolvedMeta = {
220
+ /** expo-iap's own discriminator: "subs" | "in-app". */
221
+ type?: string;
222
+ /** Play's handle on the chosen base plan. Required to buy a subscription. */
223
+ offerToken?: string;
224
+ };
225
+
226
+ /** One caller waiting for an answer. Its lifetime is NOT the transaction's. */
227
+ type Waiter = {
228
+ sku: string;
229
+ productKey: string;
230
+ settled?: PurchaseResult;
231
+ answer: (r: PurchaseResult) => void;
232
+ promise: Promise<PurchaseResult>;
233
+ };
234
+
235
+ export type ExpoIapProviderOptions = {
236
+ /**
237
+ * How long to wait for the store's verdict before answering `"pending"`.
238
+ *
239
+ * The verdict is an event and nothing bounds how long a user spends in the
240
+ * store sheet — Ask to Buy, an SCA step-up, or adding a card inside the sheet
241
+ * routinely exceed the default — so this bounds only how long the CALLER
242
+ * waits. It does not end the transaction: the provider's listeners stay
243
+ * attached, and a verdict arriving after the timeout is still acknowledged.
244
+ * It resolves `"pending"`, never `"purchased"`.
245
+ */
246
+ purchaseTimeoutMs?: number;
247
+ /**
248
+ * Honour a transaction this process never asked for, so it can be finished.
249
+ *
250
+ * StoreKit re-delivers an unfinished transaction on **every launch**, and a
251
+ * purchase can also arrive from an Ask to Buy approval, a promoted product,
252
+ * or a pending Play purchase that cleared while the app was closed. None of
253
+ * those has a caller waiting, and finishing one blind would take the money
254
+ * while granting nothing — destroying the very replay that lets the app
255
+ * recover. So the host decides: return `true` once entitlement is granted and
256
+ * the transaction is finished; return `false` (or leave this unset) and it is
257
+ * left alone to be re-delivered next launch.
258
+ *
259
+ * A purchase this provider DISPATCHED in this process never comes here — the
260
+ * caller was told about it, so acknowledging it needs no second opinion.
261
+ */
262
+ onUnclaimedPurchase?: (purchase: any) => boolean | Promise<boolean>;
263
+ };
264
+
265
+ /**
266
+ * `dispose()` is additive to `ProductProvider`: hosts that never call it are
267
+ * unaffected, but a provider holds a store subscription for its lifetime, so a
268
+ * host that rebuilds one per render should tear the old one down.
269
+ */
270
+ export type ExpoIapProvider = ProductProvider & { dispose(): void };
271
+
272
+ const DEFAULT_PURCHASE_TIMEOUT_MS = 180_000;
273
+
64
274
  /** Direct StoreKit / Play Billing provider, no vendor in the path. */
65
- export const expoIapProductProvider = (Iap: any = IAP): ProductProvider => {
275
+ export const expoIapProductProvider = (
276
+ Iap: any = IAP,
277
+ options: ExpoIapProviderOptions = {}
278
+ ): ExpoIapProvider => {
279
+ const purchaseTimeoutMs = options.purchaseTimeoutMs ?? DEFAULT_PURCHASE_TIMEOUT_MS;
280
+
66
281
  const required = () => {
67
282
  if (!Iap) {
68
283
  throw new Error(
@@ -72,6 +287,159 @@ export const expoIapProductProvider = (Iap: any = IAP): ProductProvider => {
72
287
  return Iap;
73
288
  };
74
289
 
290
+ // ---------------------------------------------------------------------------
291
+ // The finish lifetime.
292
+ //
293
+ // Acknowledging the money is a SEPARATE concern from answering the caller,
294
+ // and an earlier version of this file conflated them: it guarded both on one
295
+ // `claimed` flag and removed its listeners the moment the caller had an
296
+ // answer. Every path that answered early — an unrelated product's error, a
297
+ // `pending` update, the timeout — permanently lost the ability to finish the
298
+ // charge, and Play auto-refunds an unacknowledged purchase after 3 days.
299
+ //
300
+ // So the listeners are opened ONCE, on first connect, and live as long as the
301
+ // provider. That is also forced by expo-iap's iOS dedupe: each new
302
+ // `purchaseUpdatedListener` seeds its history from a PROCESS-WIDE set
303
+ // (`ids: new Set(purchaseUpdatedDedupeHistoryIOS.ids)`, `build/index.js`
304
+ // :148-151, recorded into the global at :164, cleared only by a successful
305
+ // `endConnection`). Subscribing per Buy tap therefore inherits every
306
+ // transaction id any other listener in the process has ever seen — the host's
307
+ // own `useIAP`, for instance — and silently drops them. One early
308
+ // subscription sees each transaction exactly once instead.
309
+ // ---------------------------------------------------------------------------
310
+ let subscriptions: { remove?(): void }[] | null = null;
311
+ /** Skus this process asked to buy. A delivery for one of these is ours. */
312
+ const dispatchedSkus = new Set<string>();
313
+ /** Transaction ids already acknowledged, so no delivery finishes twice. */
314
+ const finishedTxIds = new Set<string>();
315
+ /** Acknowledgements that threw, retried on the next store round-trip. */
316
+ const unfinished = new Map<string, { purchase: any; isConsumable: boolean }>();
317
+ const waiters = new Set<Waiter>();
318
+ let warnedUnclaimed = false;
319
+ /** Only iOS publishes a consumable discriminator; see `getProducts`. */
320
+ const consumableBySku = new Map<string, boolean>();
321
+
322
+ const finish = async (purchase: any, isConsumable: boolean) => {
323
+ const M = required();
324
+ const tx = txIdOf(purchase);
325
+ if (tx && finishedTxIds.has(tx)) return;
326
+ if (typeof M.finishTransaction !== "function") return;
327
+ try {
328
+ await M.finishTransaction({ purchase, isConsumable });
329
+ if (tx) {
330
+ finishedTxIds.add(tx);
331
+ unfinished.delete(tx);
332
+ }
333
+ } catch (e) {
334
+ // Best-effort: a failure here does not un-buy anything, so it must not
335
+ // turn a completed purchase into an error. But it must not be forgotten
336
+ // either — Play's 3-day window is still running.
337
+ if (tx) unfinished.set(tx, { purchase, isConsumable });
338
+ console.warn(
339
+ `expoIapProductProvider: could not finish transaction ${tx ?? "(no id)"} ` +
340
+ `for "${purchase?.productId}" — will retry on the next store call. ${String(e)}`
341
+ );
342
+ }
343
+ };
344
+
345
+ /** Give an earlier failed acknowledgement another go; never throws. */
346
+ const retryUnfinished = async () => {
347
+ for (const [, record] of [...unfinished]) {
348
+ try {
349
+ await finish(record.purchase, record.isConsumable);
350
+ } catch {
351
+ // finish() already swallows and re-queues; belt and braces
352
+ }
353
+ }
354
+ };
355
+
356
+ /** Hand a result to the one caller waiting on this transaction's sku, if any. */
357
+ const answer = (purchase: any, result: PurchaseResult) => {
358
+ for (const w of waiters) {
359
+ if (w.settled || !deliversFor(purchase, w.sku)) continue;
360
+ w.answer(result.status === "purchased" ? { ...result, productKey: w.productKey } : result);
361
+ return;
362
+ }
363
+ };
364
+
365
+ const handleUpdated = async (purchase: any) => {
366
+ const sku: string | undefined = purchase?.productId;
367
+ const isConsumable = (sku != null && consumableBySku.get(sku)) || false;
368
+
369
+ // Play's slow-payment path: the user has committed but the money has not
370
+ // moved, and Android cannot acknowledge it anyway (no `purchaseToken` yet,
371
+ // `build/index.js:865-874`). Tell the caller — then keep listening, because
372
+ // Play emits `purchased` for the SAME transaction once it clears. Treating
373
+ // this as terminal is what left a cleared purchase unfinished.
374
+ if (purchase?.purchaseState === "pending") {
375
+ answer(purchase, { status: "pending" });
376
+ return;
377
+ }
378
+
379
+ if (sku != null && dispatchedSkus.has(sku)) {
380
+ await finish(purchase, isConsumable);
381
+ // `productKey` is filled in by `answer` from the waiting caller's ref.
382
+ answer(purchase, { status: "purchased", productKey: "" });
383
+ return;
384
+ }
385
+
386
+ // Nobody here asked for this one: a replay from a previous process, an Ask
387
+ // to Buy approval, a promoted product. Only the host knows whether it has
388
+ // been honoured, so only the host can authorise finishing it.
389
+ if (options.onUnclaimedPurchase) {
390
+ if (await options.onUnclaimedPurchase(purchase)) await finish(purchase, isConsumable);
391
+ return;
392
+ }
393
+ if (!warnedUnclaimed) {
394
+ warnedUnclaimed = true;
395
+ console.warn(
396
+ `expoIapProductProvider: the store delivered a transaction nobody is waiting for ` +
397
+ `("${sku}"). It is left unfinished, so it will be re-delivered next launch. ` +
398
+ `Pass onUnclaimedPurchase to grant entitlement and finish it.`
399
+ );
400
+ }
401
+ };
402
+
403
+ /**
404
+ * Attribute a store failure to the purchase it belongs to.
405
+ *
406
+ * The error listener is process-wide and unfiltered — expo-iap forwards the
407
+ * event verbatim (`build/index.js:195-200`), and on Android the module emits
408
+ * from a single listener registered per module (`ExpoIapHelper.kt`), buffering
409
+ * events while disconnected and flushing them on the next successful
410
+ * `initConnection` (`ExpoIapModule.kt:198-205`). Claiming unconditionally
411
+ * therefore let another product's failure — or a stale buffered one — answer
412
+ * this purchase, after which the real transaction arrived to a caller that
413
+ * had already been told "error".
414
+ */
415
+ const handleError = (e: any) => {
416
+ const open = [...waiters].filter((w) => !w.settled);
417
+ if (open.length === 0) return;
418
+ const named = errorSkus(e);
419
+ // With no product named there is nothing to match on, so attribute it only
420
+ // when a single purchase is in flight and it cannot be anyone else's.
421
+ const target =
422
+ named.length > 0
423
+ ? open.find((w) => named.includes(w.sku))
424
+ : open.length === 1
425
+ ? open[0]
426
+ : undefined;
427
+ target?.answer(failureFor(e));
428
+ };
429
+
430
+ const listen = () => {
431
+ if (subscriptions) return;
432
+ const M = required();
433
+ const subs: { remove?(): void }[] = [];
434
+ if (typeof M.purchaseUpdatedListener === "function") {
435
+ subs.push(M.purchaseUpdatedListener((p: any) => void handleUpdated(p)));
436
+ }
437
+ if (typeof M.purchaseErrorListener === "function") {
438
+ subs.push(M.purchaseErrorListener((e: any) => handleError(e)));
439
+ }
440
+ subscriptions = subs;
441
+ };
442
+
75
443
  // Every expo-iap query fails until the store connection is open, and nothing
76
444
  // opens it implicitly — `useIAP` does it for hook consumers, but this adapter
77
445
  // is not a hook. Cached so concurrent getProducts/purchase/restore calls share
@@ -81,7 +449,10 @@ export const expoIapProductProvider = (Iap: any = IAP): ProductProvider => {
81
449
  let connecting: Promise<unknown> | null = null;
82
450
  const connect = async () => {
83
451
  const M = required();
84
- if (typeof M.initConnection !== "function") return; // older peer: implicit connection
452
+ if (typeof M.initConnection !== "function") {
453
+ listen(); // older peer: implicit connection, but events still arrive
454
+ return;
455
+ }
85
456
  if (!connecting) {
86
457
  connecting = Promise.resolve(M.initConnection()).catch((e: unknown) => {
87
458
  connecting = null;
@@ -89,51 +460,142 @@ export const expoIapProductProvider = (Iap: any = IAP): ProductProvider => {
89
460
  });
90
461
  }
91
462
  await connecting;
463
+ // As early as possible, and before any purchase: a transaction replayed at
464
+ // launch has no caller, and a listener attached later would inherit a
465
+ // dedupe history that hides it.
466
+ listen();
467
+ };
468
+
469
+ /**
470
+ * Run a READ, reopening the connection once if it turns out to be gone.
471
+ *
472
+ * `requestPurchase` is deliberately NOT run through this. An earlier version
473
+ * did, on the stated reasoning that a CONNECTION_LOST code is thrown before
474
+ * any billing flow starts — which the Android module disproves.
475
+ * `requestPurchase` sets `reachedOpenIapRequest = true` BEFORE calling
476
+ * `openIap.requestPurchase` (`ExpoIapModule.kt:435-436`), and
477
+ * `deliverPurchaseRequestFailure` (`:63-75`) rejects the pending promise on
478
+ * every path, mid-flight included. Worse, `service-disconnected` is the
479
+ * catch-all code for any failure that is not an `OpenIapError` (`:60-61`), so
480
+ * the code carries no information about whether the sheet was ever shown.
481
+ * Retrying it can present a SECOND sheet, charge a consumable twice, and
482
+ * discard the result.
483
+ */
484
+ const withConnection = async <T>(op: () => Promise<T>): Promise<T> => {
485
+ await connect();
486
+ try {
487
+ return await op();
488
+ } catch (e: any) {
489
+ if (!CONNECTION_LOST.has(String(e?.code))) throw e;
490
+ connecting = null;
491
+ await connect();
492
+ return await op();
493
+ }
92
494
  };
93
495
 
94
- // The raw store product per resolved productId, captured during getProducts.
95
- // `purchase()` needs expo-iap's own `type` discriminator ("in-app" | "subs")
96
- // and the full Purchase to finish, neither of which survives the trip through
97
- // `ResolvedProduct`. Same pattern as stripeLink's `linkByKey`.
98
- const rawById = new Map<string, any>();
496
+ // Per REF key, not per productId: two refs routinely name the same Play
497
+ // subscription through different base plans ("pro:annual", "pro:monthly"),
498
+ // and they need different offer tokens. Never cleared — a second resolve used
499
+ // to wipe the first set, leaving already-rendered products unpurchasable.
500
+ const metaByKey = new Map<string, ResolvedMeta>();
99
501
 
100
502
  return {
503
+ dispose() {
504
+ for (const s of subscriptions ?? []) {
505
+ try {
506
+ s.remove?.();
507
+ } catch {
508
+ // a peer whose subscription has no remove(); nothing to undo
509
+ }
510
+ }
511
+ subscriptions = null;
512
+ },
513
+
101
514
  async getProducts(refs: ProductRef[]): Promise<ResolvedProduct[]> {
102
515
  const M = required();
103
- const wanted = refs.map((r) => ({ ref: r, id: idFor(r) })).filter((x) => !!x.id);
516
+ const wanted = refs
517
+ .map((ref) => {
518
+ const authored = idFor(ref);
519
+ if (!authored) return null;
520
+ if (Platform.OS === "ios") return { ref, id: authored, basePlanId: undefined };
521
+ const { productId, basePlanId } = splitAndroidRef(authored);
522
+ return { ref, id: productId, basePlanId };
523
+ })
524
+ .filter((x): x is { ref: ProductRef; id: string; basePlanId: string | undefined } => !!x);
104
525
  if (wanted.length === 0) return [];
105
- await connect();
106
- const skus = wanted.map((w) => w.id as string);
526
+
527
+ // Deduped: two base plans of one subscription are one product query.
528
+ const skus = Array.from(new Set(wanted.map((w) => w.id)));
107
529
 
108
530
  // 5.x renamed `getProducts(skus)` to `fetchProducts({ skus, type })` — an
109
531
  // object arg, not a positional array. Calling the old name on 5.x throws
110
532
  // "M.getProducts is not a function", so probe rather than assume; `"all"`
111
533
  // because a paywall mixes subscriptions and one-off lifetime products.
112
- const store =
534
+ const store = await withConnection(() =>
113
535
  typeof M.fetchProducts === "function"
114
- ? await M.fetchProducts({ skus, type: "all" })
115
- : await M.getProducts(skus);
536
+ ? M.fetchProducts({ skus, type: "all" })
537
+ : M.getProducts(skus)
538
+ );
539
+
540
+ // `FetchProductsResult` includes `null` (`types.d.ts:527`). Coercing that
541
+ // to `[]` put the runtime in `status: "ready"` with an empty catalog, so
542
+ // every `{{product.*}}` rendered blank and nothing said why. A failed
543
+ // query is an error; `useProducts` has a state for it.
544
+ if (!Array.isArray(store)) {
545
+ throw new Error(
546
+ `expoIapProductProvider: expo-iap did not return a product list for [${skus.join(", ")}] ` +
547
+ `(got ${store === null ? "null" : typeof store}). The store query failed.`
548
+ );
549
+ }
550
+
551
+ const byId = new Map<string, any>(store.map((s: any) => [s.id ?? s.productId, s]));
552
+ const missing = skus.filter((id) => !byId.has(id));
553
+ if (missing.length > 0) {
554
+ // Silence here is how a blank paywall reaches `status: "ready"`: an id
555
+ // the store does not know is simply absent from the answer.
556
+ console.warn(
557
+ `expoIapProductProvider: the store returned no product for [${missing.join(", ")}]. ` +
558
+ `Check the id is registered and approved for this platform.`
559
+ );
560
+ }
116
561
 
117
- const list: any[] = Array.isArray(store) ? store : [];
118
- const byId = new Map<string, any>(list.map((s: any) => [s.id ?? s.productId, s]));
119
- rawById.clear();
120
562
  const out: ResolvedProduct[] = [];
121
- for (const { ref, id } of wanted) {
122
- const s = byId.get(id as string);
563
+ for (const { ref, id, basePlanId } of wanted) {
564
+ const s = byId.get(id);
123
565
  if (!s) continue;
124
566
  const productId = s.id ?? s.productId;
125
- rawById.set(productId, s);
126
- const iso = periodIsoFrom(s);
567
+ const offer = offerFor(s, basePlanId, productId);
568
+ const phase = recurringPhase(offer);
569
+ const iso = periodIsoFrom(s, phase);
127
570
  const { period, count } = toPeriod(iso);
571
+
572
+ metaByKey.set(ref.key, {
573
+ type: s.type,
574
+ offerToken: offer?.offerTokenAndroid ?? undefined,
575
+ });
576
+ // Only iOS publishes the discriminator. Android one-time products are
577
+ // all `type: "in-app"` and consumability is the app's decision, so a
578
+ // Play consumable still needs the host to say so — see the CHANGELOG.
579
+ consumableBySku.set(productId, s.typeIOS === "consumable");
580
+
128
581
  out.push({
129
582
  key: ref.key,
130
583
  productId,
131
584
  store: Platform.OS === "ios" ? "app_store" : "play_store",
132
585
  title: s.title ?? "",
133
586
  description: s.description ?? "",
134
- price: s.displayPrice ?? s.localizedPrice ?? "",
135
- priceAmount: Number(s.price ?? 0),
136
- currencyCode: s.currency ?? s.currencyCode ?? "",
587
+ // Phase fallbacks only: what the store reports at the top level stays
588
+ // authoritative. On Android the base plan's price lives in the phase,
589
+ // and this run had no device to confirm whether openiap fills the
590
+ // top-level fields for a subscription.
591
+ price: s.displayPrice ?? s.localizedPrice ?? phase?.formattedPrice ?? "",
592
+ priceAmount:
593
+ typeof s.price === "number"
594
+ ? s.price
595
+ : phase?.priceAmountMicros != null
596
+ ? Number(phase.priceAmountMicros) / 1_000_000
597
+ : 0,
598
+ currencyCode: s.currency ?? s.currencyCode ?? phase?.priceCurrencyCode ?? "",
137
599
  period,
138
600
  periodCount: count,
139
601
  periodIso: iso,
@@ -142,67 +604,136 @@ export const expoIapProductProvider = (Iap: any = IAP): ProductProvider => {
142
604
  return out;
143
605
  },
144
606
 
145
- async purchase(product) {
607
+ async purchase(product): Promise<PurchaseResult> {
146
608
  const M = required();
609
+ const meta = metaByKey.get(product.key);
610
+ const sku = product.productId;
611
+ // `periodIso`, not `period`: `toPeriod` rejects a compound duration like
612
+ // "P1Y1M", so a `period`-based test called a real subscription "in-app"
613
+ // and Play rejects the wrong type outright.
614
+ const isSubs = (meta?.type ?? (product.periodIso ? "subs" : "in-app")) === "subs";
615
+
147
616
  try {
148
617
  await connect();
149
- const raw = rawById.get(product.productId);
150
- // A non-null period means a subscription even when the raw product is
151
- // missing (a host that hydrated the runtime from elsewhere).
152
- const isSubs = (raw?.type ?? (product.period ? "subs" : "in-app")) === "subs";
153
- const sku = product.productId;
154
-
155
- // 5.x wants `{ request: { ios, android }, type }`. The old flat
156
- // `{ request: { sku } }` reaches neither platform branch, so StoreKit is
157
- // handed an undefined sku. `type` is required to tell a subscription
158
- // from a one-off — Play rejects the wrong one outright.
159
- const args =
160
- typeof M.fetchProducts === "function"
161
- ? {
162
- request: { ios: { sku }, android: { skus: [sku] } },
163
- type: isSubs ? "subs" : "in-app",
164
- }
165
- : { request: { sku } };
166
-
167
- const result = await M.requestPurchase(args as any);
168
-
169
- // `requestPurchase` resolves `Purchase | Purchase[] | null`. `null` is
170
- // the normal 5.x outcome: the transaction is delivered to
171
- // `purchaseUpdatedListener` instead, so at this point nothing is
172
- // confirmed. Reporting "purchased" there would grant access for a
173
- // purchase that may still fail — hence "pending", which is exactly the
174
- // outcome `PurchaseButtonAction.onPending` exists to handle.
175
- const purchase = Array.isArray(result) ? result[0] : result;
176
- if (!purchase) return { status: "pending" };
177
-
178
- // Unfinished transactions are re-delivered by StoreKit on every launch
179
- // until finished. Best-effort: a failure here does not un-buy anything,
180
- // so it must not turn a completed purchase into an error.
181
- if (typeof M.finishTransaction === "function") {
182
- try {
183
- await M.finishTransaction({ purchase, isConsumable: false });
184
- } catch {
185
- // ignore — reported as purchased, will be re-delivered and finished later
618
+ } catch (e) {
619
+ return failureFor(e);
620
+ }
621
+ // An acknowledgement that failed earlier gets another go now that the
622
+ // store is reachable, before anything new is dispatched.
623
+ await retryUnfinished();
624
+
625
+ let resolveWaiter!: (r: PurchaseResult) => void;
626
+ const waiter: Waiter = {
627
+ sku,
628
+ productKey: product.key,
629
+ answer: (r) => {
630
+ if (waiter.settled) return;
631
+ waiter.settled = r;
632
+ resolveWaiter(r);
633
+ },
634
+ promise: new Promise<PurchaseResult>((resolve) => {
635
+ resolveWaiter = resolve;
636
+ }),
637
+ };
638
+ waiters.add(waiter);
639
+ // Recorded BEFORE dispatch: on a fast store the transaction can be
640
+ // delivered before `requestPurchase` resolves.
641
+ dispatchedSkus.add(sku);
642
+
643
+ let timer: ReturnType<typeof setTimeout> | undefined;
644
+ try {
645
+ const apple = { sku };
646
+ const google: Record<string, unknown> = { skus: [sku] };
647
+ if (isSubs) {
648
+ // Play needs an offer token to know WHICH base plan is being bought;
649
+ // without one it cannot start the billing flow. `in-app` must NOT
650
+ // carry the field — expo-iap rejects the mismatch outright
651
+ // (`validateAndroidPurchaseBranchOptions`, `build/index.js:659-676`).
652
+ if (meta?.offerToken) {
653
+ google.subscriptionOffers = [{ sku, offerToken: meta.offerToken }];
654
+ } else if (Platform.OS === "android") {
655
+ console.warn(
656
+ `expoIapProductProvider: no Play offer token for "${sku}" — the base plan cannot ` +
657
+ `be selected and the purchase will fail. Author the ref as "productId:basePlanId".`
658
+ );
186
659
  }
187
660
  }
188
- return { status: "purchased", productKey: product.key };
661
+
662
+ // ONE shape for every supported peer. `normalizeRequestProps` reads
663
+ // `request.apple` / `request.google` in 5.x (`build/index.js:650-656`);
664
+ // 4.x reads the same keys first and only warns when it falls back to
665
+ // `request.ios` / `request.android` (4.7.2 `build/index.js:666-679`).
666
+ // So there is nothing to version-probe here — and probing on
667
+ // `fetchProducts` never worked anyway, since 4.4+ has it too.
668
+ //
669
+ // NOT wrapped in `withConnection`: see its comment. A retry here can
670
+ // present a second store sheet.
671
+ const dispatched = await M.requestPurchase({
672
+ request: { apple, google },
673
+ type: isSubs ? "subs" : "in-app",
674
+ });
675
+
676
+ // iOS resolves the transaction directly when StoreKit hands one back,
677
+ // and `[]` / `null` otherwise (`build/index.js:745-751`). Route it
678
+ // through the same handler — including the sku check, which the
679
+ // listener path applies and this one used to skip.
680
+ const direct = Array.isArray(dispatched) ? dispatched[0] : dispatched;
681
+ if (direct && deliversFor(direct, sku)) await handleUpdated(direct);
682
+ if (waiter.settled) return waiter.settled;
683
+
684
+ // A peer too old to have `purchaseUpdatedListener` has no way to tell us
685
+ // how this ended, so there is nothing to wait for.
686
+ if (typeof M.purchaseUpdatedListener !== "function") return { status: "pending" };
687
+
688
+ return await Promise.race([
689
+ waiter.promise,
690
+ new Promise<PurchaseResult>((resolve) => {
691
+ timer = setTimeout(() => resolve({ status: "pending" }), purchaseTimeoutMs);
692
+ }),
693
+ ]);
189
694
  } catch (e: any) {
190
- if (isCancellation(e)) return { status: "cancelled" };
191
- return { status: "error", error: e instanceof Error ? e : new Error(String(e)) };
695
+ // The store's own event is more specific than a rejection that may only
696
+ // say `service-disconnected`, so an answer already delivered wins.
697
+ return waiter.settled ?? failureFor(e);
698
+ } finally {
699
+ if (timer) clearTimeout(timer);
700
+ // Only the ANSWER slot closes here. The listeners stay attached and the
701
+ // sku stays in `dispatchedSkus`, so a verdict arriving after this call
702
+ // has returned is still acknowledged.
703
+ waiters.delete(waiter);
192
704
  }
193
705
  },
194
706
 
195
707
  async restore() {
196
708
  const M = required();
197
709
  try {
198
- await connect();
199
- const purchases = await M.getAvailablePurchases();
200
- const ids: string[] = (purchases ?? []).map((p: any) => p.id ?? p.productId).filter(Boolean);
710
+ const purchases = await withConnection(async () => {
711
+ // `restorePurchases()` performs the iOS StoreKit sync first and then
712
+ // refreshes, but deliberately returns nothing — "consumers should
713
+ // call `getAvailablePurchases`" (`build/index.js:886-899`). Behind a
714
+ // user-facing Restore button that sync is the point.
715
+ if (typeof M.restorePurchases === "function") {
716
+ await M.restorePurchases();
717
+ }
718
+ return M.getAvailablePurchases();
719
+ });
720
+ // `productId`, not `id`: `Purchase.id` is the TRANSACTION id and is
721
+ // always set (`types.d.ts:1151`), so `p.id ?? p.productId` never fell
722
+ // through and restore handed the host transaction ids to match against
723
+ // its entitlements. `?? p.id` stays for a peer that only has the one.
724
+ const ids = Array.from(
725
+ new Set(
726
+ (Array.isArray(purchases) ? purchases : [])
727
+ .filter(isPaid)
728
+ .map((p: any) => p.productId ?? p.id)
729
+ .filter(Boolean)
730
+ )
731
+ ) as string[];
201
732
  return ids.length > 0
202
- ? { status: "restored", entitlements: ids }
203
- : { status: "nothing_to_restore" };
733
+ ? { status: "restored" as const, entitlements: ids }
734
+ : { status: "nothing_to_restore" as const };
204
735
  } catch (e) {
205
- return { status: "error", error: e instanceof Error ? e : new Error(String(e)) };
736
+ return { status: "error" as const, error: asError(e) };
206
737
  }
207
738
  },
208
739
  };