@nosslabs/iap 8.0.0 → 8.1.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.
- package/CHANGELOG.md +476 -1
- package/README.md +9 -2
- package/dist/index.cjs +1911 -412
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +905 -217
- package/dist/index.d.ts +905 -217
- package/dist/index.js +1910 -413
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -60,8 +60,9 @@ var init_errors = __esm({
|
|
|
60
60
|
// appUserId pre-attach
|
|
61
61
|
/**
|
|
62
62
|
* The supplied `appUserId` (literal or fetcher-returned) is not a valid
|
|
63
|
-
* UUID
|
|
64
|
-
* same constraint cross-platform for a consistent contract.
|
|
63
|
+
* RFC 9562 UUID. Apple requires a UUID for `appAccountToken`; we enforce
|
|
64
|
+
* the same constraint cross-platform for a consistent contract. Any
|
|
65
|
+
* version is accepted — see `isValidUuid` for what is still refused.
|
|
65
66
|
*/
|
|
66
67
|
INVALID_APP_USER_ID: "INVALID_APP_USER_ID",
|
|
67
68
|
/**
|
|
@@ -101,7 +102,7 @@ var init_errors = __esm({
|
|
|
101
102
|
// Storage
|
|
102
103
|
STORAGE_ERROR: "Capacitor Preferences write failed. Check device storage availability; the in-memory state is still updated, only persistence failed.",
|
|
103
104
|
// appUserId pre-attach
|
|
104
|
-
INVALID_APP_USER_ID: "appUserId must be
|
|
105
|
+
INVALID_APP_USER_ID: "appUserId must be an RFC 9562 UUID of any version (e.g. crypto.randomUUID(), or a UUIDv5 over a stable name). Apple requires a UUID for appAccountToken; we enforce the same on Android for consistency. Refused: the nil and max UUIDs, and non-RFC version/variant nibbles \u2014 so an id that merely looks like a UUID (a hyphen-formatted hash) will not pass.",
|
|
105
106
|
APP_USER_ID_FETCH_FAILED: "The async appUserId fetcher threw or rejected. Inspect the cause field for the underlying error (network failure, backend non-2xx, parse failure)."
|
|
106
107
|
};
|
|
107
108
|
IAPError = class _IAPError extends Error {
|
|
@@ -137,6 +138,280 @@ var init_platform = __esm({
|
|
|
137
138
|
}
|
|
138
139
|
});
|
|
139
140
|
|
|
141
|
+
// src/adapters/native/capgo/map-purchase-error.ts
|
|
142
|
+
function mapPurchaseError(error, productId) {
|
|
143
|
+
if (error instanceof IAPError) return error;
|
|
144
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
145
|
+
const lower = message.toLowerCase();
|
|
146
|
+
if (lower.includes("cancel")) {
|
|
147
|
+
return new IAPError({
|
|
148
|
+
code: IAPErrorCode.USER_CANCELLED,
|
|
149
|
+
message: `Purchase of "${productId}" was cancelled.`,
|
|
150
|
+
cause: error
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
if (lower.includes("pending")) {
|
|
154
|
+
return new IAPError({
|
|
155
|
+
code: IAPErrorCode.PURCHASE_PENDING,
|
|
156
|
+
message: `Purchase of "${productId}" is pending external clearance.`,
|
|
157
|
+
cause: error
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
if (lower.includes("product not found") || lower.includes("cannot find product")) {
|
|
161
|
+
return new IAPError({
|
|
162
|
+
code: IAPErrorCode.PRODUCT_NOT_FOUND,
|
|
163
|
+
message: `Product "${productId}" was not found in the store catalog.`,
|
|
164
|
+
cause: error
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
return new IAPError({
|
|
168
|
+
code: IAPErrorCode.STORE_ERROR,
|
|
169
|
+
message: `Native purchase of "${productId}" failed.`,
|
|
170
|
+
cause: error
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
var init_map_purchase_error = __esm({
|
|
174
|
+
"src/adapters/native/capgo/map-purchase-error.ts"() {
|
|
175
|
+
init_errors();
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
// src/lib/subscription-period.ts
|
|
180
|
+
function toIso8601Duration(period) {
|
|
181
|
+
if (!period || typeof period !== "object" || Array.isArray(period)) return null;
|
|
182
|
+
const { numberOfUnits, unit, unitString } = period;
|
|
183
|
+
if (typeof numberOfUnits !== "number" || !Number.isInteger(numberOfUnits) || numberOfUnits <= 0) {
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
const designator = (typeof unitString === "string" ? UNIT_BY_NAME.get(unitString) : void 0) ?? (typeof unit === "number" ? UNIT_BY_INT.get(unit) : void 0);
|
|
187
|
+
if (!designator) return null;
|
|
188
|
+
return `P${numberOfUnits}${designator}`;
|
|
189
|
+
}
|
|
190
|
+
var UNIT_BY_INT, UNIT_BY_NAME;
|
|
191
|
+
var init_subscription_period = __esm({
|
|
192
|
+
"src/lib/subscription-period.ts"() {
|
|
193
|
+
UNIT_BY_INT = /* @__PURE__ */ new Map([
|
|
194
|
+
[0, "D"],
|
|
195
|
+
[1, "W"],
|
|
196
|
+
[2, "M"],
|
|
197
|
+
[3, "Y"]
|
|
198
|
+
]);
|
|
199
|
+
UNIT_BY_NAME = /* @__PURE__ */ new Map([
|
|
200
|
+
["day", "D"],
|
|
201
|
+
["week", "W"],
|
|
202
|
+
["month", "M"],
|
|
203
|
+
["year", "Y"]
|
|
204
|
+
]);
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
// src/adapters/native/capgo/normalize-product.ts
|
|
209
|
+
function resolveProducts(payloads, requests) {
|
|
210
|
+
const products = [];
|
|
211
|
+
for (const request of requests) {
|
|
212
|
+
const candidates = payloads.filter((payload) => {
|
|
213
|
+
const p = payload;
|
|
214
|
+
return p.identifier === request.id || p.planIdentifier === request.id;
|
|
215
|
+
});
|
|
216
|
+
if (candidates.length === 0) continue;
|
|
217
|
+
products.push(normalizeProduct(pickCandidate(candidates, request.androidPlanId), request));
|
|
218
|
+
}
|
|
219
|
+
return products;
|
|
220
|
+
}
|
|
221
|
+
function pickCandidate(candidates, androidPlanId) {
|
|
222
|
+
const named = androidPlanId !== void 0 ? candidates.find((c) => c.identifier === androidPlanId) : void 0;
|
|
223
|
+
const basePlan = candidates.find((c) => (c.offerId ?? null) === null);
|
|
224
|
+
return named ?? basePlan ?? candidates[0];
|
|
225
|
+
}
|
|
226
|
+
function normalizeProduct(raw, request) {
|
|
227
|
+
const p = raw;
|
|
228
|
+
return {
|
|
229
|
+
// The id the consumer configured, so a Product round-trips to
|
|
230
|
+
// `purchase({ productId })`. On Android `p.identifier` is a base plan,
|
|
231
|
+
// which is reported separately as `androidBasePlanId`.
|
|
232
|
+
id: request.id,
|
|
233
|
+
type: request.type,
|
|
234
|
+
title: p.title,
|
|
235
|
+
description: p.description,
|
|
236
|
+
priceString: p.priceString,
|
|
237
|
+
priceMicros: toMicros(p.price),
|
|
238
|
+
currency: p.currencyCode,
|
|
239
|
+
// `toIso8601Duration` returns null for the `{ numberOfUnits: 0, unit: 0 }`
|
|
240
|
+
// placeholder a non-subscription carries, and for Android's absent value.
|
|
241
|
+
subscriptionPeriod: toIso8601Duration(p.subscriptionPeriod),
|
|
242
|
+
// capgo sends "" rather than null for a product with no group.
|
|
243
|
+
subscriptionGroupId: p.subscriptionGroupIdentifier || null,
|
|
244
|
+
introductoryOffer: p.introductoryPrice ? normalizeOffer(p.introductoryPrice) : null,
|
|
245
|
+
promotionalOffers: (p.discounts ?? []).map(normalizeOffer),
|
|
246
|
+
androidOfferToken: p.offerToken ?? null,
|
|
247
|
+
androidOfferId: p.offerId ?? null,
|
|
248
|
+
// Android only: the base plan this entry describes. Null on iOS, where
|
|
249
|
+
// `identifier` is the product id and there is no base-plan concept.
|
|
250
|
+
androidBasePlanId: p.planIdentifier !== void 0 ? p.identifier : null
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
function toMicros(price) {
|
|
254
|
+
if (typeof price !== "number" || !Number.isFinite(price)) return "0";
|
|
255
|
+
return Math.round(price * 1e6).toString();
|
|
256
|
+
}
|
|
257
|
+
function normalizeOffer(discount) {
|
|
258
|
+
return {
|
|
259
|
+
// An iOS introductory offer and an Android base-plan intro phase both
|
|
260
|
+
// arrive with an empty identifier; neither is named by its store.
|
|
261
|
+
id: discount.identifier || null,
|
|
262
|
+
type: mapOfferType(discount.type),
|
|
263
|
+
payment: mapOfferPayment(discount.paymentMode),
|
|
264
|
+
priceString: discount.priceString,
|
|
265
|
+
priceMicros: toMicros(discount.price),
|
|
266
|
+
currency: discount.currencyCode,
|
|
267
|
+
period: toIso8601Duration(discount.subscriptionPeriod),
|
|
268
|
+
periodCount: discount.numberOfPeriods
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
function mapOfferType(type) {
|
|
272
|
+
switch (type) {
|
|
273
|
+
case 0:
|
|
274
|
+
return "introductory";
|
|
275
|
+
case 1:
|
|
276
|
+
return "promotional";
|
|
277
|
+
case 2:
|
|
278
|
+
return "win-back";
|
|
279
|
+
default:
|
|
280
|
+
return "unknown";
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
function mapOfferPayment(paymentMode) {
|
|
284
|
+
switch (paymentMode) {
|
|
285
|
+
case 0:
|
|
286
|
+
return "free-trial";
|
|
287
|
+
case 1:
|
|
288
|
+
return "pay-up-front";
|
|
289
|
+
case 2:
|
|
290
|
+
return "pay-as-you-go";
|
|
291
|
+
default:
|
|
292
|
+
return "unknown";
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
var init_normalize_product = __esm({
|
|
296
|
+
"src/adapters/native/capgo/normalize-product.ts"() {
|
|
297
|
+
init_subscription_period();
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
// src/lib/jws.ts
|
|
302
|
+
function decodeBase64UrlSegment(segment) {
|
|
303
|
+
const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
|
|
304
|
+
const padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, "=");
|
|
305
|
+
let binary;
|
|
306
|
+
try {
|
|
307
|
+
binary = atob(padded);
|
|
308
|
+
} catch {
|
|
309
|
+
return null;
|
|
310
|
+
}
|
|
311
|
+
try {
|
|
312
|
+
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
313
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
314
|
+
} catch {
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
function readJwsClaims(jws) {
|
|
319
|
+
if (typeof jws !== "string" || jws.length === 0) return null;
|
|
320
|
+
const segments = jws.split(".");
|
|
321
|
+
if (segments.length !== 3) return null;
|
|
322
|
+
const payload = segments[1];
|
|
323
|
+
if (!payload) return null;
|
|
324
|
+
const json = decodeBase64UrlSegment(payload);
|
|
325
|
+
if (json === null) return null;
|
|
326
|
+
let parsed;
|
|
327
|
+
try {
|
|
328
|
+
parsed = JSON.parse(json);
|
|
329
|
+
} catch {
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
333
|
+
return parsed;
|
|
334
|
+
}
|
|
335
|
+
var init_jws = __esm({
|
|
336
|
+
"src/lib/jws.ts"() {
|
|
337
|
+
}
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
// src/adapters/native/capgo/normalize-transaction.ts
|
|
341
|
+
function normalizeTransaction(tx, productType, packageName) {
|
|
342
|
+
const platform = inferPlatform(tx);
|
|
343
|
+
const token = platform === "google" ? tx.purchaseToken ?? tx.transactionId : tx.transactionId;
|
|
344
|
+
const native = {
|
|
345
|
+
platform,
|
|
346
|
+
productId: tx.productIdentifier,
|
|
347
|
+
token,
|
|
348
|
+
purchaseReference: purchaseReferenceFor(tx, platform, token),
|
|
349
|
+
productType,
|
|
350
|
+
// Lower-cased so it compares equal to what the caller supplied:
|
|
351
|
+
// StoreKit returns `UUID.uuidString`, which Swift renders uppercase,
|
|
352
|
+
// while `crypto.randomUUID()` and iap's case-insensitive validator both
|
|
353
|
+
// deal in lowercase. Returned raw, the binding would never `===` the
|
|
354
|
+
// value that was sent — the one comparison this field exists for.
|
|
355
|
+
appUserId: tx.appAccountToken?.toLowerCase() ?? null,
|
|
356
|
+
subscription: normalizeSubscription(tx, productType),
|
|
357
|
+
raw: tx
|
|
358
|
+
};
|
|
359
|
+
if (native.platform === "google" && packageName) {
|
|
360
|
+
native.packageName = packageName;
|
|
361
|
+
}
|
|
362
|
+
return native;
|
|
363
|
+
}
|
|
364
|
+
function purchaseReferenceFor(tx, platform, token) {
|
|
365
|
+
if (platform === "google" || !tx.jwsRepresentation) return token;
|
|
366
|
+
const claims = readJwsClaims(tx.jwsRepresentation);
|
|
367
|
+
const original = claims?.originalTransactionId;
|
|
368
|
+
return typeof original === "string" && original.length > 0 ? original : token;
|
|
369
|
+
}
|
|
370
|
+
function normalizeSubscription(tx, productType) {
|
|
371
|
+
if (productType !== "subscription") return null;
|
|
372
|
+
const renewalInfo = tx.renewalInfo;
|
|
373
|
+
const state = tx.subscriptionState ? SUBSCRIPTION_STATES.get(tx.subscriptionState) ?? "unknown" : null;
|
|
374
|
+
const autoRenewing = renewalInfo?.willAutoRenew ?? (typeof tx.willCancel === "boolean" ? !tx.willCancel : null);
|
|
375
|
+
const renewal = {
|
|
376
|
+
state,
|
|
377
|
+
autoRenewing,
|
|
378
|
+
renewsAt: renewalInfo?.renewalDate ?? null,
|
|
379
|
+
renewalProductId: renewalInfo?.autoRenewProductId ?? null,
|
|
380
|
+
expiresAt: tx.expirationDate ?? null
|
|
381
|
+
};
|
|
382
|
+
const reportedNothing = renewal.state === null && renewal.autoRenewing === null && renewal.renewsAt === null && renewal.renewalProductId === null && renewal.expiresAt === null;
|
|
383
|
+
return reportedNothing ? null : renewal;
|
|
384
|
+
}
|
|
385
|
+
function inferPlatform(tx) {
|
|
386
|
+
if (tx.purchaseToken !== void 0 || tx.purchaseState !== void 0 || tx.orderId !== void 0) {
|
|
387
|
+
return "google";
|
|
388
|
+
}
|
|
389
|
+
if (tx.receipt !== void 0 || tx.jwsRepresentation !== void 0) {
|
|
390
|
+
return "apple";
|
|
391
|
+
}
|
|
392
|
+
return getPlatform() === "android" ? "google" : "apple";
|
|
393
|
+
}
|
|
394
|
+
function inferProductType(tx, configured) {
|
|
395
|
+
if (tx.productType === "subs") return "subscription";
|
|
396
|
+
const declared = configured?.find((p) => p.id === tx.productIdentifier)?.type;
|
|
397
|
+
return declared === "consumable" ? "consumable" : "product";
|
|
398
|
+
}
|
|
399
|
+
var SUBSCRIPTION_STATES;
|
|
400
|
+
var init_normalize_transaction = __esm({
|
|
401
|
+
"src/adapters/native/capgo/normalize-transaction.ts"() {
|
|
402
|
+
init_jws();
|
|
403
|
+
init_platform();
|
|
404
|
+
SUBSCRIPTION_STATES = /* @__PURE__ */ new Map([
|
|
405
|
+
["subscribed", "subscribed"],
|
|
406
|
+
["expired", "expired"],
|
|
407
|
+
["revoked", "revoked"],
|
|
408
|
+
["inGracePeriod", "in-grace-period"],
|
|
409
|
+
["inBillingRetryPeriod", "in-billing-retry"],
|
|
410
|
+
["unknown", "unknown"]
|
|
411
|
+
]);
|
|
412
|
+
}
|
|
413
|
+
});
|
|
414
|
+
|
|
140
415
|
// src/lib/iso-country.ts
|
|
141
416
|
function toAlpha2(code) {
|
|
142
417
|
if (!code) return null;
|
|
@@ -401,12 +676,6 @@ var init_iso_country = __esm({
|
|
|
401
676
|
};
|
|
402
677
|
}
|
|
403
678
|
});
|
|
404
|
-
|
|
405
|
-
// src/adapters/native/capgo/native-adapter.ts
|
|
406
|
-
var native_adapter_exports = {};
|
|
407
|
-
__export(native_adapter_exports, {
|
|
408
|
-
CapgoNativeAdapter: () => CapgoNativeAdapter
|
|
409
|
-
});
|
|
410
679
|
function nativeStorefrontRegistered() {
|
|
411
680
|
const headers = Capacitor.PluginHeaders;
|
|
412
681
|
return headers?.find((h) => h.name === "NativePurchases")?.methods?.some((m) => m.name === "getStorefront") ?? false;
|
|
@@ -424,84 +693,139 @@ function normalizeStorefront(raw) {
|
|
|
424
693
|
platform
|
|
425
694
|
};
|
|
426
695
|
}
|
|
427
|
-
function
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
currency: p.currencyCode
|
|
437
|
-
};
|
|
438
|
-
}
|
|
439
|
-
function normalizeTransaction(tx, productType) {
|
|
440
|
-
const platform = inferPlatform(tx);
|
|
441
|
-
const token = platform === "google" ? tx.purchaseToken ?? tx.transactionId : tx.transactionId;
|
|
442
|
-
const native = {
|
|
443
|
-
platform,
|
|
444
|
-
productId: tx.productIdentifier,
|
|
445
|
-
token,
|
|
446
|
-
productType,
|
|
447
|
-
raw: tx
|
|
448
|
-
};
|
|
449
|
-
return native;
|
|
696
|
+
async function readStorefront() {
|
|
697
|
+
if (!nativeStorefrontRegistered()) return null;
|
|
698
|
+
const np = NativePurchases;
|
|
699
|
+
try {
|
|
700
|
+
const raw = await np.getStorefront?.();
|
|
701
|
+
return raw ? normalizeStorefront(raw) : null;
|
|
702
|
+
} catch {
|
|
703
|
+
return null;
|
|
704
|
+
}
|
|
450
705
|
}
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
706
|
+
var init_storefront = __esm({
|
|
707
|
+
"src/adapters/native/capgo/storefront.ts"() {
|
|
708
|
+
init_iso_country();
|
|
709
|
+
init_platform();
|
|
454
710
|
}
|
|
455
|
-
|
|
456
|
-
|
|
711
|
+
});
|
|
712
|
+
async function watchCapgoTransactions(onUpdate, logger, packageName, getConfiguredProducts) {
|
|
713
|
+
const handles = [];
|
|
714
|
+
try {
|
|
715
|
+
handles.push(
|
|
716
|
+
await NativePurchases.addListener("transactionUpdated", (tx) => {
|
|
717
|
+
try {
|
|
718
|
+
onUpdate(
|
|
719
|
+
normalizeTransaction(tx, inferProductType(tx, getConfiguredProducts?.()), packageName)
|
|
720
|
+
);
|
|
721
|
+
} catch (error) {
|
|
722
|
+
logger.warn("transactionUpdated handler threw; ignoring the update.", error);
|
|
723
|
+
}
|
|
724
|
+
})
|
|
725
|
+
);
|
|
726
|
+
} catch (error) {
|
|
727
|
+
logger.warn(
|
|
728
|
+
"Could not subscribe to native transaction updates; renewals and refunds will be picked up at the next launch or resume instead.",
|
|
729
|
+
error
|
|
730
|
+
);
|
|
731
|
+
return null;
|
|
457
732
|
}
|
|
458
|
-
|
|
733
|
+
try {
|
|
734
|
+
handles.push(
|
|
735
|
+
await NativePurchases.addListener("transactionVerificationFailed", (payload) => {
|
|
736
|
+
logger.warn(
|
|
737
|
+
`The store reported a transaction that failed Apple's verification; ignoring it. Reason: ${payload.error}`
|
|
738
|
+
);
|
|
739
|
+
})
|
|
740
|
+
);
|
|
741
|
+
} catch (error) {
|
|
742
|
+
logger.debug("Could not subscribe to transactionVerificationFailed.", error);
|
|
743
|
+
}
|
|
744
|
+
return {
|
|
745
|
+
async remove() {
|
|
746
|
+
for (const handle of handles) {
|
|
747
|
+
try {
|
|
748
|
+
await handle.remove();
|
|
749
|
+
} catch (error) {
|
|
750
|
+
logger.warn("Failed to remove a native transaction listener.", error);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
};
|
|
459
755
|
}
|
|
460
|
-
function
|
|
461
|
-
if (
|
|
462
|
-
|
|
756
|
+
async function getCapgoPendingProductIds(logger) {
|
|
757
|
+
if (getPlatform() !== "android") return null;
|
|
758
|
+
try {
|
|
759
|
+
const result = await NativePurchases.getPurchases();
|
|
760
|
+
return result.purchases.filter((tx) => tx.purchaseState !== void 0 && tx.purchaseState !== "1").map((tx) => tx.productIdentifier);
|
|
761
|
+
} catch (error) {
|
|
762
|
+
logger.warn("Could not read pending purchases from the store.", error);
|
|
763
|
+
return null;
|
|
764
|
+
}
|
|
463
765
|
}
|
|
766
|
+
var init_watch_transactions = __esm({
|
|
767
|
+
"src/adapters/native/capgo/watch-transactions.ts"() {
|
|
768
|
+
init_platform();
|
|
769
|
+
init_normalize_transaction();
|
|
770
|
+
}
|
|
771
|
+
});
|
|
772
|
+
|
|
773
|
+
// src/adapters/native/capgo/native-adapter.ts
|
|
774
|
+
var native_adapter_exports = {};
|
|
775
|
+
__export(native_adapter_exports, {
|
|
776
|
+
CapgoNativeAdapter: () => CapgoNativeAdapter
|
|
777
|
+
});
|
|
464
778
|
function mapToPluginPurchaseType(type) {
|
|
465
779
|
return type === "subscription" ? PURCHASE_TYPE.SUBS : PURCHASE_TYPE.INAPP;
|
|
466
780
|
}
|
|
467
|
-
function mapPurchaseError(error, productId) {
|
|
468
|
-
if (error instanceof IAPError) return error;
|
|
469
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
470
|
-
const lower = message.toLowerCase();
|
|
471
|
-
if (lower.includes("cancel")) {
|
|
472
|
-
return new IAPError({
|
|
473
|
-
code: IAPErrorCode.USER_CANCELLED,
|
|
474
|
-
message: `Purchase of "${productId}" was cancelled.`,
|
|
475
|
-
cause: error
|
|
476
|
-
});
|
|
477
|
-
}
|
|
478
|
-
if (lower.includes("pending")) {
|
|
479
|
-
return new IAPError({
|
|
480
|
-
code: IAPErrorCode.PURCHASE_PENDING,
|
|
481
|
-
message: `Purchase of "${productId}" is pending external clearance.`,
|
|
482
|
-
cause: error
|
|
483
|
-
});
|
|
484
|
-
}
|
|
485
|
-
if (lower.includes("product not found") || lower.includes("cannot find product")) {
|
|
486
|
-
return new IAPError({
|
|
487
|
-
code: IAPErrorCode.PRODUCT_NOT_FOUND,
|
|
488
|
-
message: `Product "${productId}" was not found in the store catalog.`,
|
|
489
|
-
cause: error
|
|
490
|
-
});
|
|
491
|
-
}
|
|
492
|
-
return new IAPError({
|
|
493
|
-
code: IAPErrorCode.STORE_ERROR,
|
|
494
|
-
message: `Native purchase of "${productId}" failed.`,
|
|
495
|
-
cause: error
|
|
496
|
-
});
|
|
497
|
-
}
|
|
498
781
|
var CapgoNativeAdapter;
|
|
499
782
|
var init_native_adapter = __esm({
|
|
500
783
|
"src/adapters/native/capgo/native-adapter.ts"() {
|
|
501
784
|
init_errors();
|
|
502
|
-
|
|
503
|
-
|
|
785
|
+
init_map_purchase_error();
|
|
786
|
+
init_normalize_product();
|
|
787
|
+
init_normalize_transaction();
|
|
788
|
+
init_storefront();
|
|
789
|
+
init_watch_transactions();
|
|
504
790
|
CapgoNativeAdapter = class {
|
|
791
|
+
/**
|
|
792
|
+
* @param logger used by the best-effort paths that swallow their failures.
|
|
793
|
+
* @param packageName the app's Android applicationId, from
|
|
794
|
+
* `config.android.packageName`. Stamped onto every Google transaction
|
|
795
|
+
* because the plugin does not report it and Google's verification
|
|
796
|
+
* APIs are keyed on it.
|
|
797
|
+
* @param getConfiguredProducts the catalog, for typing a transaction the
|
|
798
|
+
* store reported — the plugin's payload cannot distinguish a consumable
|
|
799
|
+
* from a one-time purchase, since Play calls both `'inapp'`.
|
|
800
|
+
*/
|
|
801
|
+
constructor(logger, packageName, getConfiguredProducts) {
|
|
802
|
+
this.logger = logger;
|
|
803
|
+
this.packageName = packageName;
|
|
804
|
+
this.getConfiguredProducts = getConfiguredProducts;
|
|
805
|
+
}
|
|
806
|
+
logger;
|
|
807
|
+
packageName;
|
|
808
|
+
getConfiguredProducts;
|
|
809
|
+
/**
|
|
810
|
+
* The configured catalog, for typing a transaction the store reported.
|
|
811
|
+
*
|
|
812
|
+
* An empty one is not benign: every store-reported consumable would type
|
|
813
|
+
* as `'product'`, be acknowledged rather than consumed, and stay owned —
|
|
814
|
+
* which is the bug the catalog exists to prevent, reachable by
|
|
815
|
+
* misconfiguration rather than by code. Warned once, since
|
|
816
|
+
* `getOwnedTransactions` runs on every refresh.
|
|
817
|
+
*/
|
|
818
|
+
configured() {
|
|
819
|
+
const products = this.getConfiguredProducts?.() ?? [];
|
|
820
|
+
if (products.length === 0 && !this.warnedAboutEmptyCatalog) {
|
|
821
|
+
this.warnedAboutEmptyCatalog = true;
|
|
822
|
+
this.logger.warn(
|
|
823
|
+
"The native adapter has no configured products, so a purchase the store reports cannot be recognised as a consumable and will be acknowledged rather than consumed \u2014 leaving it owned and unbuyable. This is a wiring problem inside iap; please report it."
|
|
824
|
+
);
|
|
825
|
+
}
|
|
826
|
+
return products;
|
|
827
|
+
}
|
|
828
|
+
warnedAboutEmptyCatalog = false;
|
|
505
829
|
async isAvailable() {
|
|
506
830
|
try {
|
|
507
831
|
const result = await NativePurchases.isBillingSupported();
|
|
@@ -514,9 +838,7 @@ var init_native_adapter = __esm({
|
|
|
514
838
|
if (requests.length === 0) return [];
|
|
515
839
|
const inappIds = [];
|
|
516
840
|
const subsIds = [];
|
|
517
|
-
const requestById = /* @__PURE__ */ new Map();
|
|
518
841
|
for (const req of requests) {
|
|
519
|
-
requestById.set(req.id, req.type);
|
|
520
842
|
if (req.type === "subscription") {
|
|
521
843
|
subsIds.push(req.id);
|
|
522
844
|
} else {
|
|
@@ -534,11 +856,10 @@ var init_native_adapter = __esm({
|
|
|
534
856
|
}) : Promise.resolve({ products: [] })
|
|
535
857
|
]);
|
|
536
858
|
const all = [...inapp.products, ...subs.products];
|
|
537
|
-
return all
|
|
859
|
+
return resolveProducts(all, requests);
|
|
538
860
|
}
|
|
539
861
|
async purchaseProduct(opts) {
|
|
540
862
|
const purchaseType = mapToPluginPurchaseType(opts.productType);
|
|
541
|
-
const isConsumable = opts.productType === "consumable";
|
|
542
863
|
let tx;
|
|
543
864
|
try {
|
|
544
865
|
tx = await NativePurchases.purchaseProduct({
|
|
@@ -546,17 +867,35 @@ var init_native_adapter = __esm({
|
|
|
546
867
|
productType: purchaseType,
|
|
547
868
|
planIdentifier: opts.androidPlanId,
|
|
548
869
|
appAccountToken: opts.appAccountToken,
|
|
549
|
-
|
|
870
|
+
// `false` even for a consumable, and this is load-bearing.
|
|
871
|
+
//
|
|
872
|
+
// `autoAcknowledgePurchases: false` does **not** cover the
|
|
873
|
+
// consumable case: the plugin's `PurchaseActionDecider` returns
|
|
874
|
+
// CONSUME whenever `isConsumable` is set, and its caller consumes
|
|
875
|
+
// without consulting `autoAcknowledgePurchases` — that flag is only
|
|
876
|
+
// read on the ACKNOWLEDGE branch. (Checked in the plugin's Java,
|
|
877
|
+
// not its docs, and guarded by a test in
|
|
878
|
+
// `tests/unit/native-plugin-contract.test.ts`.)
|
|
879
|
+
//
|
|
880
|
+
// So passing `true` here would have the plugin consume inside the
|
|
881
|
+
// purchase callback, before iap has verified anything — breaking
|
|
882
|
+
// acknowledge-only-after-verification for exactly the product type
|
|
883
|
+
// where it cannot be undone, since Billing 8.x drops a consumed
|
|
884
|
+
// purchase from `getPurchases()` entirely. iap consumes itself,
|
|
885
|
+
// after verification, via {@link CapgoNativeAdapter.consume}.
|
|
886
|
+
isConsumable: false,
|
|
550
887
|
autoAcknowledgePurchases: false
|
|
551
888
|
});
|
|
552
889
|
} catch (error) {
|
|
553
890
|
throw mapPurchaseError(error, opts.productId);
|
|
554
891
|
}
|
|
555
|
-
return normalizeTransaction(tx, opts.productType);
|
|
892
|
+
return normalizeTransaction(tx, opts.productType, this.packageName);
|
|
556
893
|
}
|
|
557
894
|
async getOwnedTransactions() {
|
|
558
895
|
const result = await NativePurchases.getPurchases();
|
|
559
|
-
return result.purchases.filter((tx) => tx.purchaseState === void 0 || tx.purchaseState === "1").map(
|
|
896
|
+
return result.purchases.filter((tx) => tx.purchaseState === void 0 || tx.purchaseState === "1").map(
|
|
897
|
+
(tx) => normalizeTransaction(tx, inferProductType(tx, this.configured()), this.packageName)
|
|
898
|
+
);
|
|
560
899
|
}
|
|
561
900
|
async acknowledge(transaction) {
|
|
562
901
|
try {
|
|
@@ -572,6 +911,31 @@ var init_native_adapter = __esm({
|
|
|
572
911
|
});
|
|
573
912
|
}
|
|
574
913
|
}
|
|
914
|
+
/**
|
|
915
|
+
* Consume an Android consumable, releasing ownership so it can be bought
|
|
916
|
+
* again. See {@link NativeAdapter.consume} for why acknowledging is not
|
|
917
|
+
* enough.
|
|
918
|
+
*
|
|
919
|
+
* The plugin rejects this on iOS and web, so the core calls it only for
|
|
920
|
+
* Google transactions.
|
|
921
|
+
*/
|
|
922
|
+
async consume(transaction) {
|
|
923
|
+
try {
|
|
924
|
+
await NativePurchases.consumePurchase({
|
|
925
|
+
purchaseToken: transaction.token
|
|
926
|
+
});
|
|
927
|
+
} catch (error) {
|
|
928
|
+
throw new IAPError({
|
|
929
|
+
code: IAPErrorCode.STORE_ERROR,
|
|
930
|
+
message: `Failed to consume transaction for ${transaction.productId}.`,
|
|
931
|
+
cause: error,
|
|
932
|
+
// Retried by the recovery loop like a failed acknowledge: until it
|
|
933
|
+
// succeeds, Play still reports the product owned and the user
|
|
934
|
+
// cannot buy it again.
|
|
935
|
+
recoverable: true
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
}
|
|
575
939
|
async manageSubscriptions() {
|
|
576
940
|
try {
|
|
577
941
|
await NativePurchases.manageSubscriptions();
|
|
@@ -592,14 +956,20 @@ var init_native_adapter = __esm({
|
|
|
592
956
|
* rejection, or empty country — resolves to `null` rather than throwing.
|
|
593
957
|
*/
|
|
594
958
|
async getStorefront() {
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
959
|
+
return readStorefront();
|
|
960
|
+
}
|
|
961
|
+
/**
|
|
962
|
+
* Subscribe to Apple's `Transaction.updates`. See
|
|
963
|
+
* {@link watchCapgoTransactions} — iOS only in practice, and silent
|
|
964
|
+
* about its own failures, since a missing listener degrades to
|
|
965
|
+
* reconciliation rather than breaking anything.
|
|
966
|
+
*/
|
|
967
|
+
async watchTransactions(onUpdate) {
|
|
968
|
+
return watchCapgoTransactions(onUpdate, this.logger, this.packageName, () => this.configured());
|
|
969
|
+
}
|
|
970
|
+
/** Android only; `null` on iOS. See {@link getCapgoPendingProductIds}. */
|
|
971
|
+
async getPendingProductIds() {
|
|
972
|
+
return getCapgoPendingProductIds(this.logger);
|
|
603
973
|
}
|
|
604
974
|
async dispose() {
|
|
605
975
|
}
|
|
@@ -789,6 +1159,14 @@ var HttpClient = class {
|
|
|
789
1159
|
function sleep(ms) {
|
|
790
1160
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
791
1161
|
}
|
|
1162
|
+
|
|
1163
|
+
// src/lib/uuid.ts
|
|
1164
|
+
var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
1165
|
+
function isValidUuid(value) {
|
|
1166
|
+
return typeof value === "string" && UUID_REGEX.test(value);
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
// src/types/config.ts
|
|
792
1170
|
var productTypeSchema = z.enum(["subscription", "product", "consumable"]);
|
|
793
1171
|
var configuredProductSchema = z.object({
|
|
794
1172
|
id: z.string().min(1),
|
|
@@ -888,6 +1266,38 @@ var backendConfigSchema = z.object({
|
|
|
888
1266
|
});
|
|
889
1267
|
}
|
|
890
1268
|
});
|
|
1269
|
+
var verificationConfigSchema = z.object({
|
|
1270
|
+
mode: z.literal("local"),
|
|
1271
|
+
/**
|
|
1272
|
+
* Maps a verified purchase to the entitlements it grants. Required: iap
|
|
1273
|
+
* does not know what a product entitles anyone to, and in local mode
|
|
1274
|
+
* there is no backend to ask. Type is checked at runtime via a shape
|
|
1275
|
+
* guard, not zod — see {@link VerificationConfig}.
|
|
1276
|
+
*/
|
|
1277
|
+
entitlements: z.unknown(),
|
|
1278
|
+
/**
|
|
1279
|
+
* The binding every purchase must carry, as passed to
|
|
1280
|
+
* `purchase({ appUserId })`. A purchase bound to something else is
|
|
1281
|
+
* refused. Omit it if the app does not bind purchases.
|
|
1282
|
+
*
|
|
1283
|
+
* Either the id itself, or a function returning it — in which case it is
|
|
1284
|
+
* read **at the time of each check**, so the binding follows the session.
|
|
1285
|
+
* A fixed string is captured at `createIAP()` time and cannot track a
|
|
1286
|
+
* login change, which in a multi-user app means every purchase after a
|
|
1287
|
+
* switch is refused as the previous user's.
|
|
1288
|
+
*
|
|
1289
|
+
* The function may return `null` for "nobody is signed in right now".
|
|
1290
|
+
* That is **not** the same as using no binding: iap refuses the purchase
|
|
1291
|
+
* rather than dropping the check. See `LocalVerificationAdapter`.
|
|
1292
|
+
*
|
|
1293
|
+
* Typed via the overlay on {@link VerificationConfig}; validated in the
|
|
1294
|
+
* schema's `superRefine`, the same way the backend's functions are.
|
|
1295
|
+
*/
|
|
1296
|
+
appUserId: z.unknown().optional()
|
|
1297
|
+
});
|
|
1298
|
+
var androidConfigSchema = z.object({
|
|
1299
|
+
packageName: z.string().min(1).optional()
|
|
1300
|
+
});
|
|
891
1301
|
var storageConfigSchema = z.object({
|
|
892
1302
|
type: z.enum(["preferences", "memory", "custom"]).default("preferences"),
|
|
893
1303
|
namespace: z.string().min(1).default("nosslabs_iap"),
|
|
@@ -896,6 +1306,21 @@ var storageConfigSchema = z.object({
|
|
|
896
1306
|
var optionsConfigSchema = z.object({
|
|
897
1307
|
refreshOnResume: z.boolean().default(true),
|
|
898
1308
|
entitlementCacheTtlMs: z.number().int().positive().default(60 * 60 * 1e3),
|
|
1309
|
+
/**
|
|
1310
|
+
* Extra time past an entitlement's `expiresAt` during which it still
|
|
1311
|
+
* counts as active, by the **device** clock.
|
|
1312
|
+
*
|
|
1313
|
+
* Exists because a renewal is not instantaneous: a subscription that
|
|
1314
|
+
* renews at midnight may not have a fresh receipt on the device for
|
|
1315
|
+
* minutes or hours, and locking the user out in that window is a worse
|
|
1316
|
+
* error than letting a lapsed subscription run slightly long. Store
|
|
1317
|
+
* grace periods and billing retry can stretch much further — on Android
|
|
1318
|
+
* those are server-side only, so a backendless app cannot see them at all
|
|
1319
|
+
* and this window is the only cushion it has.
|
|
1320
|
+
*
|
|
1321
|
+
* Defaults to 0: no grace, which is the strict reading of `expiresAt`.
|
|
1322
|
+
*/
|
|
1323
|
+
entitlementGraceMs: z.number().int().nonnegative().default(0),
|
|
899
1324
|
recoverUnfinishedTransactions: z.boolean().default(true),
|
|
900
1325
|
/**
|
|
901
1326
|
* Cap on how many unfinished transactions recovery inspects per launch.
|
|
@@ -929,7 +1354,16 @@ var iapConfigSchema = z.object({
|
|
|
929
1354
|
* without either path throw `INVALID_CONFIG` at parse time.
|
|
930
1355
|
*/
|
|
931
1356
|
products: z.array(configuredProductSchema).min(1).optional(),
|
|
932
|
-
|
|
1357
|
+
/**
|
|
1358
|
+
* The consumer's backend, which calls Attesto. Optional **only** when
|
|
1359
|
+
* `verification` is set instead — one of the two has to answer
|
|
1360
|
+
* whether a purchase is real.
|
|
1361
|
+
*/
|
|
1362
|
+
backend: backendConfigSchema.optional(),
|
|
1363
|
+
/** On-device verification, for an app with no backend. */
|
|
1364
|
+
verification: verificationConfigSchema.optional(),
|
|
1365
|
+
/** Android-specific settings. See {@link androidConfigSchema}. */
|
|
1366
|
+
android: androidConfigSchema.default({}),
|
|
933
1367
|
storage: storageConfigSchema.default({ type: "preferences", namespace: "nosslabs_iap" }),
|
|
934
1368
|
options: optionsConfigSchema.default({
|
|
935
1369
|
refreshOnResume: true,
|
|
@@ -940,10 +1374,49 @@ var iapConfigSchema = z.object({
|
|
|
940
1374
|
logLevel: "info"
|
|
941
1375
|
})
|
|
942
1376
|
}).superRefine((data, ctx) => {
|
|
1377
|
+
if (data.backend && data.verification) {
|
|
1378
|
+
ctx.addIssue({
|
|
1379
|
+
code: z.ZodIssueCode.custom,
|
|
1380
|
+
message: "Set either backend or verification, not both \u2014 they are two answers to the same question.",
|
|
1381
|
+
path: []
|
|
1382
|
+
});
|
|
1383
|
+
}
|
|
1384
|
+
if (!data.backend && !data.verification) {
|
|
1385
|
+
ctx.addIssue({
|
|
1386
|
+
code: z.ZodIssueCode.custom,
|
|
1387
|
+
message: 'One of backend or verification is required: something has to verify a purchase before an entitlement is granted. Use verification: { mode: "local", entitlements } for an app with no backend.',
|
|
1388
|
+
path: []
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1391
|
+
if (data.verification && typeof data.verification.entitlements !== "function") {
|
|
1392
|
+
ctx.addIssue({
|
|
1393
|
+
code: z.ZodIssueCode.custom,
|
|
1394
|
+
message: "verification.entitlements must be a function ((purchase) => TEntitlement[]) \u2014 iap cannot know what a product entitles a user to.",
|
|
1395
|
+
path: ["verification", "entitlements"]
|
|
1396
|
+
});
|
|
1397
|
+
}
|
|
1398
|
+
const binding = data.verification?.appUserId;
|
|
1399
|
+
if (data.verification && binding !== void 0 && typeof binding !== "function" && !(typeof binding === "string" && isValidUuid(binding))) {
|
|
1400
|
+
ctx.addIssue({
|
|
1401
|
+
code: z.ZodIssueCode.custom,
|
|
1402
|
+
message: "verification.appUserId must be an RFC 9562 UUID, or a function returning one (or null when nobody is signed in) \u2014 the same constraint purchase({ appUserId }) enforces.",
|
|
1403
|
+
path: ["verification", "appUserId"]
|
|
1404
|
+
});
|
|
1405
|
+
}
|
|
1406
|
+
if (data.verification && data.products === void 0) {
|
|
1407
|
+
ctx.addIssue({
|
|
1408
|
+
code: z.ZodIssueCode.custom,
|
|
1409
|
+
message: "products is required in local verification mode: there is no backend to supply the manifest.",
|
|
1410
|
+
path: ["products"]
|
|
1411
|
+
});
|
|
1412
|
+
}
|
|
943
1413
|
if (data.products !== void 0) return;
|
|
944
|
-
|
|
1414
|
+
if (data.verification) return;
|
|
1415
|
+
const backend = data.backend;
|
|
1416
|
+
if (!backend) return;
|
|
1417
|
+
const adapter = backend.adapter;
|
|
945
1418
|
const adapterCanList = adapter && typeof adapter.listProducts === "function";
|
|
946
|
-
const httpCanList = !
|
|
1419
|
+
const httpCanList = !backend.adapter && backend.endpoints?.products;
|
|
947
1420
|
if (!adapterCanList && !httpCanList) {
|
|
948
1421
|
ctx.addIssue({
|
|
949
1422
|
code: z.ZodIssueCode.custom,
|
|
@@ -984,7 +1457,8 @@ var verifyResponseSchema = z.discriminatedUnion("valid", [
|
|
|
984
1457
|
]);
|
|
985
1458
|
var restoreSuccessSchema = z.object({
|
|
986
1459
|
valid: z.literal(true),
|
|
987
|
-
entitlements: z.array(passthroughEntitlementSchema)
|
|
1460
|
+
entitlements: z.array(passthroughEntitlementSchema),
|
|
1461
|
+
verifiedTokens: z.array(z.string()).optional()
|
|
988
1462
|
}).passthrough();
|
|
989
1463
|
var restoreResponseSchema = z.discriminatedUnion("valid", [
|
|
990
1464
|
restoreSuccessSchema,
|
|
@@ -995,7 +1469,10 @@ var productManifestResponseSchema = z.object({ products: configuredProductsArray
|
|
|
995
1469
|
function isBackendAdapter(value) {
|
|
996
1470
|
if (!value || typeof value !== "object") return false;
|
|
997
1471
|
const candidate = value;
|
|
998
|
-
|
|
1472
|
+
if (typeof candidate.getEntitlements !== "function") return false;
|
|
1473
|
+
const hasExtracted = typeof candidate.verifyApple === "function" && typeof candidate.verifyGoogle === "function" && typeof candidate.restore === "function";
|
|
1474
|
+
const hasNative = typeof candidate.verifyNative === "function" && (typeof candidate.restore === "function" || typeof candidate.restoreNative === "function");
|
|
1475
|
+
return hasExtracted || hasNative;
|
|
999
1476
|
}
|
|
1000
1477
|
|
|
1001
1478
|
// src/adapters/backend/http-adapter.ts
|
|
@@ -1071,9 +1548,373 @@ var HttpBackendAdapter = class {
|
|
|
1071
1548
|
}
|
|
1072
1549
|
};
|
|
1073
1550
|
|
|
1551
|
+
// src/core/local-verification.ts
|
|
1552
|
+
function isExpired(expiresAt, now, graceMs = 0) {
|
|
1553
|
+
if (!expiresAt) return false;
|
|
1554
|
+
const expiry = Date.parse(expiresAt);
|
|
1555
|
+
if (Number.isNaN(expiry)) return false;
|
|
1556
|
+
const grace = Number.isFinite(graceMs) ? graceMs : 0;
|
|
1557
|
+
return now > expiry + grace;
|
|
1558
|
+
}
|
|
1559
|
+
function verifyPurchaseOnDevice(transaction, options) {
|
|
1560
|
+
const now = (options.now ?? Date.now)();
|
|
1561
|
+
if (!options.productIds.includes(transaction.productId)) {
|
|
1562
|
+
return {
|
|
1563
|
+
valid: false,
|
|
1564
|
+
error: "PRODUCT_NOT_CONFIGURED",
|
|
1565
|
+
message: `The store reported a purchase of "${transaction.productId}", which is not in the configured product list.`
|
|
1566
|
+
};
|
|
1567
|
+
}
|
|
1568
|
+
const expected = options.appUserId;
|
|
1569
|
+
if (expected) {
|
|
1570
|
+
const actual = transaction.appUserId ?? null;
|
|
1571
|
+
if (actual === null || actual.toLowerCase() !== expected.toLowerCase()) {
|
|
1572
|
+
return {
|
|
1573
|
+
valid: false,
|
|
1574
|
+
error: "BINDING_MISMATCH",
|
|
1575
|
+
message: `The purchase of "${transaction.productId}" is not bound to the expected account.`
|
|
1576
|
+
};
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
if (transaction.platform === "google") {
|
|
1580
|
+
const state = transaction.raw?.purchaseState;
|
|
1581
|
+
if (state !== void 0 && state !== null && String(state) !== "1") {
|
|
1582
|
+
return {
|
|
1583
|
+
valid: false,
|
|
1584
|
+
error: "NOT_PURCHASED",
|
|
1585
|
+
message: `The purchase of "${transaction.productId}" is not in Play's purchased state.`
|
|
1586
|
+
};
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
const revocationDate = transaction.raw?.revocationDate;
|
|
1590
|
+
if (transaction.subscription?.state === "revoked" || typeof revocationDate === "string") {
|
|
1591
|
+
return {
|
|
1592
|
+
valid: false,
|
|
1593
|
+
error: "REVOKED",
|
|
1594
|
+
message: `The purchase of "${transaction.productId}" has been revoked or refunded.`
|
|
1595
|
+
};
|
|
1596
|
+
}
|
|
1597
|
+
const expiresAt = transaction.subscription?.expiresAt ?? null;
|
|
1598
|
+
if (isExpired(expiresAt, now, options.graceMs)) {
|
|
1599
|
+
return {
|
|
1600
|
+
valid: false,
|
|
1601
|
+
error: "SUBSCRIPTION_EXPIRED",
|
|
1602
|
+
message: `The subscription "${transaction.productId}" expired at ${expiresAt}.`
|
|
1603
|
+
};
|
|
1604
|
+
}
|
|
1605
|
+
return {
|
|
1606
|
+
valid: true,
|
|
1607
|
+
purchase: {
|
|
1608
|
+
productId: transaction.productId,
|
|
1609
|
+
platform: transaction.platform,
|
|
1610
|
+
productType: transaction.productType,
|
|
1611
|
+
purchaseReference: transaction.purchaseReference,
|
|
1612
|
+
appUserId: transaction.appUserId ?? null,
|
|
1613
|
+
expiresAt,
|
|
1614
|
+
subscription: transaction.subscription ?? null,
|
|
1615
|
+
// iOS transactions are signature-checked by StoreKit in native code
|
|
1616
|
+
// before they cross the bridge; Android has no equivalent available.
|
|
1617
|
+
assurance: transaction.platform === "apple" ? "store-signed" : "store-reported"
|
|
1618
|
+
}
|
|
1619
|
+
};
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
// src/adapters/backend/local-adapter.ts
|
|
1623
|
+
init_errors();
|
|
1624
|
+
var LocalVerificationAdapter = class {
|
|
1625
|
+
constructor(opts) {
|
|
1626
|
+
this.opts = opts;
|
|
1627
|
+
}
|
|
1628
|
+
opts;
|
|
1629
|
+
/**
|
|
1630
|
+
* The whole transaction, not the extracted fields the HTTP contract sends.
|
|
1631
|
+
*
|
|
1632
|
+
* A local check needs the binding, the subscription state and the expiry,
|
|
1633
|
+
* and `VerifyAppleRequest` carries none of them — it is shaped for what a
|
|
1634
|
+
* server needs to look a receipt up. The router prefers this method when
|
|
1635
|
+
* an adapter has it, so the HTTP path is unaffected.
|
|
1636
|
+
*/
|
|
1637
|
+
async verifyNative(transaction) {
|
|
1638
|
+
const checked = this.check(transaction);
|
|
1639
|
+
if (!checked.valid) return checked;
|
|
1640
|
+
return {
|
|
1641
|
+
valid: true,
|
|
1642
|
+
entitlements: await this.consolidated(checked.purchase),
|
|
1643
|
+
transaction: checked.transaction
|
|
1644
|
+
};
|
|
1645
|
+
}
|
|
1646
|
+
/**
|
|
1647
|
+
* Unreachable in practice: the router prefers {@link verifyNative}. Kept
|
|
1648
|
+
* because `BackendAdapter` requires them, and failing loudly is better
|
|
1649
|
+
* than silently granting if a future caller bypasses the router.
|
|
1650
|
+
*/
|
|
1651
|
+
async verifyApple() {
|
|
1652
|
+
throw this.unsupported("verifyApple");
|
|
1653
|
+
}
|
|
1654
|
+
async verifyGoogle() {
|
|
1655
|
+
throw this.unsupported("verifyGoogle");
|
|
1656
|
+
}
|
|
1657
|
+
/**
|
|
1658
|
+
* In local mode the store **is** the source of truth, so a refresh asks
|
|
1659
|
+
* it what it owns and re-derives entitlements from that.
|
|
1660
|
+
*
|
|
1661
|
+
* This is why `refreshOnResume` keeps working with no network: there is
|
|
1662
|
+
* nothing to reach. A purchase that expired while the app was backgrounded
|
|
1663
|
+
* drops out here, which is the only downgrade local mode performs.
|
|
1664
|
+
*/
|
|
1665
|
+
async getEntitlements() {
|
|
1666
|
+
const binding = this.binding();
|
|
1667
|
+
if (!binding.ok) {
|
|
1668
|
+
this.opts.logger.debug(
|
|
1669
|
+
`Keeping the current entitlements: ${binding.error}. ${binding.message}`
|
|
1670
|
+
);
|
|
1671
|
+
return this.opts.getCurrentEntitlements();
|
|
1672
|
+
}
|
|
1673
|
+
const owned = await this.ownedTransactions();
|
|
1674
|
+
if (owned.length === 0) {
|
|
1675
|
+
const current = this.opts.getCurrentEntitlements();
|
|
1676
|
+
if (current.length > 0) {
|
|
1677
|
+
this.opts.logger.debug(
|
|
1678
|
+
"The store reported nothing owned. Keeping the current entitlements, since an empty answer is indistinguishable from a failed query."
|
|
1679
|
+
);
|
|
1680
|
+
}
|
|
1681
|
+
return current;
|
|
1682
|
+
}
|
|
1683
|
+
return this.consolidated();
|
|
1684
|
+
}
|
|
1685
|
+
/**
|
|
1686
|
+
* Restore is the same question as a refresh here — "what does this store
|
|
1687
|
+
* account own" — answered from the transactions the orchestrator already
|
|
1688
|
+
* read, so the store is not asked twice.
|
|
1689
|
+
*/
|
|
1690
|
+
async restoreNative(owned) {
|
|
1691
|
+
const binding = this.binding();
|
|
1692
|
+
if (!binding.ok) {
|
|
1693
|
+
return { valid: false, error: binding.error, message: binding.message };
|
|
1694
|
+
}
|
|
1695
|
+
const { entitlements, verifiedTokens } = this.evaluate(owned);
|
|
1696
|
+
if (verifiedTokens.length === 0) {
|
|
1697
|
+
return {
|
|
1698
|
+
valid: false,
|
|
1699
|
+
error: "NO_VERIFIED_PURCHASES",
|
|
1700
|
+
message: "The store reported purchases, but none passed the on-device checks."
|
|
1701
|
+
};
|
|
1702
|
+
}
|
|
1703
|
+
return { valid: true, entitlements, verifiedTokens };
|
|
1704
|
+
}
|
|
1705
|
+
/**
|
|
1706
|
+
* Unreachable via the orchestrator, which prefers {@link restoreNative}.
|
|
1707
|
+
* Kept so the adapter satisfies a consumer holding it as a plain
|
|
1708
|
+
* `BackendAdapter`; it re-reads the store rather than trusting an
|
|
1709
|
+
* extracted request a local check cannot verify from.
|
|
1710
|
+
*/
|
|
1711
|
+
async restore(_req) {
|
|
1712
|
+
return this.restoreNative(await this.ownedTransactions());
|
|
1713
|
+
}
|
|
1714
|
+
/**
|
|
1715
|
+
* The binding to check against, or a refusal.
|
|
1716
|
+
*
|
|
1717
|
+
* Read per check rather than once at construction, because a
|
|
1718
|
+
* `verification.appUserId` getter exists precisely so the binding can
|
|
1719
|
+
* follow the session: in a multi-user app a value captured at
|
|
1720
|
+
* `createIAP()` time is the previous user's after a switch, and every
|
|
1721
|
+
* purchase is then refused as a mismatch.
|
|
1722
|
+
*
|
|
1723
|
+
* The thing it will not do is treat "no account right now" as "this app
|
|
1724
|
+
* uses no binding". That would turn a signed-out session into an
|
|
1725
|
+
* unguarded one, accepting a purchase bound to **someone else** — a
|
|
1726
|
+
* weaker check than the app asked for, silently. Refusing is the safe
|
|
1727
|
+
* direction: the purchase stays unacknowledged and the store retries it.
|
|
1728
|
+
*/
|
|
1729
|
+
binding() {
|
|
1730
|
+
const resolve = this.opts.getAppUserId;
|
|
1731
|
+
if (!resolve) return { ok: true, appUserId: null };
|
|
1732
|
+
let value;
|
|
1733
|
+
try {
|
|
1734
|
+
value = resolve();
|
|
1735
|
+
} catch (error) {
|
|
1736
|
+
this.opts.logger.warn(
|
|
1737
|
+
"verification.appUserId threw. Refusing purchases rather than dropping the binding check.",
|
|
1738
|
+
error
|
|
1739
|
+
);
|
|
1740
|
+
return {
|
|
1741
|
+
ok: false,
|
|
1742
|
+
error: "BINDING_UNAVAILABLE",
|
|
1743
|
+
message: "The expected account binding could not be read."
|
|
1744
|
+
};
|
|
1745
|
+
}
|
|
1746
|
+
if (value === null || value === void 0 || value === "") {
|
|
1747
|
+
return {
|
|
1748
|
+
ok: false,
|
|
1749
|
+
error: "BINDING_UNAVAILABLE",
|
|
1750
|
+
message: "This app binds purchases to an account, and verification.appUserId resolved to none. Nothing can be verified until someone is signed in."
|
|
1751
|
+
};
|
|
1752
|
+
}
|
|
1753
|
+
if (!isValidUuid(value) && !this.warnedAboutBinding) {
|
|
1754
|
+
this.warnedAboutBinding = true;
|
|
1755
|
+
this.opts.logger.warn(
|
|
1756
|
+
"verification.appUserId returned a value that is not an RFC 9562 UUID. purchase({ appUserId }) only accepts UUIDs, so no purchase can ever match it."
|
|
1757
|
+
);
|
|
1758
|
+
}
|
|
1759
|
+
return { ok: true, appUserId: value };
|
|
1760
|
+
}
|
|
1761
|
+
/** Warned once per instance, not once per check — a refresh runs this. */
|
|
1762
|
+
warnedAboutBinding = false;
|
|
1763
|
+
checkOptions(appUserId) {
|
|
1764
|
+
return {
|
|
1765
|
+
productIds: this.opts.getProducts().map((p) => p.id),
|
|
1766
|
+
appUserId,
|
|
1767
|
+
graceMs: this.opts.graceMs
|
|
1768
|
+
};
|
|
1769
|
+
}
|
|
1770
|
+
check(transaction) {
|
|
1771
|
+
const binding = this.binding();
|
|
1772
|
+
if (!binding.ok) {
|
|
1773
|
+
this.opts.logger.debug(
|
|
1774
|
+
`Local verification refused "${transaction.productId}": ${binding.error}.`
|
|
1775
|
+
);
|
|
1776
|
+
return { valid: false, error: binding.error, message: binding.message };
|
|
1777
|
+
}
|
|
1778
|
+
const result = verifyPurchaseOnDevice(transaction, this.checkOptions(binding.appUserId));
|
|
1779
|
+
if (!result.valid) {
|
|
1780
|
+
this.opts.logger.debug(
|
|
1781
|
+
`Local verification refused "${transaction.productId}": ${result.error}.`
|
|
1782
|
+
);
|
|
1783
|
+
return { valid: false, error: result.error, message: result.message };
|
|
1784
|
+
}
|
|
1785
|
+
return {
|
|
1786
|
+
valid: true,
|
|
1787
|
+
purchase: result.purchase,
|
|
1788
|
+
transaction: {
|
|
1789
|
+
// The purchase's own identity, not a server-assigned id — there is
|
|
1790
|
+
// no server to assign one. Note it is stable across renewals, so it
|
|
1791
|
+
// is not a per-transaction key.
|
|
1792
|
+
id: result.purchase.purchaseReference,
|
|
1793
|
+
productId: result.purchase.productId,
|
|
1794
|
+
expiresAt: result.purchase.expiresAt
|
|
1795
|
+
}
|
|
1796
|
+
};
|
|
1797
|
+
}
|
|
1798
|
+
/**
|
|
1799
|
+
* Run the consumer's mapper and validate what it returns.
|
|
1800
|
+
*
|
|
1801
|
+
* Unlike a backend response, this value never went through a schema — it
|
|
1802
|
+
* comes straight from consumer code into iap's state and cache. An
|
|
1803
|
+
* unvalidated mapper could cache an object with no `key` (so
|
|
1804
|
+
* `hasEntitlement` could never match it, and the next launch would drop it
|
|
1805
|
+
* from the cache, making entitlements differ between sessions), or return
|
|
1806
|
+
* a non-array and throw a raw `TypeError` out of `purchase()` *after* the
|
|
1807
|
+
* transaction was acknowledged.
|
|
1808
|
+
*/
|
|
1809
|
+
map(purchase) {
|
|
1810
|
+
let mapped;
|
|
1811
|
+
try {
|
|
1812
|
+
mapped = this.opts.entitlements(purchase);
|
|
1813
|
+
} catch (error) {
|
|
1814
|
+
this.opts.logger.warn(
|
|
1815
|
+
`verification.entitlements threw for "${purchase.productId}"; granting nothing for it.`,
|
|
1816
|
+
error
|
|
1817
|
+
);
|
|
1818
|
+
return [];
|
|
1819
|
+
}
|
|
1820
|
+
const parsed = z.array(entitlementBaseSchema.passthrough()).safeParse(mapped);
|
|
1821
|
+
if (!parsed.success) {
|
|
1822
|
+
this.opts.logger.warn(
|
|
1823
|
+
`verification.entitlements returned something that is not a list of entitlements for "${purchase.productId}"; granting nothing for it. Each entry needs a key, a productId and an expiresAt (which may be null).`
|
|
1824
|
+
);
|
|
1825
|
+
return [];
|
|
1826
|
+
}
|
|
1827
|
+
return parsed.data;
|
|
1828
|
+
}
|
|
1829
|
+
/** The consolidated entitlements, optionally merging a just-verified purchase. */
|
|
1830
|
+
async consolidated(extra) {
|
|
1831
|
+
const owned = await this.ownedTransactions();
|
|
1832
|
+
const { entitlements } = this.evaluate(owned, extra);
|
|
1833
|
+
return entitlements;
|
|
1834
|
+
}
|
|
1835
|
+
/**
|
|
1836
|
+
* Evaluate an owned set: which transactions passed, and what they grant.
|
|
1837
|
+
*
|
|
1838
|
+
* Returns the tokens that passed as well as the entitlements, because the
|
|
1839
|
+
* caller needs to know *which* transactions may be acknowledged — a
|
|
1840
|
+
* single consolidated list cannot say.
|
|
1841
|
+
*/
|
|
1842
|
+
evaluate(owned, extra) {
|
|
1843
|
+
const binding = this.binding();
|
|
1844
|
+
if (!binding.ok) return { entitlements: [], verifiedTokens: [] };
|
|
1845
|
+
const options = this.checkOptions(binding.appUserId);
|
|
1846
|
+
const verifiedTokens = [];
|
|
1847
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
1848
|
+
const absorb = (purchase) => {
|
|
1849
|
+
for (const entitlement of this.map(purchase)) {
|
|
1850
|
+
const existing = byKey.get(entitlement.key);
|
|
1851
|
+
if (!existing || outlasts(entitlement.expiresAt, existing.expiresAt)) {
|
|
1852
|
+
byKey.set(entitlement.key, entitlement);
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
};
|
|
1856
|
+
for (const transaction of owned) {
|
|
1857
|
+
const result = verifyPurchaseOnDevice(transaction, options);
|
|
1858
|
+
if (!result.valid) {
|
|
1859
|
+
this.opts.logger.debug(
|
|
1860
|
+
`Local verification refused "${transaction.productId}": ${result.error}.`
|
|
1861
|
+
);
|
|
1862
|
+
continue;
|
|
1863
|
+
}
|
|
1864
|
+
verifiedTokens.push(transaction.token);
|
|
1865
|
+
absorb(result.purchase);
|
|
1866
|
+
}
|
|
1867
|
+
if (extra) absorb(extra);
|
|
1868
|
+
return { entitlements: [...byKey.values()], verifiedTokens };
|
|
1869
|
+
}
|
|
1870
|
+
async ownedTransactions() {
|
|
1871
|
+
const native = this.opts.getNativeAdapter();
|
|
1872
|
+
if (!native) {
|
|
1873
|
+
throw new IAPError({
|
|
1874
|
+
code: IAPErrorCode.NOT_INITIALIZED,
|
|
1875
|
+
message: "Local verification needs the native adapter; call iap.initialize() first."
|
|
1876
|
+
});
|
|
1877
|
+
}
|
|
1878
|
+
return native.getOwnedTransactions();
|
|
1879
|
+
}
|
|
1880
|
+
unsupported(method) {
|
|
1881
|
+
return new IAPError({
|
|
1882
|
+
code: IAPErrorCode.INVALID_CONFIG,
|
|
1883
|
+
message: `${method}() cannot verify locally: it receives only the extracted request fields, and an on-device check needs the binding, the subscription state and the expiry. Call verifyNative(transaction) instead \u2014 which is what iap's own router does.`
|
|
1884
|
+
});
|
|
1885
|
+
}
|
|
1886
|
+
};
|
|
1887
|
+
function outlasts(a, b) {
|
|
1888
|
+
if (a === null) return true;
|
|
1889
|
+
if (b === null) return false;
|
|
1890
|
+
return Date.parse(a) > Date.parse(b);
|
|
1891
|
+
}
|
|
1892
|
+
|
|
1074
1893
|
// src/adapters/backend/index.ts
|
|
1075
1894
|
function selectBackendAdapter(options) {
|
|
1076
|
-
const { config, logger, fetch: fetchImpl } = options;
|
|
1895
|
+
const { config: iapConfig, logger, fetch: fetchImpl } = options;
|
|
1896
|
+
if (iapConfig.verification) {
|
|
1897
|
+
const verification = iapConfig.verification;
|
|
1898
|
+
return new LocalVerificationAdapter({
|
|
1899
|
+
getNativeAdapter: options.getNativeAdapter ?? (() => null),
|
|
1900
|
+
getProducts: options.getProducts ?? (() => iapConfig.products ?? []),
|
|
1901
|
+
entitlements: verification.entitlements,
|
|
1902
|
+
// Passed only when the app actually binds purchases: the adapter
|
|
1903
|
+
// reads "no resolver" as "no binding required", and a resolver
|
|
1904
|
+
// returning null as "required, but nobody is signed in".
|
|
1905
|
+
...verification.appUserId === void 0 ? {} : { getAppUserId: resolveAppUserId(verification.appUserId) },
|
|
1906
|
+
getCurrentEntitlements: () => options.getCurrentEntitlements?.() ?? [],
|
|
1907
|
+
graceMs: iapConfig.options.entitlementGraceMs,
|
|
1908
|
+
logger
|
|
1909
|
+
});
|
|
1910
|
+
}
|
|
1911
|
+
const config = iapConfig.backend;
|
|
1912
|
+
if (!config) {
|
|
1913
|
+
throw new IAPError({
|
|
1914
|
+
code: IAPErrorCode.INVALID_CONFIG,
|
|
1915
|
+
message: "Neither backend nor verification is configured; the schema should have caught this. This is a library bug."
|
|
1916
|
+
});
|
|
1917
|
+
}
|
|
1077
1918
|
if (config.adapter !== void 0) {
|
|
1078
1919
|
if (!isBackendAdapter(config.adapter)) {
|
|
1079
1920
|
throw new IAPError({
|
|
@@ -1101,49 +1942,8 @@ function selectBackendAdapter(options) {
|
|
|
1101
1942
|
...fetchImpl ? { fetch: fetchImpl } : {}
|
|
1102
1943
|
});
|
|
1103
1944
|
}
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
init_platform();
|
|
1107
|
-
|
|
1108
|
-
// src/adapters/native/web/web-stub.ts
|
|
1109
|
-
init_errors();
|
|
1110
|
-
var WebStubAdapter = class {
|
|
1111
|
-
async isAvailable() {
|
|
1112
|
-
return false;
|
|
1113
|
-
}
|
|
1114
|
-
async getProducts(_requests) {
|
|
1115
|
-
return [];
|
|
1116
|
-
}
|
|
1117
|
-
async purchaseProduct(_opts) {
|
|
1118
|
-
throw new IAPError({
|
|
1119
|
-
code: IAPErrorCode.PLATFORM_NOT_SUPPORTED,
|
|
1120
|
-
message: "In-app purchases are not supported on the web platform."
|
|
1121
|
-
});
|
|
1122
|
-
}
|
|
1123
|
-
async getOwnedTransactions() {
|
|
1124
|
-
return [];
|
|
1125
|
-
}
|
|
1126
|
-
async acknowledge(_transaction) {
|
|
1127
|
-
}
|
|
1128
|
-
async manageSubscriptions() {
|
|
1129
|
-
throw new IAPError({
|
|
1130
|
-
code: IAPErrorCode.PLATFORM_NOT_SUPPORTED,
|
|
1131
|
-
message: "Subscription management is not supported on the web platform."
|
|
1132
|
-
});
|
|
1133
|
-
}
|
|
1134
|
-
async getStorefront() {
|
|
1135
|
-
return null;
|
|
1136
|
-
}
|
|
1137
|
-
};
|
|
1138
|
-
|
|
1139
|
-
// src/adapters/native/index.ts
|
|
1140
|
-
async function selectNativeAdapter() {
|
|
1141
|
-
const platform = getPlatform();
|
|
1142
|
-
if (platform === "ios" || platform === "android") {
|
|
1143
|
-
const mod = await Promise.resolve().then(() => (init_native_adapter(), native_adapter_exports));
|
|
1144
|
-
return new mod.CapgoNativeAdapter();
|
|
1145
|
-
}
|
|
1146
|
-
return new WebStubAdapter();
|
|
1945
|
+
function resolveAppUserId(appUserId) {
|
|
1946
|
+
return typeof appUserId === "function" ? appUserId : () => appUserId;
|
|
1147
1947
|
}
|
|
1148
1948
|
|
|
1149
1949
|
// src/adapters/storage/index.ts
|
|
@@ -1241,47 +2041,24 @@ function isStorageAdapter(value) {
|
|
|
1241
2041
|
return typeof candidate.get === "function" && typeof candidate.set === "function" && typeof candidate.remove === "function" && typeof candidate.clear === "function";
|
|
1242
2042
|
}
|
|
1243
2043
|
|
|
1244
|
-
// src/core/app-resume-listener.ts
|
|
1245
|
-
async function attachAppResumeListener(opts) {
|
|
1246
|
-
let mod;
|
|
1247
|
-
try {
|
|
1248
|
-
mod = await import('@capacitor/app');
|
|
1249
|
-
} catch (error) {
|
|
1250
|
-
opts.logger.warn(
|
|
1251
|
-
"refreshOnResume requested but @capacitor/app is not installed; resume listener disabled.",
|
|
1252
|
-
error
|
|
1253
|
-
);
|
|
1254
|
-
return null;
|
|
1255
|
-
}
|
|
1256
|
-
let handle;
|
|
1257
|
-
try {
|
|
1258
|
-
handle = await mod.App.addListener("appStateChange", ({ isActive }) => {
|
|
1259
|
-
if (!isActive) return;
|
|
1260
|
-
void Promise.resolve(opts.onResume()).catch((error) => {
|
|
1261
|
-
opts.logger.warn("refreshOnResume handler threw.", error);
|
|
1262
|
-
});
|
|
1263
|
-
});
|
|
1264
|
-
} catch (error) {
|
|
1265
|
-
opts.logger.warn(
|
|
1266
|
-
"Failed to attach App appStateChange listener; resume refresh disabled.",
|
|
1267
|
-
error
|
|
1268
|
-
);
|
|
1269
|
-
return null;
|
|
1270
|
-
}
|
|
1271
|
-
return {
|
|
1272
|
-
async remove() {
|
|
1273
|
-
try {
|
|
1274
|
-
await handle.remove();
|
|
1275
|
-
} catch (error) {
|
|
1276
|
-
opts.logger.warn("Failed to remove App appStateChange listener.", error);
|
|
1277
|
-
}
|
|
1278
|
-
}
|
|
1279
|
-
};
|
|
1280
|
-
}
|
|
1281
|
-
|
|
1282
2044
|
// src/core/entitlement-cache.ts
|
|
1283
2045
|
init_errors();
|
|
1284
|
-
|
|
2046
|
+
|
|
2047
|
+
// src/core/storage-keys.ts
|
|
2048
|
+
var IAP_STORAGE_KEYS = {
|
|
2049
|
+
/** The entitlement cache envelope. See `EntitlementCache`. */
|
|
2050
|
+
entitlements: "entitlements",
|
|
2051
|
+
/** Purchases awaiting backend confirmation. See `UnfinishedTransactionsStore`. */
|
|
2052
|
+
unfinishedTransactions: "unfinished_transactions",
|
|
2053
|
+
/** Products reported as awaiting clearance. See `PendingPurchasesStore`. */
|
|
2054
|
+
pendingPurchases: "pending_purchases"
|
|
2055
|
+
};
|
|
2056
|
+
var ALL_IAP_STORAGE_KEYS = Object.freeze(
|
|
2057
|
+
Object.values(IAP_STORAGE_KEYS)
|
|
2058
|
+
);
|
|
2059
|
+
|
|
2060
|
+
// src/core/entitlement-cache.ts
|
|
2061
|
+
var ENTITLEMENTS_KEY = IAP_STORAGE_KEYS.entitlements;
|
|
1285
2062
|
var EntitlementCache = class {
|
|
1286
2063
|
constructor(storage, logger) {
|
|
1287
2064
|
this.storage = storage;
|
|
@@ -1353,6 +2130,9 @@ var EntitlementCache = class {
|
|
|
1353
2130
|
}
|
|
1354
2131
|
}
|
|
1355
2132
|
};
|
|
2133
|
+
function activeEntitlements(entitlements, now, graceMs = 0) {
|
|
2134
|
+
return entitlements.filter((entitlement) => !isExpired(entitlement.expiresAt, now, graceMs));
|
|
2135
|
+
}
|
|
1356
2136
|
function entitlementsEqual(a, b) {
|
|
1357
2137
|
if (a === b) return true;
|
|
1358
2138
|
if (a.length !== b.length) return false;
|
|
@@ -1367,18 +2147,195 @@ function entitlementsEqual(a, b) {
|
|
|
1367
2147
|
return true;
|
|
1368
2148
|
}
|
|
1369
2149
|
|
|
1370
|
-
// src/core/
|
|
2150
|
+
// src/core/iap-state.ts
|
|
1371
2151
|
init_errors();
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
var UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
1375
|
-
function isValidUuidV4(value) {
|
|
1376
|
-
return UUID_V4_REGEX.test(value);
|
|
2152
|
+
function freezeAll(items) {
|
|
2153
|
+
return items.map((item) => Object.freeze({ ...item }));
|
|
1377
2154
|
}
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
2155
|
+
function ensureUniqueProductIds(products) {
|
|
2156
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2157
|
+
for (const product of products) {
|
|
2158
|
+
if (seen.has(product.id)) {
|
|
2159
|
+
throw new IAPError({
|
|
2160
|
+
code: IAPErrorCode.INVALID_CONFIG,
|
|
2161
|
+
message: `Duplicate product id "${product.id}" in product manifest.`
|
|
2162
|
+
});
|
|
2163
|
+
}
|
|
2164
|
+
seen.add(product.id);
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
function requireInitialized(state) {
|
|
2168
|
+
if (!state.initialized) {
|
|
2169
|
+
throw new IAPError({
|
|
2170
|
+
code: IAPErrorCode.NOT_INITIALIZED,
|
|
2171
|
+
message: "Call iap.initialize() before this method."
|
|
2172
|
+
});
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
|
|
2176
|
+
// src/adapters/native/index.ts
|
|
2177
|
+
init_platform();
|
|
2178
|
+
|
|
2179
|
+
// src/adapters/native/web/web-stub.ts
|
|
2180
|
+
init_errors();
|
|
2181
|
+
var WebStubAdapter = class {
|
|
2182
|
+
async isAvailable() {
|
|
2183
|
+
return false;
|
|
2184
|
+
}
|
|
2185
|
+
async getProducts(_requests) {
|
|
2186
|
+
return [];
|
|
2187
|
+
}
|
|
2188
|
+
async purchaseProduct(_opts) {
|
|
2189
|
+
throw new IAPError({
|
|
2190
|
+
code: IAPErrorCode.PLATFORM_NOT_SUPPORTED,
|
|
2191
|
+
message: "In-app purchases are not supported on the web platform."
|
|
2192
|
+
});
|
|
2193
|
+
}
|
|
2194
|
+
async getOwnedTransactions() {
|
|
2195
|
+
return [];
|
|
2196
|
+
}
|
|
2197
|
+
async acknowledge(_transaction) {
|
|
2198
|
+
}
|
|
2199
|
+
async manageSubscriptions() {
|
|
2200
|
+
throw new IAPError({
|
|
2201
|
+
code: IAPErrorCode.PLATFORM_NOT_SUPPORTED,
|
|
2202
|
+
message: "Subscription management is not supported on the web platform."
|
|
2203
|
+
});
|
|
2204
|
+
}
|
|
2205
|
+
async getStorefront() {
|
|
2206
|
+
return null;
|
|
2207
|
+
}
|
|
2208
|
+
};
|
|
2209
|
+
|
|
2210
|
+
// src/adapters/native/index.ts
|
|
2211
|
+
async function selectNativeAdapter(logger, packageName, getConfiguredProducts) {
|
|
2212
|
+
const platform = getPlatform();
|
|
2213
|
+
if (platform === "ios" || platform === "android") {
|
|
2214
|
+
const mod = await Promise.resolve().then(() => (init_native_adapter(), native_adapter_exports));
|
|
2215
|
+
return new mod.CapgoNativeAdapter(logger, packageName, getConfiguredProducts);
|
|
2216
|
+
}
|
|
2217
|
+
return new WebStubAdapter();
|
|
2218
|
+
}
|
|
2219
|
+
|
|
2220
|
+
// src/core/initialize.ts
|
|
2221
|
+
init_errors();
|
|
2222
|
+
init_platform();
|
|
2223
|
+
|
|
2224
|
+
// src/core/app-resume-listener.ts
|
|
2225
|
+
async function attachAppResumeListener(opts) {
|
|
2226
|
+
let mod;
|
|
2227
|
+
try {
|
|
2228
|
+
mod = await import('@capacitor/app');
|
|
2229
|
+
} catch (error) {
|
|
2230
|
+
opts.logger.warn(
|
|
2231
|
+
"refreshOnResume requested but @capacitor/app is not installed; resume listener disabled.",
|
|
2232
|
+
error
|
|
2233
|
+
);
|
|
2234
|
+
return null;
|
|
2235
|
+
}
|
|
2236
|
+
let handle;
|
|
2237
|
+
try {
|
|
2238
|
+
handle = await mod.App.addListener("appStateChange", ({ isActive }) => {
|
|
2239
|
+
if (!isActive) return;
|
|
2240
|
+
void Promise.resolve(opts.onResume()).catch((error) => {
|
|
2241
|
+
opts.logger.warn("refreshOnResume handler threw.", error);
|
|
2242
|
+
});
|
|
2243
|
+
});
|
|
2244
|
+
} catch (error) {
|
|
2245
|
+
opts.logger.warn(
|
|
2246
|
+
"Failed to attach App appStateChange listener; resume refresh disabled.",
|
|
2247
|
+
error
|
|
2248
|
+
);
|
|
2249
|
+
return null;
|
|
2250
|
+
}
|
|
2251
|
+
return {
|
|
2252
|
+
async remove() {
|
|
2253
|
+
try {
|
|
2254
|
+
await handle.remove();
|
|
2255
|
+
} catch (error) {
|
|
2256
|
+
opts.logger.warn("Failed to remove App appStateChange listener.", error);
|
|
2257
|
+
}
|
|
2258
|
+
}
|
|
2259
|
+
};
|
|
2260
|
+
}
|
|
2261
|
+
|
|
2262
|
+
// src/core/attach-transaction-watch.ts
|
|
2263
|
+
async function attachTransactionWatch(opts) {
|
|
2264
|
+
const { adapter, updates, logger } = opts;
|
|
2265
|
+
let handle;
|
|
2266
|
+
try {
|
|
2267
|
+
handle = await adapter.watchTransactions?.((transaction) => {
|
|
2268
|
+
void updates.handle(transaction);
|
|
2269
|
+
}) ?? null;
|
|
2270
|
+
} catch (error) {
|
|
2271
|
+
logger.warn(
|
|
2272
|
+
"Failed to subscribe to native transaction updates; renewals and refunds will be picked up at the next launch or resume instead.",
|
|
2273
|
+
error
|
|
2274
|
+
);
|
|
2275
|
+
return null;
|
|
2276
|
+
}
|
|
2277
|
+
if (handle === null) {
|
|
2278
|
+
logger.debug(
|
|
2279
|
+
"No native transaction feed on this platform; relying on recovery at launch and refresh on resume."
|
|
2280
|
+
);
|
|
2281
|
+
}
|
|
2282
|
+
return handle;
|
|
2283
|
+
}
|
|
2284
|
+
|
|
2285
|
+
// src/core/purchase-flow.ts
|
|
2286
|
+
init_errors();
|
|
2287
|
+
|
|
2288
|
+
// src/core/finalize-transaction.ts
|
|
2289
|
+
async function finalizeTransaction(opts) {
|
|
2290
|
+
const { nativeAdapter, transaction, logger } = opts;
|
|
2291
|
+
if (transaction.platform !== "google" || transaction.productType !== "consumable") {
|
|
2292
|
+
await nativeAdapter.acknowledge(transaction);
|
|
2293
|
+
return;
|
|
2294
|
+
}
|
|
2295
|
+
if (!nativeAdapter.consume) {
|
|
2296
|
+
logger.warn(
|
|
2297
|
+
`The native adapter cannot consume, so "${transaction.productId}" was only acknowledged. Google will keep reporting it owned, and buying it again will fail with ALREADY_PURCHASED.`
|
|
2298
|
+
);
|
|
2299
|
+
await nativeAdapter.acknowledge(transaction);
|
|
2300
|
+
return;
|
|
2301
|
+
}
|
|
2302
|
+
try {
|
|
2303
|
+
await nativeAdapter.consume(transaction);
|
|
2304
|
+
} catch (error) {
|
|
2305
|
+
try {
|
|
2306
|
+
await nativeAdapter.acknowledge(transaction);
|
|
2307
|
+
logger.debug(
|
|
2308
|
+
`Consuming "${transaction.productId}" failed; acknowledged it instead so Google does not auto-refund, and the consume will be retried.`
|
|
2309
|
+
);
|
|
2310
|
+
} catch {
|
|
2311
|
+
}
|
|
2312
|
+
throw error;
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
|
|
2316
|
+
// src/core/resolve-pending.ts
|
|
2317
|
+
async function resolvePendingPurchase(deps, productId, status) {
|
|
2318
|
+
if (!await deps.pending.takeIfPresent(productId)) return;
|
|
2319
|
+
deps.emitter.emit("purchase-pending-resolved", { productId, status });
|
|
2320
|
+
}
|
|
2321
|
+
|
|
2322
|
+
// src/core/store-purchase.ts
|
|
2323
|
+
function toStorePurchase(tx) {
|
|
2324
|
+
return {
|
|
2325
|
+
platform: tx.platform,
|
|
2326
|
+
productId: tx.productId,
|
|
2327
|
+
purchaseReference: tx.purchaseReference,
|
|
2328
|
+
appUserId: tx.appUserId ?? null,
|
|
2329
|
+
subscription: tx.subscription ?? null
|
|
2330
|
+
};
|
|
2331
|
+
}
|
|
2332
|
+
|
|
2333
|
+
// src/core/verify-helpers.ts
|
|
2334
|
+
init_errors();
|
|
2335
|
+
async function verifyNativeTransaction(backend, tx) {
|
|
2336
|
+
if (typeof backend.verifyNative === "function") {
|
|
2337
|
+
return backend.verifyNative(tx);
|
|
2338
|
+
}
|
|
1382
2339
|
if (tx.platform === "apple") {
|
|
1383
2340
|
return backend.verifyApple({
|
|
1384
2341
|
productId: tx.productId,
|
|
@@ -1389,7 +2346,7 @@ async function verifyNativeTransaction(backend, tx) {
|
|
|
1389
2346
|
if (!tx.packageName) {
|
|
1390
2347
|
throw new IAPError({
|
|
1391
2348
|
code: IAPErrorCode.STORE_ERROR,
|
|
1392
|
-
message: `Google transaction for "${tx.productId}" has no packageName; cannot verify.`
|
|
2349
|
+
message: `Google transaction for "${tx.productId}" has no packageName; cannot verify. Set config.android.packageName to your app's applicationId \u2014 the native plugin does not report it, so iap cannot derive it from the purchase.`
|
|
1393
2350
|
});
|
|
1394
2351
|
}
|
|
1395
2352
|
return backend.verifyGoogle({
|
|
@@ -1407,6 +2364,35 @@ var PurchaseOrchestrator = class {
|
|
|
1407
2364
|
}
|
|
1408
2365
|
deps;
|
|
1409
2366
|
inFlight = /* @__PURE__ */ new Set();
|
|
2367
|
+
/**
|
|
2368
|
+
* Whether this orchestrator is currently handling `productId`.
|
|
2369
|
+
*
|
|
2370
|
+
* Read by the transaction-update orchestrator: StoreKit delivers the
|
|
2371
|
+
* transaction a purchase produced to `Transaction.updates` as well, and
|
|
2372
|
+
* whichever path started it owns settling it.
|
|
2373
|
+
*/
|
|
2374
|
+
isInFlight(productId) {
|
|
2375
|
+
return this.inFlight.has(productId);
|
|
2376
|
+
}
|
|
2377
|
+
/**
|
|
2378
|
+
* The products currently being purchased.
|
|
2379
|
+
*
|
|
2380
|
+
* Read by `reset()`, which refuses to run while one is in flight. The
|
|
2381
|
+
* reason is the unfinished-transaction entry, not the cache: that entry is
|
|
2382
|
+
* written *before* verification precisely so a purchase survives a crash,
|
|
2383
|
+
* and deleting it mid-flight leaves a purchase that is neither
|
|
2384
|
+
* acknowledged nor tracked — which Play auto-refunds in three days. The
|
|
2385
|
+
* cache coming back is harmless by comparison, since `reset()` is not a
|
|
2386
|
+
* revocation.
|
|
2387
|
+
*
|
|
2388
|
+
* Marked from the moment the purchase is committed to running, before any
|
|
2389
|
+
* consumer-supplied `appUserId` fetcher is awaited — that await is a
|
|
2390
|
+
* network round-trip, and a window in which this said "nothing in flight"
|
|
2391
|
+
* while a purchase was already under way.
|
|
2392
|
+
*/
|
|
2393
|
+
inFlightProducts() {
|
|
2394
|
+
return [...this.inFlight];
|
|
2395
|
+
}
|
|
1410
2396
|
async purchase(opts) {
|
|
1411
2397
|
const { productId, appUserId } = opts;
|
|
1412
2398
|
if (this.inFlight.has(productId)) {
|
|
@@ -1422,14 +2408,14 @@ var PurchaseOrchestrator = class {
|
|
|
1422
2408
|
message: `Product "${productId}" is not in the configured catalog.`
|
|
1423
2409
|
});
|
|
1424
2410
|
}
|
|
1425
|
-
let resolvedAppUserId;
|
|
1426
|
-
if (appUserId !== void 0) {
|
|
1427
|
-
const ctx = typeof appUserId === "function" ? { authHeaders: await this.deps.getAuthHeaders() } : { authHeaders: {} };
|
|
1428
|
-
resolvedAppUserId = await resolveAppUserId(appUserId, ctx);
|
|
1429
|
-
}
|
|
1430
2411
|
this.inFlight.add(productId);
|
|
1431
|
-
this.deps.emitter.emit("purchase-started", { productId });
|
|
1432
2412
|
try {
|
|
2413
|
+
let resolvedAppUserId;
|
|
2414
|
+
if (appUserId !== void 0) {
|
|
2415
|
+
const ctx = typeof appUserId === "function" ? { authHeaders: await this.deps.getAuthHeaders() } : { authHeaders: {} };
|
|
2416
|
+
resolvedAppUserId = await resolveAppUserId2(appUserId, ctx);
|
|
2417
|
+
}
|
|
2418
|
+
this.deps.emitter.emit("purchase-started", { productId });
|
|
1433
2419
|
return await this.runFlow(product, resolvedAppUserId);
|
|
1434
2420
|
} finally {
|
|
1435
2421
|
this.inFlight.delete(productId);
|
|
@@ -1471,10 +2457,15 @@ var PurchaseOrchestrator = class {
|
|
|
1471
2457
|
const { nativeAdapter, cache, unfinished, emitter, logger } = this.deps;
|
|
1472
2458
|
const transaction = response.transaction;
|
|
1473
2459
|
const entitlements = response.entitlements;
|
|
2460
|
+
let acknowledged = true;
|
|
1474
2461
|
try {
|
|
1475
|
-
await nativeAdapter
|
|
2462
|
+
await finalizeTransaction({ nativeAdapter, transaction: nativeTx, logger });
|
|
1476
2463
|
} catch (error) {
|
|
1477
|
-
|
|
2464
|
+
acknowledged = false;
|
|
2465
|
+
logger.warn(
|
|
2466
|
+
`Settling "${nativeTx.productId}" with the store failed; the entitlement is granted, and the transaction is retained for recovery to retry on the next launch.`,
|
|
2467
|
+
error
|
|
2468
|
+
);
|
|
1478
2469
|
}
|
|
1479
2470
|
const previous = this.deps.getCurrentEntitlements();
|
|
1480
2471
|
try {
|
|
@@ -1487,14 +2478,17 @@ var PurchaseOrchestrator = class {
|
|
|
1487
2478
|
);
|
|
1488
2479
|
}
|
|
1489
2480
|
this.deps.setEntitlements(entitlements);
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
2481
|
+
if (acknowledged) {
|
|
2482
|
+
try {
|
|
2483
|
+
await unfinished.remove(nativeTx.token);
|
|
2484
|
+
} catch (error) {
|
|
2485
|
+
logger.warn(
|
|
2486
|
+
`Failed to remove "${productId}" from unfinished list; will be skipped on next recovery.`,
|
|
2487
|
+
error
|
|
2488
|
+
);
|
|
2489
|
+
}
|
|
1497
2490
|
}
|
|
2491
|
+
await resolvePendingPurchase(this.deps, productId, "purchased");
|
|
1498
2492
|
emitter.emit("purchase-success", { productId, transaction });
|
|
1499
2493
|
emitter.emit("entitlements-changed", {
|
|
1500
2494
|
entitlements: this.deps.getCurrentEntitlements(),
|
|
@@ -1504,6 +2498,7 @@ var PurchaseOrchestrator = class {
|
|
|
1504
2498
|
status: "success",
|
|
1505
2499
|
productId,
|
|
1506
2500
|
transaction,
|
|
2501
|
+
purchase: toStorePurchase(nativeTx),
|
|
1507
2502
|
entitlements: this.deps.getCurrentEntitlements()
|
|
1508
2503
|
};
|
|
1509
2504
|
}
|
|
@@ -1516,7 +2511,7 @@ var PurchaseOrchestrator = class {
|
|
|
1516
2511
|
this.deps.emitter.emit("verification-failed", { productId, error });
|
|
1517
2512
|
return { status: "verification_failed", productId, error };
|
|
1518
2513
|
}
|
|
1519
|
-
handleNativeError(productId, error) {
|
|
2514
|
+
async handleNativeError(productId, error) {
|
|
1520
2515
|
const iapError = toIAPError(
|
|
1521
2516
|
error,
|
|
1522
2517
|
`Native purchase of "${productId}" failed.`,
|
|
@@ -1527,6 +2522,7 @@ var PurchaseOrchestrator = class {
|
|
|
1527
2522
|
return { status: "cancelled", productId };
|
|
1528
2523
|
}
|
|
1529
2524
|
if (iapError.code === IAPErrorCode.PURCHASE_PENDING) {
|
|
2525
|
+
await this.deps.pending.add(productId);
|
|
1530
2526
|
this.deps.emitter.emit("purchase-pending", { productId });
|
|
1531
2527
|
return { status: "pending", productId };
|
|
1532
2528
|
}
|
|
@@ -1543,7 +2539,7 @@ var PurchaseOrchestrator = class {
|
|
|
1543
2539
|
return { status: "verification_failed", productId, error: iapError };
|
|
1544
2540
|
}
|
|
1545
2541
|
};
|
|
1546
|
-
async function
|
|
2542
|
+
async function resolveAppUserId2(supply, ctx) {
|
|
1547
2543
|
let resolved;
|
|
1548
2544
|
if (typeof supply === "function") {
|
|
1549
2545
|
try {
|
|
@@ -1558,10 +2554,10 @@ async function resolveAppUserId(supply, ctx) {
|
|
|
1558
2554
|
} else {
|
|
1559
2555
|
resolved = supply;
|
|
1560
2556
|
}
|
|
1561
|
-
if (
|
|
2557
|
+
if (!isValidUuid(resolved)) {
|
|
1562
2558
|
throw new IAPError({
|
|
1563
2559
|
code: IAPErrorCode.INVALID_APP_USER_ID,
|
|
1564
|
-
message: `appUserId must be
|
|
2560
|
+
message: `appUserId must be an RFC 9562 UUID (any version); received ${typeof resolved === "string" ? `"${resolved}"` : typeof resolved}.`
|
|
1565
2561
|
});
|
|
1566
2562
|
}
|
|
1567
2563
|
return resolved;
|
|
@@ -1618,67 +2614,148 @@ var RecoveryOrchestrator = class {
|
|
|
1618
2614
|
);
|
|
1619
2615
|
return { recovered, failures, droppedPermanent, inspected: entries.length };
|
|
1620
2616
|
}
|
|
2617
|
+
/**
|
|
2618
|
+
* Verify, acknowledge and settle one transaction that arrived outside a
|
|
2619
|
+
* `purchase()` call — a renewal, a refund, an Ask-to-Buy approval, a
|
|
2620
|
+
* pending Play purchase that cleared.
|
|
2621
|
+
*
|
|
2622
|
+
* Routed through the same path recovery uses, deliberately: persisted
|
|
2623
|
+
* before verification so app death cannot lose it, and left in the store
|
|
2624
|
+
* to retry if anything fails. A second settlement path would be a second
|
|
2625
|
+
* place for those to drift.
|
|
2626
|
+
*
|
|
2627
|
+
* **One invariant does not carry over, and it is worth being exact about.**
|
|
2628
|
+
* On the iOS update feed the native plugin calls `transaction.finish()`
|
|
2629
|
+
* *before* it notifies listeners, so by the time iap sees the transaction
|
|
2630
|
+
* the platform has already finished it. "Acknowledged only after the
|
|
2631
|
+
* backend confirms" therefore describes the purchase flow, not this path —
|
|
2632
|
+
* iap has no say in the ordering here. The consequence is that persisting
|
|
2633
|
+
* first matters *more*, not less: StoreKit will not redeliver a finished
|
|
2634
|
+
* transaction, so the `unfinished` entry is the only remaining handle on
|
|
2635
|
+
* it. Callers on that path pass `alreadyFinished`.
|
|
2636
|
+
*/
|
|
2637
|
+
/**
|
|
2638
|
+
* Whether an Android consumable's purchase has left the store's owned set,
|
|
2639
|
+
* which makes a failed consume terminal rather than retryable.
|
|
2640
|
+
*
|
|
2641
|
+
* The sequence this exists for: the consume succeeds on Play, then the
|
|
2642
|
+
* bridge reply or the `unfinished.remove` that follows fails. Play has
|
|
2643
|
+
* already dropped the purchase — Billing 8.x stops returning consumed
|
|
2644
|
+
* purchases from `getPurchases()` — so every later consume of that token
|
|
2645
|
+
* rejects, the entry is retained, and recovery retries it at every launch
|
|
2646
|
+
* forever, burning a `recoveryMaxBatch` slot and a verify each time. The
|
|
2647
|
+
* unfinished store has no age-based eviction to catch that.
|
|
2648
|
+
*
|
|
2649
|
+
* Acknowledging had no such trap: the purchase stayed owned, so a retry
|
|
2650
|
+
* eventually worked. So this asks the store a positive question — is the
|
|
2651
|
+
* purchase still there — rather than trying to read a meaning out of the
|
|
2652
|
+
* error, which would mean matching on Play's message text.
|
|
2653
|
+
*
|
|
2654
|
+
* Only for Google consumables, only on the failure path, and `false` on
|
|
2655
|
+
* any doubt: a store that cannot answer must not be taken to have said
|
|
2656
|
+
* "gone", or a genuinely retryable failure would be dropped.
|
|
2657
|
+
*/
|
|
2658
|
+
async alreadyGone(tx) {
|
|
2659
|
+
if (tx.platform !== "google" || tx.productType !== "consumable") return false;
|
|
2660
|
+
try {
|
|
2661
|
+
const owned = await this.deps.nativeAdapter.getOwnedTransactions();
|
|
2662
|
+
return !owned.some((candidate) => candidate.token === tx.token);
|
|
2663
|
+
} catch (error) {
|
|
2664
|
+
this.deps.logger.debug(
|
|
2665
|
+
`Recovery: could not re-read the owned set for productId=${tx.productId}; treating the settle failure as retryable.`,
|
|
2666
|
+
error
|
|
2667
|
+
);
|
|
2668
|
+
return false;
|
|
2669
|
+
}
|
|
2670
|
+
}
|
|
2671
|
+
async settleTransaction(tx, opts = {}) {
|
|
2672
|
+
if (opts.persist !== false) {
|
|
2673
|
+
try {
|
|
2674
|
+
await this.deps.unfinished.add(tx);
|
|
2675
|
+
} catch (error) {
|
|
2676
|
+
this.deps.logger.warn(
|
|
2677
|
+
`Transaction update: failed to persist unfinished entry for "${tx.productId}"; verifying anyway.`,
|
|
2678
|
+
error
|
|
2679
|
+
);
|
|
2680
|
+
}
|
|
2681
|
+
}
|
|
2682
|
+
const result = await this.processTransaction(tx, opts);
|
|
2683
|
+
if (result.kind === "recovered") {
|
|
2684
|
+
await this.applyEntitlements(result.entitlements);
|
|
2685
|
+
return "settled";
|
|
2686
|
+
}
|
|
2687
|
+
return result.kind === "dropped-permanent" ? "dropped-permanent" : "failed";
|
|
2688
|
+
}
|
|
1621
2689
|
async processEntry(entry) {
|
|
2690
|
+
return this.processTransaction(entryToNativeTransaction(entry));
|
|
2691
|
+
}
|
|
2692
|
+
async processTransaction(tx, opts = {}) {
|
|
1622
2693
|
const { nativeAdapter, unfinished, logger, emitter, permanentErrorCodes } = this.deps;
|
|
1623
|
-
const
|
|
1624
|
-
const tokenLabel = maskToken(entry.token);
|
|
2694
|
+
const tokenLabel = maskToken(tx.token);
|
|
1625
2695
|
try {
|
|
1626
2696
|
const response = await verifyNativeTransaction(this.deps.backend, tx);
|
|
1627
2697
|
if (!response.valid) {
|
|
1628
2698
|
if (permanentErrorCodes.has(response.error)) {
|
|
1629
2699
|
logger.info(
|
|
1630
|
-
`Recovery: dropping permanently-invalid token=${tokenLabel} productId=${
|
|
2700
|
+
`Recovery: dropping permanently-invalid token=${tokenLabel} productId=${tx.productId} (${response.error}).`
|
|
1631
2701
|
);
|
|
1632
2702
|
try {
|
|
1633
2703
|
await nativeAdapter.acknowledge(tx);
|
|
1634
2704
|
} catch (error) {
|
|
1635
2705
|
logger.warn(
|
|
1636
|
-
`Recovery: best-effort acknowledge() failed for productId=${
|
|
2706
|
+
`Recovery: best-effort acknowledge() failed for productId=${tx.productId}; proceeding with removal anyway.`,
|
|
1637
2707
|
error
|
|
1638
2708
|
);
|
|
1639
2709
|
}
|
|
1640
2710
|
try {
|
|
1641
|
-
await unfinished.remove(
|
|
2711
|
+
await unfinished.remove(tx.token);
|
|
1642
2712
|
} catch (error) {
|
|
1643
2713
|
logger.warn(
|
|
1644
|
-
`Recovery: unfinished.remove() failed for productId=${
|
|
2714
|
+
`Recovery: unfinished.remove() failed for productId=${tx.productId} after permanent classification; will dedupe on next launch.`,
|
|
1645
2715
|
error
|
|
1646
2716
|
);
|
|
1647
2717
|
}
|
|
1648
2718
|
emitter.emit("recovery-dropped-permanent", {
|
|
1649
|
-
productId:
|
|
1650
|
-
token:
|
|
2719
|
+
productId: tx.productId,
|
|
2720
|
+
token: tx.token,
|
|
1651
2721
|
error: response.error,
|
|
1652
2722
|
...response.message !== void 0 ? { message: response.message } : {}
|
|
1653
2723
|
});
|
|
1654
2724
|
return { kind: "dropped-permanent" };
|
|
1655
2725
|
}
|
|
1656
2726
|
logger.debug(
|
|
1657
|
-
`Recovery: backend rejected token=${tokenLabel} productId=${
|
|
2727
|
+
`Recovery: backend rejected token=${tokenLabel} productId=${tx.productId} (${response.error}); leaving in list for retry.`
|
|
1658
2728
|
);
|
|
1659
2729
|
return { kind: "failed" };
|
|
1660
2730
|
}
|
|
1661
2731
|
try {
|
|
1662
|
-
await nativeAdapter
|
|
2732
|
+
await finalizeTransaction({ nativeAdapter, transaction: tx, logger });
|
|
1663
2733
|
} catch (error) {
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
2734
|
+
if (opts.alreadyFinished || await this.alreadyGone(tx)) {
|
|
2735
|
+
logger.debug(
|
|
2736
|
+
`Recovery: settling productId=${tx.productId} failed, but the store no longer has the purchase; treating as settled.`
|
|
2737
|
+
);
|
|
2738
|
+
} else {
|
|
2739
|
+
logger.warn(
|
|
2740
|
+
`Recovery: settling productId=${tx.productId} with the store failed; entry retained for next launch.`,
|
|
2741
|
+
error
|
|
2742
|
+
);
|
|
2743
|
+
return { kind: "failed" };
|
|
2744
|
+
}
|
|
1669
2745
|
}
|
|
1670
2746
|
try {
|
|
1671
|
-
await unfinished.remove(
|
|
2747
|
+
await unfinished.remove(tx.token);
|
|
1672
2748
|
} catch (error) {
|
|
1673
2749
|
logger.warn(
|
|
1674
|
-
`Recovery: unfinished.remove() failed for productId=${
|
|
2750
|
+
`Recovery: unfinished.remove() failed for productId=${tx.productId}; will dedupe on next launch.`,
|
|
1675
2751
|
error
|
|
1676
2752
|
);
|
|
1677
2753
|
}
|
|
2754
|
+
await resolvePendingPurchase(this.deps, tx.productId, "purchased");
|
|
1678
2755
|
return { kind: "recovered", entitlements: response.entitlements };
|
|
1679
2756
|
} catch (error) {
|
|
1680
2757
|
logger.warn(
|
|
1681
|
-
`Recovery: verify failed for productId=${
|
|
2758
|
+
`Recovery: verify failed for productId=${tx.productId}; will retry next launch.`,
|
|
1682
2759
|
error
|
|
1683
2760
|
);
|
|
1684
2761
|
return { kind: "failed" };
|
|
@@ -1707,8 +2784,26 @@ function entryToNativeTransaction(entry) {
|
|
|
1707
2784
|
platform: entry.platform,
|
|
1708
2785
|
productId: entry.productId,
|
|
1709
2786
|
token: entry.token,
|
|
2787
|
+
// Entries persisted before `purchaseReference` existed carry only the
|
|
2788
|
+
// token; on Android the two are the same value anyway, and on iOS the
|
|
2789
|
+
// token is the right fallback (see `NativeTransaction`).
|
|
2790
|
+
// `||`, not `??`: a stored empty string is as unusable as an absent one.
|
|
2791
|
+
purchaseReference: entry.purchaseReference || entry.token,
|
|
1710
2792
|
productType: entry.productType
|
|
1711
2793
|
};
|
|
2794
|
+
if (entry.appUserId) tx.appUserId = entry.appUserId;
|
|
2795
|
+
if (entry.expiresAt) {
|
|
2796
|
+
tx.subscription = {
|
|
2797
|
+
state: null,
|
|
2798
|
+
autoRenewing: null,
|
|
2799
|
+
renewsAt: null,
|
|
2800
|
+
renewalProductId: null,
|
|
2801
|
+
expiresAt: entry.expiresAt
|
|
2802
|
+
};
|
|
2803
|
+
}
|
|
2804
|
+
if (entry.purchaseState) {
|
|
2805
|
+
tx.raw = { purchaseState: entry.purchaseState };
|
|
2806
|
+
}
|
|
1712
2807
|
if (entry.packageName) tx.packageName = entry.packageName;
|
|
1713
2808
|
return tx;
|
|
1714
2809
|
}
|
|
@@ -1732,14 +2827,11 @@ var RestoreOrchestrator = class {
|
|
|
1732
2827
|
if (owned.length === 0) {
|
|
1733
2828
|
const entitlements2 = this.deps.getCurrentEntitlements();
|
|
1734
2829
|
emitter.emit("restore-completed", { restored: 0, entitlements: entitlements2 });
|
|
1735
|
-
return { restored: 0, entitlements: entitlements2 };
|
|
2830
|
+
return { restored: 0, entitlements: entitlements2, purchases: [] };
|
|
1736
2831
|
}
|
|
1737
|
-
const request = {
|
|
1738
|
-
transactions: owned.map((tx) => this.toRestoreEntry(tx))
|
|
1739
|
-
};
|
|
1740
2832
|
let response;
|
|
1741
2833
|
try {
|
|
1742
|
-
response = await backend.restore(
|
|
2834
|
+
response = backend.restoreNative ? await backend.restoreNative(owned) : await backend.restore({ transactions: owned.map((tx) => this.toRestoreEntry(tx)) });
|
|
1743
2835
|
} catch (cause) {
|
|
1744
2836
|
throw toIAPError(cause, "Backend restore call failed.", IAPErrorCode.BACKEND_UNAVAILABLE);
|
|
1745
2837
|
}
|
|
@@ -1750,11 +2842,19 @@ var RestoreOrchestrator = class {
|
|
|
1750
2842
|
message: detail
|
|
1751
2843
|
});
|
|
1752
2844
|
}
|
|
1753
|
-
|
|
2845
|
+
const ackable = response.verifiedTokens === void 0 ? owned : owned.filter((tx) => response.verifiedTokens?.includes(tx.token));
|
|
2846
|
+
if (ackable.length !== owned.length) {
|
|
2847
|
+
logger.debug(
|
|
2848
|
+
`Restore: settling ${ackable.length} of ${owned.length} owned transaction(s); the rest were not verified.`
|
|
2849
|
+
);
|
|
2850
|
+
}
|
|
2851
|
+
const settled = [];
|
|
2852
|
+
for (const tx of ackable) {
|
|
1754
2853
|
try {
|
|
1755
|
-
await nativeAdapter
|
|
2854
|
+
await finalizeTransaction({ nativeAdapter, transaction: tx, logger });
|
|
2855
|
+
settled.push(tx);
|
|
1756
2856
|
} catch (error) {
|
|
1757
|
-
logger.warn(`
|
|
2857
|
+
logger.warn(`Settling "${tx.productId}" with the store failed during restore.`, error);
|
|
1758
2858
|
}
|
|
1759
2859
|
}
|
|
1760
2860
|
const entitlements = response.entitlements;
|
|
@@ -1769,7 +2869,7 @@ var RestoreOrchestrator = class {
|
|
|
1769
2869
|
);
|
|
1770
2870
|
}
|
|
1771
2871
|
this.deps.setEntitlements(entitlements);
|
|
1772
|
-
for (const tx of
|
|
2872
|
+
for (const tx of settled) {
|
|
1773
2873
|
try {
|
|
1774
2874
|
await unfinished.remove(tx.token);
|
|
1775
2875
|
} catch (error) {
|
|
@@ -1779,12 +2879,26 @@ var RestoreOrchestrator = class {
|
|
|
1779
2879
|
);
|
|
1780
2880
|
}
|
|
1781
2881
|
}
|
|
2882
|
+
for (const tx of settled) {
|
|
2883
|
+
try {
|
|
2884
|
+
await resolvePendingPurchase(this.deps, tx.productId, "purchased");
|
|
2885
|
+
} catch (error) {
|
|
2886
|
+
logger.warn(
|
|
2887
|
+
`Failed to clear the pending mark for "${tx.productId}" during restore.`,
|
|
2888
|
+
error
|
|
2889
|
+
);
|
|
2890
|
+
}
|
|
2891
|
+
}
|
|
1782
2892
|
const next = this.deps.getCurrentEntitlements();
|
|
1783
2893
|
emitter.emit("restore-completed", { restored: owned.length, entitlements: next });
|
|
1784
2894
|
if (!entitlementsEqual(previous, next)) {
|
|
1785
2895
|
emitter.emit("entitlements-changed", { entitlements: next, previous });
|
|
1786
2896
|
}
|
|
1787
|
-
return {
|
|
2897
|
+
return {
|
|
2898
|
+
restored: owned.length,
|
|
2899
|
+
entitlements: next,
|
|
2900
|
+
purchases: owned.map(toStorePurchase)
|
|
2901
|
+
};
|
|
1788
2902
|
}
|
|
1789
2903
|
toRestoreEntry(tx) {
|
|
1790
2904
|
if (tx.platform === "apple") {
|
|
@@ -1797,7 +2911,7 @@ var RestoreOrchestrator = class {
|
|
|
1797
2911
|
if (!tx.packageName) {
|
|
1798
2912
|
throw new IAPError({
|
|
1799
2913
|
code: IAPErrorCode.STORE_ERROR,
|
|
1800
|
-
message: `Google owned transaction for "${tx.productId}" has no packageName; cannot restore.`
|
|
2914
|
+
message: `Google owned transaction for "${tx.productId}" has no packageName; cannot restore. Set config.android.packageName to your app's applicationId \u2014 the native plugin does not report it, so iap cannot derive it from the purchase.`
|
|
1801
2915
|
});
|
|
1802
2916
|
}
|
|
1803
2917
|
return {
|
|
@@ -1809,19 +2923,509 @@ var RestoreOrchestrator = class {
|
|
|
1809
2923
|
}
|
|
1810
2924
|
};
|
|
1811
2925
|
|
|
2926
|
+
// src/core/transaction-updates.ts
|
|
2927
|
+
var TransactionUpdateOrchestrator = class {
|
|
2928
|
+
constructor(deps) {
|
|
2929
|
+
this.deps = deps;
|
|
2930
|
+
}
|
|
2931
|
+
deps;
|
|
2932
|
+
/**
|
|
2933
|
+
* Tokens currently being settled, so two paths cannot settle the same
|
|
2934
|
+
* transaction at once.
|
|
2935
|
+
*
|
|
2936
|
+
* The listener is fire-and-forget and reconciliation runs on resume, so
|
|
2937
|
+
* they genuinely overlap. Without this, both verify and both acknowledge —
|
|
2938
|
+
* and on Android a second `acknowledge` of an already-acked token errors,
|
|
2939
|
+
* which the settle path reads as a failure and retains the entry for.
|
|
2940
|
+
*/
|
|
2941
|
+
settling = /* @__PURE__ */ new Set();
|
|
2942
|
+
/** The in-flight reconciliation pass, so concurrent callers join it. */
|
|
2943
|
+
reconciling = null;
|
|
2944
|
+
/** Settle a transaction pushed by the platform. Never throws. */
|
|
2945
|
+
async handle(transaction) {
|
|
2946
|
+
const { logger, emitter, isPurchaseInFlight } = this.deps;
|
|
2947
|
+
try {
|
|
2948
|
+
if (!this.deps.isActive()) {
|
|
2949
|
+
logger.debug("Transaction update arrived after teardown; ignoring.");
|
|
2950
|
+
return;
|
|
2951
|
+
}
|
|
2952
|
+
if (isPurchaseInFlight(transaction.productId)) {
|
|
2953
|
+
logger.debug(
|
|
2954
|
+
`Transaction update for "${transaction.productId}" arrived while a purchase is in flight; leaving it to the purchase flow.`
|
|
2955
|
+
);
|
|
2956
|
+
return;
|
|
2957
|
+
}
|
|
2958
|
+
emitter.emit("transaction-updated", {
|
|
2959
|
+
productId: transaction.productId,
|
|
2960
|
+
purchase: toStorePurchase(transaction)
|
|
2961
|
+
});
|
|
2962
|
+
const isRevocation = transaction.subscription?.state === "revoked";
|
|
2963
|
+
const outcome = await this.settleOnce(transaction, {
|
|
2964
|
+
persist: !isRevocation,
|
|
2965
|
+
alreadyFinished: transaction.platform === "apple"
|
|
2966
|
+
});
|
|
2967
|
+
if (outcome !== "settled") {
|
|
2968
|
+
logger.debug(
|
|
2969
|
+
`Transaction update for "${transaction.productId}" did not settle (${outcome}).`
|
|
2970
|
+
);
|
|
2971
|
+
}
|
|
2972
|
+
} catch (error) {
|
|
2973
|
+
logger.warn(
|
|
2974
|
+
`Transaction update handling threw for "${transaction.productId}"; ignoring.`,
|
|
2975
|
+
error
|
|
2976
|
+
);
|
|
2977
|
+
}
|
|
2978
|
+
}
|
|
2979
|
+
/**
|
|
2980
|
+
* Ask the store what became of the purchases iap reported as pending.
|
|
2981
|
+
*
|
|
2982
|
+
* Call at `initialize()` and on resume. Does nothing when nothing is
|
|
2983
|
+
* tracked, so the common case costs no native calls. Never throws.
|
|
2984
|
+
*/
|
|
2985
|
+
async reconcilePending() {
|
|
2986
|
+
if (this.reconciling) return this.reconciling;
|
|
2987
|
+
this.reconciling = this.runReconcile().finally(() => {
|
|
2988
|
+
this.reconciling = null;
|
|
2989
|
+
});
|
|
2990
|
+
return this.reconciling;
|
|
2991
|
+
}
|
|
2992
|
+
async runReconcile() {
|
|
2993
|
+
const { nativeAdapter, logger, pending } = this.deps;
|
|
2994
|
+
try {
|
|
2995
|
+
if (!this.deps.isActive()) return;
|
|
2996
|
+
const tracked = await pending.list();
|
|
2997
|
+
if (tracked.length === 0) return;
|
|
2998
|
+
const stillPending = await nativeAdapter.getPendingProductIds?.() ?? null;
|
|
2999
|
+
const owned = await nativeAdapter.getOwnedTransactions();
|
|
3000
|
+
const ownedByProduct = new Map(owned.map((tx) => [tx.productId, tx]));
|
|
3001
|
+
for (const productId of tracked) {
|
|
3002
|
+
if (this.deps.isPurchaseInFlight(productId)) {
|
|
3003
|
+
logger.debug(
|
|
3004
|
+
`Pending purchase "${productId}" is being purchased right now; leaving it to the purchase flow.`
|
|
3005
|
+
);
|
|
3006
|
+
continue;
|
|
3007
|
+
}
|
|
3008
|
+
const ownedTx = ownedByProduct.get(productId);
|
|
3009
|
+
if (ownedTx) {
|
|
3010
|
+
const outcome = await this.settleOnce(ownedTx);
|
|
3011
|
+
if (outcome !== "settled") {
|
|
3012
|
+
logger.debug(
|
|
3013
|
+
`Pending purchase "${productId}" is owned but did not settle (${outcome}); keeping it pending.`
|
|
3014
|
+
);
|
|
3015
|
+
}
|
|
3016
|
+
continue;
|
|
3017
|
+
}
|
|
3018
|
+
if (stillPending === null) {
|
|
3019
|
+
logger.debug(
|
|
3020
|
+
`Pending purchase "${productId}" is not owned, but this platform cannot report pending state; keeping it pending.`
|
|
3021
|
+
);
|
|
3022
|
+
continue;
|
|
3023
|
+
}
|
|
3024
|
+
if (stillPending.includes(productId)) continue;
|
|
3025
|
+
await this.resolvePending(productId, "cancelled");
|
|
3026
|
+
}
|
|
3027
|
+
} catch (error) {
|
|
3028
|
+
logger.warn("Reconciling pending purchases failed; markers kept for the next pass.", error);
|
|
3029
|
+
}
|
|
3030
|
+
}
|
|
3031
|
+
/**
|
|
3032
|
+
* Settle a transaction, unless it is already being settled.
|
|
3033
|
+
*
|
|
3034
|
+
* Keyed on the token, not the product: two different transactions for one
|
|
3035
|
+
* product (an iOS subscription has a token per renewal) should both
|
|
3036
|
+
* settle, while the same transaction reaching both paths should not.
|
|
3037
|
+
*/
|
|
3038
|
+
async settleOnce(tx, opts = {}) {
|
|
3039
|
+
if (this.settling.has(tx.token)) return "already-settling";
|
|
3040
|
+
this.settling.add(tx.token);
|
|
3041
|
+
try {
|
|
3042
|
+
return await this.deps.recoverer.settleTransaction(tx, opts);
|
|
3043
|
+
} finally {
|
|
3044
|
+
this.settling.delete(tx.token);
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
3047
|
+
/** Announce how a pending purchase ended. See `resolve-pending.ts`. */
|
|
3048
|
+
async resolvePending(productId, status) {
|
|
3049
|
+
await resolvePendingPurchase(this.deps, productId, status);
|
|
3050
|
+
}
|
|
3051
|
+
};
|
|
3052
|
+
|
|
3053
|
+
// src/core/initialize.ts
|
|
3054
|
+
async function initializeIap(state, refreshEntitlements) {
|
|
3055
|
+
if (state.destroyed) {
|
|
3056
|
+
throw new IAPError({
|
|
3057
|
+
code: IAPErrorCode.NOT_INITIALIZED,
|
|
3058
|
+
message: "IAP instance has been destroyed; create a new one with createIAP()."
|
|
3059
|
+
});
|
|
3060
|
+
}
|
|
3061
|
+
if (state.initialized) {
|
|
3062
|
+
state.logger.debug("initialize() called more than once; ignoring.");
|
|
3063
|
+
return;
|
|
3064
|
+
}
|
|
3065
|
+
const platform = getPlatform();
|
|
3066
|
+
if (!isNative()) {
|
|
3067
|
+
state.logger.info("Native purchases unavailable on web; entitlement queries still functional.");
|
|
3068
|
+
} else {
|
|
3069
|
+
state.logger.debug(`Initializing on platform=${platform}`);
|
|
3070
|
+
}
|
|
3071
|
+
if (!state.config.products) {
|
|
3072
|
+
if (typeof state.backend.listProducts !== "function") {
|
|
3073
|
+
throw new IAPError({
|
|
3074
|
+
code: IAPErrorCode.INVALID_CONFIG,
|
|
3075
|
+
message: "config.products is omitted but backend adapter does not implement listProducts(). This is a library bug; the schema should have caught it."
|
|
3076
|
+
});
|
|
3077
|
+
}
|
|
3078
|
+
const fetched = await state.backend.listProducts();
|
|
3079
|
+
const validated = configuredProductsArraySchema.safeParse(fetched);
|
|
3080
|
+
if (!validated.success) {
|
|
3081
|
+
throw new IAPError({
|
|
3082
|
+
code: IAPErrorCode.BACKEND_BAD_RESPONSE,
|
|
3083
|
+
message: `backend.listProducts() returned an invalid manifest: ${validated.error.issues.map((i) => `${i.path.join(".") || "<root>"}: ${i.message}`).join("; ")}`,
|
|
3084
|
+
cause: validated.error
|
|
3085
|
+
});
|
|
3086
|
+
}
|
|
3087
|
+
ensureUniqueProductIds(validated.data);
|
|
3088
|
+
state.products = Object.freeze([...validated.data]);
|
|
3089
|
+
state.logger.debug(`Resolved ${validated.data.length} product(s) from backend manifest.`);
|
|
3090
|
+
}
|
|
3091
|
+
state.adapter = await selectNativeAdapter(
|
|
3092
|
+
state.logger,
|
|
3093
|
+
state.config.android.packageName,
|
|
3094
|
+
() => state.products
|
|
3095
|
+
);
|
|
3096
|
+
const configGetAuthHeaders = state.config.backend?.getAuthHeaders;
|
|
3097
|
+
const getAuthHeaders = configGetAuthHeaders ? async () => configGetAuthHeaders() : async () => ({});
|
|
3098
|
+
const sharedDeps = {
|
|
3099
|
+
nativeAdapter: state.adapter,
|
|
3100
|
+
backend: state.backend,
|
|
3101
|
+
cache: state.cache,
|
|
3102
|
+
unfinished: state.unfinished,
|
|
3103
|
+
emitter: state.emitter,
|
|
3104
|
+
logger: state.logger,
|
|
3105
|
+
getCurrentEntitlements: () => state.entitlements,
|
|
3106
|
+
setEntitlements: (next) => {
|
|
3107
|
+
state.entitlements = freezeAll(next);
|
|
3108
|
+
},
|
|
3109
|
+
setCachePersisted: (cachedAt) => {
|
|
3110
|
+
state.cachedAt = cachedAt;
|
|
3111
|
+
},
|
|
3112
|
+
getAuthHeaders
|
|
3113
|
+
};
|
|
3114
|
+
state.orchestrator = new PurchaseOrchestrator({
|
|
3115
|
+
...sharedDeps,
|
|
3116
|
+
products: state.products,
|
|
3117
|
+
pending: state.pending
|
|
3118
|
+
});
|
|
3119
|
+
state.restorer = new RestoreOrchestrator({ ...sharedDeps, pending: state.pending });
|
|
3120
|
+
state.recoverer = new RecoveryOrchestrator({
|
|
3121
|
+
...sharedDeps,
|
|
3122
|
+
pending: state.pending,
|
|
3123
|
+
maxBatch: state.config.options.recoveryMaxBatch,
|
|
3124
|
+
permanentErrorCodes: new Set(
|
|
3125
|
+
state.config.options.permanentErrorCodes ?? DEFAULT_PERMANENT_ERROR_CODES
|
|
3126
|
+
)
|
|
3127
|
+
});
|
|
3128
|
+
state.updates = new TransactionUpdateOrchestrator({
|
|
3129
|
+
nativeAdapter: state.adapter,
|
|
3130
|
+
recoverer: state.recoverer,
|
|
3131
|
+
pending: state.pending,
|
|
3132
|
+
emitter: state.emitter,
|
|
3133
|
+
logger: state.logger,
|
|
3134
|
+
isPurchaseInFlight: (productId) => state.orchestrator?.isInFlight(productId) ?? false,
|
|
3135
|
+
isActive: () => state.initialized && !state.destroyed
|
|
3136
|
+
});
|
|
3137
|
+
if (platform === "android" && !state.config.android.packageName) {
|
|
3138
|
+
state.logger.warn(
|
|
3139
|
+
"config.android.packageName is not set. Google verification and restore requests cannot be built without it, so purchases will fail with STORE_ERROR. Set it to your app's applicationId."
|
|
3140
|
+
);
|
|
3141
|
+
}
|
|
3142
|
+
try {
|
|
3143
|
+
await state.adapter.isAvailable();
|
|
3144
|
+
} catch (error) {
|
|
3145
|
+
state.logger.warn("Native adapter availability check threw; continuing.", error);
|
|
3146
|
+
}
|
|
3147
|
+
const cached = await state.cache.load();
|
|
3148
|
+
if (cached) {
|
|
3149
|
+
state.entitlements = freezeAll(cached.entitlements);
|
|
3150
|
+
state.cachedAt = cached.cachedAt;
|
|
3151
|
+
state.logger.debug(
|
|
3152
|
+
`Loaded ${cached.entitlements.length} cached entitlement(s) from ${new Date(cached.cachedAt).toISOString()}.`
|
|
3153
|
+
);
|
|
3154
|
+
}
|
|
3155
|
+
if (state.config.options.recoverUnfinishedTransactions && isNative()) {
|
|
3156
|
+
try {
|
|
3157
|
+
const result = await state.recoverer.recoverUnfinishedTransactions();
|
|
3158
|
+
if (result.inspected > 0) {
|
|
3159
|
+
state.logger.info(
|
|
3160
|
+
`Recovery inspected ${result.inspected} unfinished transaction(s): ${result.recovered} recovered, ${result.failures} retained.`
|
|
3161
|
+
);
|
|
3162
|
+
}
|
|
3163
|
+
} catch (error) {
|
|
3164
|
+
state.logger.warn("Recovery threw unexpectedly; continuing initialize.", error);
|
|
3165
|
+
}
|
|
3166
|
+
}
|
|
3167
|
+
if (isNative()) {
|
|
3168
|
+
state.txWatch = await attachTransactionWatch({
|
|
3169
|
+
adapter: state.adapter,
|
|
3170
|
+
updates: state.updates,
|
|
3171
|
+
logger: state.logger
|
|
3172
|
+
});
|
|
3173
|
+
}
|
|
3174
|
+
if (state.config.options.refreshOnResume && isNative()) {
|
|
3175
|
+
state.resumeListener = await attachAppResumeListener({
|
|
3176
|
+
logger: state.logger,
|
|
3177
|
+
onResume: async () => {
|
|
3178
|
+
try {
|
|
3179
|
+
await refreshEntitlements();
|
|
3180
|
+
} catch (error) {
|
|
3181
|
+
state.logger.warn("refreshOnResume: refresh() failed.", error);
|
|
3182
|
+
}
|
|
3183
|
+
await state.updates?.reconcilePending();
|
|
3184
|
+
}
|
|
3185
|
+
});
|
|
3186
|
+
}
|
|
3187
|
+
if (state.cachedAt !== null && Date.now() - state.cachedAt > state.config.options.entitlementCacheTtlMs) {
|
|
3188
|
+
state.logger.debug("Cache exceeds TTL; scheduling background refresh.");
|
|
3189
|
+
queueMicrotask(() => {
|
|
3190
|
+
if (!state.initialized || state.destroyed) return;
|
|
3191
|
+
refreshEntitlements().catch((error) => {
|
|
3192
|
+
state.logger.warn("TTL background refresh failed.", error);
|
|
3193
|
+
});
|
|
3194
|
+
});
|
|
3195
|
+
}
|
|
3196
|
+
state.initialized = true;
|
|
3197
|
+
state.emitter.emit("ready", void 0);
|
|
3198
|
+
if (isNative()) {
|
|
3199
|
+
queueMicrotask(() => {
|
|
3200
|
+
if (!state.initialized || state.destroyed) return;
|
|
3201
|
+
void state.updates?.reconcilePending();
|
|
3202
|
+
});
|
|
3203
|
+
}
|
|
3204
|
+
}
|
|
3205
|
+
|
|
3206
|
+
// src/core/mutation-lock.ts
|
|
3207
|
+
function createMutationLock() {
|
|
3208
|
+
let tail = Promise.resolve();
|
|
3209
|
+
return async function runExclusive(fn) {
|
|
3210
|
+
const previous = tail;
|
|
3211
|
+
let release;
|
|
3212
|
+
tail = new Promise((resolve) => {
|
|
3213
|
+
release = resolve;
|
|
3214
|
+
});
|
|
3215
|
+
try {
|
|
3216
|
+
await previous;
|
|
3217
|
+
return await fn();
|
|
3218
|
+
} finally {
|
|
3219
|
+
release();
|
|
3220
|
+
}
|
|
3221
|
+
};
|
|
3222
|
+
}
|
|
3223
|
+
|
|
3224
|
+
// src/core/pending-purchases.ts
|
|
3225
|
+
var STORE_KEY = IAP_STORAGE_KEYS.pendingPurchases;
|
|
3226
|
+
var pendingEntrySchema = z.union([
|
|
3227
|
+
z.object({ productId: z.string().min(1), recordedAt: z.string().min(1) }),
|
|
3228
|
+
z.string().min(1).transform((productId) => ({ productId, recordedAt: "" }))
|
|
3229
|
+
]);
|
|
3230
|
+
var pendingListSchema = z.array(pendingEntrySchema);
|
|
3231
|
+
var MAX_PENDING_AGE_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
3232
|
+
var PendingPurchasesStore = class {
|
|
3233
|
+
constructor(storage, logger) {
|
|
3234
|
+
this.storage = storage;
|
|
3235
|
+
this.logger = logger;
|
|
3236
|
+
}
|
|
3237
|
+
storage;
|
|
3238
|
+
logger;
|
|
3239
|
+
runExclusive = createMutationLock();
|
|
3240
|
+
/** Product ids currently marked pending, or `[]` if empty / corrupt. */
|
|
3241
|
+
async list() {
|
|
3242
|
+
return (await this.readLive()).map((entry) => entry.productId);
|
|
3243
|
+
}
|
|
3244
|
+
/** Live entries, with anything past {@link MAX_PENDING_AGE_MS} dropped. */
|
|
3245
|
+
async readLive() {
|
|
3246
|
+
let raw;
|
|
3247
|
+
try {
|
|
3248
|
+
raw = await this.storage.get(STORE_KEY);
|
|
3249
|
+
} catch (cause) {
|
|
3250
|
+
this.logger.warn("Storage read failed; treating pending list as empty.", cause);
|
|
3251
|
+
return [];
|
|
3252
|
+
}
|
|
3253
|
+
if (!raw) return [];
|
|
3254
|
+
let parsed;
|
|
3255
|
+
try {
|
|
3256
|
+
parsed = JSON.parse(raw);
|
|
3257
|
+
} catch (cause) {
|
|
3258
|
+
this.logger.warn("pending_purchases payload is not valid JSON; clearing.", cause);
|
|
3259
|
+
await this.safeRemove();
|
|
3260
|
+
return [];
|
|
3261
|
+
}
|
|
3262
|
+
const result = pendingListSchema.safeParse(parsed);
|
|
3263
|
+
if (!result.success) {
|
|
3264
|
+
this.logger.warn("pending_purchases has unexpected shape; clearing.", result.error);
|
|
3265
|
+
await this.safeRemove();
|
|
3266
|
+
return [];
|
|
3267
|
+
}
|
|
3268
|
+
const now = Date.now();
|
|
3269
|
+
const live = result.data.filter((entry) => {
|
|
3270
|
+
if (entry.recordedAt === "") return true;
|
|
3271
|
+
const marked = Date.parse(entry.recordedAt);
|
|
3272
|
+
if (Number.isNaN(marked)) return false;
|
|
3273
|
+
return now - marked < MAX_PENDING_AGE_MS;
|
|
3274
|
+
});
|
|
3275
|
+
if (live.length !== result.data.length) {
|
|
3276
|
+
this.logger.debug(
|
|
3277
|
+
`Dropping ${result.data.length - live.length} pending mark(s) past the age limit.`
|
|
3278
|
+
);
|
|
3279
|
+
await this.persist(live);
|
|
3280
|
+
}
|
|
3281
|
+
return live;
|
|
3282
|
+
}
|
|
3283
|
+
async has(productId) {
|
|
3284
|
+
return (await this.list()).includes(productId);
|
|
3285
|
+
}
|
|
3286
|
+
/**
|
|
3287
|
+
* Remove a product's pending mark and report whether it was there.
|
|
3288
|
+
*
|
|
3289
|
+
* The atomic form of `has()` then `remove()`, and the reason it exists:
|
|
3290
|
+
* `purchase-pending-resolved` promises to fire at most once per pending
|
|
3291
|
+
* purchase, and the two callers that resolve one can run concurrently —
|
|
3292
|
+
* the iOS transaction listener is fire-and-forget, so it can interleave
|
|
3293
|
+
* with the reconciliation that runs on resume. Checked and removed
|
|
3294
|
+
* separately, both would observe the mark and both would emit.
|
|
3295
|
+
*/
|
|
3296
|
+
async takeIfPresent(productId) {
|
|
3297
|
+
return this.runExclusive(async () => {
|
|
3298
|
+
const current = await this.readLive();
|
|
3299
|
+
if (!current.some((entry) => entry.productId === productId)) return false;
|
|
3300
|
+
await this.persist(current.filter((entry) => entry.productId !== productId));
|
|
3301
|
+
return true;
|
|
3302
|
+
});
|
|
3303
|
+
}
|
|
3304
|
+
/** Mark a product pending. Idempotent — re-marking does not reset the age. */
|
|
3305
|
+
async add(productId) {
|
|
3306
|
+
return this.runExclusive(async () => {
|
|
3307
|
+
const current = await this.readLive();
|
|
3308
|
+
if (current.some((entry) => entry.productId === productId)) return;
|
|
3309
|
+
await this.persist([...current, { productId, recordedAt: (/* @__PURE__ */ new Date()).toISOString() }]);
|
|
3310
|
+
});
|
|
3311
|
+
}
|
|
3312
|
+
/** Clear a product's pending mark. No-op if absent. */
|
|
3313
|
+
async remove(productId) {
|
|
3314
|
+
return this.runExclusive(async () => {
|
|
3315
|
+
const current = await this.readLive();
|
|
3316
|
+
const next = current.filter((entry) => entry.productId !== productId);
|
|
3317
|
+
if (next.length === current.length) return;
|
|
3318
|
+
await this.persist(next);
|
|
3319
|
+
});
|
|
3320
|
+
}
|
|
3321
|
+
/** Drop every pending mark. Used by `iap.reset()`. */
|
|
3322
|
+
async clear() {
|
|
3323
|
+
return this.runExclusive(() => this.safeRemove());
|
|
3324
|
+
}
|
|
3325
|
+
async persist(entries) {
|
|
3326
|
+
try {
|
|
3327
|
+
await this.storage.set(STORE_KEY, JSON.stringify(entries));
|
|
3328
|
+
} catch (cause) {
|
|
3329
|
+
this.logger.warn("Failed to persist pending_purchases; pending state may be lost.", cause);
|
|
3330
|
+
}
|
|
3331
|
+
}
|
|
3332
|
+
async safeRemove() {
|
|
3333
|
+
try {
|
|
3334
|
+
await this.storage.remove(STORE_KEY);
|
|
3335
|
+
} catch (cause) {
|
|
3336
|
+
this.logger.warn("Failed to clear pending_purchases key.", cause);
|
|
3337
|
+
}
|
|
3338
|
+
}
|
|
3339
|
+
};
|
|
3340
|
+
|
|
3341
|
+
// src/core/reset.ts
|
|
3342
|
+
init_errors();
|
|
3343
|
+
async function resetIap(state) {
|
|
3344
|
+
const inFlight = state.orchestrator?.inFlightProducts() ?? [];
|
|
3345
|
+
if (inFlight.length > 0) {
|
|
3346
|
+
throw new IAPError({
|
|
3347
|
+
code: IAPErrorCode.ALREADY_IN_PROGRESS,
|
|
3348
|
+
message: `Cannot reset while a purchase of ${inFlight.map((id) => `"${id}"`).join(", ")} is in progress: its unfinished-transaction record is still needed. Await the purchase, then reset.`,
|
|
3349
|
+
// The per-code hint is written for the other caller of this code — a
|
|
3350
|
+
// double `purchase()` of one product — and would tell a consumer
|
|
3351
|
+
// debugging a failed reset that they double-called `purchase()`.
|
|
3352
|
+
includeHint: false,
|
|
3353
|
+
// It is recoverable, whatever the code's default says: await the
|
|
3354
|
+
// purchase and try again.
|
|
3355
|
+
recoverable: true
|
|
3356
|
+
});
|
|
3357
|
+
}
|
|
3358
|
+
const previous = state.entitlements;
|
|
3359
|
+
state.entitlements = [];
|
|
3360
|
+
state.cachedAt = null;
|
|
3361
|
+
await state.cache.clear();
|
|
3362
|
+
await state.unfinished.clear();
|
|
3363
|
+
await state.pending.clear();
|
|
3364
|
+
for (const key of ALL_IAP_STORAGE_KEYS) {
|
|
3365
|
+
try {
|
|
3366
|
+
await state.storage.remove(key);
|
|
3367
|
+
} catch (error) {
|
|
3368
|
+
state.logger.warn(`reset(): failed to remove the "${key}" key.`, error);
|
|
3369
|
+
}
|
|
3370
|
+
}
|
|
3371
|
+
try {
|
|
3372
|
+
await state.storage.clear();
|
|
3373
|
+
} catch (error) {
|
|
3374
|
+
state.logger.warn("reset(): failed to clear the storage namespace.", error);
|
|
3375
|
+
}
|
|
3376
|
+
if (previous.length > 0) {
|
|
3377
|
+
state.emitter.emit("entitlements-changed", {
|
|
3378
|
+
entitlements: [...state.entitlements],
|
|
3379
|
+
previous
|
|
3380
|
+
});
|
|
3381
|
+
}
|
|
3382
|
+
}
|
|
3383
|
+
function activeNow(state) {
|
|
3384
|
+
if (!state.config.verification) return [...state.entitlements];
|
|
3385
|
+
return activeEntitlements(
|
|
3386
|
+
state.entitlements,
|
|
3387
|
+
Date.now(),
|
|
3388
|
+
state.config.options.entitlementGraceMs
|
|
3389
|
+
);
|
|
3390
|
+
}
|
|
3391
|
+
|
|
1812
3392
|
// src/core/unfinished-transactions.ts
|
|
1813
3393
|
init_errors();
|
|
1814
|
-
var
|
|
3394
|
+
var STORE_KEY2 = IAP_STORAGE_KEYS.unfinishedTransactions;
|
|
1815
3395
|
var unfinishedEntrySchema = z.object({
|
|
1816
3396
|
platform: z.enum(["apple", "google"]),
|
|
1817
3397
|
productId: z.string().min(1),
|
|
1818
3398
|
token: z.string().min(1),
|
|
1819
3399
|
productType: productTypeSchema,
|
|
1820
3400
|
packageName: z.string().optional(),
|
|
3401
|
+
/**
|
|
3402
|
+
* The renewal-stable purchase reference. Optional, and deliberately
|
|
3403
|
+
* unconstrained beyond its type: entries written before it existed are
|
|
3404
|
+
* still valid, and readers fall back to `token`. A `min(1)` here would
|
|
3405
|
+
* make an empty string fail the whole entry's parse — rejecting a
|
|
3406
|
+
* recoverable purchase over a field recovery does not even read.
|
|
3407
|
+
*/
|
|
3408
|
+
purchaseReference: z.string().optional(),
|
|
3409
|
+
/**
|
|
3410
|
+
* The fields a verification needs that the extracted request shapes do
|
|
3411
|
+
* not carry. All optional, so entries written before they existed still
|
|
3412
|
+
* parse.
|
|
3413
|
+
*
|
|
3414
|
+
* These exist because recovery re-verifies from the **stored entry**, not
|
|
3415
|
+
* from a live transaction. Without them a rebuilt transaction has no
|
|
3416
|
+
* binding, no expiry and no purchase state — so an on-device check sees
|
|
3417
|
+
* an amputated object and answers differently than it did at purchase
|
|
3418
|
+
* time: an expired subscription verifies as non-expiring and is granted,
|
|
3419
|
+
* and a purchase with a binding fails `BINDING_MISMATCH` forever and is
|
|
3420
|
+
* never acknowledged (which on Android means Google refunds it).
|
|
3421
|
+
*/
|
|
3422
|
+
appUserId: z.string().optional(),
|
|
3423
|
+
expiresAt: z.string().optional(),
|
|
3424
|
+
purchaseState: z.string().optional(),
|
|
1821
3425
|
/** ISO 8601 timestamp the entry was first persisted. */
|
|
1822
3426
|
recordedAt: z.string()
|
|
1823
3427
|
});
|
|
1824
|
-
var
|
|
3428
|
+
var entryListSchema = z.array(z.unknown());
|
|
1825
3429
|
var UnfinishedTransactionsStore = class {
|
|
1826
3430
|
constructor(storage, logger) {
|
|
1827
3431
|
this.storage = storage;
|
|
@@ -1836,12 +3440,12 @@ var UnfinishedTransactionsStore = class {
|
|
|
1836
3440
|
* could each `list()` the same snapshot and overwrite each other's
|
|
1837
3441
|
* `persist()`.
|
|
1838
3442
|
*/
|
|
1839
|
-
|
|
3443
|
+
runExclusive = createMutationLock();
|
|
1840
3444
|
/** Returns the current list, or `[]` if empty / corrupt. */
|
|
1841
3445
|
async list() {
|
|
1842
3446
|
let raw;
|
|
1843
3447
|
try {
|
|
1844
|
-
raw = await this.storage.get(
|
|
3448
|
+
raw = await this.storage.get(STORE_KEY2);
|
|
1845
3449
|
} catch (cause) {
|
|
1846
3450
|
this.logger.warn("Storage read failed; treating unfinished list as empty.", cause);
|
|
1847
3451
|
return [];
|
|
@@ -1855,18 +3459,39 @@ var UnfinishedTransactionsStore = class {
|
|
|
1855
3459
|
await this.safeClear();
|
|
1856
3460
|
return [];
|
|
1857
3461
|
}
|
|
1858
|
-
const
|
|
1859
|
-
if (!
|
|
1860
|
-
this.logger.warn("unfinished_transactions
|
|
3462
|
+
const list = entryListSchema.safeParse(parsed);
|
|
3463
|
+
if (!list.success) {
|
|
3464
|
+
this.logger.warn("unfinished_transactions is not a list; clearing.", list.error);
|
|
1861
3465
|
await this.safeClear();
|
|
1862
3466
|
return [];
|
|
1863
3467
|
}
|
|
1864
|
-
|
|
3468
|
+
const entries = [];
|
|
3469
|
+
let dropped = 0;
|
|
3470
|
+
for (const candidate of list.data) {
|
|
3471
|
+
const entry = unfinishedEntrySchema.safeParse(candidate);
|
|
3472
|
+
if (entry.success) {
|
|
3473
|
+
entries.push(entry.data);
|
|
3474
|
+
} else {
|
|
3475
|
+
dropped++;
|
|
3476
|
+
}
|
|
3477
|
+
}
|
|
3478
|
+
if (dropped > 0) {
|
|
3479
|
+
this.logger.warn(
|
|
3480
|
+
`Dropped ${dropped} unreadable unfinished-transaction entry/entries; kept ${entries.length}.`
|
|
3481
|
+
);
|
|
3482
|
+
}
|
|
3483
|
+
return entries;
|
|
1865
3484
|
}
|
|
1866
3485
|
/**
|
|
1867
3486
|
* Append a transaction to the list. Idempotent: if a same-token entry
|
|
1868
3487
|
* already exists, this is a no-op (avoids dupes when restore + active
|
|
1869
3488
|
* purchase race for the same StoreKit replay).
|
|
3489
|
+
*
|
|
3490
|
+
* **Keyed on `token`, deliberately — not on `purchaseReference`.** The
|
|
3491
|
+
* token is what acknowledges one transaction, and on iOS a subscription
|
|
3492
|
+
* has a separate token per renewal while sharing one reference. Keying
|
|
3493
|
+
* on the reference would collapse several unacknowledged renewals into
|
|
3494
|
+
* one entry and leave the rest unfinished.
|
|
1870
3495
|
*/
|
|
1871
3496
|
async add(tx) {
|
|
1872
3497
|
return this.runExclusive(async () => {
|
|
@@ -1878,6 +3503,12 @@ var UnfinishedTransactionsStore = class {
|
|
|
1878
3503
|
token: tx.token,
|
|
1879
3504
|
productType: tx.productType,
|
|
1880
3505
|
...tx.packageName ? { packageName: tx.packageName } : {},
|
|
3506
|
+
...tx.purchaseReference ? { purchaseReference: tx.purchaseReference } : {},
|
|
3507
|
+
...tx.appUserId ? { appUserId: tx.appUserId } : {},
|
|
3508
|
+
...tx.subscription?.expiresAt ? { expiresAt: tx.subscription.expiresAt } : {},
|
|
3509
|
+
...typeof tx.raw?.purchaseState === "string" || typeof tx.raw?.purchaseState === "number" ? {
|
|
3510
|
+
purchaseState: String(tx.raw.purchaseState)
|
|
3511
|
+
} : {},
|
|
1881
3512
|
recordedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1882
3513
|
};
|
|
1883
3514
|
await this.persist([...current, entry]);
|
|
@@ -1896,28 +3527,9 @@ var UnfinishedTransactionsStore = class {
|
|
|
1896
3527
|
async clear() {
|
|
1897
3528
|
return this.runExclusive(() => this.safeClear());
|
|
1898
3529
|
}
|
|
1899
|
-
/**
|
|
1900
|
-
* Run `fn` with exclusive access to the storage key. Implements a simple
|
|
1901
|
-
* promise chain — every mutation awaits the previous one's completion.
|
|
1902
|
-
* Reads (`list()`) are NOT serialized because they're tolerant of stale
|
|
1903
|
-
* snapshots (callers either compose or accept the read-once semantic).
|
|
1904
|
-
*/
|
|
1905
|
-
async runExclusive(fn) {
|
|
1906
|
-
const prev = this.mutationLock;
|
|
1907
|
-
let release;
|
|
1908
|
-
this.mutationLock = new Promise((resolve) => {
|
|
1909
|
-
release = resolve;
|
|
1910
|
-
});
|
|
1911
|
-
try {
|
|
1912
|
-
await prev;
|
|
1913
|
-
return await fn();
|
|
1914
|
-
} finally {
|
|
1915
|
-
release();
|
|
1916
|
-
}
|
|
1917
|
-
}
|
|
1918
3530
|
async persist(entries) {
|
|
1919
3531
|
try {
|
|
1920
|
-
await this.storage.set(
|
|
3532
|
+
await this.storage.set(STORE_KEY2, JSON.stringify(entries));
|
|
1921
3533
|
} catch (cause) {
|
|
1922
3534
|
throw new IAPError({
|
|
1923
3535
|
code: IAPErrorCode.STORAGE_ERROR,
|
|
@@ -1929,7 +3541,7 @@ var UnfinishedTransactionsStore = class {
|
|
|
1929
3541
|
}
|
|
1930
3542
|
async safeClear() {
|
|
1931
3543
|
try {
|
|
1932
|
-
await this.storage.remove(
|
|
3544
|
+
await this.storage.remove(STORE_KEY2);
|
|
1933
3545
|
} catch (cause) {
|
|
1934
3546
|
this.logger.warn("Failed to clear unfinished_transactions key.", cause);
|
|
1935
3547
|
}
|
|
@@ -2008,14 +3620,20 @@ function isLogger(value) {
|
|
|
2008
3620
|
}
|
|
2009
3621
|
|
|
2010
3622
|
// src/createIAP.ts
|
|
2011
|
-
init_platform();
|
|
2012
3623
|
function createIAP(input) {
|
|
2013
3624
|
const config = parseConfig(input);
|
|
2014
3625
|
const logger = resolveLogger(config.options.logLevel, config.options.logger);
|
|
2015
3626
|
const storage = selectStorageAdapter(config.storage);
|
|
2016
3627
|
const cache = new EntitlementCache(storage, logger);
|
|
2017
3628
|
const unfinished = new UnfinishedTransactionsStore(storage, logger);
|
|
2018
|
-
const
|
|
3629
|
+
const pending = new PendingPurchasesStore(storage, logger);
|
|
3630
|
+
const backend = selectBackendAdapter({
|
|
3631
|
+
config,
|
|
3632
|
+
logger,
|
|
3633
|
+
getNativeAdapter: () => state.adapter,
|
|
3634
|
+
getProducts: () => state.products,
|
|
3635
|
+
getCurrentEntitlements: () => state.entitlements
|
|
3636
|
+
});
|
|
2019
3637
|
const emitter = new TypedEventEmitter();
|
|
2020
3638
|
if (config.products) {
|
|
2021
3639
|
ensureUniqueProductIds(config.products);
|
|
@@ -2027,9 +3645,12 @@ function createIAP(input) {
|
|
|
2027
3645
|
storage,
|
|
2028
3646
|
cache,
|
|
2029
3647
|
unfinished,
|
|
3648
|
+
pending,
|
|
2030
3649
|
orchestrator: null,
|
|
2031
3650
|
restorer: null,
|
|
2032
3651
|
recoverer: null,
|
|
3652
|
+
updates: null,
|
|
3653
|
+
txWatch: null,
|
|
2033
3654
|
resumeListener: null,
|
|
2034
3655
|
emitter,
|
|
2035
3656
|
logger,
|
|
@@ -2059,123 +3680,7 @@ function createIAP(input) {
|
|
|
2059
3680
|
}
|
|
2060
3681
|
return {
|
|
2061
3682
|
async initialize() {
|
|
2062
|
-
|
|
2063
|
-
throw new IAPError({
|
|
2064
|
-
code: IAPErrorCode.NOT_INITIALIZED,
|
|
2065
|
-
message: "IAP instance has been destroyed; create a new one with createIAP()."
|
|
2066
|
-
});
|
|
2067
|
-
}
|
|
2068
|
-
if (state.initialized) {
|
|
2069
|
-
state.logger.debug("initialize() called more than once; ignoring.");
|
|
2070
|
-
return;
|
|
2071
|
-
}
|
|
2072
|
-
const platform = getPlatform();
|
|
2073
|
-
if (!isNative()) {
|
|
2074
|
-
state.logger.info(
|
|
2075
|
-
"Native purchases unavailable on web; entitlement queries still functional."
|
|
2076
|
-
);
|
|
2077
|
-
} else {
|
|
2078
|
-
state.logger.debug(`Initializing on platform=${platform}`);
|
|
2079
|
-
}
|
|
2080
|
-
if (!state.config.products) {
|
|
2081
|
-
if (typeof state.backend.listProducts !== "function") {
|
|
2082
|
-
throw new IAPError({
|
|
2083
|
-
code: IAPErrorCode.INVALID_CONFIG,
|
|
2084
|
-
message: "config.products is omitted but backend adapter does not implement listProducts(). This is a library bug; the schema should have caught it."
|
|
2085
|
-
});
|
|
2086
|
-
}
|
|
2087
|
-
const fetched = await state.backend.listProducts();
|
|
2088
|
-
const validated = configuredProductsArraySchema.safeParse(fetched);
|
|
2089
|
-
if (!validated.success) {
|
|
2090
|
-
throw new IAPError({
|
|
2091
|
-
code: IAPErrorCode.BACKEND_BAD_RESPONSE,
|
|
2092
|
-
message: `backend.listProducts() returned an invalid manifest: ${validated.error.issues.map((i) => `${i.path.join(".") || "<root>"}: ${i.message}`).join("; ")}`,
|
|
2093
|
-
cause: validated.error
|
|
2094
|
-
});
|
|
2095
|
-
}
|
|
2096
|
-
ensureUniqueProductIds(validated.data);
|
|
2097
|
-
state.products = Object.freeze([...validated.data]);
|
|
2098
|
-
state.logger.debug(`Resolved ${validated.data.length} product(s) from backend manifest.`);
|
|
2099
|
-
}
|
|
2100
|
-
state.adapter = await selectNativeAdapter();
|
|
2101
|
-
const configGetAuthHeaders = state.config.backend.getAuthHeaders;
|
|
2102
|
-
const getAuthHeaders = configGetAuthHeaders ? async () => configGetAuthHeaders() : async () => ({});
|
|
2103
|
-
const sharedDeps = {
|
|
2104
|
-
nativeAdapter: state.adapter,
|
|
2105
|
-
backend: state.backend,
|
|
2106
|
-
cache: state.cache,
|
|
2107
|
-
unfinished: state.unfinished,
|
|
2108
|
-
emitter: state.emitter,
|
|
2109
|
-
logger: state.logger,
|
|
2110
|
-
getCurrentEntitlements: () => state.entitlements,
|
|
2111
|
-
setEntitlements: (next) => {
|
|
2112
|
-
state.entitlements = freezeAll(next);
|
|
2113
|
-
},
|
|
2114
|
-
setCachePersisted: (cachedAt) => {
|
|
2115
|
-
state.cachedAt = cachedAt;
|
|
2116
|
-
},
|
|
2117
|
-
getAuthHeaders
|
|
2118
|
-
};
|
|
2119
|
-
state.orchestrator = new PurchaseOrchestrator({
|
|
2120
|
-
...sharedDeps,
|
|
2121
|
-
products: state.products
|
|
2122
|
-
});
|
|
2123
|
-
state.restorer = new RestoreOrchestrator(sharedDeps);
|
|
2124
|
-
state.recoverer = new RecoveryOrchestrator({
|
|
2125
|
-
...sharedDeps,
|
|
2126
|
-
maxBatch: state.config.options.recoveryMaxBatch,
|
|
2127
|
-
permanentErrorCodes: new Set(
|
|
2128
|
-
state.config.options.permanentErrorCodes ?? DEFAULT_PERMANENT_ERROR_CODES
|
|
2129
|
-
)
|
|
2130
|
-
});
|
|
2131
|
-
try {
|
|
2132
|
-
await state.adapter.isAvailable();
|
|
2133
|
-
} catch (error) {
|
|
2134
|
-
state.logger.warn("Native adapter availability check threw; continuing.", error);
|
|
2135
|
-
}
|
|
2136
|
-
const cached = await state.cache.load();
|
|
2137
|
-
if (cached) {
|
|
2138
|
-
state.entitlements = freezeAll(cached.entitlements);
|
|
2139
|
-
state.cachedAt = cached.cachedAt;
|
|
2140
|
-
state.logger.debug(
|
|
2141
|
-
`Loaded ${cached.entitlements.length} cached entitlement(s) from ${new Date(cached.cachedAt).toISOString()}.`
|
|
2142
|
-
);
|
|
2143
|
-
}
|
|
2144
|
-
if (state.config.options.recoverUnfinishedTransactions && isNative()) {
|
|
2145
|
-
try {
|
|
2146
|
-
const result = await state.recoverer.recoverUnfinishedTransactions();
|
|
2147
|
-
if (result.inspected > 0) {
|
|
2148
|
-
state.logger.info(
|
|
2149
|
-
`Recovery inspected ${result.inspected} unfinished transaction(s): ${result.recovered} recovered, ${result.failures} retained.`
|
|
2150
|
-
);
|
|
2151
|
-
}
|
|
2152
|
-
} catch (error) {
|
|
2153
|
-
state.logger.warn("Recovery threw unexpectedly; continuing initialize.", error);
|
|
2154
|
-
}
|
|
2155
|
-
}
|
|
2156
|
-
if (state.config.options.refreshOnResume && isNative()) {
|
|
2157
|
-
state.resumeListener = await attachAppResumeListener({
|
|
2158
|
-
logger: state.logger,
|
|
2159
|
-
onResume: async () => {
|
|
2160
|
-
try {
|
|
2161
|
-
await refreshEntitlements();
|
|
2162
|
-
} catch (error) {
|
|
2163
|
-
state.logger.warn("refreshOnResume: refresh() failed.", error);
|
|
2164
|
-
}
|
|
2165
|
-
}
|
|
2166
|
-
});
|
|
2167
|
-
}
|
|
2168
|
-
if (state.cachedAt !== null && Date.now() - state.cachedAt > state.config.options.entitlementCacheTtlMs) {
|
|
2169
|
-
state.logger.debug("Cache exceeds TTL; scheduling background refresh.");
|
|
2170
|
-
queueMicrotask(() => {
|
|
2171
|
-
if (!state.initialized || state.destroyed) return;
|
|
2172
|
-
refreshEntitlements().catch((error) => {
|
|
2173
|
-
state.logger.warn("TTL background refresh failed.", error);
|
|
2174
|
-
});
|
|
2175
|
-
});
|
|
2176
|
-
}
|
|
2177
|
-
state.initialized = true;
|
|
2178
|
-
state.emitter.emit("ready", void 0);
|
|
3683
|
+
return initializeIap(state, refreshEntitlements);
|
|
2179
3684
|
},
|
|
2180
3685
|
refresh: refreshEntitlements,
|
|
2181
3686
|
async destroy() {
|
|
@@ -2193,6 +3698,14 @@ function createIAP(input) {
|
|
|
2193
3698
|
}
|
|
2194
3699
|
state.resumeListener = null;
|
|
2195
3700
|
}
|
|
3701
|
+
if (state.txWatch) {
|
|
3702
|
+
try {
|
|
3703
|
+
await state.txWatch.remove();
|
|
3704
|
+
} catch (error) {
|
|
3705
|
+
state.logger.warn("Transaction listener remove threw; continuing teardown.", error);
|
|
3706
|
+
}
|
|
3707
|
+
state.txWatch = null;
|
|
3708
|
+
}
|
|
2196
3709
|
if (state.adapter?.dispose) {
|
|
2197
3710
|
try {
|
|
2198
3711
|
await state.adapter.dispose();
|
|
@@ -2204,6 +3717,7 @@ function createIAP(input) {
|
|
|
2204
3717
|
state.orchestrator = null;
|
|
2205
3718
|
state.restorer = null;
|
|
2206
3719
|
state.recoverer = null;
|
|
3720
|
+
state.updates = null;
|
|
2207
3721
|
},
|
|
2208
3722
|
async purchase(opts) {
|
|
2209
3723
|
requireInitialized(state);
|
|
@@ -2233,29 +3747,32 @@ function createIAP(input) {
|
|
|
2233
3747
|
message: "Native adapter not constructed; this is a library bug."
|
|
2234
3748
|
});
|
|
2235
3749
|
}
|
|
2236
|
-
return state.adapter.getProducts(state.products
|
|
3750
|
+
return state.adapter.getProducts([...state.products]);
|
|
2237
3751
|
},
|
|
2238
3752
|
async getStorefront() {
|
|
2239
3753
|
requireInitialized(state);
|
|
2240
3754
|
return state.adapter?.getStorefront?.() ?? null;
|
|
2241
3755
|
},
|
|
2242
3756
|
hasEntitlement(key) {
|
|
2243
|
-
return state.
|
|
3757
|
+
return activeNow(state).some((e) => e.key === key);
|
|
2244
3758
|
},
|
|
2245
3759
|
getEntitlements() {
|
|
2246
|
-
return
|
|
3760
|
+
return activeNow(state);
|
|
2247
3761
|
},
|
|
2248
3762
|
getEntitlement(key) {
|
|
2249
|
-
return state.
|
|
3763
|
+
return activeNow(state).find((e) => e.key === key) ?? null;
|
|
3764
|
+
},
|
|
3765
|
+
getEntitlementsVerifiedAt() {
|
|
3766
|
+
return state.cachedAt === null ? null : new Date(state.cachedAt).toISOString();
|
|
3767
|
+
},
|
|
3768
|
+
async reset() {
|
|
3769
|
+
return resetIap(state);
|
|
2250
3770
|
},
|
|
2251
3771
|
on(event, handler) {
|
|
2252
3772
|
return state.emitter.on(event, handler);
|
|
2253
3773
|
}
|
|
2254
3774
|
};
|
|
2255
3775
|
}
|
|
2256
|
-
function freezeAll(items) {
|
|
2257
|
-
return items.map((item) => Object.freeze({ ...item }));
|
|
2258
|
-
}
|
|
2259
3776
|
function parseConfig(input) {
|
|
2260
3777
|
try {
|
|
2261
3778
|
const parsed = iapConfigSchema.parse(input);
|
|
@@ -2273,37 +3790,17 @@ ${issues}`,
|
|
|
2273
3790
|
throw error;
|
|
2274
3791
|
}
|
|
2275
3792
|
}
|
|
2276
|
-
function ensureUniqueProductIds(products) {
|
|
2277
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2278
|
-
for (const product of products) {
|
|
2279
|
-
if (seen.has(product.id)) {
|
|
2280
|
-
throw new IAPError({
|
|
2281
|
-
code: IAPErrorCode.INVALID_CONFIG,
|
|
2282
|
-
message: `Duplicate product id "${product.id}" in product manifest.`
|
|
2283
|
-
});
|
|
2284
|
-
}
|
|
2285
|
-
seen.add(product.id);
|
|
2286
|
-
}
|
|
2287
|
-
}
|
|
2288
3793
|
function resolveLogger(level, candidate) {
|
|
2289
3794
|
if (isLogger(candidate)) return candidate;
|
|
2290
3795
|
return createDefaultLogger(level);
|
|
2291
3796
|
}
|
|
2292
|
-
function requireInitialized(state) {
|
|
2293
|
-
if (!state.initialized) {
|
|
2294
|
-
throw new IAPError({
|
|
2295
|
-
code: IAPErrorCode.NOT_INITIALIZED,
|
|
2296
|
-
message: "Call iap.initialize() before this method."
|
|
2297
|
-
});
|
|
2298
|
-
}
|
|
2299
|
-
}
|
|
2300
3797
|
|
|
2301
3798
|
// src/index.ts
|
|
2302
3799
|
init_errors();
|
|
2303
3800
|
|
|
2304
3801
|
// src/version.ts
|
|
2305
|
-
var VERSION = "8.
|
|
3802
|
+
var VERSION = "8.1.0";
|
|
2306
3803
|
|
|
2307
|
-
export { DEFAULT_PERMANENT_ERROR_CODES, HttpBackendAdapter, HttpClient, IAPError, IAPErrorCode, VERSION, createIAP, errorHint, isIAPError };
|
|
3804
|
+
export { DEFAULT_PERMANENT_ERROR_CODES, HttpBackendAdapter, HttpClient, IAPError, IAPErrorCode, VERSION, createIAP, errorHint, isExpired, isIAPError, verifyPurchaseOnDevice };
|
|
2308
3805
|
//# sourceMappingURL=index.js.map
|
|
2309
3806
|
//# sourceMappingURL=index.js.map
|