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

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.
@@ -9,9 +9,10 @@
9
9
  // A purchase or restore that finds the client not ready resets that budget,
10
10
  // reconnects, and runs once the client is connected.
11
11
  // - Every OK setup (the first one comes from configure) reconciles: it
12
- // queries SUBS and INAPP purchases and validates + acknowledges each
13
- // PURCHASED one that is still unacknowledged, under the user id stamped on
14
- // it at launch when there is one. Google auto-refunds an
12
+ // queries SUBS and INAPP purchases and validates + acknowledges (or
13
+ // consumes, see below) each PURCHASED one that is still unacknowledged,
14
+ // and each consumable an earlier SDK left unconsumed, under the user id
15
+ // stamped on it at launch when there is one. Google auto-refunds an
15
16
  // unacknowledged purchase after three days, and nothing server-side
16
17
  // acknowledges on our behalf, so an ack lost to a network error or a
17
18
  // process kill must be picked up here.
@@ -38,14 +39,24 @@
38
39
  // - Offerings/products fetching - that's OfferingsRepository, which
39
40
  // SwissKnife.getOfferings() reads. This gateway only queries
40
41
  // ProductDetails on-demand for purchase.
41
- // - Acknowledge details: we acknowledge() every purchased product,
42
- // consumables included, and never consume() one: the backend's product
43
- // type is not known here, and consuming a non-consumable would take a
44
- // lifetime unlock away from the user. An acknowledged consumable stays
45
- // owned on Play until something consumes it.
46
- // acknowledge() checks the BillingResult and retries a non-OK answer a
47
- // bounded number of times; what is still unacknowledged after that is left
48
- // to the next reconcile.
42
+ // - Acknowledge or consume: a purchase is consumed (consumeAsync, which also
43
+ // acknowledges it) only when the backend's validate answer for each of its
44
+ // products says `product_type: "consumable"`. That answer comes after the
45
+ // backend recorded the purchase in its ledger, so a crash or a failed
46
+ // consume never loses the credit, and the ledger is keyed on the purchase
47
+ // token, so validating it again never grants it twice. Anything else (a
48
+ // non-consumable, a subscription, an answer that names no type, a failed
49
+ // validate) keeps the acknowledge-only path: consuming a non-consumable
50
+ // would take a lifetime unlock away from the user.
51
+ // A consumable an earlier SDK only acknowledged is still owned on Play, so
52
+ // it cannot be bought again. The reconcile consumes it once the server's
53
+ // catalogue ([onServerProductTypes]) or an earlier validate answer says the
54
+ // product is a consumable, after validating it again; a restore consumes it
55
+ // too. Acknowledged purchases of any other product are never re-validated
56
+ // by the reconcile.
57
+ // acknowledge() and consume() check the BillingResult and retry a non-OK
58
+ // answer a bounded number of times; what is still unsettled after that is
59
+ // left to the next reconcile, and never fails the purchase call.
49
60
 
50
61
  package com.appswissknife.purchases
51
62
 
@@ -60,6 +71,7 @@ import com.android.billingclient.api.BillingClient
60
71
  import com.android.billingclient.api.BillingClientStateListener
61
72
  import com.android.billingclient.api.BillingFlowParams
62
73
  import com.android.billingclient.api.BillingResult
74
+ import com.android.billingclient.api.ConsumeParams
63
75
  import com.android.billingclient.api.PendingPurchasesParams
64
76
  import com.android.billingclient.api.ProductDetails
65
77
  import com.android.billingclient.api.Purchase
@@ -151,6 +163,29 @@ class BillingClientGateway(
151
163
  */
152
164
  private val ackClaimed: MutableSet<String> = Collections.synchronizedSet(mutableSetOf())
153
165
 
166
+ /** Purchase tokens whose consume is in flight or succeeded in this process (see [ackClaimed]). */
167
+ private val consumeClaimed: MutableSet<String> = Collections.synchronizedSet(mutableSetOf())
168
+
169
+ /**
170
+ * The backend's product type (`auto_renewable`, `non_renewing`, `consumable`,
171
+ * `non_consumable`) of each product id it has described in this process: from
172
+ * the offerings it served ([onServerProductTypes]) and from validate answers.
173
+ * Only picks the acknowledged purchases a reconcile validates again; whether
174
+ * a purchase is consumed is decided by the validate answer itself.
175
+ */
176
+ private val serverProductTypes = java.util.concurrent.ConcurrentHashMap<String, String>()
177
+
178
+ /**
179
+ * Product ids a validate answer has typed in this process. The catalogue
180
+ * never overrides those: the validate answer is what decides a consume, and
181
+ * a catalogue row that disagrees with it would otherwise re-validate the
182
+ * purchase on every offerings read.
183
+ */
184
+ private val typedByValidate: MutableSet<String> = java.util.concurrent.ConcurrentHashMap.newKeySet()
185
+
186
+ /** A reconcile was asked for while one was running; run another when it ends. */
187
+ private val reconcileAgain = AtomicBoolean(false)
188
+
154
189
  private val executor: ExecutorService =
155
190
  Executors.newSingleThreadExecutor { r -> Thread(r, "swissknife-billing").apply { isDaemon = true } }
156
191
 
@@ -375,6 +410,7 @@ class BillingClientGateway(
375
410
  val launchResult = client.launchBillingFlow(activity, flowParams)
376
411
  if (launchResult.responseCode != BillingClient.BillingResponseCode.OK) {
377
412
  pendingPurchase = null
413
+ if (launchResult.responseCode == BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED) reconcileSoon()
378
414
  onError(toPurchasesError(launchResult), launchResult.isUserCancelled())
379
415
  }
380
416
  }
@@ -430,6 +466,23 @@ class BillingClientGateway(
430
466
  PRODUCT_TYPES
431
467
  }
432
468
 
469
+ /**
470
+ * The backend's catalogue named these product types. A consumable learned
471
+ * here may be one an earlier SDK acknowledged and never consumed, which Play
472
+ * then refuses to sell again (ITEM_ALREADY_OWNED), so learning one runs a
473
+ * reconcile, which validates such a purchase again and consumes it if the
474
+ * backend confirms it is a consumable.
475
+ */
476
+ override fun onServerProductTypes(types: Map<String, String>) {
477
+ var learnedConsumable = false
478
+ for ((productId, type) in types) {
479
+ if (productId.isEmpty() || type.isEmpty() || productId in typedByValidate) continue
480
+ val previous = serverProductTypes.put(productId, type)
481
+ if (type == CONSUMABLE && previous != CONSUMABLE) learnedConsumable = true
482
+ }
483
+ if (learnedConsumable) reconcileSoon()
484
+ }
485
+
433
486
  override fun restorePurchases(
434
487
  onSuccess: (CustomerInfo) -> Unit,
435
488
  onError: (PurchasesError) -> Unit,
@@ -459,12 +512,9 @@ class BillingClientGateway(
459
512
  for (p in purchases) {
460
513
  // A pending payment is not a purchase yet: never validate or ack it.
461
514
  if (p.purchaseState != Purchase.PurchaseState.PURCHASED) continue
462
- runCatching {
463
- for (productId in p.products) {
464
- validatePurchaseWithBackend(p.packageName, productId, p.purchaseToken)
465
- }
466
- if (!p.isAcknowledged) acknowledge(p)
467
- }.onFailure { errors.add(it) }
515
+ // Acknowledged consumables included: one the backend confirms as a
516
+ // consumable is consumed, so the user can buy it again.
517
+ runCatching { validateAndSettle(p) }.onFailure { errors.add(it) }
468
518
  }
469
519
  val repo = entitlementsRepo
470
520
  val info = try {
@@ -571,6 +621,10 @@ class BillingClientGateway(
571
621
  pending?.onError?.invoke(PurchasesError.PurchaseCancelled(), true); return
572
622
  }
573
623
  if (code != BillingClient.BillingResponseCode.OK) {
624
+ // Play still holds a purchase of the product. When it is a consumable an
625
+ // earlier SDK only acknowledged, the reconcile consumes it, so the next
626
+ // attempt goes through; the call still fails as before.
627
+ if (code == BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED) reconcileSoon()
574
628
  pending?.onError?.invoke(toPurchasesError(result), false); return
575
629
  }
576
630
  if (purchases.isNullOrEmpty()) {
@@ -609,11 +663,11 @@ class BillingClientGateway(
609
663
  // connect finds it otherwise.
610
664
  if (p.purchaseState != Purchase.PurchaseState.PURCHASED) continue
611
665
  try {
612
- for (productId in p.products) {
613
- validatePurchaseWithBackend(p.packageName, productId, p.purchaseToken)
614
- }
666
+ // Consumed or acknowledged after the backend recorded it. A consume
667
+ // or acknowledge that fails is retried and left to the reconcile; it
668
+ // never fails this call.
669
+ validateAndSettle(p)
615
670
  validatedAny = true
616
- if (!p.isAcknowledged) acknowledge(p)
617
671
  } catch (e: Exception) {
618
672
  if (p === matched) {
619
673
  matchedFailure = e
@@ -765,11 +819,25 @@ class BillingClientGateway(
765
819
  * the app was not running all land here. There is no server-side
766
820
  * acknowledge (that would be a store write from the backend).
767
821
  *
822
+ * It also consumes the consumables an earlier SDK acknowledged and never
823
+ * consumed: an acknowledged purchase whose every product the backend has
824
+ * described as a consumable ([serverProductTypes]) is validated again (the
825
+ * backend's ledger is keyed on the token, so this grants nothing twice) and
826
+ * consumed when the answer confirms it. No other acknowledged purchase is
827
+ * validated again.
828
+ *
768
829
  * When it validated anything, it then re-reads the entitlements, so the app
769
830
  * sees what those purchases unlocked without a restore.
831
+ *
832
+ * [rerunIfBusy]: a reconcile asked for while one runs is dropped (the running
833
+ * one covers a new setup), unless the caller learned something the running
834
+ * one may have missed; then another runs when it ends.
770
835
  */
771
- private fun reconcilePurchases(client: BillingClient) {
772
- if (!reconcileInFlight.compareAndSet(false, true)) return
836
+ private fun reconcilePurchases(client: BillingClient, rerunIfBusy: Boolean = false) {
837
+ if (!reconcileInFlight.compareAndSet(false, true)) {
838
+ if (rerunIfBusy) reconcileAgain.set(true)
839
+ return
840
+ }
773
841
  try {
774
842
  queryOwnedPurchases(client, PRODUCT_TYPES, mutableListOf()) { owned, _ ->
775
843
  executor.execute {
@@ -777,23 +845,22 @@ class BillingClientGateway(
777
845
  try {
778
846
  for (p in owned) {
779
847
  if (p.purchaseState != Purchase.PurchaseState.PURCHASED) continue
780
- if (p.isAcknowledged || p.purchaseToken in ackClaimed) continue
848
+ val token = p.purchaseToken
849
+ if (token in ackClaimed || token in consumeClaimed) continue
850
+ if (p.isAcknowledged && !isKnownConsumable(p)) continue
781
851
  try {
782
- val subject = reconcileSubject(p)
783
- for (productId in p.products) {
784
- validatePurchaseWithBackend(p.packageName, productId, p.purchaseToken, subject)
785
- }
852
+ validateAndSettle(p, reconcileSubject(p))
786
853
  validatedAny = true
787
- acknowledge(p)
788
854
  } catch (e: Exception) {
789
- // Not acknowledged, so the next connect tries again.
790
- Log.w(TAG, "reconcile: validate failed for an unacknowledged purchase", e)
855
+ // Not settled, so the next connect tries again.
856
+ Log.w(TAG, "reconcile: validate failed for a purchase left to settle", e)
791
857
  }
792
858
  }
793
859
  } finally {
794
860
  reconcileInFlight.set(false)
795
861
  }
796
862
  if (validatedAny) refreshEntitlements()
863
+ if (reconcileAgain.getAndSet(false)) reconcileSoon()
797
864
  }
798
865
  }
799
866
  } catch (e: RuntimeException) {
@@ -802,6 +869,36 @@ class BillingClientGateway(
802
869
  }
803
870
  }
804
871
 
872
+ /** Reconcile now if Play is connected; otherwise the next OK setup reconciles anyway. */
873
+ private fun reconcileSoon() {
874
+ val client = billingClient?.takeIf { it.isReady } ?: return
875
+ reconcilePurchases(client, rerunIfBusy = true)
876
+ }
877
+
878
+ /** Every product of [p] is one the backend has described as a consumable. */
879
+ private fun isKnownConsumable(p: Purchase): Boolean =
880
+ p.products.isNotEmpty() && p.products.all { serverProductTypes[it] == CONSUMABLE }
881
+
882
+ /**
883
+ * Validate [p] with the backend under [subject], then settle it with Play:
884
+ * consume it when the backend answered that every one of its products is a
885
+ * consumable (it has recorded the purchase by then), otherwise acknowledge it
886
+ * if Play still holds it unacknowledged. Throws what a validate threw, and
887
+ * settles nothing then.
888
+ */
889
+ @Throws(IOException::class)
890
+ private fun validateAndSettle(p: Purchase, subject: String = getAppUserID()) {
891
+ // Every product is validated before anything is settled.
892
+ val types = p.products.map { productId ->
893
+ validatePurchaseWithBackend(p.packageName, productId, p.purchaseToken, subject)
894
+ }
895
+ if (types.isNotEmpty() && types.all { it == CONSUMABLE }) {
896
+ consume(p)
897
+ } else if (!p.isAcknowledged) {
898
+ acknowledge(p)
899
+ }
900
+ }
901
+
805
902
  /**
806
903
  * The subject a reconciled purchase is validated under.
807
904
  *
@@ -881,6 +978,10 @@ class BillingClientGateway(
881
978
  * validates against Google's Real-Time Developer Notifications channel
882
979
  * and the Play Developer API. Returns when the backend ack'd; throws on
883
980
  * non-2xx.
981
+ *
982
+ * Returns the backend's `product_type` for [productId] from its answer, or
983
+ * null when the answer names none (or names another product). The backend
984
+ * answers only after it has recorded the purchase.
884
985
  */
885
986
  @Throws(IOException::class)
886
987
  private fun validatePurchaseWithBackend(
@@ -888,7 +989,7 @@ class BillingClientGateway(
888
989
  productId: String,
889
990
  purchaseToken: String,
890
991
  userId: String = getAppUserID(),
891
- ) {
992
+ ): String? {
892
993
  val body = JSONObject().apply {
893
994
  put("user_id", userId)
894
995
  put("platform", "android")
@@ -899,7 +1000,7 @@ class BillingClientGateway(
899
1000
  // sent `Authorization: Bearer ...` which the route ignored — every
900
1001
  // validate POST was returning 401 in production. Aligning with the
901
1002
  // backend contract here.
902
- httpClient.post(
1003
+ val answer = httpClient.post(
903
1004
  url = "$serverUrl/api/sdk/subscriptions/validate",
904
1005
  body = body,
905
1006
  headers = mapOf(
@@ -907,6 +1008,21 @@ class BillingClientGateway(
907
1008
  "Content-Type" to "application/json",
908
1009
  ),
909
1010
  )
1011
+ val type = productTypeIn(answer, productId) ?: return null
1012
+ typedByValidate.add(productId)
1013
+ serverProductTypes[productId] = type
1014
+ return type
1015
+ }
1016
+
1017
+ /** The `product_type` a validate answer gives [productId]; null when it names none or another product. */
1018
+ private fun productTypeIn(answer: String?, productId: String): String? {
1019
+ val json = try {
1020
+ JSONObject(answer ?: return null)
1021
+ } catch (_: org.json.JSONException) {
1022
+ return null
1023
+ }
1024
+ if (json.isNull("product_type") || json.optString("product_id") != productId) return null
1025
+ return json.optString("product_type").takeIf { it.isNotEmpty() }
910
1026
  }
911
1027
 
912
1028
  /**
@@ -981,6 +1097,39 @@ class BillingClientGateway(
981
1097
  }
982
1098
  }
983
1099
 
1100
+ /**
1101
+ * Consume [purchase] (which also acknowledges it), so Play sells the product
1102
+ * again. Called only after the backend recorded the purchase and answered
1103
+ * that it is a consumable. Same bounded retry as [acknowledge]; a consume
1104
+ * that still fails is left to the next reconcile, which finds the purchase
1105
+ * owned and validates it again (the backend grants it once) before consuming.
1106
+ */
1107
+ private fun consume(purchase: Purchase) {
1108
+ // Consumed, or a consume is in flight, in this process.
1109
+ if (!consumeClaimed.add(purchase.purchaseToken)) return
1110
+ sendConsume(purchase, attempt = 0)
1111
+ }
1112
+
1113
+ private fun sendConsume(purchase: Purchase, attempt: Int) {
1114
+ val token = purchase.purchaseToken
1115
+ val client = billingClient ?: run { consumeClaimed.remove(token); return }
1116
+ val params = ConsumeParams.newBuilder()
1117
+ .setPurchaseToken(token)
1118
+ .build()
1119
+ client.consumeAsync(params) { result, _ ->
1120
+ val code = result.responseCode
1121
+ if (code == BillingClient.BillingResponseCode.OK) return@consumeAsync
1122
+ if (attempt + 1 < MAX_ACK_ATTEMPTS && code !in TERMINAL_ACK_CODES) {
1123
+ reconnectScheduler.schedule(ACK_RETRY_BASE_DELAY_MS shl attempt) {
1124
+ sendConsume(purchase, attempt + 1)
1125
+ }
1126
+ } else {
1127
+ consumeClaimed.remove(token)
1128
+ Log.w(TAG, "consumeAsync failed (code=$code, attempts=${attempt + 1}); left for the next reconcile")
1129
+ }
1130
+ }
1131
+ }
1132
+
984
1133
  private fun Purchase.toStoreTransaction(): StoreTransaction = object : StoreTransaction {
985
1134
  override val productIdentifier: String = products.firstOrNull().orEmpty()
986
1135
  override val transactionIdentifier: String = orderId.orEmpty()
@@ -1010,6 +1159,9 @@ class BillingClientGateway(
1010
1159
 
1011
1160
  companion object {
1012
1161
  private const val TAG = "SwissKnife.Billing"
1162
+
1163
+ /** The backend's `product_type` for a one-time product that is bought again and again. */
1164
+ private const val CONSUMABLE = "consumable"
1013
1165
  private val ANONYMOUS_ID_PREFIXES = listOf("\$SKAnonymousID:", "\$RCAnonymousID:")
1014
1166
 
1015
1167
  private fun newFallbackAnonymousId(): String =
@@ -18,4 +18,12 @@ package com.appswissknife.purchases
18
18
  interface ProductKindHint {
19
19
  /** True for a one-time product (Play INAPP, consumable or not), false for a subscription. */
20
20
  val isOneTime: Boolean
21
+
22
+ /**
23
+ * The server's product type when its catalogue names one (auto_renewable,
24
+ * non_renewing, consumable, non_consumable); null when unknown. The React
25
+ * Native bridge labels a one-time product CONSUMABLE or NON_CONSUMABLE from it.
26
+ */
27
+ val productKind: String?
28
+ get() = null
21
29
  }
@@ -87,6 +87,16 @@ interface PurchasesGateway {
87
87
  */
88
88
  fun priceEnrichmentProvider(): PriceEnrichmentProvider? = null
89
89
 
90
+ /**
91
+ * The backend's product type for this store's products, product id to
92
+ * `auto_renewable`, `non_renewing`, `consumable` or `non_consumable`, as the
93
+ * offerings the SDK just read describe them (only the products whose type the
94
+ * backend named). The Play gateway uses it to find consumables an earlier SDK
95
+ * acknowledged without consuming; it never consumes on this alone, only after
96
+ * the backend's validate answer confirms the type. The default ignores it.
97
+ */
98
+ fun onServerProductTypes(types: Map<String, String>) {}
99
+
90
100
  // --- Identity -------------------------------------------------------------
91
101
 
92
102
  fun logIn(
package/app.plugin.js CHANGED
@@ -34,6 +34,11 @@
34
34
  * app module (the SDK declares it compileOnly so non-push apps stay clean)
35
35
  * - `defaultChannel` is written as manifest meta-data
36
36
  * (`com.appswissknife.notifications.default_channel_{id,name}`).
37
+ * - store: the `swissKnifeStore` Gradle property, plus RuStore's strings and
38
+ * manifest entries for a RuStore build. `SWISS_KNIFE_ANDROID_STORE`
39
+ * (`play` | `rustore`, read at prebuild, e.g. from an EAS build profile's
40
+ * `env`) picks it; unset, `android.rustore` being configured means RuStore
41
+ * (see resolveAndroidStore).
37
42
  *
38
43
  * The pure mutation helpers below are exported for unit tests; `expo/config-plugins`
39
44
  * is loaded lazily so they can be used without Expo installed.
@@ -185,20 +190,69 @@ function loadConfigPlugins() {
185
190
  }
186
191
  }
187
192
 
193
+ const ANDROID_STORE_ENV = "SWISS_KNIFE_ANDROID_STORE";
194
+
195
+ /** What is missing or invalid in an `android.rustore` option, by field. */
196
+ function ruStoreConfigProblems(rustore) {
197
+ const r = rustore && typeof rustore === "object" ? rustore : {};
198
+ const problems = [];
199
+ if (!/^\d+$/.test(String(r.consoleAppId ?? ""))) {
200
+ problems.push(r.consoleAppId === undefined ? "consoleAppId (missing)" : "consoleAppId (must be digits)");
201
+ }
202
+ if (!/^[a-z][a-z0-9+.-]*$/.test(r.scheme ?? "")) {
203
+ problems.push(r.scheme === undefined ? "scheme (missing)" : "scheme (not a valid deeplink scheme)");
204
+ }
205
+ return problems;
206
+ }
207
+
208
+ /**
209
+ * The Android store this prebuild targets: `{ store: "play" | "rustore",
210
+ * rustore }`, where `rustore` is the `android.rustore` option for a RuStore
211
+ * build and null for a Play build.
212
+ *
213
+ * `SWISS_KNIFE_ANDROID_STORE` (from `env`, normally `process.env`) chooses it,
214
+ * so one app config can produce both builds (set it per EAS build profile):
215
+ * - unset or empty: as before the variable existed, RuStore when
216
+ * `android.rustore` is configured, else Play;
217
+ * - `play`: Play, ignoring `android.rustore`;
218
+ * - `rustore`: RuStore, which needs `android.rustore`;
219
+ * - anything else: an error.
220
+ * A RuStore build with an incomplete `android.rustore` is an error naming the
221
+ * fields.
222
+ */
223
+ function resolveAndroidStore(android, env) {
224
+ const rustore = android ? android.rustore : undefined;
225
+ const raw = env && typeof env[ANDROID_STORE_ENV] === "string" ? env[ANDROID_STORE_ENV].trim() : "";
226
+ if (raw !== "" && raw !== "play" && raw !== "rustore") {
227
+ throw new Error(
228
+ `[swiss-knife] ${ANDROID_STORE_ENV} must be "play" or "rustore", got ${JSON.stringify(raw)}. ` +
229
+ "Leave it unset to build for RuStore when android.rustore is configured and for Google Play otherwise."
230
+ );
231
+ }
232
+ if (raw === "play" || (raw === "" && !rustore)) return { store: "play", rustore: null };
233
+ const problems = ruStoreConfigProblems(rustore);
234
+ if (problems.length > 0) {
235
+ const prefix =
236
+ raw === "rustore"
237
+ ? `${ANDROID_STORE_ENV}=rustore needs the plugin's android.rustore option ` +
238
+ '({ "consoleAppId": "<digits>", "scheme": "<deeplink scheme>" })'
239
+ : "android.rustore requires consoleAppId (digits) and a valid deeplink scheme";
240
+ throw new Error(`${prefix}; missing or invalid: ${problems.map((p) => "android.rustore." + p).join(", ")}`);
241
+ }
242
+ return { store: "rustore", rustore };
243
+ }
244
+
188
245
  function withSwissKnifePush(config, props) {
189
246
  const { withEntitlementsPlist, withInfoPlist, withAndroidManifest, withAppBuildGradle, withGradleProperties, withStringsXml } =
190
247
  loadConfigPlugins();
191
248
  const opts = normalizeProps(props);
192
- const rustore = props?.android?.rustore;
249
+ const { store, rustore } = resolveAndroidStore(props && props.android, typeof process === "undefined" ? {} : process.env);
193
250
  config = withGradleProperties(config, (c) => {
194
251
  c.modResults = c.modResults.filter((entry) => entry.key !== "swissKnifeStore");
195
- c.modResults.push({ type: "property", key: "swissKnifeStore", value: rustore ? "rustore" : "play" });
252
+ c.modResults.push({ type: "property", key: "swissKnifeStore", value: store });
196
253
  return c;
197
254
  });
198
255
  if (rustore) {
199
- if (!/^\d+$/.test(String(rustore.consoleAppId ?? "")) || !/^[a-z][a-z0-9+.-]*$/.test(rustore.scheme ?? "")) {
200
- throw new Error("android.rustore requires consoleAppId (digits) and a valid deeplink scheme");
201
- }
202
256
  config = withStringsXml(config, (c) => {
203
257
  c.modResults.resources.string = (c.modResults.resources.string || []).filter((entry) => entry.$?.name !== "swissknife_rustore_app_id");
204
258
  c.modResults.resources.string.push({ $: { name: "swissknife_rustore_app_id", translatable: "false" }, _: String(rustore.consoleAppId) });
@@ -264,6 +318,8 @@ module.exports.applyAndroidManifest = applyAndroidManifest;
264
318
  module.exports.detectMessagingConflict = detectMessagingConflict;
265
319
  module.exports.applyAppBuildGradle = applyAppBuildGradle;
266
320
  module.exports.applyGoogleServicesFile = applyGoogleServicesFile;
321
+ module.exports.resolveAndroidStore = resolveAndroidStore;
322
+ module.exports.ANDROID_STORE_ENV = ANDROID_STORE_ENV;
267
323
  module.exports.MESSAGING_SERVICE = MESSAGING_SERVICE;
268
324
 
269
325
  function applyRuStoreManifest(manifest, scheme) {
@@ -102,8 +102,10 @@ enum SwissKnifeJSON {
102
102
  "priceString": product.displayPrice,
103
103
  "price": NSDecimalNumber(decimal: product.price).doubleValue,
104
104
  "currencyCode": product.currencyCode,
105
- "productCategory": "SUBSCRIPTION",
106
- "productType": "AUTO_RENEWABLE_SUBSCRIPTION",
105
+ "productCategory": productCategoryString(product.productType),
106
+ "productType": productTypeString(product.productType),
107
+ // Both nil unless the product is an auto-renewable subscription (the
108
+ // SDK's OfferingsService sets them only then).
107
109
  "subscriptionPeriod": product.subscriptionPeriod.map { periodString($0) } ?? NSNull(),
108
110
  "defaultOption": NSNull(),
109
111
  "subscriptionOptions": NSNull(),
@@ -217,6 +219,26 @@ enum SwissKnifeJSON {
217
219
  }
218
220
  }
219
221
 
222
+ /// `PurchasesStoreProduct.productType` in src/types.ts. No `default:`, so a
223
+ /// new `StoreProductType` case fails the compile instead of mislabelling.
224
+ static func productTypeString(_ t: StoreProductType) -> String {
225
+ switch t {
226
+ case .autoRenewableSubscription: return "AUTO_RENEWABLE_SUBSCRIPTION"
227
+ case .nonRenewableSubscription: return "NON_RENEWABLE_SUBSCRIPTION"
228
+ case .consumable: return "CONSUMABLE"
229
+ case .nonConsumable: return "NON_CONSUMABLE"
230
+ case .unknown: return "UNKNOWN"
231
+ }
232
+ }
233
+
234
+ /// `PurchasesStoreProduct.productCategory` in src/types.ts: SUBSCRIPTION only
235
+ /// for an auto-renewable subscription (RevenueCat's convention), so a
236
+ /// non-renewing subscription, a consumable or a lifetime unlock is
237
+ /// NON_SUBSCRIPTION — as the Android bridge reports a one-time product.
238
+ static func productCategoryString(_ t: StoreProductType) -> String {
239
+ t.isSubscription ? "SUBSCRIPTION" : "NON_SUBSCRIPTION"
240
+ }
241
+
220
242
  private static func packageTypeString(_ p: PackageType) -> String {
221
243
  switch p {
222
244
  case .unknown: return "UNKNOWN"
@@ -4,6 +4,7 @@ Copied verbatim by packages/react-native-sdk/scripts/vendor-native.mjs from the
4
4
  standalone native SDK sources in the monorepo. Edit those instead:
5
5
 
6
6
  packages/swiss-knife-ios/Sources/SwissKnifeiOS/**
7
+ packages/swiss-knife-ios/Sources/SwissKnifeNotificationService/**
7
8
  packages/swiss-knife-android/src/main/{java,res}/**
8
9
 
9
10
  This directory is gitignored and regenerated on every `build` / `prepack`.
@@ -99,7 +99,7 @@ internal enum DeviceContextProvider {
99
99
  /// Round A baseline. The build pipeline (`swiss-build`) will eventually
100
100
  /// inject this via `-D` flag, but for now keep it in source so we don't
101
101
  /// have to thread build settings through the SPM Package.swift.
102
- static let sdkVersionConstant: String = "0.5.0"
102
+ static let sdkVersionConstant: String = "0.5.1"
103
103
 
104
104
  private static let cacheLock = DispatchQueue(label: "com.swissknife.context.device")
105
105
  private static var cached: DeviceContext?
@@ -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