@app-swiss-knife/react-native-sdk 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +165 -2
  2. package/README.md +75 -19
  3. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +17 -4
  4. package/android/vendor/GENERATED.md +1 -0
  5. package/android/vendor/java/com/appswissknife/SwissKnife.kt +4 -0
  6. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  7. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +1 -1
  8. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +47 -2
  9. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +185 -33
  10. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +8 -0
  11. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +10 -0
  12. package/app.plugin.js +61 -5
  13. package/ios/SwissKnifeJSON.swift +24 -2
  14. package/ios/SwissKnifePurchases.swift +9 -1
  15. package/ios/vendor/GENERATED.md +1 -0
  16. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  17. package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +7 -0
  18. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +2 -3
  19. package/ios/vendor/SwissKnifeiOS/Services/EntitlementSync.swift +104 -0
  20. package/ios/vendor/SwissKnifeiOS/Services/IntroEligibility.swift +137 -0
  21. package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +37 -5
  22. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +368 -52
  23. package/ios/vendor/SwissKnifeiOS/Services/TransactionEvents.swift +371 -0
  24. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +73 -8
  25. package/ios/vendor/SwissKnifeiOS/Types.swift +31 -1
  26. package/ios-notification-service/SwissKnifeNotificationService.podspec +37 -0
  27. package/ios-notification-service/vendor/GENERATED.md +11 -0
  28. package/ios-notification-service/vendor/SwissKnifeNotificationService/SwissKnifeNotificationServiceExtension.swift +177 -0
  29. package/lib/commonjs/internal/config.js +3 -0
  30. package/lib/commonjs/internal/config.js.map +1 -1
  31. package/lib/commonjs/native/spec.js.map +1 -1
  32. package/lib/commonjs/types.js.map +1 -1
  33. package/lib/module/internal/config.js +3 -0
  34. package/lib/module/internal/config.js.map +1 -1
  35. package/lib/module/native/spec.js.map +1 -1
  36. package/lib/module/types.js.map +1 -1
  37. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  38. package/lib/typescript/commonjs/native/spec.d.ts +2 -0
  39. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  40. package/lib/typescript/commonjs/types.d.ts +13 -0
  41. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  42. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  43. package/lib/typescript/module/native/spec.d.ts +2 -0
  44. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  45. package/lib/typescript/module/types.d.ts +13 -0
  46. package/lib/typescript/module/types.d.ts.map +1 -1
  47. package/package.json +3 -2
  48. package/src/internal/config.ts +3 -0
  49. package/src/native/spec.ts +4 -0
  50. package/src/types.ts +13 -0
@@ -0,0 +1,104 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/Services/EntitlementSync.swift
2
+ //
3
+ // Purchase-engine settings, and the on-device record of which transactions
4
+ // the backend already accepted for which subject, so the silent entitlement
5
+ // sync (`PurchaseService.syncCurrentEntitlements`) sends nothing when nothing
6
+ // is new.
7
+
8
+ import CryptoKit
9
+ import Foundation
10
+
11
+ extension SwissKnife {
12
+
13
+ /// Settings for the purchase engine (`configure(...)` /
14
+ /// `configurePurchases(...)`). The defaults are what most apps want.
15
+ public struct PurchasesConfiguration: Sendable, Equatable {
16
+
17
+ /// Silently sync the device's current entitlements with the backend
18
+ /// after `configure` and after every `Identity.logIn`: transactions
19
+ /// the backend has not accepted for the current user are posted, and
20
+ /// nothing is sent when there are none. It never calls
21
+ /// `AppStore.sync()`, so it never shows the Apple ID sheet
22
+ /// (`restorePurchases()` still does, for a Restore button).
23
+ ///
24
+ /// A sync, automatic or `syncCurrentEntitlements()`, never moves a
25
+ /// purchase between users: the backend leaves one it holds for
26
+ /// another user where it is, whatever the app's transfer setting, and
27
+ /// the SDK reports it (`TransactionEvent.ownedByAnotherUser`). Only
28
+ /// `restorePurchases()` applies the transfer setting.
29
+ ///
30
+ /// The automatic run also skips a transaction whose `appAccountToken`
31
+ /// is a different UUID than the signed-in user's own id (while
32
+ /// `automaticAppAccountToken` is on): it was bought by another account
33
+ /// of this app on the same Apple ID, so it is not even posted.
34
+ public var syncEntitlementsAutomatically: Bool
35
+
36
+ /// When the current app user id is a UUID, attach it to every
37
+ /// purchase as StoreKit's `appAccountToken`, unless the call passes
38
+ /// one. Apple then repeats it in every transaction and App Store
39
+ /// Server Notification of that purchase, which ties a renewal or a
40
+ /// refund to the user even when it reaches the backend first.
41
+ public var automaticAppAccountToken: Bool
42
+
43
+ public init(
44
+ syncEntitlementsAutomatically: Bool = true,
45
+ automaticAppAccountToken: Bool = true
46
+ ) {
47
+ self.syncEntitlementsAutomatically = syncEntitlementsAutomatically
48
+ self.automaticAppAccountToken = automaticAppAccountToken
49
+ }
50
+ }
51
+ }
52
+
53
+ /// Fingerprints of `(project key, subject, transaction id)` the backend
54
+ /// accepted, persisted in `UserDefaults`. Hashed so the store holds no user
55
+ /// ids; bounded so it cannot grow without limit (the oldest entries go first,
56
+ /// which at worst re-posts an old transaction once — the backend is
57
+ /// idempotent on it).
58
+ internal final class SyncedTransactionLedger: @unchecked Sendable {
59
+
60
+ static let defaultsKey = "com.swissknife.purchases.syncedTransactions.v1"
61
+ static let capacity = 512
62
+
63
+ private let defaults: UserDefaults
64
+ private let lock = NSLock()
65
+ private var loaded: [String]?
66
+
67
+ init(defaults: UserDefaults = .standard) {
68
+ self.defaults = defaults
69
+ }
70
+
71
+ static func fingerprint(apiKey: String, subject: String, transactionId: String) -> String {
72
+ let digest = SHA256.hash(data: Data("\(apiKey)\n\(subject)\n\(transactionId)".utf8))
73
+ return digest.prefix(16).map { String(format: "%02x", $0) }.joined()
74
+ }
75
+
76
+ func contains(_ fingerprint: String) -> Bool {
77
+ lock.lock(); defer { lock.unlock() }
78
+ return entriesLocked().contains(fingerprint)
79
+ }
80
+
81
+ func insert(_ fingerprint: String) {
82
+ lock.lock(); defer { lock.unlock() }
83
+ var entries = entriesLocked()
84
+ guard !entries.contains(fingerprint) else { return }
85
+ entries.append(fingerprint)
86
+ if entries.count > Self.capacity {
87
+ entries.removeFirst(entries.count - Self.capacity)
88
+ }
89
+ loaded = entries
90
+ defaults.set(entries, forKey: Self.defaultsKey)
91
+ }
92
+
93
+ var count: Int {
94
+ lock.lock(); defer { lock.unlock() }
95
+ return entriesLocked().count
96
+ }
97
+
98
+ private func entriesLocked() -> [String] {
99
+ if let loaded { return loaded }
100
+ let stored = defaults.stringArray(forKey: Self.defaultsKey) ?? []
101
+ loaded = stored
102
+ return stored
103
+ }
104
+ }
@@ -0,0 +1,137 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/Services/IntroEligibility.swift
2
+ //
3
+ // Whether the current Apple ID can still get a subscription's introductory
4
+ // offer (free trial or paid intro), straight from StoreKit 2
5
+ // (`Product.SubscriptionInfo.isEligibleForIntroOffer`). Apple decides
6
+ // eligibility per subscription group: once someone has had an intro offer for
7
+ // any product of a group, every product of that group answers "ineligible".
8
+ //
9
+ // Read-only: it asks StoreKit, never the backend, never shows UI, and works
10
+ // without `configure(...)`.
11
+
12
+ import Foundation
13
+ import StoreKit
14
+
15
+ /// Mirrors RevenueCat's `IntroEligibilityStatus`.
16
+ public enum IntroEligibilityStatus: String, Sendable, Codable, Equatable {
17
+ /// The product has an introductory offer and this Apple ID can get it.
18
+ case eligible
19
+ /// The product has an introductory offer, but this Apple ID already had
20
+ /// one in the product's subscription group.
21
+ case ineligible
22
+ /// The product is not a subscription or has no introductory offer.
23
+ case noIntroOfferExists = "no_intro_offer_exists"
24
+ /// StoreKit could not say: the product id is unknown to the App Store,
25
+ /// or the product request failed.
26
+ case unknown
27
+ }
28
+
29
+ extension SwissKnife {
30
+
31
+ /// Introductory-offer eligibility for each of `productIdentifiers`.
32
+ /// Every requested id gets an answer (`.unknown` when StoreKit does not
33
+ /// know it or cannot be reached).
34
+ public static func checkTrialOrIntroDiscountEligibility(
35
+ productIdentifiers: [String]
36
+ ) async -> [String: IntroEligibilityStatus] {
37
+ if #available(iOS 15.0, macOS 12.0, *) {
38
+ return await IntroEligibility.check(productIdentifiers: productIdentifiers)
39
+ }
40
+ return Dictionary(uniqueKeysWithValues: Set(productIdentifiers).map { ($0, .unknown) })
41
+ }
42
+
43
+ /// Introductory-offer eligibility for a whole subscription group
44
+ /// (`Product.SubscriptionInfo.subscriptionGroupID`). Answers
45
+ /// `.eligible` / `.ineligible` only: StoreKit's group check does not say
46
+ /// whether the group has an intro offer at all, so ask per product for
47
+ /// `.noIntroOfferExists`.
48
+ public static func checkTrialOrIntroDiscountEligibility(
49
+ subscriptionGroupIdentifier: String
50
+ ) async -> IntroEligibilityStatus {
51
+ if #available(iOS 15.0, macOS 12.0, *) {
52
+ return await IntroEligibility.groupEligibility(subscriptionGroupIdentifier)
53
+ ? .eligible : .ineligible
54
+ }
55
+ return .unknown
56
+ }
57
+ }
58
+
59
+ /// What the eligibility answer needs to know about one product. Built from a
60
+ /// StoreKit `Product` in production, directly in tests.
61
+ internal struct IntroOfferProbe: Sendable {
62
+ var isSubscription: Bool
63
+ var hasIntroOffer: Bool
64
+ var subscriptionGroupId: String?
65
+ }
66
+
67
+ internal enum IntroEligibility {
68
+
69
+ /// The answer for one product, given its probe and (for a subscription
70
+ /// with an intro offer) StoreKit's group verdict.
71
+ static func status(
72
+ probe: IntroOfferProbe?,
73
+ groupEligible: Bool?
74
+ ) -> IntroEligibilityStatus {
75
+ guard let probe else { return .unknown }
76
+ guard probe.isSubscription, probe.hasIntroOffer else { return .noIntroOfferExists }
77
+ guard let groupEligible else { return .unknown }
78
+ return groupEligible ? .eligible : .ineligible
79
+ }
80
+
81
+ /// Product lookup seam (tests replace it; production asks StoreKit).
82
+ /// Returns nil when the request itself failed.
83
+ static var loadProbes: @Sendable ([String]) async -> [String: IntroOfferProbe]? =
84
+ defaultLoadProbes
85
+
86
+ /// Group verdict seam.
87
+ static var groupEligibility: @Sendable (String) async -> Bool =
88
+ defaultGroupEligibility
89
+
90
+ static let defaultLoadProbes: @Sendable ([String]) async -> [String: IntroOfferProbe]? = { ids in
91
+ guard #available(iOS 15.0, macOS 12.0, *) else { return nil }
92
+ guard let products = try? await Product.products(for: Set(ids)) else { return nil }
93
+ var probes: [String: IntroOfferProbe] = [:]
94
+ for product in products {
95
+ probes[product.id] = IntroOfferProbe(
96
+ isSubscription: product.subscription != nil,
97
+ hasIntroOffer: product.subscription?.introductoryOffer != nil,
98
+ subscriptionGroupId: product.subscription?.subscriptionGroupID
99
+ )
100
+ }
101
+ return probes
102
+ }
103
+
104
+ static let defaultGroupEligibility: @Sendable (String) async -> Bool = { groupId in
105
+ guard #available(iOS 15.0, macOS 12.0, *) else { return false }
106
+ return await Product.SubscriptionInfo.isEligibleForIntroOffer(for: groupId)
107
+ }
108
+
109
+ static func check(productIdentifiers: [String]) async -> [String: IntroEligibilityStatus] {
110
+ let ids = Array(Set(productIdentifiers))
111
+ guard !ids.isEmpty else { return [:] }
112
+ guard let probes = await loadProbes(ids) else {
113
+ return Dictionary(uniqueKeysWithValues: ids.map { ($0, .unknown) })
114
+ }
115
+ // One StoreKit question per subscription group, however many of its
116
+ // products were asked about.
117
+ var groupVerdicts: [String: Bool] = [:]
118
+ for probe in probes.values where probe.isSubscription && probe.hasIntroOffer {
119
+ guard let group = probe.subscriptionGroupId, groupVerdicts[group] == nil else { continue }
120
+ groupVerdicts[group] = await groupEligibility(group)
121
+ }
122
+ var result: [String: IntroEligibilityStatus] = [:]
123
+ for id in ids {
124
+ let probe = probes[id]
125
+ result[id] = status(
126
+ probe: probe,
127
+ groupEligible: probe?.subscriptionGroupId.flatMap { groupVerdicts[$0] }
128
+ )
129
+ }
130
+ return result
131
+ }
132
+
133
+ static func _resetForTesting() {
134
+ loadProbes = defaultLoadProbes
135
+ groupEligibility = defaultGroupEligibility
136
+ }
137
+ }
@@ -272,7 +272,10 @@ public final class OfferingsService {
272
272
  let name = (rawPkg["name"] as? String) ?? productId
273
273
  let priceVal = (rawPkg["price"] as? Double) ?? 0
274
274
  let durationDays = (rawPkg["duration_days"] as? Int) ?? 30
275
- let period = subscriptionPeriodFromDays(durationDays)
275
+ let type = Self.backendProductType(
276
+ rawProductType: rawPkg["product_type"] as? String,
277
+ durationDays: durationDays
278
+ )
276
279
  return StoreProduct(
277
280
  productIdentifier: productId,
278
281
  localizedTitle: name,
@@ -280,12 +283,25 @@ public final class OfferingsService {
280
283
  price: Decimal(priceVal),
281
284
  currencyCode: "USD",
282
285
  displayPrice: String(format: "$%.2f", priceVal),
283
- subscriptionPeriod: period,
286
+ subscriptionPeriod: type.isSubscription ? subscriptionPeriodFromDays(durationDays) : nil,
284
287
  introductoryDiscount: nil,
285
- discounts: []
288
+ discounts: [],
289
+ productType: type
286
290
  )
287
291
  }
288
292
 
293
+ /// The type of a product StoreKit did not return, from its backend
294
+ /// package: the server's `product_type` when it sends a known one;
295
+ /// otherwise a zero-day duration is a one-time product whose kind is not
296
+ /// known, and any other duration a subscription (the zero-day rule is
297
+ /// Android's `OfferingsRepository.BackendProduct.isOneTime`).
298
+ internal static func backendProductType(rawProductType: String?, durationDays: Int) -> StoreProductType {
299
+ if let raw = rawProductType, let known = StoreProductType(rawValue: raw), known != .unknown {
300
+ return known
301
+ }
302
+ return durationDays == 0 ? .unknown : .autoRenewableSubscription
303
+ }
304
+
289
305
  private func subscriptionPeriodFromDays(_ days: Int) -> SubscriptionPeriod? {
290
306
  switch days {
291
307
  case 7: return SubscriptionPeriod(value: 1, unit: .week)
@@ -381,9 +397,24 @@ internal final class StoreKit2ProductResolver: StoreProductResolver {
381
397
  }
382
398
  }
383
399
 
400
+ /// StoreKit's `Product.ProductType` as the SDK's `StoreProductType`. A
401
+ /// type StoreKit adds later is `.unknown`.
402
+ @available(iOS 15.0, macOS 12.0, *)
403
+ internal static func productType(_ type: Product.ProductType) -> StoreProductType {
404
+ switch type {
405
+ case .autoRenewable: return .autoRenewableSubscription
406
+ case .nonRenewable: return .nonRenewableSubscription
407
+ case .consumable: return .consumable
408
+ case .nonConsumable: return .nonConsumable
409
+ default: return .unknown
410
+ }
411
+ }
412
+
384
413
  @available(iOS 15.0, macOS 12.0, *)
385
414
  private static func toStoreProduct(_ p: Product) -> StoreProduct {
386
- // Subscription period (only present on auto-renewable subscriptions).
415
+ // Subscription period and offers: StoreKit sets `p.subscription` only
416
+ // on an auto-renewable subscription, so they stay nil for every other
417
+ // product type.
387
418
  var period: SubscriptionPeriod?
388
419
  if let sub = p.subscription {
389
420
  let unit: SubscriptionPeriod.Unit
@@ -413,7 +444,8 @@ internal final class StoreKit2ProductResolver: StoreProductResolver {
413
444
  displayPrice: p.displayPrice,
414
445
  subscriptionPeriod: period,
415
446
  introductoryDiscount: introDiscount,
416
- discounts: discounts
447
+ discounts: discounts,
448
+ productType: productType(p.type)
417
449
  )
418
450
  }
419
451