@voidhash/nitro-ui 0.0.0-stage → 0.4.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 (442) hide show
  1. package/LICENSE.md +21 -0
  2. package/Package.swift +161 -0
  3. package/README.md +127 -2
  4. package/android/nitro-ui.gradle +35 -0
  5. package/android/src/main/java/com/margelo/nitro/voidhash/HybridVoidhashNativeClient.kt +53 -0
  6. package/android/src/main/java/com/margelo/nitro/voidhash/VoidhashNitroUIModule.kt +65 -0
  7. package/android/src/main/java/com/margelo/nitro/voidhash/client/LegacyStorageImporter.kt +526 -0
  8. package/android/src/main/java/com/margelo/nitro/voidhash/client/SdkBackedNativeClient.kt +1131 -0
  9. package/android/src/main/java/com/margelo/nitro/voidhash/client/StoreMapping.kt +257 -0
  10. package/android/src/main/java/com/margelo/nitro/voidhash/client/VoidhashFlowPermissionHandlers.kt +23 -0
  11. package/android/src/main/java/com/margelo/nitro/voidhash/flows/VoidhashFlowsCore.kt +93 -0
  12. package/build/chunk-Z6TDMZMZ.js +326 -0
  13. package/build/chunk-Z6TDMZMZ.js.map +1 -0
  14. package/build/index.d.ts +2866 -0
  15. package/build/index.js +4182 -0
  16. package/build/index.js.map +1 -0
  17. package/build/navigation.d.ts +66 -0
  18. package/build/navigation.js +72 -0
  19. package/build/navigation.js.map +1 -0
  20. package/ios/HybridVoidhashNativeClient.swift +427 -0
  21. package/ios/Shared/NativeClientMapping.swift +184 -0
  22. package/ios/Shared/NativeStoreJson.swift +126 -0
  23. package/ios/Shared/VoidhashCoreExports.swift +5 -0
  24. package/ios/Shared/VoidhashLegacyImporter.swift +686 -0
  25. package/ios/Shared/VoidhashNativeClientCore.swift +1400 -0
  26. package/nitro.json +8 -0
  27. package/nitrogen/generated/.gitattributes +1 -0
  28. package/nitrogen/generated/android/NitroVoidhash+autolinking.cmake +86 -0
  29. package/nitrogen/generated/android/NitroVoidhash+autolinking.gradle +10 -0
  30. package/nitrogen/generated/android/NitroVoidhashOnLoad.cpp +22 -0
  31. package/nitrogen/generated/android/c++/JCallback_Promise_std__string__std__string_std__string.cpp +57 -0
  32. package/nitrogen/generated/android/c++/JCallback_void_NativeClientEvent.cpp +55 -0
  33. package/nitrogen/generated/android/c++/JHybridVoidhashNativeClientSpec.cpp +387 -0
  34. package/nitrogen/generated/android/c++/JNativeAnalyticsConsent.cpp +55 -0
  35. package/nitrogen/generated/android/c++/JNativeAppStoreMessages.cpp +52 -0
  36. package/nitrogen/generated/android/c++/JNativeAppStorePurchaseOptions.cpp +36 -0
  37. package/nitrogen/generated/android/c++/JNativeAppStoreSubscriptionState.cpp +64 -0
  38. package/nitrogen/generated/android/c++/JNativeAppStoreSubscriptionStatus.cpp +38 -0
  39. package/nitrogen/generated/android/c++/JNativeClientConfiguration.cpp +75 -0
  40. package/nitrogen/generated/android/c++/JNativeClientEvent.cpp +52 -0
  41. package/nitrogen/generated/android/c++/JNativeClientEventType.cpp +70 -0
  42. package/nitrogen/generated/android/c++/JNativeDiagnostic.cpp +44 -0
  43. package/nitrogen/generated/android/c++/JNativeDiagnosticKind.cpp +67 -0
  44. package/nitrogen/generated/android/c++/JNativeEnvironment.cpp +61 -0
  45. package/nitrogen/generated/android/c++/JNativeFeatureFlag.cpp +41 -0
  46. package/nitrogen/generated/android/c++/JNativeFeatureFlagsResult.cpp +45 -0
  47. package/nitrogen/generated/android/c++/JNativeFlowCapability.cpp +58 -0
  48. package/nitrogen/generated/android/c++/JNativeFlowLoading.cpp +52 -0
  49. package/nitrogen/generated/android/c++/JNativeFlowPresentation.cpp +42 -0
  50. package/nitrogen/generated/android/c++/JNativeFlowRevision.cpp +37 -0
  51. package/nitrogen/generated/android/c++/JNativeFlowRuntime.cpp +52 -0
  52. package/nitrogen/generated/android/c++/JNativeFlushStatus.cpp +40 -0
  53. package/nitrogen/generated/android/c++/JNativeFreshnessReason.cpp +58 -0
  54. package/nitrogen/generated/android/c++/JNativeGooglePlayPurchaseOptions.cpp +40 -0
  55. package/nitrogen/generated/android/c++/JNativeIdentifyResult.cpp +40 -0
  56. package/nitrogen/generated/android/c++/JNativeIdentityChange.cpp +38 -0
  57. package/nitrogen/generated/android/c++/JNativeInAppMessageResult.cpp +38 -0
  58. package/nitrogen/generated/android/c++/JNativeInAppMessageStatus.cpp +52 -0
  59. package/nitrogen/generated/android/c++/JNativeOffer.cpp +44 -0
  60. package/nitrogen/generated/android/c++/JNativeOfferKind.cpp +61 -0
  61. package/nitrogen/generated/android/c++/JNativeOfferSelection.cpp +55 -0
  62. package/nitrogen/generated/android/c++/JNativePaymentMode.cpp +58 -0
  63. package/nitrogen/generated/android/c++/JNativePendingAnalytics.cpp +52 -0
  64. package/nitrogen/generated/android/c++/JNativePeriod.cpp +39 -0
  65. package/nitrogen/generated/android/c++/JNativePeriodUnit.cpp +61 -0
  66. package/nitrogen/generated/android/c++/JNativePersonState.cpp +44 -0
  67. package/nitrogen/generated/android/c++/JNativePersonWriteResult.cpp +38 -0
  68. package/nitrogen/generated/android/c++/JNativePrice.cpp +39 -0
  69. package/nitrogen/generated/android/c++/JNativePricingPhase.cpp +40 -0
  70. package/nitrogen/generated/android/c++/JNativeProduct.cpp +55 -0
  71. package/nitrogen/generated/android/c++/JNativeProductType.cpp +61 -0
  72. package/nitrogen/generated/android/c++/JNativePurchaseIntent.cpp +38 -0
  73. package/nitrogen/generated/android/c++/JNativePurchaseIntents.cpp +52 -0
  74. package/nitrogen/generated/android/c++/JNativePurchaseOptions.cpp +49 -0
  75. package/nitrogen/generated/android/c++/JNativePurchaseOutcome.cpp +55 -0
  76. package/nitrogen/generated/android/c++/JNativePurchaseResult.cpp +40 -0
  77. package/nitrogen/generated/android/c++/JNativeRefundRequestStatus.cpp +52 -0
  78. package/nitrogen/generated/android/c++/JNativeReportedPurchaseState.cpp +55 -0
  79. package/nitrogen/generated/android/c++/JNativeReportedTransaction.cpp +42 -0
  80. package/nitrogen/generated/android/c++/JNativeStore.cpp +58 -0
  81. package/nitrogen/generated/android/c++/JNativeStorePlatform.cpp +52 -0
  82. package/nitrogen/generated/android/c++/JNativeStorefront.cpp +37 -0
  83. package/nitrogen/generated/android/c++/JNativeSubscriptionInfo.cpp +45 -0
  84. package/nitrogen/generated/android/c++/JNativeSubscriptionReplacement.cpp +36 -0
  85. package/nitrogen/generated/android/c++/JNativeSubscriptionReplacementMode.cpp +61 -0
  86. package/nitrogen/generated/android/c++/JNativeTransaction.cpp +53 -0
  87. package/nitrogen/generated/android/c++/JNativeTransactionOffer.cpp +40 -0
  88. package/nitrogen/generated/android/c++/JNativeTransactionOfferKind.cpp +64 -0
  89. package/nitrogen/generated/android/c++/JNativeTransactionUpdate.cpp +36 -0
  90. package/nitrogen/generated/android/c++/JNativeWriteStatus.cpp +55 -0
  91. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JCallback_Promise_std__string__std__string_std__string.hpp +55 -0
  92. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JCallback_void_NativeClientEvent.hpp +54 -0
  93. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JHybridVoidhashNativeClientSpec.hpp +166 -0
  94. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JHybridVoidhashNativeClientSpecJavaPart.hpp +26 -0
  95. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeAnalyticsConsent.hpp +77 -0
  96. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeAppStoreMessages.hpp +72 -0
  97. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeAppStorePurchaseOptions.hpp +51 -0
  98. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeAppStoreSubscriptionState.hpp +92 -0
  99. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeAppStoreSubscriptionStatus.hpp +61 -0
  100. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeClientConfiguration.hpp +190 -0
  101. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeClientEvent.hpp +99 -0
  102. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeClientEventType.hpp +102 -0
  103. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeDiagnostic.hpp +79 -0
  104. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeDiagnosticKind.hpp +97 -0
  105. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeEnvironment.hpp +87 -0
  106. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeFeatureFlag.hpp +68 -0
  107. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeFeatureFlagsResult.hpp +76 -0
  108. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeFlowCapability.hpp +82 -0
  109. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeFlowLoading.hpp +72 -0
  110. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeFlowPresentation.hpp +65 -0
  111. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeFlowRevision.hpp +56 -0
  112. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeFlowRuntime.hpp +72 -0
  113. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeFlushStatus.hpp +63 -0
  114. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeFreshnessReason.hpp +82 -0
  115. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeGooglePlayPurchaseOptions.hpp +63 -0
  116. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeIdentifyResult.hpp +63 -0
  117. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeIdentityChange.hpp +61 -0
  118. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeInAppMessageResult.hpp +57 -0
  119. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeInAppMessageStatus.hpp +72 -0
  120. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeOffer.hpp +71 -0
  121. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeOfferKind.hpp +87 -0
  122. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeOfferSelection.hpp +77 -0
  123. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativePaymentMode.hpp +82 -0
  124. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativePendingAnalytics.hpp +72 -0
  125. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativePeriod.hpp +62 -0
  126. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativePeriodUnit.hpp +87 -0
  127. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativePersonState.hpp +79 -0
  128. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativePersonWriteResult.hpp +57 -0
  129. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativePrice.hpp +66 -0
  130. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativePricingPhase.hpp +67 -0
  131. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeProduct.hpp +118 -0
  132. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeProductType.hpp +87 -0
  133. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativePurchaseIntent.hpp +57 -0
  134. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativePurchaseIntents.hpp +72 -0
  135. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativePurchaseOptions.hpp +88 -0
  136. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativePurchaseOutcome.hpp +77 -0
  137. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativePurchaseResult.hpp +63 -0
  138. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeRefundRequestStatus.hpp +72 -0
  139. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeReportedPurchaseState.hpp +77 -0
  140. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeReportedTransaction.hpp +73 -0
  141. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeStore.hpp +82 -0
  142. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeStorePlatform.hpp +72 -0
  143. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeStorefront.hpp +56 -0
  144. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeSubscriptionInfo.hpp +84 -0
  145. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeSubscriptionReplacement.hpp +55 -0
  146. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeSubscriptionReplacementMode.hpp +87 -0
  147. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeTransaction.hpp +116 -0
  148. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeTransactionOffer.hpp +63 -0
  149. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeTransactionOfferKind.hpp +92 -0
  150. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeTransactionUpdate.hpp +55 -0
  151. package/nitrogen/generated/android/c++/include/NitroVoidhash/private/JNativeWriteStatus.hpp +77 -0
  152. package/nitrogen/generated/android/include/NitroVoidhash/private/NitroVoidhashOnLoad.hpp +13 -0
  153. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/Callback_Promise_std__string__std__string_std__string.kt +69 -0
  154. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/Callback_void_NativeClientEvent.kt +69 -0
  155. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/HybridVoidhashNativeClientSpec.kt +278 -0
  156. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeAnalyticsConsent.kt +49 -0
  157. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeAppStoreMessages.kt +46 -0
  158. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeAppStorePurchaseOptions.kt +46 -0
  159. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeAppStoreSubscriptionState.kt +58 -0
  160. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeAppStoreSubscriptionStatus.kt +57 -0
  161. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeClientConfiguration.kt +172 -0
  162. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeClientEvent.kt +87 -0
  163. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeClientEventType.kt +64 -0
  164. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeDiagnostic.kt +72 -0
  165. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeDiagnosticKind.kt +61 -0
  166. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeEnvironment.kt +55 -0
  167. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeFeatureFlag.kt +62 -0
  168. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeFeatureFlagsResult.kt +67 -0
  169. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeFlowCapability.kt +52 -0
  170. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeFlowLoading.kt +46 -0
  171. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeFlowPresentation.kt +57 -0
  172. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeFlowRevision.kt +52 -0
  173. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeFlowRuntime.kt +46 -0
  174. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeFlushStatus.kt +57 -0
  175. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeFreshnessReason.kt +52 -0
  176. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeGooglePlayPurchaseOptions.kt +57 -0
  177. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeIdentifyResult.kt +57 -0
  178. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeIdentityChange.kt +57 -0
  179. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeInAppMessageResult.kt +52 -0
  180. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeInAppMessageStatus.kt +46 -0
  181. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeOffer.kt +62 -0
  182. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeOfferKind.kt +55 -0
  183. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeOfferSelection.kt +49 -0
  184. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativePaymentMode.kt +52 -0
  185. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativePendingAnalytics.kt +46 -0
  186. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativePeriod.kt +57 -0
  187. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativePeriodUnit.kt +55 -0
  188. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativePersonState.kt +72 -0
  189. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativePersonWriteResult.kt +52 -0
  190. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativePrice.kt +62 -0
  191. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativePricingPhase.kt +62 -0
  192. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeProduct.kt +107 -0
  193. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeProductType.kt +55 -0
  194. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativePurchaseIntent.kt +52 -0
  195. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativePurchaseIntents.kt +46 -0
  196. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativePurchaseOptions.kt +77 -0
  197. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativePurchaseOutcome.kt +49 -0
  198. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativePurchaseResult.kt +57 -0
  199. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeRefundRequestStatus.kt +46 -0
  200. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeReportedPurchaseState.kt +49 -0
  201. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeReportedTransaction.kt +67 -0
  202. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeStore.kt +52 -0
  203. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeStorePlatform.kt +46 -0
  204. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeStorefront.kt +52 -0
  205. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeSubscriptionInfo.kt +77 -0
  206. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeSubscriptionReplacement.kt +52 -0
  207. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeSubscriptionReplacementMode.kt +55 -0
  208. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeTransaction.kt +107 -0
  209. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeTransactionOffer.kt +57 -0
  210. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeTransactionOfferKind.kt +58 -0
  211. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeTransactionUpdate.kt +52 -0
  212. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NativeWriteStatus.kt +49 -0
  213. package/nitrogen/generated/android/kotlin/com/margelo/nitro/voidhash/NitroVoidhashOnLoad.kt +22 -0
  214. package/nitrogen/generated/apple/NitroVoidhash-Swift-Cxx-Bridge.cpp +381 -0
  215. package/nitrogen/generated/apple/NitroVoidhashAppleCxx/NitroVoidhashAppleCxx.cpp +9 -0
  216. package/nitrogen/generated/apple/NitroVoidhashAppleCxx/include/NitroVoidhashAppleCxx/NitroVoidhashAppleCxx.h +265 -0
  217. package/nitrogen/generated/apple/NitroVoidhashAutolinking.cpp +20 -0
  218. package/nitrogen/generated/apple/NitroVoidhashAutolinking.mm +24 -0
  219. package/nitrogen/generated/apple/c++/HybridVoidhashNativeClientSpecSwift.cpp +555 -0
  220. package/nitrogen/generated/apple/c++/HybridVoidhashNativeClientSpec_cxx-Swift.cpp +28 -0
  221. package/nitrogen/generated/apple/c++/NativeAnalyticsConsent-Swift.cpp +49 -0
  222. package/nitrogen/generated/apple/c++/NativeAppStoreMessages-Swift.cpp +46 -0
  223. package/nitrogen/generated/apple/c++/NativeAppStorePurchaseOptions-Swift.cpp +32 -0
  224. package/nitrogen/generated/apple/c++/NativeAppStoreSubscriptionState-Swift.cpp +58 -0
  225. package/nitrogen/generated/apple/c++/NativeAppStoreSubscriptionStatus-Swift.cpp +34 -0
  226. package/nitrogen/generated/apple/c++/NativeClientConfiguration-Swift.cpp +57 -0
  227. package/nitrogen/generated/apple/c++/NativeClientEvent-Swift.cpp +40 -0
  228. package/nitrogen/generated/apple/c++/NativeClientEventType-Swift.cpp +64 -0
  229. package/nitrogen/generated/apple/c++/NativeDiagnostic-Swift.cpp +37 -0
  230. package/nitrogen/generated/apple/c++/NativeDiagnosticKind-Swift.cpp +61 -0
  231. package/nitrogen/generated/apple/c++/NativeEnvironment-Swift.cpp +55 -0
  232. package/nitrogen/generated/apple/c++/NativeFeatureFlag-Swift.cpp +35 -0
  233. package/nitrogen/generated/apple/c++/NativeFeatureFlagsResult-Swift.cpp +36 -0
  234. package/nitrogen/generated/apple/c++/NativeFlowCapability-Swift.cpp +52 -0
  235. package/nitrogen/generated/apple/c++/NativeFlowLoading-Swift.cpp +46 -0
  236. package/nitrogen/generated/apple/c++/NativeFlowPresentation-Swift.cpp +34 -0
  237. package/nitrogen/generated/apple/c++/NativeFlowRevision-Swift.cpp +33 -0
  238. package/nitrogen/generated/apple/c++/NativeFlowRuntime-Swift.cpp +46 -0
  239. package/nitrogen/generated/apple/c++/NativeFlushStatus-Swift.cpp +34 -0
  240. package/nitrogen/generated/apple/c++/NativeFreshnessReason-Swift.cpp +52 -0
  241. package/nitrogen/generated/apple/c++/NativeGooglePlayPurchaseOptions-Swift.cpp +34 -0
  242. package/nitrogen/generated/apple/c++/NativeIdentifyResult-Swift.cpp +34 -0
  243. package/nitrogen/generated/apple/c++/NativeIdentityChange-Swift.cpp +34 -0
  244. package/nitrogen/generated/apple/c++/NativeInAppMessageResult-Swift.cpp +33 -0
  245. package/nitrogen/generated/apple/c++/NativeInAppMessageStatus-Swift.cpp +46 -0
  246. package/nitrogen/generated/apple/c++/NativeOffer-Swift.cpp +35 -0
  247. package/nitrogen/generated/apple/c++/NativeOfferKind-Swift.cpp +55 -0
  248. package/nitrogen/generated/apple/c++/NativeOfferSelection-Swift.cpp +49 -0
  249. package/nitrogen/generated/apple/c++/NativePaymentMode-Swift.cpp +52 -0
  250. package/nitrogen/generated/apple/c++/NativePendingAnalytics-Swift.cpp +46 -0
  251. package/nitrogen/generated/apple/c++/NativePeriod-Swift.cpp +34 -0
  252. package/nitrogen/generated/apple/c++/NativePeriodUnit-Swift.cpp +55 -0
  253. package/nitrogen/generated/apple/c++/NativePersonState-Swift.cpp +37 -0
  254. package/nitrogen/generated/apple/c++/NativePersonWriteResult-Swift.cpp +33 -0
  255. package/nitrogen/generated/apple/c++/NativePrice-Swift.cpp +35 -0
  256. package/nitrogen/generated/apple/c++/NativePricingPhase-Swift.cpp +35 -0
  257. package/nitrogen/generated/apple/c++/NativeProduct-Swift.cpp +44 -0
  258. package/nitrogen/generated/apple/c++/NativeProductType-Swift.cpp +55 -0
  259. package/nitrogen/generated/apple/c++/NativePurchaseIntent-Swift.cpp +33 -0
  260. package/nitrogen/generated/apple/c++/NativePurchaseIntents-Swift.cpp +46 -0
  261. package/nitrogen/generated/apple/c++/NativePurchaseOptions-Swift.cpp +38 -0
  262. package/nitrogen/generated/apple/c++/NativePurchaseOutcome-Swift.cpp +49 -0
  263. package/nitrogen/generated/apple/c++/NativePurchaseResult-Swift.cpp +34 -0
  264. package/nitrogen/generated/apple/c++/NativeRefundRequestStatus-Swift.cpp +46 -0
  265. package/nitrogen/generated/apple/c++/NativeReportedPurchaseState-Swift.cpp +49 -0
  266. package/nitrogen/generated/apple/c++/NativeReportedTransaction-Swift.cpp +36 -0
  267. package/nitrogen/generated/apple/c++/NativeStore-Swift.cpp +52 -0
  268. package/nitrogen/generated/apple/c++/NativeStorePlatform-Swift.cpp +46 -0
  269. package/nitrogen/generated/apple/c++/NativeStorefront-Swift.cpp +33 -0
  270. package/nitrogen/generated/apple/c++/NativeSubscriptionInfo-Swift.cpp +38 -0
  271. package/nitrogen/generated/apple/c++/NativeSubscriptionReplacement-Swift.cpp +33 -0
  272. package/nitrogen/generated/apple/c++/NativeSubscriptionReplacementMode-Swift.cpp +55 -0
  273. package/nitrogen/generated/apple/c++/NativeTransaction-Swift.cpp +44 -0
  274. package/nitrogen/generated/apple/c++/NativeTransactionOffer-Swift.cpp +34 -0
  275. package/nitrogen/generated/apple/c++/NativeTransactionOfferKind-Swift.cpp +58 -0
  276. package/nitrogen/generated/apple/c++/NativeTransactionUpdate-Swift.cpp +33 -0
  277. package/nitrogen/generated/apple/c++/NativeWriteStatus-Swift.cpp +49 -0
  278. package/nitrogen/generated/apple/c++/Record_swift__String_bool-Swift.cpp +26 -0
  279. package/nitrogen/generated/apple/c++/Record_swift__String_swift__String-Swift.cpp +26 -0
  280. package/nitrogen/generated/apple/c++/SwiftContainer_swift__Array___NitroVoidhash__NativeAppStoreSubscriptionStatus_-Swift.cpp +38 -0
  281. package/nitrogen/generated/apple/c++/SwiftContainer_swift__Array___NitroVoidhash__NativeProduct_-Swift.cpp +41 -0
  282. package/nitrogen/generated/apple/c++/SwiftContainer_swift__Array___NitroVoidhash__NativeTransaction_-Swift.cpp +36 -0
  283. package/nitrogen/generated/apple/c++/SwiftContainer_swift__Optional___NitroVoidhash__NativeStorefront_-Swift.cpp +30 -0
  284. package/nitrogen/generated/apple/c++/include/NitroVoidhash/NitroVoidhashAutolinking.hpp +13 -0
  285. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/HybridVoidhashNativeClientSpecSwift.hpp +121 -0
  286. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/HybridVoidhashNativeClientSpec_cxx-Swift.hpp +23 -0
  287. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeAnalyticsConsent-Swift.hpp +23 -0
  288. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeAppStoreMessages-Swift.hpp +23 -0
  289. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeAppStorePurchaseOptions-Swift.hpp +23 -0
  290. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeAppStoreSubscriptionState-Swift.hpp +23 -0
  291. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeAppStoreSubscriptionStatus-Swift.hpp +23 -0
  292. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeClientConfiguration-Swift.hpp +23 -0
  293. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeClientEvent-Swift.hpp +23 -0
  294. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeClientEventType-Swift.hpp +23 -0
  295. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeDiagnostic-Swift.hpp +23 -0
  296. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeDiagnosticKind-Swift.hpp +23 -0
  297. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeEnvironment-Swift.hpp +23 -0
  298. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeFeatureFlag-Swift.hpp +23 -0
  299. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeFeatureFlagsResult-Swift.hpp +23 -0
  300. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeFlowCapability-Swift.hpp +23 -0
  301. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeFlowLoading-Swift.hpp +23 -0
  302. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeFlowPresentation-Swift.hpp +23 -0
  303. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeFlowRevision-Swift.hpp +23 -0
  304. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeFlowRuntime-Swift.hpp +23 -0
  305. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeFlushStatus-Swift.hpp +23 -0
  306. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeFreshnessReason-Swift.hpp +23 -0
  307. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeGooglePlayPurchaseOptions-Swift.hpp +23 -0
  308. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeIdentifyResult-Swift.hpp +23 -0
  309. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeIdentityChange-Swift.hpp +23 -0
  310. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeInAppMessageResult-Swift.hpp +23 -0
  311. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeInAppMessageStatus-Swift.hpp +23 -0
  312. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeOffer-Swift.hpp +23 -0
  313. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeOfferKind-Swift.hpp +23 -0
  314. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeOfferSelection-Swift.hpp +23 -0
  315. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativePaymentMode-Swift.hpp +23 -0
  316. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativePendingAnalytics-Swift.hpp +23 -0
  317. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativePeriod-Swift.hpp +23 -0
  318. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativePeriodUnit-Swift.hpp +23 -0
  319. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativePersonState-Swift.hpp +23 -0
  320. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativePersonWriteResult-Swift.hpp +23 -0
  321. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativePrice-Swift.hpp +23 -0
  322. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativePricingPhase-Swift.hpp +23 -0
  323. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeProduct-Swift.hpp +23 -0
  324. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeProductType-Swift.hpp +23 -0
  325. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativePurchaseIntent-Swift.hpp +23 -0
  326. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativePurchaseIntents-Swift.hpp +23 -0
  327. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativePurchaseOptions-Swift.hpp +23 -0
  328. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativePurchaseOutcome-Swift.hpp +23 -0
  329. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativePurchaseResult-Swift.hpp +23 -0
  330. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeRefundRequestStatus-Swift.hpp +23 -0
  331. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeReportedPurchaseState-Swift.hpp +23 -0
  332. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeReportedTransaction-Swift.hpp +23 -0
  333. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeStore-Swift.hpp +23 -0
  334. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeStorePlatform-Swift.hpp +23 -0
  335. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeStorefront-Swift.hpp +23 -0
  336. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeSubscriptionInfo-Swift.hpp +23 -0
  337. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeSubscriptionReplacement-Swift.hpp +23 -0
  338. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeSubscriptionReplacementMode-Swift.hpp +23 -0
  339. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeTransaction-Swift.hpp +23 -0
  340. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeTransactionOffer-Swift.hpp +23 -0
  341. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeTransactionOfferKind-Swift.hpp +23 -0
  342. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeTransactionUpdate-Swift.hpp +23 -0
  343. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NativeWriteStatus-Swift.hpp +23 -0
  344. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/NitroVoidhash-Swift-Cxx-Umbrella.hpp +100 -0
  345. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/Record_swift__String_bool-Swift.hpp +23 -0
  346. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/Record_swift__String_swift__String-Swift.hpp +23 -0
  347. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/SwiftContainer_swift__Array___NitroVoidhash__NativeAppStoreSubscriptionStatus_-Swift.hpp +23 -0
  348. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/SwiftContainer_swift__Array___NitroVoidhash__NativeProduct_-Swift.hpp +23 -0
  349. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/SwiftContainer_swift__Array___NitroVoidhash__NativeTransaction_-Swift.hpp +23 -0
  350. package/nitrogen/generated/apple/c++/include/NitroVoidhash/private/SwiftContainer_swift__Optional___NitroVoidhash__NativeStorefront_-Swift.hpp +23 -0
  351. package/nitrogen/generated/apple/c++/include/module.modulemap +12 -0
  352. package/nitrogen/generated/apple/swift/Callback_Promise_swift__String__swift__String_swift__String.swift +73 -0
  353. package/nitrogen/generated/apple/swift/Callback_void___NitroVoidhash__NativeClientEvent.swift +66 -0
  354. package/nitrogen/generated/apple/swift/HybridVoidhashNativeClientSpec.swift +113 -0
  355. package/nitrogen/generated/apple/swift/HybridVoidhashNativeClientSpec_cxx.swift +629 -0
  356. package/nitrogen/generated/apple/swift/NativeAnalyticsConsent.swift +59 -0
  357. package/nitrogen/generated/apple/swift/NativeAppStoreMessages.swift +54 -0
  358. package/nitrogen/generated/apple/swift/NativeAppStorePurchaseOptions.swift +28 -0
  359. package/nitrogen/generated/apple/swift/NativeAppStoreSubscriptionState.swift +74 -0
  360. package/nitrogen/generated/apple/swift/NativeAppStoreSubscriptionStatus.swift +42 -0
  361. package/nitrogen/generated/apple/swift/NativeClientConfiguration.swift +203 -0
  362. package/nitrogen/generated/apple/swift/NativeClientEvent.swift +84 -0
  363. package/nitrogen/generated/apple/swift/NativeClientEventType.swift +84 -0
  364. package/nitrogen/generated/apple/swift/NativeDiagnostic.swift +63 -0
  365. package/nitrogen/generated/apple/swift/NativeDiagnosticKind.swift +79 -0
  366. package/nitrogen/generated/apple/swift/NativeEnvironment.swift +69 -0
  367. package/nitrogen/generated/apple/swift/NativeFeatureFlag.swift +49 -0
  368. package/nitrogen/generated/apple/swift/NativeFeatureFlagsResult.swift +56 -0
  369. package/nitrogen/generated/apple/swift/NativeFlowCapability.swift +64 -0
  370. package/nitrogen/generated/apple/swift/NativeFlowLoading.swift +54 -0
  371. package/nitrogen/generated/apple/swift/NativeFlowPresentation.swift +42 -0
  372. package/nitrogen/generated/apple/swift/NativeFlowRevision.swift +35 -0
  373. package/nitrogen/generated/apple/swift/NativeFlowRuntime.swift +54 -0
  374. package/nitrogen/generated/apple/swift/NativeFlushStatus.swift +42 -0
  375. package/nitrogen/generated/apple/swift/NativeFreshnessReason.swift +64 -0
  376. package/nitrogen/generated/apple/swift/NativeGooglePlayPurchaseOptions.swift +42 -0
  377. package/nitrogen/generated/apple/swift/NativeIdentifyResult.swift +42 -0
  378. package/nitrogen/generated/apple/swift/NativeIdentityChange.swift +42 -0
  379. package/nitrogen/generated/apple/swift/NativeInAppMessageResult.swift +35 -0
  380. package/nitrogen/generated/apple/swift/NativeInAppMessageStatus.swift +54 -0
  381. package/nitrogen/generated/apple/swift/NativeOffer.swift +49 -0
  382. package/nitrogen/generated/apple/swift/NativeOfferKind.swift +69 -0
  383. package/nitrogen/generated/apple/swift/NativeOfferSelection.swift +59 -0
  384. package/nitrogen/generated/apple/swift/NativePaymentMode.swift +64 -0
  385. package/nitrogen/generated/apple/swift/NativePendingAnalytics.swift +54 -0
  386. package/nitrogen/generated/apple/swift/NativePeriod.swift +42 -0
  387. package/nitrogen/generated/apple/swift/NativePeriodUnit.swift +69 -0
  388. package/nitrogen/generated/apple/swift/NativePersonState.swift +63 -0
  389. package/nitrogen/generated/apple/swift/NativePersonWriteResult.swift +35 -0
  390. package/nitrogen/generated/apple/swift/NativePrice.swift +49 -0
  391. package/nitrogen/generated/apple/swift/NativePricingPhase.swift +49 -0
  392. package/nitrogen/generated/apple/swift/NativeProduct.swift +112 -0
  393. package/nitrogen/generated/apple/swift/NativeProductType.swift +69 -0
  394. package/nitrogen/generated/apple/swift/NativePurchaseIntent.swift +35 -0
  395. package/nitrogen/generated/apple/swift/NativePurchaseIntents.swift +54 -0
  396. package/nitrogen/generated/apple/swift/NativePurchaseOptions.swift +70 -0
  397. package/nitrogen/generated/apple/swift/NativePurchaseOutcome.swift +59 -0
  398. package/nitrogen/generated/apple/swift/NativePurchaseResult.swift +42 -0
  399. package/nitrogen/generated/apple/swift/NativeRefundRequestStatus.swift +54 -0
  400. package/nitrogen/generated/apple/swift/NativeReportedPurchaseState.swift +59 -0
  401. package/nitrogen/generated/apple/swift/NativeReportedTransaction.swift +56 -0
  402. package/nitrogen/generated/apple/swift/NativeStore.swift +64 -0
  403. package/nitrogen/generated/apple/swift/NativeStorePlatform.swift +54 -0
  404. package/nitrogen/generated/apple/swift/NativeStorefront.swift +35 -0
  405. package/nitrogen/generated/apple/swift/NativeSubscriptionInfo.swift +70 -0
  406. package/nitrogen/generated/apple/swift/NativeSubscriptionReplacement.swift +35 -0
  407. package/nitrogen/generated/apple/swift/NativeSubscriptionReplacementMode.swift +69 -0
  408. package/nitrogen/generated/apple/swift/NativeTransaction.swift +112 -0
  409. package/nitrogen/generated/apple/swift/NativeTransactionOffer.swift +42 -0
  410. package/nitrogen/generated/apple/swift/NativeTransactionOfferKind.swift +74 -0
  411. package/nitrogen/generated/apple/swift/NativeTransactionUpdate.swift +35 -0
  412. package/nitrogen/generated/apple/swift/NativeWriteStatus.swift +59 -0
  413. package/nitrogen/generated/apple/swift/Promise_Promise_swift__String_.swift +100 -0
  414. package/nitrogen/generated/apple/swift/Promise___NitroVoidhash__NativeFeatureFlagsResult.swift +102 -0
  415. package/nitrogen/generated/apple/swift/Promise___NitroVoidhash__NativeFlushStatus.swift +102 -0
  416. package/nitrogen/generated/apple/swift/Promise___NitroVoidhash__NativeIdentifyResult.swift +102 -0
  417. package/nitrogen/generated/apple/swift/Promise___NitroVoidhash__NativeIdentityChange.swift +102 -0
  418. package/nitrogen/generated/apple/swift/Promise___NitroVoidhash__NativeInAppMessageResult.swift +102 -0
  419. package/nitrogen/generated/apple/swift/Promise___NitroVoidhash__NativePersonState.swift +102 -0
  420. package/nitrogen/generated/apple/swift/Promise___NitroVoidhash__NativePersonWriteResult.swift +102 -0
  421. package/nitrogen/generated/apple/swift/Promise___NitroVoidhash__NativePurchaseResult.swift +102 -0
  422. package/nitrogen/generated/apple/swift/Promise___NitroVoidhash__NativeRefundRequestStatus.swift +102 -0
  423. package/nitrogen/generated/apple/swift/Promise___NitroVoidhash__SwiftContainer_swift__Array___NitroVoidhash__NativeAppStoreSubscriptionStatus_.swift +102 -0
  424. package/nitrogen/generated/apple/swift/Promise___NitroVoidhash__SwiftContainer_swift__Array___NitroVoidhash__NativeProduct_.swift +102 -0
  425. package/nitrogen/generated/apple/swift/Promise___NitroVoidhash__SwiftContainer_swift__Array___NitroVoidhash__NativeTransaction_.swift +102 -0
  426. package/nitrogen/generated/apple/swift/Promise___NitroVoidhash__SwiftContainer_swift__Optional___NitroVoidhash__NativeStorefront_.swift +102 -0
  427. package/nitrogen/generated/apple/swift/Promise_bool.swift +100 -0
  428. package/nitrogen/generated/apple/swift/Promise_swift__String.swift +102 -0
  429. package/nitrogen/generated/apple/swift/Promise_void.swift +100 -0
  430. package/nitrogen/generated/apple/swift/Record_swift__String_bool.swift +48 -0
  431. package/nitrogen/generated/apple/swift/Record_swift__String_swift__String.swift +48 -0
  432. package/nitrogen/generated/apple/swift/SwiftContainer_swift__Array___NitroVoidhash__NativeAppStoreSubscriptionStatus_.swift +21 -0
  433. package/nitrogen/generated/apple/swift/SwiftContainer_swift__Array___NitroVoidhash__NativeProduct_.swift +21 -0
  434. package/nitrogen/generated/apple/swift/SwiftContainer_swift__Array___NitroVoidhash__NativeTransaction_.swift +21 -0
  435. package/nitrogen/generated/apple/swift/SwiftContainer_swift__Optional___NitroVoidhash__NativeStorefront_.swift +21 -0
  436. package/nitrogen/generated/hybrid-classes.json +19 -0
  437. package/nitrogen/generated/shared/c++/NitroVoidhashCxxModule.cpp +2 -0
  438. package/nitrogen/generated/shared/c++/include/NitroVoidhash/NitroVoidhashCxxModule.hpp +2 -0
  439. package/nitrogen/generated/shared/javascript/VoidhashNativeClient.cjs +19 -0
  440. package/nitrogen/generated/shared/javascript/VoidhashNativeClient.d.cts +9 -0
  441. package/package.json +103 -3
  442. package/src/specs/VoidhashNativeClient.nitro.ts +1162 -0
package/build/index.js ADDED
@@ -0,0 +1,4182 @@
1
+ import {
2
+ InvalidArgumentError,
3
+ NotInitializedError,
4
+ PurchaseInProgressError,
5
+ ReadOnlyModePurchaseNotAllowedError,
6
+ UnknownVoidhashError,
7
+ UnsupportedPlatformError,
8
+ VOIDHASH_ERROR_CODES,
9
+ VoidhashError,
10
+ __reExport,
11
+ useProviderStatus,
12
+ useVoidhashClient,
13
+ voidhashProviderFactory
14
+ } from "./chunk-Z6TDMZMZ.js";
15
+
16
+ // ../react-native/src/client.tsx
17
+ import { Result as Result6 } from "better-result";
18
+ import * as Arr9 from "effect/Array";
19
+ import * as MutableHashMap from "effect/MutableHashMap";
20
+ import * as MutableHashSet from "effect/MutableHashSet";
21
+ import * as Option13 from "effect/Option";
22
+ import * as P8 from "effect/Predicate";
23
+ import * as R7 from "effect/Record";
24
+ import * as EffectResult2 from "effect/Result";
25
+ import * as Schema11 from "effect/Schema";
26
+
27
+ // ../react-native/src/core/analytics/constants.ts
28
+ var AUTOMATIC_EVENTS = {
29
+ /** First launch the SDK has seen on this install (no cached release). */
30
+ APP_INSTALLED: "$app_installed",
31
+ /** Launch where the app build/version differs from the last seen one. */
32
+ APP_UPDATED: "$app_updated",
33
+ /** Every SDK startup, after install/update has been resolved. */
34
+ APP_OPENED: "$app_opened",
35
+ /** App moved to the background. */
36
+ APP_BACKGROUNDED: "$app_backgrounded",
37
+ /** App returned to the foreground from a non-active state. */
38
+ APP_BECAME_ACTIVE: "$app_became_active",
39
+ /** The app ended in a crash the system recorded, reported natively at a later launch. */
40
+ APP_CRASHED: "$app_crashed",
41
+ /** User signed out (identity reset triggered via `signOut`). */
42
+ SIGN_OUT: "$sign_out",
43
+ /** The user arrived on a screen (route, view controller, activity, …). */
44
+ SCREEN: "$screen",
45
+ /** The user opened a notification sent through Voidhash; see `client.trackPushOpened()`. */
46
+ PUSH_OPENED: "$push_opened"
47
+ };
48
+ var PUSH_SEND_ID_DATA_KEY = "voidhash_send_id";
49
+ var PUSH_SEND_ID_PROPERTY = "push_notification_send_id";
50
+ var SCREEN_PROPERTIES = {
51
+ /** Stable, low-cardinality identity of the screen (route pattern, route or class name). */
52
+ NAME: "$screen_name",
53
+ /** Concrete location, including dynamic segment values where the router has them. */
54
+ PATH: "$screen_path",
55
+ /** Human title when the platform exposes one. */
56
+ TITLE: "$screen_title",
57
+ /** `$screen_name` of the screen the user came from; `null` for the first screen. */
58
+ PREVIOUS_NAME: "$previous_screen_name",
59
+ /** `$screen_path` of the screen the user came from; `null` for the first screen. */
60
+ PREVIOUS_PATH: "$previous_screen_path",
61
+ /** Wall-clock milliseconds spent on the previous screen; `null` for the first screen. */
62
+ PREVIOUS_DURATION_MS: "$previous_screen_duration_ms",
63
+ /** Integration that produced the event (`expo-router`, `react-navigation`, `manual`, …). */
64
+ SOURCE: "$screen_source",
65
+ /** Route params, string-coerced and capped at 20 keys. Only with `includeParams`. */
66
+ PARAMS: "$screen_params"
67
+ };
68
+
69
+ // ../react-native/src/core/caching/namespace.ts
70
+ import * as Arr from "effect/Array";
71
+ var CACHE_SCHEMA_VERSION = 1;
72
+ var hashCacheNamespace = (value3) => (Arr.reduce(
73
+ Array.from(new TextEncoder().encode(value3)),
74
+ 2166136261,
75
+ (hash, byte) => Math.imul(hash ^ byte, 16777619)
76
+ ) >>> 0).toString(16).padStart(8, "0");
77
+ var buildCacheNamespace = (publishableKey, baseUrl) => `vh:${CACHE_SCHEMA_VERSION}:${hashCacheNamespace(`${publishableKey}|${baseUrl}`)}:`;
78
+
79
+ // ../react-native/package.json
80
+ var version = "0.4.0";
81
+
82
+ // ../react-native/src/core/constants.ts
83
+ var SDK_VERSION = version;
84
+
85
+ // ../react-native/src/core/diagnostics/diagnostics.ts
86
+ import * as Option from "effect/Option";
87
+ var DIAGNOSTIC_CODES = {
88
+ /**
89
+ * An analytics event was dropped: evicted because the queue hit its cap,
90
+ * refused by the ingest API with a verdict re-sending cannot change, or
91
+ * captured with properties that could not be copied into JSON.
92
+ */
93
+ ANALYTICS_EVENT_DROPPED: "ANALYTICS_EVENT_DROPPED",
94
+ /**
95
+ * Analytics work (an event, a screen, an opened notification) was skipped
96
+ * because analytics consent is not granted. Reported once until consent is
97
+ * granted again.
98
+ */
99
+ ANALYTICS_CONSENT_DENIED: "ANALYTICS_CONSENT_DENIED",
100
+ /** The publishable key was rejected; outbound traffic is paused. */
101
+ AUTHENTICATION_FAILED: "AUTHENTICATION_FAILED",
102
+ /** The store could not say which ad brought the install yet; a later launch asks again. */
103
+ INSTALL_ATTRIBUTION_DEFERRED: "INSTALL_ATTRIBUTION_DEFERRED",
104
+ /** The SDK stopped asking the store which ad brought the install, without an answer. */
105
+ INSTALL_ATTRIBUTION_ABANDONED: "INSTALL_ATTRIBUTION_ABANDONED",
106
+ /**
107
+ * Device storage could not be read, or a stored entry could not be decoded.
108
+ * An unreadable value counts as unknown, never as absent: the SDK does not
109
+ * overwrite it. A corrupt entry is discarded and treated as a miss.
110
+ */
111
+ CACHE_READ_FAILED: "CACHE_READ_FAILED",
112
+ /** A write to device storage failed; the value is still held in memory. */
113
+ CACHE_WRITE_FAILED: "CACHE_WRITE_FAILED",
114
+ /**
115
+ * @deprecated No longer emitted: the SDK has no pre-namespace entries to
116
+ * migrate. Kept so handlers that match on it still compile.
117
+ */
118
+ CACHE_MIGRATION_FAILED: "CACHE_MIGRATION_FAILED",
119
+ /** The breaker for a host is open, so the request was skipped. */
120
+ CIRCUIT_OPEN: "CIRCUIT_OPEN",
121
+ /**
122
+ * A callback the app handed the SDK threw (a `usePurchase` callback,
123
+ * `screenTracking.mapScreen`, the `connectivity` source). The SDK carried on
124
+ * without it: the purchase kept its result, the screen was tracked unmapped.
125
+ */
126
+ HOST_CALLBACK_FAILED: "HOST_CALLBACK_FAILED",
127
+ /** A client option was invalid and the SDK fell back to its default (release builds only). */
128
+ INVALID_CONFIGURATION: "INVALID_CONFIGURATION",
129
+ /** A request failed and the SDK fell back to cache or a retry. */
130
+ REQUEST_FAILED: "REQUEST_FAILED",
131
+ /** A request exceeded the per-attempt timeout. */
132
+ REQUEST_TIMEOUT: "REQUEST_TIMEOUT",
133
+ /** A background task the SDK owns failed outright. */
134
+ BACKGROUND_TASK_FAILED: "BACKGROUND_TASK_FAILED",
135
+ /**
136
+ * A product, perk or paywall location in the project schema could not be
137
+ * read by this SDK version and was left out. Every other entry is still
138
+ * served; updating the SDK makes the entry available.
139
+ */
140
+ SCHEMA_ENTRY_SKIPPED: "SCHEMA_ENTRY_SKIPPED",
141
+ /**
142
+ * A queued `identify` or person-attribute write was dropped because the
143
+ * Voidhash API refused it with a verdict re-sending cannot change.
144
+ */
145
+ PERSON_WRITE_REJECTED: "PERSON_WRITE_REJECTED",
146
+ /**
147
+ * A product the project defines was not returned by the store, so
148
+ * `getProducts()` and `useProducts()` leave it out. Reported once per
149
+ * product per load; the message names its slug and the store's reason.
150
+ * Check the store product id in Studio and the product's state in App Store
151
+ * Connect or the Play Console.
152
+ */
153
+ PRODUCT_NOT_FOUND: "PRODUCT_NOT_FOUND",
154
+ /**
155
+ * The store sells a product as another type than Studio, such as a Studio
156
+ * subscription the App Store sells as a non-renewing one or Google Play as
157
+ * an in-app product, so `getProducts()` and `useProducts()` leave it out.
158
+ * The message names its slug and both types.
159
+ */
160
+ PRODUCT_TYPE_MISMATCH: "PRODUCT_TYPE_MISMATCH",
161
+ /**
162
+ * iOS, with `purchaseIntents: "manual"`: more App Store purchase intents
163
+ * arrived before any `appStore.addPurchaseIntentListener()` than the SDK
164
+ * holds for it (10), so the oldest was dropped. The end user can start that
165
+ * purchase again on the App Store.
166
+ */
167
+ PURCHASE_INTENT_DROPPED: "PURCHASE_INTENT_DROPPED",
168
+ /** A queued transaction receipt was discarded as unsendable. */
169
+ TRANSACTION_RECEIPT_DROPPED: "TRANSACTION_RECEIPT_DROPPED",
170
+ /**
171
+ * The Voidhash API refused a store receipt with a verdict re-sending cannot
172
+ * change on its own: the store is not configured for this app, or the
173
+ * transaction is unknown or belongs to another environment. The receipt
174
+ * stays queued and is sent again at the next launch or after six hours.
175
+ * Reported once per receipt.
176
+ */
177
+ TRANSACTION_REJECTED: "TRANSACTION_REJECTED",
178
+ /**
179
+ * Android: a purchase the SDK started was still not recorded by Voidhash 48
180
+ * hours after its payment went through, so the background check acknowledged
181
+ * it on the device before Google Play refunds it. The SDK still holds the
182
+ * receipt and delivers it.
183
+ */
184
+ PURCHASE_FINISHED_BEFORE_SYNC: "PURCHASE_FINISHED_BEFORE_SYNC",
185
+ /** A transaction receipt is waiting in the outbox for a successful sync. */
186
+ TRANSACTION_SYNC_DEFERRED: "TRANSACTION_SYNC_DEFERRED",
187
+ /**
188
+ * iOS: what an earlier release of this package stored on the device was not
189
+ * carried over, because the storage it was kept under doesn't match the
190
+ * configured base URL. Reported once per start.
191
+ */
192
+ LEGACY_IMPORT_SKIPPED: "LEGACY_IMPORT_SKIPPED"
193
+ };
194
+ var makeDiagnosticEmitter = (handler) => (diagnostic) => {
195
+ if (Option.isNone(handler)) return;
196
+ try {
197
+ handler.value(diagnostic);
198
+ } catch {
199
+ }
200
+ };
201
+
202
+ // ../react-native/src/core/entities/reported-transaction.ts
203
+ import { Base64Url } from "effect/encoding";
204
+ import * as Result from "effect/Result";
205
+ import * as P from "effect/Predicate";
206
+ import * as Schema from "effect/Schema";
207
+ var identifier = Schema.String.check(Schema.isPattern(/\S/));
208
+ var decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
209
+ var decodeReport = Schema.decodeUnknownSync(
210
+ Schema.Union([
211
+ Schema.Struct({
212
+ platform: Schema.Literal("ios"),
213
+ transactionId: identifier,
214
+ signedTransaction: Schema.optional(identifier)
215
+ }),
216
+ Schema.Struct({
217
+ platform: Schema.Literal("android"),
218
+ purchaseToken: identifier,
219
+ purchaseState: Schema.optional(Schema.Literals(["purchased", "pending", "unspecified"]))
220
+ })
221
+ ])
222
+ );
223
+ var fromStoreKitJws = (jws) => {
224
+ const parts = jws.split(".");
225
+ if (parts.length !== 3 || !parts[1]) throw new TypeError("Expected a StoreKit transaction JWS");
226
+ const payload = Schema.decodeUnknownSync(Schema.Struct({ transactionId: identifier }))(
227
+ Result.match(Base64Url.decodeString(parts[1]), {
228
+ onFailure: () => {
229
+ throw new TypeError("Invalid StoreKit transaction encoding");
230
+ },
231
+ onSuccess: decodeJson
232
+ })
233
+ );
234
+ return { platform: "ios", signedTransaction: jws, transactionId: payload.transactionId };
235
+ };
236
+ var fromPlayPurchase = (input) => {
237
+ const payload = Schema.decodeUnknownSync(
238
+ Schema.Struct({
239
+ token: Schema.optional(identifier),
240
+ purchaseToken: Schema.optional(identifier),
241
+ purchaseState: Schema.optional(Schema.Literals([0, 1, 4])),
242
+ productIds: Schema.optional(Schema.Array(Schema.Unknown))
243
+ })
244
+ )(decodeJson(input.originalJson));
245
+ if (payload.productIds && payload.productIds.length > 1) {
246
+ throw new TypeError("Multi-product purchases are not supported");
247
+ }
248
+ const token = payload.token ?? payload.purchaseToken;
249
+ if (!token) throw new TypeError("A Google Play purchase token is required");
250
+ return {
251
+ platform: "android",
252
+ purchaseToken: token,
253
+ purchaseState: payload.purchaseState === 4 ? "pending" : "purchased"
254
+ };
255
+ };
256
+ var fromReportedTransaction = (input) => decodeReport(
257
+ P.isString(input) ? fromStoreKitJws(input) : input && "originalJson" in input ? fromPlayPurchase(input) : input
258
+ );
259
+
260
+ // ../react-native/src/core/flows/flows.ts
261
+ import * as Result2 from "effect/Result";
262
+ import * as Schema2 from "effect/Schema";
263
+ var DEFAULT_FLOW_CAPABILITIES = ["links"];
264
+ var flowError = (code, message) => new VoidhashError(code, `${code}: ${message}`);
265
+ var NativeFlowValue = Schema2.Union([
266
+ Schema2.String,
267
+ Schema2.Number,
268
+ Schema2.Boolean,
269
+ Schema2.Array(Schema2.String)
270
+ ]);
271
+ var NativeFlowResult = Schema2.Union([
272
+ Schema2.Struct({
273
+ outcome: Schema2.String,
274
+ output: Schema2.Record(Schema2.String, NativeFlowValue),
275
+ productId: Schema2.optional(Schema2.String),
276
+ wasShown: Schema2.optional(Schema2.Boolean)
277
+ }),
278
+ Schema2.Struct({
279
+ failure: Schema2.Struct({
280
+ code: Schema2.Literals([
281
+ "FLOW_DISABLED",
282
+ "FLOW_NOT_ASSIGNED",
283
+ "FLOW_UNAVAILABLE",
284
+ "FLOW_RENDERER_MISSING",
285
+ "FLOW_UNSUPPORTED_PACKAGE",
286
+ "FLOW_PRESENTATION_FAILED"
287
+ ]),
288
+ message: Schema2.String
289
+ })
290
+ })
291
+ ]);
292
+ var decodeNativeFlowResult = Schema2.decodeUnknownResult(Schema2.fromJsonString(NativeFlowResult));
293
+ var parseFlowResult = (json) => {
294
+ const decoded = decodeNativeFlowResult(json);
295
+ if (Result2.isFailure(decoded)) {
296
+ return Result2.fail(flowError("FLOW_PRESENTATION_FAILED", `unreadable flow result ${json}`));
297
+ }
298
+ const native = decoded.success;
299
+ if ("failure" in native) {
300
+ return Result2.fail(new VoidhashError(native.failure.code, native.failure.message));
301
+ }
302
+ return Result2.succeed({
303
+ outcome: native.outcome,
304
+ output: native.output,
305
+ ...native.productId === void 0 ? {} : { productId: native.productId },
306
+ ...native.wasShown === void 0 ? {} : { wasShown: native.wasShown }
307
+ });
308
+ };
309
+
310
+ // ../react-native/src/core/native/native-client.ts
311
+ import { Result as Result4 } from "better-result";
312
+ import * as Arr6 from "effect/Array";
313
+ import * as Cause from "effect/Cause";
314
+ import * as Effect6 from "effect/Effect";
315
+ import * as Exit from "effect/Exit";
316
+ import * as Match2 from "effect/Match";
317
+ import * as MutableRef from "effect/MutableRef";
318
+ import * as Option10 from "effect/Option";
319
+ import * as P5 from "effect/Predicate";
320
+ import * as R4 from "effect/Record";
321
+ import * as EffectResult from "effect/Result";
322
+ import * as Schema10 from "effect/Schema";
323
+ import { Atom as Atom2 } from "effect/reactivity";
324
+
325
+ // ../react-native/src/core/analytics/json-safe.ts
326
+ import * as Arr2 from "effect/Array";
327
+ import * as Option2 from "effect/Option";
328
+ import * as P2 from "effect/Predicate";
329
+ import * as R from "effect/Record";
330
+ import * as Result3 from "effect/Result";
331
+ var EVENT_PROPERTY_VALUE_LIMIT = 1e4;
332
+ var EventPropertyValueLimitExceeded = class extends Error {
333
+ constructor() {
334
+ super(`holds more than ${EVENT_PROPERTY_VALUE_LIMIT} values`);
335
+ }
336
+ };
337
+ var toJsonSafeProperties = (properties) => {
338
+ let remaining = EVENT_PROPERTY_VALUE_LIMIT;
339
+ const ancestors = /* @__PURE__ */ new WeakSet();
340
+ const copy = (value3) => {
341
+ remaining -= 1;
342
+ if (remaining < 0) throw new EventPropertyValueLimitExceeded();
343
+ if (P2.isString(value3) || P2.isBoolean(value3)) return Option2.some(value3);
344
+ if (P2.isNumber(value3)) return Option2.some(Number.isFinite(value3) ? value3 : null);
345
+ if (P2.isBigInt(value3)) return Option2.some(value3.toString());
346
+ if (P2.isNull(value3)) return Option2.some(null);
347
+ return P2.isObjectOrArray(value3) ? copyObject(value3) : Option2.none();
348
+ };
349
+ const copyEntries = (value3) => {
350
+ if (Array.isArray(value3)) {
351
+ return Option2.some(value3.map((item) => Option2.getOrNull(copy(item))));
352
+ }
353
+ if (!P2.isObject(value3)) return Option2.none();
354
+ return Option2.some(
355
+ R.fromEntries(
356
+ R.keys(value3).flatMap(
357
+ (key) => Arr2.fromOption(Option2.map(copy(value3[key]), (item) => [key, item]))
358
+ )
359
+ )
360
+ );
361
+ };
362
+ const copyObject = (value3) => {
363
+ if (ancestors.has(value3)) return Option2.none();
364
+ ancestors.add(value3);
365
+ const toJson = Reflect.get(value3, "toJSON");
366
+ const json = P2.isFunction(toJson) ? Reflect.apply(toJson, value3, []) : value3;
367
+ const copied = json === value3 ? copyEntries(value3) : copy(json);
368
+ ancestors.delete(value3);
369
+ return copied;
370
+ };
371
+ return Result3.try({
372
+ catch: (error) => error instanceof EventPropertyValueLimitExceeded ? error.message : `could not be read${P2.isError(error) ? ` (${error.message})` : ""}`,
373
+ try: () => Option2.getOrElse(Option2.filter(copy(properties), P2.isObject), () => ({}))
374
+ });
375
+ };
376
+
377
+ // ../react-native/src/core/entitlements/find-grant.ts
378
+ import * as Arr3 from "effect/Array";
379
+ import * as Option3 from "effect/Option";
380
+ var findActiveGrant = (person, perkSlug) => Option3.flatMap(
381
+ person,
382
+ (snapshot) => Arr3.findFirst(
383
+ snapshot.entitlements.grants,
384
+ (grant) => grant.status === "active" && (grant.perkSlug === perkSlug || grant.perkId === perkSlug)
385
+ )
386
+ );
387
+
388
+ // ../react-native/src/core/entities/app-store.ts
389
+ import * as Schema4 from "effect/Schema";
390
+
391
+ // ../react-native/src/core/entities/decoding.ts
392
+ import * as Arr4 from "effect/Array";
393
+ import * as Effect from "effect/Effect";
394
+ import * as Option4 from "effect/Option";
395
+ import * as P3 from "effect/Predicate";
396
+ import * as R2 from "effect/Record";
397
+ import * as Schema3 from "effect/Schema";
398
+ import * as SchemaTransformation from "effect/SchemaTransformation";
399
+ var enumOrUnknown = (values2) => {
400
+ const isKnown = (value3) => values2.some((known) => known === value3);
401
+ return Schema3.String.pipe(
402
+ Schema3.decodeTo(
403
+ Schema3.Literals([...values2, "unknown"]),
404
+ SchemaTransformation.transform({
405
+ decode: (value3) => isKnown(value3) ? value3 : "unknown",
406
+ encode: (value3) => value3
407
+ })
408
+ )
409
+ );
410
+ };
411
+ var renamedEnumOrUnknown = (names) => Schema3.String.pipe(
412
+ Schema3.decodeTo(
413
+ Schema3.Literals([...R2.values(names), "unknown"]),
414
+ SchemaTransformation.transform({
415
+ decode: (wire) => Option4.getOrElse(R2.get(names, wire), () => "unknown"),
416
+ encode: (value3) => Option4.getOrElse(
417
+ Arr4.findFirst(R2.toEntries(names), ([, name]) => name === value3),
418
+ () => [value3, value3]
419
+ )[0]
420
+ })
421
+ )
422
+ );
423
+ var optionalNullable = (schema) => Schema3.optional(
424
+ Schema3.NullOr(schema).pipe(
425
+ Schema3.decodeTo(
426
+ Schema3.UndefinedOr(Schema3.toType(schema)),
427
+ // oxlint-disable-next-line effect/prefer-option-over-null -- the payload's own `null`, read as the absent key the SDK's types use.
428
+ SchemaTransformation.transform({
429
+ decode: (value3) => value3 ?? void 0,
430
+ encode: (value3) => value3 ?? null
431
+ })
432
+ )
433
+ )
434
+ );
435
+ var OptionalEpochMillis = Schema3.optional(
436
+ Schema3.Unknown.pipe(
437
+ Schema3.decodeTo(
438
+ Schema3.UndefinedOr(Schema3.Finite),
439
+ // oxlint-disable-next-line effect/prefer-option-over-null -- the payload's own `null`, read as the absent key the SDK's types use.
440
+ SchemaTransformation.transform({
441
+ decode: (value3) => {
442
+ const millis = P3.isString(value3) ? Date.parse(value3) : Number.NaN;
443
+ return Number.isFinite(millis) ? millis : void 0;
444
+ },
445
+ // oxlint-disable-next-line effect/use-clock-service -- formats a timestamp; no clock is read.
446
+ encode: (millis) => millis === void 0 ? null : new Date(millis).toISOString()
447
+ })
448
+ )
449
+ )
450
+ );
451
+ var readableElements = (element) => {
452
+ const decodeElement = Schema3.decodeUnknownOption(element);
453
+ return Schema3.Array(Schema3.Unknown).pipe(
454
+ Schema3.decodeTo(
455
+ Schema3.Array(Schema3.toType(element)),
456
+ SchemaTransformation.transform({
457
+ decode: (items) => Arr4.getSomes(items.map((item) => decodeElement(item))),
458
+ encode: (items) => items
459
+ })
460
+ )
461
+ );
462
+ };
463
+ var listOrEmpty = (element) => readableElements(element).pipe(Schema3.withDecodingDefaultKey(Effect.succeed([])));
464
+ var PriceValue = Schema3.Struct({
465
+ amount: Schema3.Number,
466
+ amountMicros: Schema3.Number,
467
+ currencyCode: Schema3.String,
468
+ formatted: Schema3.String
469
+ });
470
+ var PeriodValue = Schema3.Struct({
471
+ unit: enumOrUnknown(["day", "week", "month", "year"]),
472
+ count: Schema3.Number,
473
+ iso8601: Schema3.String
474
+ });
475
+ var PaymentModeValue = enumOrUnknown(["freeTrial", "payAsYouGo", "payUpFront"]);
476
+ var EnvironmentValue = enumOrUnknown(["production", "sandbox", "xcode", "development"]);
477
+
478
+ // ../react-native/src/core/entities/app-store.ts
479
+ var AppStoreOfferValue = Schema4.Struct({
480
+ id: optionalNullable(Schema4.String),
481
+ type: enumOrUnknown(["introductory", "promotional", "winBack"]),
482
+ paymentMode: PaymentModeValue,
483
+ period: PeriodValue,
484
+ periodCount: Schema4.Number,
485
+ price: PriceValue
486
+ });
487
+ var AppStoreProductJson = Schema4.fromJsonString(
488
+ Schema4.Struct({
489
+ subscriptionGroupId: optionalNullable(Schema4.String),
490
+ subscriptionGroupLevel: optionalNullable(Schema4.Number),
491
+ subscriptionGroupDisplayName: optionalNullable(Schema4.String),
492
+ isFamilyShareable: Schema4.Boolean,
493
+ productType: enumOrUnknown(["consumable", "nonConsumable", "autoRenewable", "nonRenewable"]),
494
+ introductoryOffer: optionalNullable(AppStoreOfferValue),
495
+ promotionalOffers: listOrEmpty(AppStoreOfferValue),
496
+ winBackOffers: listOrEmpty(AppStoreOfferValue),
497
+ isEligibleForIntroOffer: optionalNullable(Schema4.Boolean)
498
+ })
499
+ );
500
+ var AppStoreTransactionJson = Schema4.fromJsonString(
501
+ Schema4.Struct({
502
+ ownershipType: enumOrUnknown(["purchased", "familyShared"]),
503
+ storefrontCountryCode: optionalNullable(Schema4.String),
504
+ isUpgraded: Schema4.Boolean,
505
+ revocationDate: optionalNullable(Schema4.Number),
506
+ revocationReason: optionalNullable(enumOrUnknown(["developerIssue", "other"])),
507
+ appTransactionId: optionalNullable(Schema4.String),
508
+ jwsRepresentation: Schema4.String
509
+ })
510
+ );
511
+ var AppStoreRenewalInfoJson = Schema4.fromJsonString(
512
+ Schema4.Struct({
513
+ willAutoRenew: Schema4.Boolean,
514
+ autoRenewProductId: optionalNullable(Schema4.String),
515
+ expirationReason: optionalNullable(
516
+ enumOrUnknown([
517
+ "autoRenewDisabled",
518
+ "billingError",
519
+ "didNotConsentToPriceIncrease",
520
+ "productUnavailable"
521
+ ])
522
+ ),
523
+ gracePeriodExpiresAt: optionalNullable(Schema4.Number),
524
+ isInBillingRetry: Schema4.Boolean,
525
+ priceIncreaseStatus: optionalNullable(
526
+ enumOrUnknown(["noIncreasePending", "pending", "agreed"])
527
+ ),
528
+ renewalPrice: optionalNullable(PriceValue),
529
+ eligibleWinBackOfferIds: listOrEmpty(Schema4.String)
530
+ })
531
+ );
532
+ var AppTransactionJson = Schema4.fromJsonString(
533
+ Schema4.Struct({
534
+ originalAppVersion: Schema4.String,
535
+ originalPurchaseDate: Schema4.Number,
536
+ environment: EnvironmentValue,
537
+ appTransactionId: optionalNullable(Schema4.String),
538
+ originalPlatform: optionalNullable(enumOrUnknown(["iOS", "macOS", "tvOS", "visionOS"])),
539
+ jwsRepresentation: Schema4.String
540
+ })
541
+ );
542
+ var decodeAppStoreProduct = (json) => Schema4.decodeUnknownOption(AppStoreProductJson)(json);
543
+ var decodeAppStoreTransaction = (json) => Schema4.decodeUnknownOption(AppStoreTransactionJson)(json);
544
+ var decodeAppStoreRenewalInfo = (json) => Schema4.decodeUnknownOption(AppStoreRenewalInfoJson)(json);
545
+ var decodeAppTransaction = (json) => Schema4.decodeUnknownOption(AppTransactionJson)(json);
546
+
547
+ // ../react-native/src/core/entities/person.ts
548
+ import * as Effect2 from "effect/Effect";
549
+ import * as Option5 from "effect/Option";
550
+ import * as Schema5 from "effect/Schema";
551
+ var StoreValue = renamedEnumOrUnknown({
552
+ app_store: "appStore",
553
+ google_play: "googlePlay",
554
+ stripe: "stripe",
555
+ other: "other"
556
+ });
557
+ var withDefault = (schema, value3) => schema.pipe(Schema5.withDecodingDefaultKey(Effect2.succeed(value3)));
558
+ var GrantValue = Schema5.Struct({
559
+ perkId: Schema5.String,
560
+ perkSlug: optionalNullable(Schema5.String),
561
+ status: enumOrUnknown(["active", "expired"]),
562
+ source: withDefault(enumOrUnknown(["subscription", "purchase", "manual"]), "unknown"),
563
+ sourceId: optionalNullable(Schema5.String),
564
+ sourcePersonId: withDefault(Schema5.String, ""),
565
+ expiresAt: OptionalEpochMillis
566
+ });
567
+ var SubscriptionStatusValue = renamedEnumOrUnknown({
568
+ active: "active",
569
+ trialing: "trialing",
570
+ in_grace_period: "inGracePeriod",
571
+ in_billing_retry: "inBillingRetry",
572
+ on_hold: "onHold",
573
+ paused: "paused",
574
+ expired: "expired",
575
+ revoked: "revoked"
576
+ });
577
+ var SubscriptionValue = Schema5.Struct({
578
+ subscriptionId: Schema5.String,
579
+ productId: optionalNullable(Schema5.String),
580
+ productSlug: optionalNullable(Schema5.String),
581
+ store: withDefault(StoreValue, "unknown"),
582
+ environment: withDefault(
583
+ renamedEnumOrUnknown({ production: "production", sandbox: "sandbox", test: "development" }),
584
+ "unknown"
585
+ ),
586
+ status: SubscriptionStatusValue,
587
+ periodType: withDefault(enumOrUnknown(["trial", "intro", "regular"]), "unknown"),
588
+ startsAt: OptionalEpochMillis,
589
+ expiresAt: OptionalEpochMillis,
590
+ willRenew: withDefault(Schema5.Boolean, false),
591
+ canceledAt: OptionalEpochMillis,
592
+ renewsToProductSlug: optionalNullable(Schema5.String),
593
+ gracePeriodExpiresAt: OptionalEpochMillis,
594
+ billingIssueDetectedAt: OptionalEpochMillis,
595
+ resumesAt: OptionalEpochMillis,
596
+ pendingPrice: optionalNullable(
597
+ Schema5.Struct({
598
+ amountMicros: Schema5.Number,
599
+ currency: Schema5.String,
600
+ effectiveAt: OptionalEpochMillis,
601
+ consent: optionalNullable(enumOrUnknown(["pending", "accepted"]))
602
+ })
603
+ ),
604
+ offerId: optionalNullable(Schema5.String),
605
+ isFamilyShared: withDefault(Schema5.Boolean, false),
606
+ refundedAt: OptionalEpochMillis,
607
+ revokedAt: OptionalEpochMillis
608
+ });
609
+ var SubscriptionHistoryEntryValue = Schema5.Struct({
610
+ subscriptionId: Schema5.String,
611
+ productId: optionalNullable(Schema5.String),
612
+ productSlug: optionalNullable(Schema5.String),
613
+ store: withDefault(StoreValue, "unknown"),
614
+ status: SubscriptionStatusValue,
615
+ isTrial: withDefault(Schema5.Boolean, false),
616
+ startsAt: OptionalEpochMillis,
617
+ expiresAt: OptionalEpochMillis,
618
+ canceledAt: OptionalEpochMillis,
619
+ refundedAt: OptionalEpochMillis,
620
+ sourcePersonId: withDefault(Schema5.String, "")
621
+ });
622
+ var PurchaseHistoryEntryValue = Schema5.Struct({
623
+ purchaseId: Schema5.String,
624
+ productId: optionalNullable(Schema5.String),
625
+ productSlug: optionalNullable(Schema5.String),
626
+ providerKey: Schema5.String,
627
+ type: renamedEnumOrUnknown({
628
+ one_time: "oneTime",
629
+ consumable: "consumable",
630
+ subscription: "subscription"
631
+ }),
632
+ createdAt: OptionalEpochMillis,
633
+ refundedAt: OptionalEpochMillis,
634
+ revokedAt: OptionalEpochMillis,
635
+ sourcePersonId: withDefault(Schema5.String, "")
636
+ });
637
+ var decodeCurrentSubscription = Schema5.decodeUnknownOption(SubscriptionValue);
638
+ var PersonJson = Schema5.fromJsonString(
639
+ Schema5.Struct({
640
+ personId: withDefault(Schema5.String, ""),
641
+ distinctId: Schema5.String,
642
+ email: optionalNullable(Schema5.String),
643
+ name: optionalNullable(Schema5.String),
644
+ entitlements: withDefault(Schema5.Struct({ grants: listOrEmpty(GrantValue) }), { grants: [] }),
645
+ subscriptions: withDefault(
646
+ Schema5.Struct({
647
+ current: optionalNullable(Schema5.Unknown),
648
+ all: listOrEmpty(SubscriptionValue),
649
+ history: listOrEmpty(SubscriptionHistoryEntryValue)
650
+ }),
651
+ { all: [], history: [] }
652
+ ),
653
+ purchases: withDefault(Schema5.Struct({ history: listOrEmpty(PurchaseHistoryEntryValue) }), {
654
+ history: []
655
+ })
656
+ })
657
+ );
658
+ var decodePerson = (json) => Option5.map(Schema5.decodeUnknownOption(PersonJson)(json), (wire) => {
659
+ const current = Option5.getOrUndefined(decodeCurrentSubscription(wire.subscriptions.current));
660
+ return {
661
+ ...wire,
662
+ subscriptions: {
663
+ all: wire.subscriptions.all,
664
+ history: wire.subscriptions.history,
665
+ ...current === void 0 ? {} : { current }
666
+ }
667
+ };
668
+ });
669
+
670
+ // ../react-native/src/core/reactivity/client-state.ts
671
+ import * as Arr5 from "effect/Array";
672
+ import * as Option6 from "effect/Option";
673
+ import * as Schema6 from "effect/Schema";
674
+ import * as Str from "effect/String";
675
+ import { Atom } from "effect/reactivity";
676
+ var currentPersonAtom = Atom.keepAlive(
677
+ Atom.make(Option6.none())
678
+ );
679
+ var FRESH_PERSON = { isExpired: false, isStale: false };
680
+ var UNCONFIRMED_PERSON = { isExpired: false, isStale: true };
681
+ var currentPersonFreshnessAtom = Atom.keepAlive(
682
+ Atom.make(FRESH_PERSON)
683
+ );
684
+ var publishCurrentPerson = (registry, person, freshness) => Atom.batch(() => {
685
+ registry.set(currentPersonFreshnessAtom, freshness);
686
+ registry.set(currentPersonAtom, person);
687
+ });
688
+ var schemaAtom = Atom.keepAlive(
689
+ Atom.make(Option6.none())
690
+ );
691
+ var NO_PRODUCTS = {
692
+ error: Option6.none(),
693
+ isLoading: false,
694
+ products: Option6.none()
695
+ };
696
+ var productsAtom = Atom.keepAlive(
697
+ Atom.make(NO_PRODUCTS)
698
+ );
699
+ var featureFlagsByKeyAtom = Atom.keepAlive(Atom.make({}));
700
+ var identityEpochAtom = Atom.keepAlive(Atom.make(0));
701
+ var clientRunAtom = Atom.keepAlive(Atom.make(0));
702
+ var FeatureFlagKeysFromJson = Schema6.fromJsonString(Schema6.Array(Schema6.String));
703
+ var encodeFeatureFlagKeys = Schema6.encodeSync(FeatureFlagKeysFromJson);
704
+ var decodeFeatureFlagKeysFromJson = Schema6.decodeSync(FeatureFlagKeysFromJson);
705
+ var decodeFeatureFlagKeys = (signature) => decodeFeatureFlagKeysFromJson(signature);
706
+ var normalizeFeatureFlagKeys = (flagKeys) => {
707
+ return Option6.match(Option6.fromUndefinedOr(flagKeys), {
708
+ onNone: () => "all",
709
+ onSome: (keys6) => Arr5.match(keys6, {
710
+ onEmpty: () => "all",
711
+ onNonEmpty: (values2) => encodeFeatureFlagKeys(Arr5.sort(values2, Str.Order))
712
+ })
713
+ });
714
+ };
715
+ var featureFlagsForNormalizedKeyAtom = Atom.family(
716
+ (normalizedKey) => Atom.make((get6) => {
717
+ const byKey = get6(featureFlagsByKeyAtom);
718
+ return Option6.fromUndefinedOr(byKey[normalizedKey]);
719
+ })
720
+ );
721
+ var featureFlagsForKeysAtom = (flagKeys) => featureFlagsForNormalizedKeyAtom(normalizeFeatureFlagKeys(flagKeys));
722
+
723
+ // ../react-native/src/core/schema/decode.ts
724
+ import * as Effect4 from "effect/Effect";
725
+ import * as R3 from "effect/Record";
726
+ import * as Schema8 from "effect/Schema";
727
+
728
+ // ../react-native/src/core/schema/runtime.ts
729
+ import * as Effect3 from "effect/Effect";
730
+ import * as Option7 from "effect/Option";
731
+ import * as Schema7 from "effect/Schema";
732
+ var RuntimeProductDuration = Schema7.Literals([
733
+ "weekly",
734
+ "monthly",
735
+ "quarterly",
736
+ "semi-annual",
737
+ "annual"
738
+ ]);
739
+ var RuntimeStoreOffer = Schema7.Struct({
740
+ id: Schema7.String,
741
+ offerId: Schema7.String
742
+ });
743
+ var RuntimeAppleAppStoreProductConfiguration = Schema7.Struct({
744
+ offers: Schema7.optional(Schema7.Array(RuntimeStoreOffer)),
745
+ productId: Schema7.String
746
+ });
747
+ var RuntimeGooglePlayProductConfiguration = Schema7.Struct({
748
+ basePlanId: Schema7.optional(Schema7.String),
749
+ /** Developer offers on the base plan. */
750
+ offers: Schema7.optional(Schema7.Array(RuntimeStoreOffer)),
751
+ productId: Schema7.String
752
+ });
753
+ var RuntimeDevelopmentProductConfiguration = Schema7.Struct({
754
+ currencyCode: Schema7.String,
755
+ duration: Schema7.OptionFromNullOr(Schema7.String),
756
+ period: Schema7.String,
757
+ periodCount: Schema7.Number,
758
+ price: Schema7.Number,
759
+ priceInMinorUnits: Schema7.Number,
760
+ productId: Schema7.String,
761
+ warning: Schema7.OptionFromNullOr(Schema7.String)
762
+ });
763
+ var RuntimeProductProviders = Schema7.Struct({
764
+ appleAppStore: Schema7.optional(RuntimeAppleAppStoreProductConfiguration),
765
+ development: Schema7.optional(RuntimeDevelopmentProductConfiguration),
766
+ googlePlay: Schema7.optional(RuntimeGooglePlayProductConfiguration)
767
+ });
768
+ var RuntimeProductDefinition = Schema7.Struct({
769
+ configuration: Schema7.Struct({
770
+ perks: Schema7.Record(Schema7.String, Schema7.Literal(true)),
771
+ providers: RuntimeProductProviders
772
+ }),
773
+ duration: Schema7.optional(Schema7.OptionFromNullOr(Schema7.String)),
774
+ id: Schema7.optional(Schema7.String),
775
+ properties: Schema7.Struct({ name: Schema7.String }),
776
+ slug: Schema7.String,
777
+ type: Schema7.String
778
+ });
779
+ var RuntimePaywallLocationDefinition = Schema7.Struct({
780
+ description: Schema7.OptionFromNullOr(Schema7.String).pipe(
781
+ Schema7.withDecodingDefaultTypeKey(Effect3.succeed(Option7.none()))
782
+ ),
783
+ name: Schema7.String,
784
+ slug: Schema7.String
785
+ });
786
+ var RuntimePerkDefinition = Schema7.Struct({
787
+ name: Schema7.String,
788
+ slug: Schema7.String
789
+ });
790
+ var RuntimeSchemaValue = Schema7.Struct({
791
+ locations: Schema7.Record(Schema7.String, RuntimePaywallLocationDefinition),
792
+ perks: Schema7.Record(Schema7.String, RuntimePerkDefinition),
793
+ products: Schema7.Record(Schema7.String, RuntimeProductDefinition),
794
+ version: Schema7.String
795
+ });
796
+ var createEmptyRuntimeSchema = () => ({
797
+ locations: {},
798
+ perks: {},
799
+ products: {},
800
+ version: ""
801
+ });
802
+
803
+ // ../react-native/src/core/schema/decode.ts
804
+ var decodeLocation = Schema8.decodeUnknownResult(RuntimePaywallLocationDefinition);
805
+ var decodePerk = Schema8.decodeUnknownResult(RuntimePerkDefinition);
806
+ var decodeProduct = Schema8.decodeUnknownResult(RuntimeProductDefinition);
807
+ var RuntimeSchemaDocument = Schema8.Struct({
808
+ locations: Schema8.Record(Schema8.String, Schema8.Unknown),
809
+ // The native iOS client's schema has no perks of its own; they are read from each product.
810
+ perks: Schema8.optional(Schema8.Record(Schema8.String, Schema8.Unknown)),
811
+ products: Schema8.Record(Schema8.String, Schema8.Unknown),
812
+ version: Schema8.String
813
+ });
814
+ var decodeRuntimeSchema = (input) => Effect4.map(Schema8.decodeUnknownEffect(RuntimeSchemaDocument)(input), (document) => {
815
+ const [locations, unreadableLocations] = R3.partition(
816
+ document.locations,
817
+ (entry) => decodeLocation(entry)
818
+ );
819
+ const [perks, unreadablePerks] = R3.partition(
820
+ document.perks ?? {},
821
+ (entry) => decodePerk(entry)
822
+ );
823
+ const [products, unreadableProducts] = R3.partition(
824
+ document.products,
825
+ (entry) => decodeProduct(entry)
826
+ );
827
+ const skipped = [
828
+ ...R3.keys(unreadableLocations).map((slug) => ({ collection: "locations", slug })),
829
+ ...R3.keys(unreadablePerks).map((slug) => ({ collection: "perks", slug })),
830
+ ...R3.keys(unreadableProducts).map((slug) => ({ collection: "products", slug }))
831
+ ];
832
+ const schema = { locations, perks, products, version: document.version };
833
+ return { schema, skipped };
834
+ });
835
+
836
+ // ../react-native/src/core/sdk-configuration.ts
837
+ var isAnalyticsConsent = (value3) => value3 === "granted" || value3 === "denied" || value3 === "pending";
838
+
839
+ // ../react-native/src/core/utils/native-error.ts
840
+ import * as Option8 from "effect/Option";
841
+ import * as P4 from "effect/Predicate";
842
+ var CODE = /^[A-Z][A-Z0-9_]*$/;
843
+ var LABEL = /^`?([A-Za-z_$][\w$.]*(?:\(\.\.\.\))?)`?:(?:\s+([\s\S]*))?$/;
844
+ var MAX_LABELS = 3;
845
+ var readNativeError = (error) => {
846
+ const raw = P4.isError(error) ? error.message : P4.isString(error) ? error : String(error);
847
+ const firstLine = (raw.split(/\r?\n/, 1)[0] ?? "").trim();
848
+ const findCode = (message, depth) => {
849
+ if (CODE.test(message)) return Option8.some({ code: Option8.some(message), message });
850
+ const label = LABEL.exec(message);
851
+ if (label === null) return Option8.none();
852
+ const [, name = "", rest = ""] = label;
853
+ if (CODE.test(name)) return Option8.some({ code: Option8.some(name), message });
854
+ return depth < MAX_LABELS ? findCode(rest, depth + 1) : Option8.none();
855
+ };
856
+ return Option8.getOrElse(findCode(firstLine, 0), () => ({
857
+ code: Option8.none(),
858
+ message: firstLine
859
+ }));
860
+ };
861
+
862
+ // ../react-native/src/core/native/billing.ts
863
+ import * as Match from "effect/Match";
864
+ import * as Option9 from "effect/Option";
865
+
866
+ // ../react-native/src/core/entities/google-play.ts
867
+ import * as Effect5 from "effect/Effect";
868
+ import * as Schema9 from "effect/Schema";
869
+ var GooglePlaySubscriptionOfferValue = Schema9.Struct({
870
+ basePlanId: Schema9.String,
871
+ offerId: optionalNullable(Schema9.String),
872
+ offerToken: Schema9.String,
873
+ offerTags: listOrEmpty(Schema9.String),
874
+ pricingPhases: listOrEmpty(
875
+ Schema9.Struct({
876
+ formattedPrice: Schema9.String,
877
+ priceAmountMicros: Schema9.Number,
878
+ priceCurrencyCode: Schema9.String,
879
+ billingPeriod: Schema9.String,
880
+ billingCycleCount: Schema9.Number,
881
+ recurrenceMode: enumOrUnknown(["infinite", "finite", "nonRecurring"])
882
+ })
883
+ ),
884
+ installmentPlan: optionalNullable(
885
+ Schema9.Struct({
886
+ commitmentPaymentsCount: Schema9.Number,
887
+ subsequentCommitmentPaymentsCount: Schema9.Number
888
+ })
889
+ )
890
+ });
891
+ var GooglePlayOneTimeOfferValue = Schema9.Struct({
892
+ purchaseOptionId: optionalNullable(Schema9.String),
893
+ offerId: optionalNullable(Schema9.String),
894
+ offerToken: Schema9.String,
895
+ offerTags: listOrEmpty(Schema9.String),
896
+ price: PriceValue,
897
+ fullPrice: optionalNullable(PriceValue),
898
+ discountPercentage: optionalNullable(Schema9.Number),
899
+ limitedQuantity: optionalNullable(
900
+ Schema9.Struct({ maximumQuantity: Schema9.Number, remainingQuantity: Schema9.Number })
901
+ ),
902
+ validTimeWindow: optionalNullable(
903
+ Schema9.Struct({
904
+ startTimeMillis: optionalNullable(Schema9.Number),
905
+ endTimeMillis: optionalNullable(Schema9.Number)
906
+ })
907
+ ),
908
+ preorder: optionalNullable(
909
+ Schema9.Struct({ releaseTimeMillis: Schema9.Number, presaleEndTimeMillis: Schema9.Number })
910
+ ),
911
+ rental: optionalNullable(
912
+ Schema9.Struct({
913
+ rentalPeriod: Schema9.String,
914
+ rentalExpirationPeriod: optionalNullable(Schema9.String)
915
+ })
916
+ )
917
+ });
918
+ var GooglePlayProductJson = Schema9.fromJsonString(
919
+ Schema9.Struct({
920
+ productId: Schema9.String,
921
+ productType: enumOrUnknown(["subs", "inapp"]),
922
+ basePlanId: optionalNullable(Schema9.String),
923
+ subscriptionOffers: listOrEmpty(GooglePlaySubscriptionOfferValue),
924
+ oneTimeOffers: listOrEmpty(GooglePlayOneTimeOfferValue)
925
+ })
926
+ );
927
+ var GooglePlayTransactionJson = Schema9.fromJsonString(
928
+ Schema9.Struct({
929
+ orderId: optionalNullable(Schema9.String),
930
+ purchaseToken: Schema9.String,
931
+ productIds: listOrEmpty(Schema9.String),
932
+ purchaseState: enumOrUnknown(["purchased", "pending"]),
933
+ isAcknowledged: Schema9.Boolean,
934
+ isAutoRenewing: optionalNullable(Schema9.Boolean),
935
+ obfuscatedAccountId: optionalNullable(Schema9.String),
936
+ obfuscatedProfileId: optionalNullable(Schema9.String),
937
+ isSuspended: Schema9.Boolean.pipe(Schema9.withDecodingDefaultKey(Effect5.succeed(false)))
938
+ })
939
+ );
940
+ var decodeGooglePlayProduct = (json) => Schema9.decodeUnknownOption(GooglePlayProductJson)(json);
941
+ var decodeGooglePlayTransaction = (json) => Schema9.decodeUnknownOption(GooglePlayTransactionJson)(json);
942
+
943
+ // ../react-native/src/core/native/billing.ts
944
+ var decodePart = (json, decode, onUnreadable) => Option9.flatMap(Option9.fromUndefinedOr(json), (value3) => {
945
+ const decoded = decode(value3);
946
+ if (Option9.isNone(decoded)) onUnreadable();
947
+ return decoded;
948
+ });
949
+ var toProduct = (native, violation) => {
950
+ const appStore = decodePart(
951
+ native.appStoreJson,
952
+ decodeAppStoreProduct,
953
+ () => violation(`The App Store part of product "${native.slug}" could not be read`)
954
+ );
955
+ const googlePlay = decodePart(
956
+ native.googlePlayJson,
957
+ decodeGooglePlayProduct,
958
+ () => violation(`The Google Play part of product "${native.slug}" could not be read`)
959
+ );
960
+ const fields = {
961
+ description: native.description,
962
+ displayName: native.displayName,
963
+ name: native.name,
964
+ offers: native.offers,
965
+ price: native.price,
966
+ productId: native.productId,
967
+ slug: native.slug,
968
+ store: native.store,
969
+ storeProductId: native.storeProductId,
970
+ ...Option9.match(appStore, { onNone: () => ({}), onSome: (part) => ({ appStore: part }) }),
971
+ ...Option9.match(googlePlay, { onNone: () => ({}), onSome: (part) => ({ googlePlay: part }) })
972
+ };
973
+ return Match.value(native.type).pipe(
974
+ Match.withReturnType(),
975
+ Match.when("subscription", () => {
976
+ if (native.subscription !== void 0) {
977
+ return Option9.some({ ...fields, subscription: native.subscription, type: "subscription" });
978
+ }
979
+ violation(
980
+ `Subscription product "${native.slug}" came without its subscription info and is left out`
981
+ );
982
+ return Option9.none();
983
+ }),
984
+ Match.when("consumable", (type) => Option9.some({ ...fields, type })),
985
+ Match.when("nonConsumable", (type) => Option9.some({ ...fields, type })),
986
+ Match.when("nonRenewingSubscription", (type) => Option9.some({ ...fields, type })),
987
+ Match.when(
988
+ "unknown",
989
+ () => Option9.some(
990
+ native.subscription === void 0 ? { ...fields, type: "unknown" } : { ...fields, subscription: native.subscription, type: "unknown" }
991
+ )
992
+ ),
993
+ Match.exhaustive
994
+ );
995
+ };
996
+ var toTransaction = (native, violation) => {
997
+ const appStore = decodePart(
998
+ native.appStoreJson,
999
+ decodeAppStoreTransaction,
1000
+ () => violation(`The App Store part of transaction ${native.id} could not be read`)
1001
+ );
1002
+ const googlePlay = decodePart(
1003
+ native.googlePlayJson,
1004
+ decodeGooglePlayTransaction,
1005
+ () => violation(`The Google Play part of transaction ${native.id} could not be read`)
1006
+ );
1007
+ return {
1008
+ environment: native.environment,
1009
+ id: native.id,
1010
+ purchasedAt: native.purchasedAt,
1011
+ quantity: native.quantity,
1012
+ store: native.store,
1013
+ storeProductId: native.storeProductId,
1014
+ ...native.originalId === void 0 ? {} : { originalId: native.originalId },
1015
+ ...native.productSlug === void 0 ? {} : { productSlug: native.productSlug },
1016
+ ...native.expiresAt === void 0 ? {} : { expiresAt: native.expiresAt },
1017
+ ...native.isRenewal === void 0 ? {} : { isRenewal: native.isRenewal },
1018
+ ...native.offer === void 0 ? {} : { offer: native.offer },
1019
+ ...Option9.match(appStore, { onNone: () => ({}), onSome: (part) => ({ appStore: part }) }),
1020
+ ...Option9.match(googlePlay, { onNone: () => ({}), onSome: (part) => ({ googlePlay: part }) })
1021
+ };
1022
+ };
1023
+ var toPurchaseResult = (native, violation) => Match.value(native.outcome).pipe(
1024
+ Match.withReturnType(),
1025
+ Match.when(
1026
+ "purchased",
1027
+ () => Option9.map(Option9.fromUndefinedOr(native.transaction), (transaction) => ({
1028
+ status: "purchased",
1029
+ synced: native.synced ?? false,
1030
+ transaction: toTransaction(transaction, violation)
1031
+ }))
1032
+ ),
1033
+ Match.when("pending", () => Option9.some({ status: "pending" })),
1034
+ Match.when("cancelled", () => Option9.some({ status: "cancelled" })),
1035
+ Match.exhaustive
1036
+ );
1037
+
1038
+ // ../react-native/src/core/native/native-client.ts
1039
+ var NATIVE_CONTRACT_VERSION = 1;
1040
+ var contractVersionOf = (native) => {
1041
+ const version2 = EffectResult.try(
1042
+ () => P5.isFunction(Reflect.get(native, "contractVersion")) ? native.contractVersion() : 0
1043
+ );
1044
+ return EffectResult.isSuccess(version2) && P5.isNumber(version2.success) ? version2.success : 0;
1045
+ };
1046
+ var NOT_STARTED_CODES = ["NOT_INITIALIZED", "NOT_CONFIGURED"];
1047
+ var toVoidhashError = (error, codes) => {
1048
+ if (error instanceof VoidhashError) return error;
1049
+ const native = readNativeError(error);
1050
+ const code = Option10.getOrElse(native.code, () => "");
1051
+ if ((codes.notStarted ?? true) && NOT_STARTED_CODES.includes(code)) {
1052
+ return new NotInitializedError();
1053
+ }
1054
+ const passing = Arr6.findFirst(codes.passThrough ?? [], (known) => known === code);
1055
+ return Option10.match(passing, {
1056
+ onNone: () => new VoidhashError(codes.fallback, `${codes.fallback}: ${native.message}`, { cause: error }),
1057
+ onSome: (known) => new VoidhashError(known, native.message, { cause: error })
1058
+ });
1059
+ };
1060
+ var FAILURES = {
1061
+ appStoreAppTransaction: {
1062
+ fallback: "FAILED_TO_GET_APP_TRANSACTION",
1063
+ passThrough: ["UNSUPPORTED_PLATFORM"]
1064
+ },
1065
+ appStoreBeginRefundRequest: {
1066
+ fallback: "FAILED_TO_BEGIN_REFUND_REQUEST",
1067
+ passThrough: ["INVALID_ARGUMENT", "UNSUPPORTED_PLATFORM"]
1068
+ },
1069
+ appStoreCurrentEntitlements: {
1070
+ fallback: "FAILED_TO_GET_CURRENT_ENTITLEMENTS",
1071
+ passThrough: ["UNSUPPORTED_PLATFORM"]
1072
+ },
1073
+ appStoreSubscriptionStatus: {
1074
+ fallback: "FAILED_TO_GET_SUBSCRIPTION_STATUS",
1075
+ passThrough: ["UNSUPPORTED_PLATFORM"]
1076
+ },
1077
+ canMakePayments: { fallback: "FAILED_TO_CHECK_CAN_MAKE_PAYMENTS" },
1078
+ dismissFlow: { fallback: "FLOW_PRESENTATION_FAILED" },
1079
+ updateFlowInput: { fallback: "FLOW_PRESENTATION_FAILED" },
1080
+ flush: { fallback: "FAILED_TO_FLUSH_ANALYTICS" },
1081
+ getCurrentPerson: {
1082
+ fallback: "FAILED_TO_GET_CURRENT_PERSON",
1083
+ passThrough: ["AUTHENTICATION_FAILED"]
1084
+ },
1085
+ getDistinctId: { fallback: "FAILED_TO_GET_DISTINCT_ID" },
1086
+ getFeatureFlags: {
1087
+ fallback: "FAILED_TO_GET_FEATURE_FLAGS",
1088
+ passThrough: ["AUTHENTICATION_FAILED"]
1089
+ },
1090
+ getPaywallForLocation: {
1091
+ fallback: "FAILED_TO_GET_PAYWALL_FOR_LOCATION",
1092
+ passThrough: ["AUTHENTICATION_FAILED", "PAYWALL_UNAVAILABLE"]
1093
+ },
1094
+ getProducts: { fallback: "FAILED_TO_GET_PRODUCTS" },
1095
+ getStorefront: { fallback: "FAILED_TO_GET_STOREFRONT" },
1096
+ googlePlayIsFeatureSupported: {
1097
+ fallback: "FAILED_TO_CHECK_FEATURE_SUPPORT",
1098
+ passThrough: ["INVALID_ARGUMENT", "UNSUPPORTED_PLATFORM"]
1099
+ },
1100
+ googlePlayQueryPurchases: {
1101
+ fallback: "FAILED_TO_QUERY_PURCHASES",
1102
+ passThrough: ["UNSUPPORTED_PLATFORM"]
1103
+ },
1104
+ googlePlayShowInAppMessages: {
1105
+ fallback: "FAILED_TO_SHOW_IN_APP_MESSAGES",
1106
+ passThrough: ["UNSUPPORTED_PLATFORM"]
1107
+ },
1108
+ group: { fallback: "FAILED_TO_SET_GROUP", passThrough: ["INVALID_ARGUMENT"] },
1109
+ setGroups: { fallback: "FAILED_TO_SET_GROUP", passThrough: ["INVALID_ARGUMENT"] },
1110
+ identify: { fallback: "FAILED_TO_IDENTIFY", passThrough: ["INVALID_ARGUMENT"] },
1111
+ presentCodeRedemption: { fallback: "FAILED_TO_PRESENT_CODE_REDEMPTION" },
1112
+ purchase: {
1113
+ fallback: "FAILED_TO_PURCHASE",
1114
+ passThrough: [
1115
+ "INVALID_ARGUMENT",
1116
+ "OFFER_UNAVAILABLE",
1117
+ "PURCHASE_IN_PROGRESS",
1118
+ "READ_ONLY_PURCHASE_NOT_ALLOWED",
1119
+ "REPLACED_SUBSCRIPTION_NOT_OWNED",
1120
+ "SUBSCRIPTION_REPLACEMENT_REFUSED"
1121
+ ]
1122
+ },
1123
+ reportTransaction: { fallback: "FAILED_TO_REPORT_TRANSACTION" },
1124
+ reset: { fallback: "FAILED_TO_RESET" },
1125
+ resetCache: { fallback: "FAILED_TO_RESET_PERSON_CACHE" },
1126
+ resetGroups: { fallback: "FAILED_TO_RESET_GROUPS" },
1127
+ restorePurchases: { fallback: "FAILED_TO_RESTORE_PURCHASES" },
1128
+ setAnalyticsConsent: { fallback: "FAILED_TO_SET_ANALYTICS_CONSENT" },
1129
+ setPersonAttributes: {
1130
+ fallback: "FAILED_TO_SET_PERSON_ATTRIBUTES",
1131
+ passThrough: ["INVALID_ARGUMENT"]
1132
+ },
1133
+ setPersonAttributesSync: {
1134
+ fallback: "FAILED_TO_SET_PERSON_ATTRIBUTES_SYNC",
1135
+ passThrough: ["INVALID_ARGUMENT", "READ_ONLY_PURCHASE_NOT_ALLOWED"]
1136
+ },
1137
+ showManageSubscriptions: { fallback: "FAILED_TO_SHOW_MANAGE_SUBSCRIPTIONS" },
1138
+ shutdown: { fallback: "FAILED_TO_END_VOIDHASH_CLIENT" },
1139
+ signOut: { fallback: "FAILED_TO_SIGN_OUT" },
1140
+ start: { fallback: "FAILED_TO_INITIALIZE_VOIDHASH_CLIENT", notStarted: false },
1141
+ syncPurchases: { fallback: "FAILED_TO_SYNC_PURCHASES" }
1142
+ };
1143
+ var call = async (codes, run) => {
1144
+ const exit2 = await Effect6.runPromiseExit(
1145
+ Effect6.tryPromise({ catch: (error) => error, try: () => run() })
1146
+ );
1147
+ return Exit.isSuccess(exit2) ? Result4.ok(exit2.value) : Result4.err(toVoidhashError(Cause.squash(exit2.cause), codes));
1148
+ };
1149
+ var PURCHASE_FAILURE_REASONS = {
1150
+ INELIGIBLE_FOR_OFFER: "ineligibleForOffer",
1151
+ PAYMENT_DECLINED: "paymentDeclined"
1152
+ };
1153
+ var decodeJson2 = Schema10.decodeUnknownResult(Schema10.fromJsonString(Schema10.Unknown));
1154
+ var encodeJson = Schema10.encodeUnknownResult(Schema10.fromJsonString(Schema10.Unknown));
1155
+ var PaywallValue = Schema10.declare(
1156
+ (value3) => value3 === null || P5.isObject(value3)
1157
+ );
1158
+ var decodePaywall = Schema10.decodeUnknownResult(PaywallValue);
1159
+ var personOf = (payload) => Option10.flatMap(Option10.fromUndefinedOr(payload.personJson), decodePerson);
1160
+ var REASONS = {
1161
+ fresh: "fresh",
1162
+ noCache: "no-cache",
1163
+ refreshFailed: "refresh-failed",
1164
+ refreshInFlight: "refresh-in-flight"
1165
+ };
1166
+ var toCurrentPerson = (state) => ({
1167
+ isExpired: state.isExpired,
1168
+ isStale: state.isStale,
1169
+ person: Option10.getOrNull(personOf(state)),
1170
+ reason: REASONS[state.reason]
1171
+ });
1172
+ var toFlag = (flag) => ({
1173
+ enabled: flag.enabled,
1174
+ key: flag.key,
1175
+ payload: Option10.getOrNull(
1176
+ Option10.flatMap(
1177
+ Option10.fromUndefinedOr(flag.payloadJson),
1178
+ (json) => EffectResult.getSuccess(decodeJson2(json))
1179
+ )
1180
+ ),
1181
+ variantKey: flag.variantKey ?? null
1182
+ });
1183
+ var toFlags = (result) => ({
1184
+ flags: result.flags.map(toFlag),
1185
+ isStale: result.isStale
1186
+ });
1187
+ var toDiagnostic = (diagnostic) => ({
1188
+ code: diagnostic.code,
1189
+ kind: diagnostic.kind,
1190
+ operation: diagnostic.operation,
1191
+ retryable: diagnostic.retryable,
1192
+ ...diagnostic.httpStatus === void 0 ? {} : { httpStatus: diagnostic.httpStatus },
1193
+ ...diagnostic.message === void 0 ? {} : { message: diagnostic.message }
1194
+ });
1195
+ var toFlushResult = (status) => ({
1196
+ flushed: status.flushed,
1197
+ pending: status.pending,
1198
+ ...status.lastErrorMessage === void 0 ? {} : {
1199
+ lastError: new VoidhashError(
1200
+ "FAILED_TO_FLUSH_ANALYTICS",
1201
+ `FAILED_TO_FLUSH_ANALYTICS: ${status.lastErrorMessage}`
1202
+ )
1203
+ }
1204
+ });
1205
+ var FlowValuesFromJson = Schema10.fromJsonString(
1206
+ Schema10.Record(
1207
+ Schema10.String,
1208
+ Schema10.Union([Schema10.String, Schema10.Number, Schema10.Boolean, Schema10.Array(Schema10.String)])
1209
+ )
1210
+ );
1211
+ var decodeFlowValues = Schema10.decodeUnknownSync(FlowValuesFromJson);
1212
+ var encodeFlowValues = Schema10.encodeSync(FlowValuesFromJson);
1213
+ var isFlowErrorCode = (code) => code.startsWith("FLOW_") && VOIDHASH_ERROR_CODES.some((known) => known === code);
1214
+ var makeNativeClientAdapter = (options) => {
1215
+ const { atomRegistry, native } = options;
1216
+ const currentIdentity = MutableRef.make(Option10.none());
1217
+ const publishedGeneration = MutableRef.make(-1);
1218
+ const listening = MutableRef.make(false);
1219
+ const productsRevision = MutableRef.make(0);
1220
+ const productsLoad = MutableRef.make(
1221
+ Option10.none()
1222
+ );
1223
+ const scheduledReload = MutableRef.make(Option10.none());
1224
+ const productDefinitions = MutableRef.make("");
1225
+ const report = (diagnostic) => {
1226
+ EffectResult.try(() => options.onDiagnostic(diagnostic));
1227
+ };
1228
+ const cancelScheduledReload = () => {
1229
+ Option10.map(MutableRef.get(scheduledReload), clearTimeout);
1230
+ MutableRef.set(scheduledReload, Option10.none());
1231
+ };
1232
+ const loadProducts = () => {
1233
+ const revision = MutableRef.get(productsRevision);
1234
+ const running = MutableRef.get(productsLoad);
1235
+ if (Option10.isSome(running) && running.value.revision === revision) {
1236
+ return running.value.settled;
1237
+ }
1238
+ cancelScheduledReload();
1239
+ atomRegistry.update(productsAtom, (state) => ({ ...state, isLoading: true }));
1240
+ const settled = call(
1241
+ FAILURES.getProducts,
1242
+ async () => Arr6.getSomes(
1243
+ (await native.getProducts()).map(
1244
+ (product) => toProduct(product, (message) => reportContractViolation("getProducts", message))
1245
+ )
1246
+ )
1247
+ ).then((products) => {
1248
+ const isCurrent2 = MutableRef.get(productsRevision) === revision;
1249
+ if (Option10.exists(MutableRef.get(productsLoad), (load) => load.settled === settled)) {
1250
+ MutableRef.set(productsLoad, Option10.none());
1251
+ }
1252
+ if (isCurrent2) {
1253
+ atomRegistry.update(
1254
+ productsAtom,
1255
+ (state) => products.isOk() ? { error: Option10.none(), isLoading: false, products: Option10.some(products.value) } : { ...state, error: Option10.some(products.error), isLoading: false }
1256
+ );
1257
+ } else if (Option10.isNone(MutableRef.get(productsLoad)) && Option10.isNone(MutableRef.get(scheduledReload))) {
1258
+ atomRegistry.update(productsAtom, (state) => ({ ...state, isLoading: false }));
1259
+ }
1260
+ return products;
1261
+ });
1262
+ MutableRef.set(productsLoad, Option10.some({ revision, settled }));
1263
+ return settled;
1264
+ };
1265
+ const invalidateProducts = () => {
1266
+ MutableRef.update(productsRevision, (revision) => revision + 1);
1267
+ if (Option10.isSome(MutableRef.get(scheduledReload))) return;
1268
+ const state = atomRegistry.get(productsAtom);
1269
+ if (Option10.isNone(state.products) && Option10.isNone(state.error) && !state.isLoading) return;
1270
+ MutableRef.set(
1271
+ scheduledReload,
1272
+ Option10.some(
1273
+ setTimeout(() => {
1274
+ MutableRef.set(scheduledReload, Option10.none());
1275
+ void loadProducts();
1276
+ }, 0)
1277
+ )
1278
+ );
1279
+ };
1280
+ const isCurrent = (generation) => Option10.exists(
1281
+ MutableRef.get(currentIdentity),
1282
+ (identity) => identity.generation === generation
1283
+ );
1284
+ const publishPerson = (state) => {
1285
+ if (!isCurrent(state.generation)) return;
1286
+ MutableRef.set(publishedGeneration, state.generation);
1287
+ publishCurrentPerson(atomRegistry, personOf(state), {
1288
+ isExpired: state.isExpired,
1289
+ isStale: state.isStale
1290
+ });
1291
+ };
1292
+ const publishFlags = (result, signature) => {
1293
+ if (!isCurrent(result.generation)) return;
1294
+ MutableRef.set(publishedGeneration, result.generation);
1295
+ atomRegistry.update(featureFlagsByKeyAtom, (current) => ({
1296
+ ...current,
1297
+ [signature]: toFlags(result)
1298
+ }));
1299
+ };
1300
+ const adoptIdentity = (change) => {
1301
+ if (Option10.exists(
1302
+ MutableRef.get(currentIdentity),
1303
+ (current) => current.generation >= change.generation
1304
+ )) {
1305
+ return;
1306
+ }
1307
+ MutableRef.set(currentIdentity, Option10.some(change));
1308
+ options.onIdentitySwitched?.();
1309
+ Atom2.batch(() => {
1310
+ atomRegistry.set(featureFlagsByKeyAtom, {});
1311
+ publishCurrentPerson(atomRegistry, Option10.none(), UNCONFIRMED_PERSON);
1312
+ atomRegistry.update(identityEpochAtom, (switches) => switches + 1);
1313
+ });
1314
+ invalidateProducts();
1315
+ };
1316
+ const reportContractViolation = (operation, message) => report({
1317
+ code: "BACKGROUND_TASK_FAILED",
1318
+ kind: "configuration",
1319
+ message,
1320
+ operation,
1321
+ retryable: false
1322
+ });
1323
+ const publishSchema = (schemaJson) => {
1324
+ const decoded = EffectResult.flatMap(decodeJson2(schemaJson), (document) => {
1325
+ const exit2 = Effect6.runSyncExit(decodeRuntimeSchema(document));
1326
+ return Exit.isSuccess(exit2) ? EffectResult.succeed(exit2.value.schema) : EffectResult.fail(Cause.squash(exit2.cause));
1327
+ });
1328
+ if (EffectResult.isSuccess(decoded)) {
1329
+ atomRegistry.set(schemaAtom, Option10.some(decoded.success));
1330
+ const definitions = EffectResult.getOrElse(encodeJson(decoded.success.products), () => "");
1331
+ if (definitions !== MutableRef.get(productDefinitions)) {
1332
+ MutableRef.set(productDefinitions, definitions);
1333
+ invalidateProducts();
1334
+ }
1335
+ return;
1336
+ }
1337
+ reportContractViolation("getSchema", "The native client sent a schema this SDK cannot read");
1338
+ };
1339
+ const routeEvent = (event) => Match2.value(event.type).pipe(
1340
+ Match2.when(
1341
+ "identity",
1342
+ () => Option10.map(Option10.fromUndefinedOr(event.identity), adoptIdentity)
1343
+ ),
1344
+ Match2.when("person", () => Option10.map(Option10.fromUndefinedOr(event.person), publishPerson)),
1345
+ Match2.when(
1346
+ "flags",
1347
+ () => Option10.map(
1348
+ Option10.fromUndefinedOr(event.flags),
1349
+ (flags) => publishFlags(flags, normalizeFeatureFlagKeys(flags.flagKeys))
1350
+ )
1351
+ ),
1352
+ Match2.when(
1353
+ "schema",
1354
+ () => Option10.map(Option10.fromUndefinedOr(event.schemaJson), publishSchema)
1355
+ ),
1356
+ Match2.when(
1357
+ "consent",
1358
+ () => Option10.map(
1359
+ Option10.fromUndefinedOr(event.consent),
1360
+ (consent) => options.onAnalyticsConsentChanged?.(consent)
1361
+ )
1362
+ ),
1363
+ Match2.when(
1364
+ "diagnostic",
1365
+ () => Option10.map(
1366
+ Option10.fromUndefinedOr(event.diagnostic),
1367
+ (diagnostic) => report(toDiagnostic(diagnostic))
1368
+ )
1369
+ ),
1370
+ Match2.when(
1371
+ "transaction",
1372
+ () => Option10.map(Option10.fromUndefinedOr(event.transaction), (update2) => {
1373
+ if (update2.transaction.isRenewal !== true) invalidateProducts();
1374
+ options.onTransaction?.({
1375
+ synced: update2.synced,
1376
+ transaction: toTransaction(
1377
+ update2.transaction,
1378
+ (message) => reportContractViolation("transactionUpdates", message)
1379
+ )
1380
+ });
1381
+ })
1382
+ ),
1383
+ Match2.when(
1384
+ "purchaseIntent",
1385
+ () => Option10.map(
1386
+ Option10.fromUndefinedOr(event.purchaseIntent),
1387
+ (intent) => options.onPurchaseIntent?.({
1388
+ productSlug: intent.productSlug,
1389
+ ...intent.offer === void 0 ? {} : { offer: intent.offer }
1390
+ })
1391
+ )
1392
+ ),
1393
+ Match2.exhaustive
1394
+ );
1395
+ const handleEvent = (event) => {
1396
+ if (!MutableRef.get(listening)) return;
1397
+ const handled = EffectResult.try(() => routeEvent(event));
1398
+ if (EffectResult.isFailure(handled)) {
1399
+ report({
1400
+ code: "BACKGROUND_TASK_FAILED",
1401
+ kind: "configuration",
1402
+ message: `Handling a native ${event.type} event failed: ${String(handled.failure)}`,
1403
+ operation: "nativeEvent",
1404
+ retryable: false
1405
+ });
1406
+ }
1407
+ };
1408
+ const reportThrow = (operation, error) => report({
1409
+ code: "BACKGROUND_TASK_FAILED",
1410
+ kind: "configuration",
1411
+ message: `${operation} failed: ${readNativeError(error).message}`,
1412
+ operation,
1413
+ retryable: false
1414
+ });
1415
+ const trySync = (operation, run) => {
1416
+ const ran = EffectResult.try(run);
1417
+ if (EffectResult.isSuccess(ran)) return Option10.some(ran.success);
1418
+ reportThrow(operation, ran.failure);
1419
+ return Option10.none();
1420
+ };
1421
+ const stopListening = () => {
1422
+ MutableRef.set(listening, false);
1423
+ trySync("removeEventListener", () => native.removeEventListener());
1424
+ };
1425
+ const readPerson = (forceFetch) => call(FAILURES.getCurrentPerson, async () => {
1426
+ const state = await native.getPersonState(forceFetch);
1427
+ publishPerson(state);
1428
+ return state;
1429
+ });
1430
+ const switchIdentity = async (externalUserId, profile) => {
1431
+ const before = MutableRef.get(currentIdentity);
1432
+ const held = {
1433
+ flags: atomRegistry.get(featureFlagsByKeyAtom),
1434
+ freshness: atomRegistry.get(currentPersonFreshnessAtom),
1435
+ person: atomRegistry.get(currentPersonAtom)
1436
+ };
1437
+ const result = await call(
1438
+ FAILURES.identify,
1439
+ () => native.identify(externalUserId, profile.email, profile.name)
1440
+ );
1441
+ if (result.isOk()) {
1442
+ adoptIdentity(result.value.identity);
1443
+ return result;
1444
+ }
1445
+ const after = MutableRef.get(currentIdentity);
1446
+ const restored = Option10.isSome(before) && Option10.isSome(after) && after.value.distinctId === before.value.distinctId && after.value.generation > before.value.generation && MutableRef.get(publishedGeneration) <= before.value.generation;
1447
+ if (restored) {
1448
+ Atom2.batch(() => {
1449
+ atomRegistry.set(featureFlagsByKeyAtom, held.flags);
1450
+ publishCurrentPerson(atomRegistry, held.person, held.freshness);
1451
+ });
1452
+ }
1453
+ return result;
1454
+ };
1455
+ const switchToAnonymous = async (codes, run) => (await call(codes, run)).map((identity) => {
1456
+ adoptIdentity(identity);
1457
+ return void 0;
1458
+ });
1459
+ const toAttributesResult = (result) => {
1460
+ const person = personOf(result);
1461
+ if (result.status === "skipped") return { person: null, status: "skipped" };
1462
+ return result.status === "confirmed" && Option10.isSome(person) ? { person: person.value, status: "confirmed" } : { person: Option10.getOrNull(person), status: "deferred" };
1463
+ };
1464
+ const encodeAttributes = (attributes) => Option10.match(EffectResult.getSuccess(encodeJson(attributes)), {
1465
+ onNone: () => Result4.err(
1466
+ new VoidhashError(
1467
+ "INVALID_ARGUMENT",
1468
+ "INVALID_ARGUMENT: person attributes must be values JSON can hold"
1469
+ )
1470
+ ),
1471
+ onSome: (json) => Result4.ok(json)
1472
+ });
1473
+ const encodeEvent = (operation, name, properties) => {
1474
+ const json = EffectResult.flatMap(
1475
+ toJsonSafeProperties(properties),
1476
+ (copied) => Option10.match(EffectResult.getSuccess(encodeJson(copied)), {
1477
+ onNone: () => EffectResult.fail("cannot be encoded as JSON"),
1478
+ onSome: (encoded) => EffectResult.succeed(encoded)
1479
+ })
1480
+ );
1481
+ if (EffectResult.isFailure(json)) {
1482
+ report({
1483
+ code: "ANALYTICS_EVENT_DROPPED",
1484
+ kind: "eviction",
1485
+ message: `Dropped "${name}": its properties ${json.failure}`,
1486
+ operation,
1487
+ retryable: false
1488
+ });
1489
+ return Option10.none();
1490
+ }
1491
+ return Option10.some(json.success);
1492
+ };
1493
+ const takesCaptureTime = P5.isFunction(Reflect.get(native, "captureAt")) && P5.isFunction(Reflect.get(native, "screenAt"));
1494
+ const sendEvent = (operation, name, propertiesJson, capturedAt) => {
1495
+ const sent = EffectResult.try(() => {
1496
+ if (Option10.isSome(capturedAt) && takesCaptureTime) {
1497
+ if (operation === "capture") native.captureAt(name, propertiesJson, capturedAt.value);
1498
+ else native.screenAt(name, propertiesJson, capturedAt.value);
1499
+ return;
1500
+ }
1501
+ if (operation === "capture") native.capture(name, propertiesJson);
1502
+ else native.screen(name, propertiesJson);
1503
+ });
1504
+ if (EffectResult.isFailure(sent)) {
1505
+ report({
1506
+ code: "ANALYTICS_EVENT_DROPPED",
1507
+ kind: "eviction",
1508
+ message: `Dropped "${name}": ${readNativeError(sent.failure).message}`,
1509
+ operation,
1510
+ retryable: false
1511
+ });
1512
+ }
1513
+ };
1514
+ return {
1515
+ /**
1516
+ * Configures and starts the native client, also again after `shutdown()`
1517
+ * (a re-init). The listener is attached first, so what `start()`
1518
+ * announces reaches the atoms. The identity a new run loads has a newer
1519
+ * generation than anything of the previous run, so a read the previous
1520
+ * run left pending is never published. A failed start detaches the
1521
+ * listener again.
1522
+ */
1523
+ start: async (configuration) => {
1524
+ const version2 = contractVersionOf(native);
1525
+ if (version2 !== NATIVE_CONTRACT_VERSION) {
1526
+ return Result4.err(
1527
+ new VoidhashError(
1528
+ "FAILED_TO_INITIALIZE_VOIDHASH_CLIENT",
1529
+ `FAILED_TO_INITIALIZE_VOIDHASH_CLIENT: the app's native Voidhash module implements version ${version2} of its contract, and this JavaScript bundle needs version ${NATIVE_CONTRACT_VERSION}. Make a new native build of the app with this version of ${options.packageName}; an over-the-air update cannot change the native module.`
1530
+ )
1531
+ );
1532
+ }
1533
+ MutableRef.set(listening, true);
1534
+ const started = await call(FAILURES.start, async () => {
1535
+ native.setEventListener(handleEvent);
1536
+ native.configure(configuration);
1537
+ await native.start();
1538
+ });
1539
+ if (started.isErr()) stopListening();
1540
+ return started;
1541
+ },
1542
+ /**
1543
+ * Shuts the native client down; events it emits from then on are ignored.
1544
+ * The products go with it: a later run loads them for its own identity.
1545
+ */
1546
+ shutdown: async () => {
1547
+ const result = await call(FAILURES.shutdown, () => native.shutdown());
1548
+ stopListening();
1549
+ MutableRef.update(productsRevision, (revision) => revision + 1);
1550
+ cancelScheduledReload();
1551
+ MutableRef.set(productsLoad, Option10.none());
1552
+ atomRegistry.set(productsAtom, NO_PRODUCTS);
1553
+ return result.map(toFlushResult);
1554
+ },
1555
+ getDistinctId: () => call(FAILURES.getDistinctId, () => native.getDistinctId()),
1556
+ /** Backs `identify()`: the switch, without the confirmation. */
1557
+ identify: async (externalUserId, profile = {}) => (await switchIdentity(externalUserId, profile)).map(() => void 0),
1558
+ /** Backs `identifySync()`: the switch and whether the server confirmed it. */
1559
+ identifySync: async (externalUserId, profile = {}) => (await switchIdentity(externalUserId, profile)).map((result) => {
1560
+ const person = personOf(result);
1561
+ return result.status === "confirmed" && Option10.isSome(person) ? { person: person.value, status: "confirmed" } : { person: Option10.getOrNull(person), status: "deferred" };
1562
+ }),
1563
+ reset: () => switchToAnonymous(FAILURES.reset, () => native.reset()),
1564
+ signOut: () => switchToAnonymous(FAILURES.signOut, () => native.signOut()),
1565
+ /**
1566
+ * Backs `group()`. The native SDK checks the type and key (an invalid one
1567
+ * rejects `INVALID_ARGUMENT`), keeps the group with the identity and sends
1568
+ * the `$groupidentify`.
1569
+ */
1570
+ group: async (groupType, groupKey, properties) => {
1571
+ if (Option10.isNone(properties)) {
1572
+ return call(FAILURES.group, () => native.group(groupType, groupKey, void 0));
1573
+ }
1574
+ return Option10.match(EffectResult.getSuccess(encodeJson(properties.value)), {
1575
+ onNone: () => Promise.resolve(
1576
+ Result4.err(
1577
+ new VoidhashError(
1578
+ "INVALID_ARGUMENT",
1579
+ "INVALID_ARGUMENT: group properties must be values JSON can hold"
1580
+ )
1581
+ )
1582
+ ),
1583
+ onSome: (json) => call(FAILURES.group, () => native.group(groupType, groupKey, json))
1584
+ });
1585
+ },
1586
+ /**
1587
+ * Backs `setGroups()`. The native SDK replaces the held groups, checks
1588
+ * each type and id, and sends a `$groupidentify` only for what changed.
1589
+ */
1590
+ setGroups: async (groups) => {
1591
+ const entries = R4.filterMap(groups, (group) => {
1592
+ if (P5.isNullish(group)) return EffectResult.failVoid;
1593
+ if (!P5.isObject(group)) return EffectResult.succeed({ id: String(group), properties: {} });
1594
+ const { id, ...properties } = group;
1595
+ return EffectResult.succeed({ id: String(id), properties });
1596
+ });
1597
+ return Option10.match(EffectResult.getSuccess(encodeJson(entries)), {
1598
+ onNone: () => Promise.resolve(
1599
+ Result4.err(
1600
+ new VoidhashError(
1601
+ "INVALID_ARGUMENT",
1602
+ "INVALID_ARGUMENT: group properties must be values JSON can hold"
1603
+ )
1604
+ )
1605
+ ),
1606
+ onSome: (json) => call(FAILURES.setGroups, () => native.setGroups(json))
1607
+ });
1608
+ },
1609
+ resetGroups: () => call(FAILURES.resetGroups, () => native.resetGroups()),
1610
+ /** The groups the native client holds; none when it could not say. */
1611
+ getGroups: () => Option10.getOrElse(
1612
+ trySync("getGroups", () => native.getGroups()),
1613
+ () => ({})
1614
+ ),
1615
+ setPersonAttributes: async (attributes) => {
1616
+ const encoded = encodeAttributes(attributes);
1617
+ if (encoded.isErr()) return Result4.err(encoded.error);
1618
+ return call(FAILURES.setPersonAttributes, () => native.setPersonAttributes(encoded.value));
1619
+ },
1620
+ setPersonAttributesSync: async (attributes) => {
1621
+ const encoded = encodeAttributes(attributes);
1622
+ if (encoded.isErr()) return Result4.err(encoded.error);
1623
+ return (await call(
1624
+ FAILURES.setPersonAttributesSync,
1625
+ () => native.setPersonAttributesState(encoded.value)
1626
+ )).map(toAttributesResult);
1627
+ },
1628
+ getCurrentPerson: async (options2 = {}) => (await readPerson(options2.forceFetch ?? false)).map(toCurrentPerson),
1629
+ /** Answers an entitlement check from the person read, as the TypeScript core does. */
1630
+ hasPerk: async (perkSlug, options2 = {}) => (await readPerson(options2.forceFetch ?? false)).map((state) => {
1631
+ const snapshot = toCurrentPerson(state);
1632
+ const grant = findActiveGrant(Option10.fromNullOr(snapshot.person), perkSlug);
1633
+ return {
1634
+ ...Option10.match(grant, { onNone: () => ({}), onSome: (found) => ({ grant: found }) }),
1635
+ hasAccess: Option10.isSome(grant),
1636
+ isExpired: snapshot.isExpired,
1637
+ isStale: snapshot.isStale,
1638
+ reason: snapshot.reason
1639
+ };
1640
+ }),
1641
+ resetCache: () => call(FAILURES.resetCache, () => native.resetPersonCache()),
1642
+ /**
1643
+ * Evaluates flags and stores the answer under the keys asked for, which
1644
+ * is where the hook that asked reads it, whatever the native side echoes.
1645
+ */
1646
+ getFeatureFlags: (flagKeys) => call(FAILURES.getFeatureFlags, async () => {
1647
+ const result = await native.getFeatureFlags(
1648
+ flagKeys === void 0 ? void 0 : [...flagKeys]
1649
+ );
1650
+ publishFlags(result, normalizeFeatureFlagKeys(flagKeys));
1651
+ return toFlags(result);
1652
+ }),
1653
+ getPaywallForLocation: async (location) => {
1654
+ const json = await call(FAILURES.getPaywallForLocation, () => native.getPaywall(location));
1655
+ return json.andThen(
1656
+ (value3) => EffectResult.match(EffectResult.flatMap(decodeJson2(value3), decodePaywall), {
1657
+ onFailure: () => Result4.err(
1658
+ new VoidhashError(
1659
+ "FAILED_TO_GET_PAYWALL_FOR_LOCATION",
1660
+ `FAILED_TO_GET_PAYWALL_FOR_LOCATION: unreadable paywall for "${location}"`
1661
+ )
1662
+ ),
1663
+ onSuccess: (paywall) => Result4.ok(paywall)
1664
+ })
1665
+ );
1666
+ },
1667
+ /** Loads the products, sharing a load already running; see `loadProducts`. */
1668
+ loadProducts,
1669
+ /**
1670
+ * Buys a product. A cancelled sheet and a pending payment are results; a
1671
+ * native client that rejects them with `USER_CANCELLED` or
1672
+ * `PURCHASE_PENDING` is read the same way. A store refusal with a reason
1673
+ * is `FAILED_TO_PURCHASE` with that reason. A completed purchase, and an
1674
+ * offer the end user could not get (`INELIGIBLE_FOR_OFFER` or
1675
+ * `OFFER_UNAVAILABLE`), outdate the products: the offers they list may
1676
+ * have changed.
1677
+ */
1678
+ purchase: async (productSlug, purchaseOptions) => {
1679
+ const exit2 = await Effect6.runPromiseExit(
1680
+ Effect6.tryPromise({
1681
+ catch: (error2) => error2,
1682
+ try: () => native.purchase(productSlug, purchaseOptions)
1683
+ })
1684
+ );
1685
+ if (Exit.isSuccess(exit2)) {
1686
+ const result = toPurchaseResult(
1687
+ exit2.value,
1688
+ (message) => reportContractViolation("purchase", message)
1689
+ );
1690
+ if (Option10.isNone(result)) {
1691
+ return Result4.err(
1692
+ new VoidhashError(
1693
+ "FAILED_TO_PURCHASE",
1694
+ "FAILED_TO_PURCHASE: the native client reported a purchase without its transaction"
1695
+ )
1696
+ );
1697
+ }
1698
+ if (result.value.status === "purchased") invalidateProducts();
1699
+ return Result4.ok(result.value);
1700
+ }
1701
+ const error = Cause.squash(exit2.cause);
1702
+ const failure = readNativeError(error);
1703
+ const code = Option10.getOrElse(failure.code, () => "");
1704
+ if (code === "USER_CANCELLED") return Result4.ok({ status: "cancelled" });
1705
+ if (code === "PURCHASE_PENDING") return Result4.ok({ status: "pending" });
1706
+ if (code === "INELIGIBLE_FOR_OFFER" || code === "OFFER_UNAVAILABLE") invalidateProducts();
1707
+ const reason = R4.get(PURCHASE_FAILURE_REASONS, code);
1708
+ if (Option10.isSome(reason)) {
1709
+ return Result4.err(
1710
+ new VoidhashError("FAILED_TO_PURCHASE", `FAILED_TO_PURCHASE: ${failure.message}`, {
1711
+ cause: error,
1712
+ reason: reason.value
1713
+ })
1714
+ );
1715
+ }
1716
+ return Result4.err(toVoidhashError(error, FAILURES.purchase));
1717
+ },
1718
+ /**
1719
+ * Revalidates the store's purchase history and answers the refreshed
1720
+ * person (`null` when there is none), publishing it as a read does. A
1721
+ * restore outdates the products: what was restored can change the
1722
+ * offers the end user is eligible for.
1723
+ */
1724
+ // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.
1725
+ restorePurchases: async () => {
1726
+ const restored = await call(FAILURES.restorePurchases, async () => {
1727
+ const state = await native.restorePurchases();
1728
+ publishPerson(state);
1729
+ return state;
1730
+ });
1731
+ if (restored.isOk()) invalidateProducts();
1732
+ return restored.map((state) => Option10.getOrNull(personOf(state)));
1733
+ },
1734
+ syncPurchases: () => call(FAILURES.syncPurchases, () => native.syncPurchases()),
1735
+ reportTransaction: (transaction, isRestore) => call(FAILURES.reportTransaction, () => native.reportTransaction(transaction, isRestore)),
1736
+ /** Answers whether the consent was also stored for later launches. */
1737
+ setAnalyticsConsent: (consent) => call(FAILURES.setAnalyticsConsent, () => native.setAnalyticsConsent(consent)),
1738
+ /** The consent the native client has in effect; `None` when it could not say. */
1739
+ getAnalyticsConsent: () => Option10.filter(
1740
+ trySync("getAnalyticsConsent", () => native.getAnalyticsConsent()),
1741
+ isAnalyticsConsent
1742
+ ),
1743
+ /** Switches observer mode natively; a throw is reported, the facade's mode still switches. */
1744
+ setReadOnly: (readOnly) => {
1745
+ trySync("setReadOnly", () => native.setReadOnly(readOnly));
1746
+ },
1747
+ flush: async () => (await call(FAILURES.flush, () => native.flush())).map(toFlushResult),
1748
+ /** The active session id, or `undefined` when there is none. */
1749
+ // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the facade's `getSessionId()` answer.
1750
+ getSessionId: () => Option10.getOrUndefined(
1751
+ Option10.filter(
1752
+ trySync("getSessionId", () => native.getSessionId()),
1753
+ (sessionId) => sessionId !== ""
1754
+ )
1755
+ ),
1756
+ capture: (eventName, properties = {}) => Option10.map(
1757
+ encodeEvent("capture", eventName, properties),
1758
+ (json) => sendEvent("capture", eventName, json, Option10.none())
1759
+ ),
1760
+ screen: (name, properties = {}) => Option10.map(
1761
+ encodeEvent("screen", name, properties),
1762
+ (json) => sendEvent("screen", name, json, Option10.none())
1763
+ ),
1764
+ /**
1765
+ * Copies an event's (or a screen's) properties now and answers what
1766
+ * queues it later, given the time it was captured at: for an event the
1767
+ * facade holds back until an identity change switched the identity.
1768
+ * `None` for an event whose properties cannot be copied, already reported.
1769
+ */
1770
+ holdEvent: (operation, name, properties) => Option10.map(
1771
+ encodeEvent(operation, name, properties),
1772
+ (json) => (capturedAt) => sendEvent(operation, name, json, Option10.some(capturedAt))
1773
+ ),
1774
+ /** The distinct id in effect, as last announced; `None` before the first `start()`. */
1775
+ currentDistinctId: () => Option10.map(MutableRef.get(currentIdentity), (identity) => identity.distinctId),
1776
+ // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the Nitro contract, where an optional is `undefined`.
1777
+ showManageSubscriptions: (productSlug) => call(FAILURES.showManageSubscriptions, () => native.showManageSubscriptions(productSlug)),
1778
+ // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the Nitro contract, where an optional is `undefined`.
1779
+ presentCodeRedemption: (code) => call(FAILURES.presentCodeRedemption, () => native.presentCodeRedemption(code)),
1780
+ getStorefront: async () => (await call(FAILURES.getStorefront, () => native.getStorefront())).map(
1781
+ // oxlint-disable-next-line effect/prefer-option-over-null -- mirrors the Nitro contract, where an optional is `undefined`.
1782
+ (storefront) => storefront === void 0 ? void 0 : {
1783
+ countryCode: storefront.countryCode,
1784
+ ...storefront.currencyCode === void 0 ? {} : { currencyCode: storefront.currencyCode }
1785
+ }
1786
+ ),
1787
+ canMakePayments: () => call(FAILURES.canMakePayments, () => native.canMakePayments()),
1788
+ appStoreBeginRefundRequest: (transactionId) => call(
1789
+ FAILURES.appStoreBeginRefundRequest,
1790
+ () => native.appStoreBeginRefundRequest(transactionId)
1791
+ ),
1792
+ /**
1793
+ * The group's statuses. One whose renewal info cannot be read breaks the
1794
+ * contract: it is left out and reported.
1795
+ */
1796
+ appStoreSubscriptionStatus: async (groupId) => (await call(
1797
+ FAILURES.appStoreSubscriptionStatus,
1798
+ () => native.appStoreSubscriptionStatus(groupId)
1799
+ )).map(
1800
+ (statuses) => Arr6.filterMap(statuses, (status) => {
1801
+ const renewalInfo = decodeAppStoreRenewalInfo(status.renewalInfoJson);
1802
+ if (Option10.isNone(renewalInfo)) {
1803
+ reportContractViolation(
1804
+ "appStore.subscriptionStatus",
1805
+ `The renewal info of transaction ${status.transaction.id} could not be read`
1806
+ );
1807
+ return EffectResult.failVoid;
1808
+ }
1809
+ return EffectResult.succeed({
1810
+ renewalInfo: renewalInfo.value,
1811
+ state: status.state,
1812
+ transaction: toTransaction(
1813
+ status.transaction,
1814
+ (message) => reportContractViolation("appStore.subscriptionStatus", message)
1815
+ )
1816
+ });
1817
+ })
1818
+ ),
1819
+ appStoreCurrentEntitlements: async () => (await call(FAILURES.appStoreCurrentEntitlements, () => native.appStoreCurrentEntitlements())).map(
1820
+ (transactions) => transactions.map(
1821
+ (transaction) => toTransaction(
1822
+ transaction,
1823
+ (message) => reportContractViolation("appStore.currentEntitlements", message)
1824
+ )
1825
+ )
1826
+ ),
1827
+ appStoreAppTransaction: async () => (await call(FAILURES.appStoreAppTransaction, () => native.appStoreAppTransaction())).andThen(
1828
+ (json) => Option10.match(decodeAppTransaction(json), {
1829
+ onNone: () => Result4.err(
1830
+ new VoidhashError(
1831
+ "FAILED_TO_GET_APP_TRANSACTION",
1832
+ "FAILED_TO_GET_APP_TRANSACTION: the native client sent an app transaction this SDK cannot read"
1833
+ )
1834
+ ),
1835
+ onSome: (appTransaction) => Result4.ok(appTransaction)
1836
+ })
1837
+ ),
1838
+ googlePlayShowInAppMessages: async () => (await call(FAILURES.googlePlayShowInAppMessages, () => native.googlePlayShowInAppMessages())).map(
1839
+ (result) => result.status === "subscriptionStatusUpdated" && result.purchaseToken !== void 0 ? { purchaseToken: result.purchaseToken, status: "subscriptionStatusUpdated" } : { status: "noActionNeeded" }
1840
+ ),
1841
+ googlePlayQueryPurchases: async (includeSuspended) => (await call(
1842
+ FAILURES.googlePlayQueryPurchases,
1843
+ () => native.googlePlayQueryPurchases(includeSuspended)
1844
+ )).map(
1845
+ (transactions) => transactions.map(
1846
+ (transaction) => toTransaction(
1847
+ transaction,
1848
+ (message) => reportContractViolation("googlePlay.queryPurchases", message)
1849
+ )
1850
+ )
1851
+ ),
1852
+ googlePlayIsFeatureSupported: (feature) => call(
1853
+ FAILURES.googlePlayIsFeatureSupported,
1854
+ () => native.googlePlayIsFeatureSupported(feature)
1855
+ ),
1856
+ /**
1857
+ * Resolves with how the flow ended and rejects with a `VoidhashError` when
1858
+ * it could not be presented. A `FLOW_*` code the native side gives is
1859
+ * kept; a client that is not started is `FLOW_UNAVAILABLE`.
1860
+ *
1861
+ * The native coordinator runs the flow: it calls back only for the
1862
+ * actions named here, and answers a rejected call, a slow one and one
1863
+ * whose flow has ended itself.
1864
+ * A flow that ended in a purchase or a restore outdates the products, as
1865
+ * `purchase()` and `restorePurchases()` do: the native client reports
1866
+ * neither as a transaction update.
1867
+ */
1868
+ presentFlow: async (location, options2 = {}) => {
1869
+ const handlers = options2.actions ?? {};
1870
+ const onAction = async (name, argsJson) => {
1871
+ const handler = handlers[name];
1872
+ if (handler === void 0) {
1873
+ throw new VoidhashError("INVALID_ARGUMENT", `no handler for app action "${name}"`);
1874
+ }
1875
+ const reply = await handler(decodeFlowValues(argsJson));
1876
+ return encodeFlowValues(reply ?? {});
1877
+ };
1878
+ const exit2 = await Effect6.runPromiseExit(
1879
+ Effect6.tryPromise({
1880
+ catch: (error) => error,
1881
+ try: () => native.presentFlow(
1882
+ location,
1883
+ {
1884
+ actions: R4.keys(handlers),
1885
+ inputJson: encodeFlowValues(options2.input ?? {}),
1886
+ ...options2.revision === void 0 ? {} : { revision: options2.revision }
1887
+ },
1888
+ onAction
1889
+ )
1890
+ })
1891
+ );
1892
+ if (Exit.isSuccess(exit2)) {
1893
+ const parsed = parseFlowResult(exit2.value);
1894
+ if (EffectResult.isFailure(parsed)) throw parsed.failure;
1895
+ if (parsed.success.outcome === "purchased" || parsed.success.outcome === "restored") {
1896
+ invalidateProducts();
1897
+ }
1898
+ return parsed.success;
1899
+ }
1900
+ const failure = readNativeError(Cause.squash(exit2.cause));
1901
+ const code = Option10.getOrElse(failure.code, () => "");
1902
+ if (NOT_STARTED_CODES.includes(code)) {
1903
+ throw flowError("FLOW_UNAVAILABLE", new NotInitializedError().message);
1904
+ }
1905
+ throw isFlowErrorCode(code) ? new VoidhashError(code, failure.message) : flowError("FLOW_PRESENTATION_FAILED", failure.message);
1906
+ },
1907
+ updateFlowInput: (values2) => call(FAILURES.updateFlowInput, () => native.updateFlowInput(encodeFlowValues(values2))),
1908
+ dismissFlow: () => call(FAILURES.dismissFlow, () => native.dismissFlow())
1909
+ };
1910
+ };
1911
+
1912
+ // ../react-native/src/core/person-attributes.ts
1913
+ import * as Arr7 from "effect/Array";
1914
+ import * as Option11 from "effect/Option";
1915
+ import * as P6 from "effect/Predicate";
1916
+ import * as R5 from "effect/Record";
1917
+ var isTraitValue = (value3) => value3 === null || P6.isString(value3) || P6.isNumber(value3) || P6.isBoolean(value3);
1918
+ var invalidPersonAttributes = (attributes) => {
1919
+ if (!P6.isObject(attributes)) {
1920
+ return Option11.some(new InvalidArgumentError("Person attributes must be an object"));
1921
+ }
1922
+ const invalidKeys = R5.keys(
1923
+ R5.filter(
1924
+ attributes,
1925
+ (value3, key) => key === "email" || key === "name" ? value3 !== void 0 && !P6.isString(value3) : value3 !== void 0 && !isTraitValue(value3)
1926
+ )
1927
+ );
1928
+ return Arr7.match(invalidKeys, {
1929
+ onEmpty: () => Option11.none(),
1930
+ onNonEmpty: (keys6) => Option11.some(
1931
+ new InvalidArgumentError(
1932
+ `Invalid person attributes (${keys6.join(", ")}): trait values must be strings, numbers, booleans or null, and email and name must be strings`
1933
+ )
1934
+ )
1935
+ });
1936
+ };
1937
+
1938
+ // ../react-native/src/core/screens/screen-tracker.ts
1939
+ import * as Arr8 from "effect/Array";
1940
+ import * as Option12 from "effect/Option";
1941
+ import * as P7 from "effect/Predicate";
1942
+ import * as R6 from "effect/Record";
1943
+ import * as Result5 from "effect/Result";
1944
+ var SCREEN_NAME_MAX_LENGTH = 200;
1945
+ var SCREEN_PARAMS_MAX_KEYS = 20;
1946
+ var truncate = (value3) => value3.slice(0, SCREEN_NAME_MAX_LENGTH);
1947
+ var coerceParam = (value3) => P7.isString(value3) ? value3 : Array.isArray(value3) ? value3.map(coerceParam).join(",") : Result5.getOrElse(
1948
+ Result5.try(() => String(value3)),
1949
+ () => "[object Object]"
1950
+ );
1951
+ var coerceParams = (params) => R6.fromEntries(
1952
+ Arr8.map(
1953
+ Arr8.take(R6.toEntries(params), SCREEN_PARAMS_MAX_KEYS),
1954
+ ([key, value3]) => [key, coerceParam(value3)]
1955
+ )
1956
+ );
1957
+ function createScreenTracker(options) {
1958
+ const now = options.now ?? Date.now;
1959
+ let state = Option12.none();
1960
+ const transition = (input) => {
1961
+ if (!options.enabled) {
1962
+ return Option12.none();
1963
+ }
1964
+ const mappedView = options.mapScreen ? options.mapScreen(input) : Option12.some(input);
1965
+ if (Option12.isNone(mappedView)) {
1966
+ return Option12.none();
1967
+ }
1968
+ const mapped = mappedView.value;
1969
+ if (Option12.isSome(state) && state.value.identity === mapped.identity) {
1970
+ return Option12.none();
1971
+ }
1972
+ const arrivedAt = now();
1973
+ const name = truncate(mapped.name);
1974
+ const path = truncate(mapped.path);
1975
+ const previous = Option12.getOrNull(state);
1976
+ const properties = {
1977
+ [SCREEN_PROPERTIES.NAME]: name,
1978
+ [SCREEN_PROPERTIES.PATH]: path,
1979
+ [SCREEN_PROPERTIES.SOURCE]: mapped.source,
1980
+ [SCREEN_PROPERTIES.PREVIOUS_NAME]: previous?.name ?? null,
1981
+ [SCREEN_PROPERTIES.PREVIOUS_PATH]: previous?.path ?? null,
1982
+ // A clock set back between two screens must not report a negative stay.
1983
+ [SCREEN_PROPERTIES.PREVIOUS_DURATION_MS]: previous ? Math.max(arrivedAt - previous.arrivedAt, 0) : null
1984
+ };
1985
+ if (P7.isString(mapped.title) && mapped.title !== "") {
1986
+ properties[SCREEN_PROPERTIES.TITLE] = mapped.title;
1987
+ }
1988
+ if (options.includeParams && P7.isObject(mapped.params)) {
1989
+ properties[SCREEN_PROPERTIES.PARAMS] = coerceParams(mapped.params);
1990
+ }
1991
+ state = Option12.some({ identity: mapped.identity, name, path, arrivedAt });
1992
+ return Option12.some(properties);
1993
+ };
1994
+ return {
1995
+ transition,
1996
+ reset: () => {
1997
+ state = Option12.none();
1998
+ }
1999
+ };
2000
+ }
2001
+
2002
+ // ../react-native/src/client.tsx
2003
+ var DISABLED_FEATURE_FLAGS = { flags: [], isStale: false };
2004
+ var LIVE_CLIENTS = /* @__PURE__ */ Symbol.for("@voidhash/react-native/live-clients");
2005
+ var runtimeState = globalThis;
2006
+ var liveClients = runtimeState[LIVE_CLIENTS] ??= MutableHashMap.empty();
2007
+ var PROCESS_SLOT = "process";
2008
+ var MAX_HELD_PURCHASE_INTENTS = 10;
2009
+ var MAX_EVENTS_HELD_FOR_IDENTITY = 100;
2010
+ var isNonBlankString = (value3) => P8.isString(value3) && value3.trim() !== "";
2011
+ var encodeProjectSchemaJson = Schema11.encodeSync(Schema11.fromJsonString(RuntimeSchemaValue));
2012
+ var encodeJson2 = Schema11.encodeUnknownOption(Schema11.fromJsonString(Schema11.Unknown));
2013
+ var isTrackableScreen = (view) => P8.hasProperty(view, "identity") && P8.isString(view.identity) && P8.hasProperty(view, "name") && P8.isString(view.name) && P8.hasProperty(view, "path") && P8.isString(view.path);
2014
+ var REPLACEMENT_MODES = [
2015
+ "withTimeProration",
2016
+ "chargeProratedPrice",
2017
+ "chargeFullPrice",
2018
+ "withoutProration",
2019
+ "deferred"
2020
+ ];
2021
+ var isReplacementMode = (value3) => REPLACEMENT_MODES.some((mode) => mode === value3);
2022
+ var toNativeReplacement = (replacing) => {
2023
+ const product = P8.hasProperty(replacing, "product") ? replacing.product : void 0;
2024
+ const productSlug = P8.hasProperty(product, "slug") ? product.slug : void 0;
2025
+ if (!isNonBlankString(productSlug)) {
2026
+ return EffectResult2.fail(
2027
+ new InvalidArgumentError(
2028
+ "purchase() needs `replacing.product` to be the product being replaced, from getProducts()"
2029
+ )
2030
+ );
2031
+ }
2032
+ const mode = (P8.hasProperty(replacing, "mode") ? replacing.mode : void 0) ?? "withTimeProration";
2033
+ return isReplacementMode(mode) ? EffectResult2.succeed({ mode, productSlug }) : EffectResult2.fail(
2034
+ new InvalidArgumentError(
2035
+ `purchase() needs \`replacing.mode\` to be one of ${REPLACEMENT_MODES.join(", ")}${P8.isString(mode) ? `, got "${mode}"` : ""}`
2036
+ )
2037
+ );
2038
+ };
2039
+ var toNativeOfferSelection = (offer) => {
2040
+ if (offer === void 0 || offer === "automatic") {
2041
+ return EffectResult2.succeed({ offerSelection: "automatic" });
2042
+ }
2043
+ if (offer === "none") return EffectResult2.succeed({ offerSelection: "regularPrice" });
2044
+ if (isNonBlankString(offer))
2045
+ return EffectResult2.succeed({ offerId: offer, offerSelection: "offer" });
2046
+ const kind = P8.hasProperty(offer, "kind") ? offer.kind : void 0;
2047
+ const offerKind = Option13.filter(
2048
+ Option13.some(kind),
2049
+ (value3) => value3 === "introductory" || value3 === "promotional" || value3 === "winBack" || value3 === "oneTime"
2050
+ );
2051
+ const id = P8.hasProperty(offer, "id") ? offer.id : void 0;
2052
+ if (P8.isString(id) && (Option13.isSome(offerKind) || isNonBlankString(id))) {
2053
+ return EffectResult2.succeed({
2054
+ offerId: id,
2055
+ offerSelection: "offer",
2056
+ ...Option13.match(offerKind, { onNone: () => ({}), onSome: (value3) => ({ offerKind: value3 }) })
2057
+ });
2058
+ }
2059
+ return EffectResult2.fail(
2060
+ new InvalidArgumentError(
2061
+ 'purchase() needs `offer` to be "automatic", "none", an offer of the product or its id'
2062
+ )
2063
+ );
2064
+ };
2065
+ var toNativePurchaseOptions = (product, options) => {
2066
+ const quantity = options.quantity ?? 1;
2067
+ if (!P8.isNumber(quantity) || !Number.isInteger(quantity) || quantity < 1) {
2068
+ return EffectResult2.fail(
2069
+ new InvalidArgumentError("purchase() needs `quantity` to be a whole number of at least 1")
2070
+ );
2071
+ }
2072
+ if (quantity !== 1 && !(product.store === "appStore" && product.type === "consumable")) {
2073
+ return EffectResult2.fail(
2074
+ new InvalidArgumentError(
2075
+ `purchase() can buy several only of an App Store consumable; "${product.slug}" is bought one at a time`
2076
+ )
2077
+ );
2078
+ }
2079
+ const offer = toNativeOfferSelection(options.offer);
2080
+ if (EffectResult2.isFailure(offer)) return EffectResult2.fail(offer.failure);
2081
+ const replacing = Option13.map(Option13.fromNullishOr(options.replacing), toNativeReplacement);
2082
+ if (Option13.isSome(replacing) && EffectResult2.isFailure(replacing.value)) {
2083
+ return EffectResult2.fail(replacing.value.failure);
2084
+ }
2085
+ const { appStore, googlePlay } = options;
2086
+ return EffectResult2.succeed({
2087
+ ...offer.success,
2088
+ quantity,
2089
+ ...Option13.isSome(replacing) && EffectResult2.isSuccess(replacing.value) ? { replacing: replacing.value.success } : {},
2090
+ ...appStore?.simulatesAskToBuyInSandbox === void 0 ? {} : { appStore: { simulatesAskToBuyInSandbox: appStore.simulatesAskToBuyInSandbox } },
2091
+ ...googlePlay === void 0 ? {} : {
2092
+ googlePlay: {
2093
+ ...googlePlay.isOfferPersonalized === void 0 ? {} : { isOfferPersonalized: googlePlay.isOfferPersonalized },
2094
+ ...googlePlay.obfuscatedProfileId === void 0 ? {} : { obfuscatedProfileId: googlePlay.obfuscatedProfileId },
2095
+ ...googlePlay.offerToken === void 0 ? {} : { offerToken: googlePlay.offerToken }
2096
+ }
2097
+ }
2098
+ });
2099
+ };
2100
+ var invalidGroups = (groups) => {
2101
+ const invalidTypes = R7.keys(
2102
+ R7.filter(groups, (group) => {
2103
+ if (P8.isNullish(group)) return false;
2104
+ const id = P8.hasProperty(group, "id") ? group.id : group;
2105
+ return !(P8.isString(id) || P8.isNumber(id) && Number.isFinite(id));
2106
+ })
2107
+ );
2108
+ return Arr9.match(invalidTypes, {
2109
+ onEmpty: () => Option13.none(),
2110
+ onNonEmpty: (types) => Option13.some(
2111
+ new InvalidArgumentError(
2112
+ `setGroups() needs each group's id to be a string or a finite number (${types.join(", ")})`
2113
+ )
2114
+ )
2115
+ });
2116
+ };
2117
+ var toNativeReport = (report) => report.platform === "ios" ? {
2118
+ platform: "appStore",
2119
+ transactionId: report.transactionId,
2120
+ ...report.signedTransaction === void 0 ? {} : { signedTransaction: report.signedTransaction }
2121
+ } : {
2122
+ platform: "googlePlay",
2123
+ purchaseToken: report.purchaseToken,
2124
+ ...report.purchaseState === void 0 ? {} : { purchaseState: report.purchaseState }
2125
+ };
2126
+ var VoidhashClient = class {
2127
+ setup;
2128
+ atomRegistry;
2129
+ namespace;
2130
+ /** What this client holds in `liveClients` while it runs: its namespace, or the process. */
2131
+ slot;
2132
+ emitDiagnostic;
2133
+ screenTracker;
2134
+ manualScreenCounter = 0;
2135
+ /** The send id `trackPushOpened()` reported last. */
2136
+ lastPushOpenedSendId = Option13.none();
2137
+ /** The native client and its adapter, made on first use. */
2138
+ native = Option13.none();
2139
+ /** Seeds the first `init()` of the process; cleared once applied or by an identity change. */
2140
+ initialDistinctId;
2141
+ /** The consent in effect, mirrored from the native client once it runs. */
2142
+ analyticsConsent;
2143
+ /** A consent `setAnalyticsConsent()` chose before `init()`; it wins over the stored one. */
2144
+ chosenAnalyticsConsent = Option13.none();
2145
+ analyticsConsentDeniedReported = false;
2146
+ readOnly;
2147
+ _isInitialized = false;
2148
+ /** Set by `end()` until the next `init()`. */
2149
+ ended = false;
2150
+ /**
2151
+ * The `init()` or `end()` called last, until it settles. A call for the
2152
+ * same transition joins it and a call for the other one runs after it, so
2153
+ * the client ends up in the state asked for last.
2154
+ */
2155
+ transition = Option13.none();
2156
+ flushInFlight = Option13.none();
2157
+ /** The purchase this client runs, until it settles; a second one fails `PURCHASE_IN_PROGRESS`. */
2158
+ purchaseInFlight = Option13.none();
2159
+ identityChangeTail = Promise.resolve();
2160
+ /**
2161
+ * The `identify()`, `reset()` and `signOut()` calls made, and how many of
2162
+ * them, in call order, have switched the identity or settled without doing
2163
+ * so. An event, a screen or a purchase report waits for the ones called
2164
+ * before it, so it is recorded for the person the app switched to; see
2165
+ * {@link identityChangeSwitched}.
2166
+ */
2167
+ identityChangesCalled = 0;
2168
+ identityChangesSwitched = 0;
2169
+ /** The identity change the native client is running now, by its number among those called. */
2170
+ identityChangeRunning = Option13.none();
2171
+ eventsHeldForIdentity = [];
2172
+ reportsHeldForIdentity = [];
2173
+ /**
2174
+ * One entry per `addTransactionListener()` call, each its own function, so
2175
+ * adding a listener twice calls it twice.
2176
+ */
2177
+ transactionListeners = MutableHashSet.empty();
2178
+ purchaseIntentListeners = MutableHashSet.empty();
2179
+ /**
2180
+ * Purchase intents that arrived while no listener was registered (they
2181
+ * arrive from `init()` on, before the app may have added one), oldest
2182
+ * first, for the first listener the app adds.
2183
+ */
2184
+ heldPurchaseIntents = [];
2185
+ /**
2186
+ * @internal Not part of the public API: create clients with
2187
+ * `createVoidhashClient()`, which validates the options and builds the
2188
+ * provider and hooks. The parameters change between releases.
2189
+ */
2190
+ constructor(setup) {
2191
+ this.setup = setup;
2192
+ this.atomRegistry = setup.atomRegistry;
2193
+ this.namespace = buildCacheNamespace(setup.publishableKey, setup.baseUrl);
2194
+ this.slot = setup.oneNativeClientPerProcess ? PROCESS_SLOT : this.namespace;
2195
+ this.emitDiagnostic = makeDiagnosticEmitter(setup.onDiagnostic);
2196
+ this.initialDistinctId = setup.distinctId;
2197
+ this.analyticsConsent = setup.analyticsConsent;
2198
+ this.readOnly = setup.readOnly;
2199
+ const mapScreen = setup.screenTracking.mapScreen;
2200
+ this.screenTracker = createScreenTracker({
2201
+ enabled: setup.enabled && (setup.screenTracking.enabled ?? true),
2202
+ includeParams: setup.screenTracking.includeParams ?? false,
2203
+ mapScreen: mapScreen ? (view) => {
2204
+ try {
2205
+ const mapped = mapScreen(view);
2206
+ if (P8.isNullish(mapped)) return Option13.none();
2207
+ if (isTrackableScreen(mapped)) return Option13.some(mapped);
2208
+ this.emitDiagnostic({
2209
+ code: "HOST_CALLBACK_FAILED",
2210
+ kind: "configuration",
2211
+ message: "screenTracking.mapScreen returned a screen whose identity, name or path is not a string; the screen was tracked unmapped",
2212
+ operation: "screenTracking.mapScreen",
2213
+ retryable: false
2214
+ });
2215
+ return Option13.some(view);
2216
+ } catch (error) {
2217
+ this.reportHostCallbackFailure("screenTracking.mapScreen", error);
2218
+ return Option13.some(view);
2219
+ }
2220
+ } : void 0
2221
+ });
2222
+ }
2223
+ /** The adapter over this client's native client, created on first use. */
2224
+ nativeClient() {
2225
+ if (Option13.isSome(this.native)) return this.native;
2226
+ this.native = Option13.map(
2227
+ this.setup.createNativeClient(),
2228
+ (native) => makeNativeClientAdapter({
2229
+ atomRegistry: this.atomRegistry,
2230
+ native,
2231
+ packageName: this.setup.packageName,
2232
+ onAnalyticsConsentChanged: (consent) => {
2233
+ this.analyticsConsent = consent;
2234
+ if (consent === "granted") this.analyticsConsentDeniedReported = false;
2235
+ },
2236
+ // The switch a running identity change made: what waited for it goes on
2237
+ // now, not once Voidhash answered the call.
2238
+ onIdentitySwitched: () => {
2239
+ Option13.map(this.identityChangeRunning, (change) => this.identityChangeSwitched(change));
2240
+ },
2241
+ onDiagnostic: this.emitDiagnostic,
2242
+ onPurchaseIntent: (intent) => this.receivePurchaseIntent(intent),
2243
+ onTransaction: (update2) => this.notify("addTransactionListener", this.transactionListeners, update2)
2244
+ })
2245
+ );
2246
+ return this.native;
2247
+ }
2248
+ /** The configuration the next `start()` runs with. */
2249
+ configuration() {
2250
+ const setup = this.setup;
2251
+ return {
2252
+ analyticsConsent: setup.analyticsConsent,
2253
+ analyticsWhilePending: setup.analyticsWhilePending,
2254
+ appStoreMessages: setup.appStoreMessages,
2255
+ automaticLifecycleEvents: setup.automaticLifecycleEvents,
2256
+ baseUrl: setup.baseUrl,
2257
+ grantConsentOnIdentify: setup.grantConsentOnIdentify,
2258
+ debug: setup.debug,
2259
+ developmentMode: setup.developmentMode,
2260
+ featureFlagDefaults: { ...setup.featureFlagDefaults },
2261
+ flowCapabilities: [...setup.flowCapabilities],
2262
+ flowRuntime: setup.flowRuntime,
2263
+ flowLoading: setup.flowLoading,
2264
+ installAttribution: setup.installAttribution,
2265
+ flowRevisions: R7.collect(setup.flowRevisions, (location, revision) => ({
2266
+ location,
2267
+ revision
2268
+ })),
2269
+ preloadLocations: [...setup.preloadLocations],
2270
+ publishableKey: setup.publishableKey,
2271
+ purchaseIntents: setup.purchaseIntents,
2272
+ readOnly: this.readOnly,
2273
+ screenTrackingEnabled: setup.screenTracking.enabled ?? true,
2274
+ sdkVersion: SDK_VERSION,
2275
+ ...Option13.match(this.initialDistinctId, {
2276
+ onNone: () => ({}),
2277
+ onSome: (distinctId) => ({ distinctId })
2278
+ }),
2279
+ ...Option13.match(setup.metaAppId, {
2280
+ onNone: () => ({}),
2281
+ onSome: (metaAppId) => ({ metaAppId })
2282
+ }),
2283
+ ...Option13.match(this.chosenAnalyticsConsent, {
2284
+ onNone: () => ({}),
2285
+ onSome: (chosenAnalyticsConsent) => ({ chosenAnalyticsConsent })
2286
+ }),
2287
+ ...Option13.match(setup.ingestUrl, {
2288
+ onNone: () => ({}),
2289
+ onSome: (ingestUrl) => ({ ingestUrl })
2290
+ }),
2291
+ ...Option13.match(setup.featureFlagMaxWaitMs, {
2292
+ onNone: () => ({}),
2293
+ onSome: (featureFlagMaxWaitMs) => ({ featureFlagMaxWaitMs })
2294
+ }),
2295
+ ...Option13.match(setup.internalSchema, {
2296
+ onNone: () => ({}),
2297
+ onSome: (schema) => ({ internalSchemaJson: encodeProjectSchemaJson(schema) })
2298
+ })
2299
+ };
2300
+ }
2301
+ /**
2302
+ * The answer of a side-effect call, unless `unstable_swallowErrors` asks for
2303
+ * failures to be logged and answered as success.
2304
+ */
2305
+ swallowed(operation, result) {
2306
+ if (result.isErr() && this.setup.unstableSwallowErrors) {
2307
+ console.warn(`[voidhash] swallowed error in ${operation}`, result.error);
2308
+ return Result6.ok(void 0);
2309
+ }
2310
+ return result;
2311
+ }
2312
+ /** The started adapter, or `NOT_INITIALIZED`. */
2313
+ started() {
2314
+ return this._isInitialized && Option13.isSome(this.native) ? Result6.ok(this.native.value) : Result6.err(new NotInitializedError());
2315
+ }
2316
+ /**
2317
+ * Joins an `init()` in progress or starts one — after `end()` and behind an
2318
+ * `end()` still running too — the way identity calls do, so a purchase
2319
+ * reported during launch or teardown is not refused.
2320
+ */
2321
+ async whenInitialized() {
2322
+ await this.init();
2323
+ return this.started();
2324
+ }
2325
+ /** Runs an `init()` or `end()` as the transition called last. */
2326
+ runTransition(to, run) {
2327
+ const settled = run().finally(() => {
2328
+ if (Option13.exists(this.transition, (current) => current.settled === settled)) {
2329
+ this.transition = Option13.none();
2330
+ }
2331
+ });
2332
+ this.transition = Option13.some({ settled, to });
2333
+ return settled;
2334
+ }
2335
+ /**
2336
+ * The client that took over this client's storage namespace while this one
2337
+ * is not running. Identity and purchase calls on a replaced instance go to
2338
+ * it: starting this instance again would end the live one. A live client of
2339
+ * another project is never a replacement: nothing made for one project is
2340
+ * handed to another.
2341
+ */
2342
+ replacement() {
2343
+ const starting = Option13.exists(this.transition, (current) => current.to === "initialized");
2344
+ if (this._isInitialized || starting) return Option13.none();
2345
+ return Option13.filter(
2346
+ MutableHashMap.get(liveClients, this.slot),
2347
+ (owner) => owner !== this && owner.namespace === this.namespace
2348
+ );
2349
+ }
2350
+ /**
2351
+ * Runs an identity change in call order. Events, screens and purchase
2352
+ * reports made after it wait until it switched the identity, which the
2353
+ * native client announces at once, before it waits for Voidhash. A change
2354
+ * that switches nothing lets them go on when it starts (an `identify()` of
2355
+ * `target`, already the identity) or when it settles.
2356
+ */
2357
+ enqueueIdentityChange(operation, target = Option13.none()) {
2358
+ this.initialDistinctId = Option13.none();
2359
+ this.identityChangesCalled += 1;
2360
+ const change = this.identityChangesCalled;
2361
+ const settled = this.enqueueInIdentityOrder(() => {
2362
+ this.identityChangeRunning = Option13.some(change);
2363
+ const current = Option13.flatMap(this.native, (native) => native.currentDistinctId());
2364
+ if (Option13.isSome(target) && Option13.contains(current, target.value) && this.analyticsConsent === "granted") {
2365
+ this.identityChangeSwitched(change);
2366
+ }
2367
+ return operation();
2368
+ });
2369
+ const switched = () => {
2370
+ if (Option13.contains(this.identityChangeRunning, change)) {
2371
+ this.identityChangeRunning = Option13.none();
2372
+ }
2373
+ this.identityChangeSwitched(change);
2374
+ };
2375
+ void settled.then(switched, switched);
2376
+ return settled;
2377
+ }
2378
+ /**
2379
+ * Identity change number `change` switched the identity, or will not: sends
2380
+ * the events and screens held for it and lets the purchase reports go on.
2381
+ * Changes run one at a time, so the ones before it have switched too.
2382
+ */
2383
+ identityChangeSwitched(change) {
2384
+ if (change <= this.identityChangesSwitched) return;
2385
+ this.identityChangesSwitched = change;
2386
+ const isDue = (held) => held.after <= change;
2387
+ const events = this.eventsHeldForIdentity.splice(
2388
+ 0,
2389
+ this.eventsHeldForIdentity.filter(isDue).length
2390
+ );
2391
+ events.forEach((event) => event.send());
2392
+ const reports = this.reportsHeldForIdentity.splice(
2393
+ 0,
2394
+ this.reportsHeldForIdentity.filter(isDue).length
2395
+ );
2396
+ reports.forEach((report) => report.proceed());
2397
+ }
2398
+ /** Whether an identity change called before now has not switched the identity yet. */
2399
+ awaitsIdentityChange() {
2400
+ return this.identityChangesSwitched < this.identityChangesCalled;
2401
+ }
2402
+ /**
2403
+ * Keeps an event or a screen until the identity changes called before it
2404
+ * switched the identity, then calls `send` with the time it was captured
2405
+ * at. In memory, as the native client holds events before it starts: past
2406
+ * {@link MAX_EVENTS_HELD_FOR_IDENTITY} the oldest is dropped and reported.
2407
+ */
2408
+ holdEventForIdentity(operation, name, send) {
2409
+ const capturedAt = Date.now();
2410
+ this.eventsHeldForIdentity.push({
2411
+ after: this.identityChangesCalled,
2412
+ name,
2413
+ operation,
2414
+ // Whether it may be recorded is settled as it is sent: the consent may
2415
+ // have changed since, and an `identify()` can grant a pending one.
2416
+ send: () => {
2417
+ if (Option13.isSome(this.analyticsIntake(operation, name))) send(capturedAt);
2418
+ }
2419
+ });
2420
+ if (this.eventsHeldForIdentity.length <= MAX_EVENTS_HELD_FOR_IDENTITY) return;
2421
+ Option13.map(
2422
+ Option13.fromUndefinedOr(this.eventsHeldForIdentity.shift()),
2423
+ (dropped) => this.emitDiagnostic({
2424
+ code: "ANALYTICS_EVENT_DROPPED",
2425
+ kind: "eviction",
2426
+ message: `Dropped "${dropped.name}": more than ${MAX_EVENTS_HELD_FOR_IDENTITY} events were captured while identify(), reset() or signOut() was switching the identity`,
2427
+ operation: dropped.operation,
2428
+ retryable: false
2429
+ })
2430
+ );
2431
+ }
2432
+ /** Resolves once the identity changes called before now switched the identity. */
2433
+ afterIdentityChanges() {
2434
+ if (!this.awaitsIdentityChange()) return Promise.resolve();
2435
+ return new Promise((proceed) => {
2436
+ this.reportsHeldForIdentity.push({ after: this.identityChangesCalled, proceed });
2437
+ });
2438
+ }
2439
+ /**
2440
+ * Runs `operation` once `init()` has settled, after every identity change
2441
+ * and group call made before it.
2442
+ */
2443
+ enqueueInIdentityOrder(operation) {
2444
+ const next = this.identityChangeTail.then(async () => {
2445
+ const initialized = await this.init();
2446
+ if (initialized.isErr()) return Result6.err(initialized.error);
2447
+ return operation();
2448
+ });
2449
+ this.identityChangeTail = next.then(
2450
+ () => void 0,
2451
+ () => void 0
2452
+ );
2453
+ return next;
2454
+ }
2455
+ /**
2456
+ * Starts the native client from local state: identity, caches and queues
2457
+ * are loaded without waiting for the network, and the refreshes, store
2458
+ * observation and delivery continue in the background. Resolves
2459
+ * immediately without touching the native client when the client was
2460
+ * created with `enabled: false`.
2461
+ *
2462
+ * An app launched in the background before the device has been unlocked
2463
+ * since it started (on Android, only an app with a `directBootAware`
2464
+ * component) cannot read anything the SDK stored, so this waits for that
2465
+ * first unlock; events captured meanwhile are kept.
2466
+ *
2467
+ * Idempotent: a call that overlaps a running `init()` joins it, and a call
2468
+ * on an initialized client resolves at once. A call made while `end()` is
2469
+ * still running waits for it and then starts the client again, unless
2470
+ * another client took over its storage meanwhile: then this one stays ended
2471
+ * and the call answers `VOIDHASH_CLIENT_NOT_INITIALIZED`.
2472
+ */
2473
+ async init() {
2474
+ if (!this.setup.enabled) return Result6.ok(void 0);
2475
+ const pending = this.transition;
2476
+ if (Option13.isSome(pending) && pending.value.to === "initialized") {
2477
+ return pending.value.settled;
2478
+ }
2479
+ if (Option13.isNone(pending) && this._isInitialized) return Result6.ok(void 0);
2480
+ return this.runTransition("initialized", async () => {
2481
+ if (Option13.isSome(pending)) {
2482
+ await pending.value.settled;
2483
+ const takenOver = Option13.exists(
2484
+ MutableHashMap.get(liveClients, this.slot),
2485
+ (owner) => owner !== this
2486
+ );
2487
+ if (takenOver && Option13.exists(this.transition, (current) => current.to === "ended")) {
2488
+ return Result6.err(new NotInitializedError());
2489
+ }
2490
+ }
2491
+ return this.runInit();
2492
+ });
2493
+ }
2494
+ async runInit() {
2495
+ await this.claimNamespace();
2496
+ const native = this.nativeClient();
2497
+ if (Option13.isNone(native)) {
2498
+ this.releaseNamespace();
2499
+ return this.swallowed(
2500
+ "init",
2501
+ Result6.err(
2502
+ new VoidhashError(
2503
+ "FAILED_TO_INITIALIZE_VOIDHASH_CLIENT",
2504
+ `FAILED_TO_INITIALIZE_VOIDHASH_CLIENT: the Voidhash native module is missing. Rebuild the app after installing ${this.setup.packageName}.`
2505
+ )
2506
+ )
2507
+ );
2508
+ }
2509
+ const started = await native.value.start(this.configuration());
2510
+ if (started.isErr()) {
2511
+ this.releaseNamespace();
2512
+ return this.swallowed("init", started);
2513
+ }
2514
+ this.initialDistinctId = Option13.none();
2515
+ this.chosenAnalyticsConsent = Option13.none();
2516
+ this.analyticsConsent = Option13.getOrElse(
2517
+ native.value.getAnalyticsConsent(),
2518
+ () => this.analyticsConsent
2519
+ );
2520
+ this.ended = false;
2521
+ this._isInitialized = true;
2522
+ this.atomRegistry.update(clientRunAtom, (runs) => runs + 1);
2523
+ return Result6.ok(void 0);
2524
+ }
2525
+ /**
2526
+ * Makes this client the owner of its storage namespace (of the process,
2527
+ * where it runs one native client), ending the client that owned it until
2528
+ * now. It is the owner before that client has ended, so identity and
2529
+ * purchase calls made on a replaced client of the same namespace meanwhile
2530
+ * already go to this one instead of starting the replaced one again.
2531
+ */
2532
+ async claimNamespace() {
2533
+ const owner = MutableHashMap.get(liveClients, this.slot);
2534
+ MutableHashMap.set(liveClients, this.slot, this);
2535
+ if (Option13.isNone(owner) || owner.value === this) return;
2536
+ if (__DEV__) {
2537
+ console.warn(
2538
+ owner.value.namespace === this.namespace ? "[voidhash] A second client for the same publishable key and base URL replaced the first one. Create the client once, at module scope." : "[voidhash] A client for another publishable key or base URL ended the one that was running: Android runs one Voidhash client at a time."
2539
+ );
2540
+ }
2541
+ await owner.value.end();
2542
+ }
2543
+ /** Gives up this client's storage namespace, if it still owns it. */
2544
+ releaseNamespace() {
2545
+ if (Option13.exists(MutableHashMap.get(liveClients, this.slot), (owner) => owner === this)) {
2546
+ MutableHashMap.remove(liveClients, this.slot);
2547
+ }
2548
+ }
2549
+ /**
2550
+ * Ends the client: flushes for at most about two seconds, persists what is
2551
+ * still queued and stops every observer, timer and listener. Whatever was
2552
+ * not delivered goes out after the next `init()`. An `init()` still running
2553
+ * is waited for first. The client stops being initialized as soon as the
2554
+ * teardown begins: reads answer `VOIDHASH_CLIENT_NOT_INITIALIZED` from then
2555
+ * on. Afterwards `capture()` drops events with a diagnostic and `init()`
2556
+ * starts the client again. Overlapping calls share one teardown. No-ops on
2557
+ * a disabled client.
2558
+ */
2559
+ async end() {
2560
+ if (!this.setup.enabled) return Result6.ok(void 0);
2561
+ const pending = this.transition;
2562
+ if (Option13.isSome(pending) && pending.value.to === "ended") return pending.value.settled;
2563
+ return this.runTransition("ended", async () => {
2564
+ if (Option13.isSome(pending)) await pending.value.settled;
2565
+ const started = this.started();
2566
+ if (started.isErr()) {
2567
+ this.releaseNamespace();
2568
+ return Result6.err(started.error);
2569
+ }
2570
+ this.eventsHeldForIdentity.splice(0).forEach((event) => event.send());
2571
+ this._isInitialized = false;
2572
+ const shutdown = await started.value.shutdown().finally(() => {
2573
+ this.ended = true;
2574
+ this.releaseNamespace();
2575
+ });
2576
+ return shutdown.map(() => void 0);
2577
+ });
2578
+ }
2579
+ /** Whether the client is initialized. Always false while the client is disabled. */
2580
+ get isInitialized() {
2581
+ return this._isInitialized;
2582
+ }
2583
+ /** Whether this client does anything at all, fixed at construction by the `enabled` option. */
2584
+ get isEnabled() {
2585
+ return this.setup.enabled;
2586
+ }
2587
+ /** Whether the SDK currently runs in observer ("read-only") mode. */
2588
+ get isReadOnly() {
2589
+ return this.readOnly;
2590
+ }
2591
+ /**
2592
+ * Switches observer mode at runtime, so an app migrating onto Voidhash can
2593
+ * flip from watching another SDK's purchases to owning them without
2594
+ * recreating the client. A purchase that already started keeps the mode it
2595
+ * started with. No-ops in effect on a disabled client.
2596
+ */
2597
+ setReadOnly(readOnly) {
2598
+ this.readOnly = readOnly;
2599
+ Option13.map(this.native, (native) => native.setReadOnly(readOnly));
2600
+ }
2601
+ /**
2602
+ * The end user's analytics consent in effect: the last
2603
+ * {@link setAnalyticsConsent} value, else (once `init()` has read it) the
2604
+ * stored one, else the `analyticsConsent` option.
2605
+ */
2606
+ getAnalyticsConsent() {
2607
+ return this.analyticsConsent;
2608
+ }
2609
+ /**
2610
+ * Records whether the end user consents to usage analytics. Takes effect
2611
+ * immediately and is stored on the device, where it takes precedence over
2612
+ * the `analyticsConsent` option on later launches; `reset()` and
2613
+ * `signOut()` keep it.
2614
+ *
2615
+ * `"denied"` and `"pending"` stop all analytics: events, screens, lifecycle
2616
+ * and install events and paywall impressions are dropped, and every event
2617
+ * still queued on the device is discarded together with the analytics
2618
+ * session. Purchases, restores, entitlements, `identify()`, person
2619
+ * attributes, groups, feature flags and paywalls are unaffected. `"granted"`
2620
+ * resumes analytics for what is captured from then on.
2621
+ *
2622
+ * Called before `init()` the consent applies at once and is stored when
2623
+ * `init()` runs. An `Err` with `FAILED_TO_SET_ANALYTICS_CONSENT` means the
2624
+ * consent applies to this process but could not be stored; an invalid value
2625
+ * is an `INVALID_ARGUMENT` error and changes nothing.
2626
+ */
2627
+ async setAnalyticsConsent(consent) {
2628
+ if (!isAnalyticsConsent(consent)) {
2629
+ return Result6.err(
2630
+ new InvalidArgumentError(
2631
+ `setAnalyticsConsent() needs "granted", "denied" or "pending", got ${String(consent)}`
2632
+ )
2633
+ );
2634
+ }
2635
+ this.analyticsConsent = consent;
2636
+ if (consent === "granted") this.analyticsConsentDeniedReported = false;
2637
+ if (!this.setup.enabled) return Result6.ok(void 0);
2638
+ if (Option13.isSome(this.transition)) await this.transition.value.settled;
2639
+ const started = this.started();
2640
+ if (started.isErr()) {
2641
+ this.chosenAnalyticsConsent = Option13.some(consent);
2642
+ await Option13.match(this.native, {
2643
+ onNone: () => Promise.resolve(),
2644
+ onSome: (native) => native.setAnalyticsConsent(consent)
2645
+ });
2646
+ return Result6.ok(void 0);
2647
+ }
2648
+ const stored = await started.value.setAnalyticsConsent(consent);
2649
+ if (stored.isErr()) return Result6.err(stored.error);
2650
+ return stored.value ? Result6.ok(void 0) : Result6.err(
2651
+ new VoidhashError(
2652
+ "FAILED_TO_SET_ANALYTICS_CONSENT",
2653
+ "FAILED_TO_SET_ANALYTICS_CONSENT: the consent applies now but could not be stored on the device"
2654
+ )
2655
+ );
2656
+ }
2657
+ /**
2658
+ * Returns the current person snapshot together with how much to trust it.
2659
+ * The answer comes from cache whenever one exists — a stale entry is served
2660
+ * while a refresh runs behind the read — so this never waits long on the
2661
+ * network and never fails because the server is unreachable. Pass
2662
+ * `{ forceFetch: true }` to prefer the server. Answers an empty snapshot
2663
+ * while disabled.
2664
+ */
2665
+ async getCurrentPerson(options = {}) {
2666
+ if (!this.setup.enabled) {
2667
+ return Result6.ok({ isExpired: false, isStale: false, person: null, reason: "no-cache" });
2668
+ }
2669
+ const started = this.started();
2670
+ if (started.isErr()) return Result6.err(started.error);
2671
+ return started.value.getCurrentPerson(options);
2672
+ }
2673
+ /**
2674
+ * Checks whether the current person holds an active grant for a perk.
2675
+ *
2676
+ * Cache-first: a fresh snapshot answers immediately, a stale one is served
2677
+ * while a refresh runs behind the read, and an entitlement granted before
2678
+ * the device went offline keeps answering `true`. The result always says how
2679
+ * fresh it is (`isStale`, `isExpired`, `reason`) — it never fails because
2680
+ * the server is unreachable. Pass `{ forceFetch: true }` to prefer the
2681
+ * server.
2682
+ */
2683
+ async hasPerk(perkSlug, options = {}) {
2684
+ if (!this.setup.enabled) {
2685
+ return Result6.ok({
2686
+ hasAccess: false,
2687
+ isExpired: false,
2688
+ isStale: false,
2689
+ reason: "no-cache"
2690
+ });
2691
+ }
2692
+ const started = this.started();
2693
+ if (started.isErr()) return Result6.err(started.error);
2694
+ return started.value.hasPerk(perkSlug, { forceFetch: options.forceFetch });
2695
+ }
2696
+ /**
2697
+ * Sets person attributes without waiting on the network. Reserved
2698
+ * `email`/`name` keys map to the dedicated server fields (strings); any
2699
+ * other key is a custom trait whose value must be a string, a number, a
2700
+ * boolean or `null`. Anything else is an `INVALID_ARGUMENT` error and
2701
+ * nothing is written. The update is stored on the device and sent right
2702
+ * away, then retried until the server applies it; `flush()` waits for it.
2703
+ * Attributes are written whatever the analytics consent, except that the
2704
+ * native SDK leaves `$ad_data_sharing` set to anything but `false` out until
2705
+ * it is granted: see {@link setAdDataSharing}.
2706
+ *
2707
+ * Like identity calls, it waits for initialization and runs in call order
2708
+ * with `identify()`, `reset()` and `signOut()`, so the attributes belong to
2709
+ * the person identified when this was called. Called right after an
2710
+ * `identify()` that wasn't awaited, it resolves once that identify settles.
2711
+ */
2712
+ async setPersonAttributes(attributes) {
2713
+ if (!this.setup.enabled) return Result6.ok(void 0);
2714
+ const invalid = invalidPersonAttributes(attributes);
2715
+ if (Option13.isSome(invalid)) return Result6.err(invalid.value);
2716
+ const replacement = this.replacement();
2717
+ if (Option13.isSome(replacement)) return replacement.value.setPersonAttributes(attributes);
2718
+ return this.enqueueInIdentityOrder(async () => {
2719
+ const started = this.started();
2720
+ if (started.isErr()) return this.swallowed("setPersonAttributes", Result6.err(started.error));
2721
+ return this.swallowed(
2722
+ "setPersonAttributes",
2723
+ await started.value.setPersonAttributes(attributes)
2724
+ );
2725
+ });
2726
+ }
2727
+ /**
2728
+ * Records whether the end user agreed to you sharing their purchases with ad
2729
+ * platforms, as the person trait `$ad_data_sharing`. Voidhash sends a
2730
+ * person's purchases to a Conversions API you turned on only when it is
2731
+ * `true`.
2732
+ *
2733
+ * `true` needs analytics consent: it does nothing while that is not
2734
+ * granted. Once written, it also drops a revocation
2735
+ * still queued for the person. `false` is a revocation, which analytics
2736
+ * consent neither blocks nor discards: the native SDK stores it on the device
2737
+ * and retries it until Voidhash has written it, or for 48 hours while Voidhash
2738
+ * has no such person, and it records no analytics. When someone rejects
2739
+ * everything, call it next to `setAnalyticsConsent("denied")`. Withdrawing
2740
+ * analytics consent does not take this back by itself.
2741
+ *
2742
+ * Waits for initialization and runs in call order with identity changes, as
2743
+ * {@link setPersonAttributes} does.
2744
+ */
2745
+ async setAdDataSharing(granted) {
2746
+ return this.setPersonAttributes({ $ad_data_sharing: granted === true });
2747
+ }
2748
+ /**
2749
+ * Sets person attributes and reports whether the server confirmed them.
2750
+ * When the server cannot confirm the update now (it is unreachable, the key
2751
+ * was rejected, or an earlier write for this person is still queued) the
2752
+ * update is queued and the result is `deferred` with the last known
2753
+ * snapshot, rather than an error. Values, ordering and observer mode follow
2754
+ * {@link setPersonAttributes}: attributes are written whatever the analytics
2755
+ * consent and whether or not the client is read-only. The result is
2756
+ * `skipped` only when the one attribute was an agreement to ad data sharing
2757
+ * made without analytics consent: see {@link setAdDataSharing}.
2758
+ */
2759
+ async setPersonAttributesSync(attributes) {
2760
+ if (!this.setup.enabled) return Result6.ok({ person: null, status: "disabled" });
2761
+ const invalid = invalidPersonAttributes(attributes);
2762
+ if (Option13.isSome(invalid)) return Result6.err(invalid.value);
2763
+ const replacement = this.replacement();
2764
+ if (Option13.isSome(replacement)) return replacement.value.setPersonAttributesSync(attributes);
2765
+ return this.enqueueInIdentityOrder(async () => {
2766
+ const started = this.started();
2767
+ if (started.isErr()) return Result6.err(started.error);
2768
+ return started.value.setPersonAttributesSync(attributes);
2769
+ });
2770
+ }
2771
+ /**
2772
+ * Returns the active analytics session id, or `undefined` before `init()`,
2773
+ * while disabled, or once the session has been idle past the inactivity
2774
+ * timeout. Reading does not extend the session.
2775
+ */
2776
+ // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK method consumed by non-Effect app code; `undefined` is the documented "no active session" answer and mirrors the iOS and Android SDKs.
2777
+ getSessionId() {
2778
+ const started = this.started();
2779
+ return this.setup.enabled && started.isOk() ? started.value.getSessionId() : void 0;
2780
+ }
2781
+ /** Returns the current distinct id, or `Ok(null)` while disabled. */
2782
+ // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK method consumed by non-Effect app code; `null` is the documented answer of a disabled client.
2783
+ async getDistinctId() {
2784
+ if (!this.setup.enabled) return Result6.ok(null);
2785
+ const started = this.started();
2786
+ if (started.isErr()) return Result6.err(started.error);
2787
+ return started.value.getDistinctId();
2788
+ }
2789
+ /**
2790
+ * Identifies the user by switching the current distinct id. The switch
2791
+ * happens locally first, and the link from the previous (anonymous)
2792
+ * identity is stored on the device before it is sent; when the server
2793
+ * cannot confirm it now, the link is retried until it lands rather than
2794
+ * failing, and an anonymous purchaser keeps their cached access meanwhile.
2795
+ * Use {@link identifySync} to learn which of the two happened. Identity
2796
+ * calls wait for initialization and run in invocation order. Repeating the
2797
+ * same ID without profile changes preserves the session and cached state.
2798
+ * A blank ID is an `INVALID_ARGUMENT` error and leaves the identity alone.
2799
+ */
2800
+ async identify(externalUserId, options = {}) {
2801
+ if (!this.setup.enabled) return Result6.ok(void 0);
2802
+ if (!isNonBlankString(externalUserId)) {
2803
+ return Result6.err(new InvalidArgumentError("identify() needs a non-blank distinct id"));
2804
+ }
2805
+ const replacement = this.replacement();
2806
+ if (Option13.isSome(replacement)) return replacement.value.identify(externalUserId, options);
2807
+ return this.enqueueIdentityChange(async () => {
2808
+ const started = this.started();
2809
+ if (started.isErr()) return Result6.err(started.error);
2810
+ return this.swallowed("identify", await started.value.identify(externalUserId, options));
2811
+ }, Option13.some(externalUserId));
2812
+ }
2813
+ /**
2814
+ * Identifies the user and reports whether the server confirmed the switch
2815
+ * (`confirmed`, with the person) or the device switched locally and queued
2816
+ * the link for later delivery (`deferred`, with the last known snapshot
2817
+ * for that identity, if any). Only a verdict the Voidhash API will not
2818
+ * change — which also restores the previous identity — or a blank ID
2819
+ * (`INVALID_ARGUMENT`) is an `Err`.
2820
+ */
2821
+ async identifySync(externalUserId, options = {}) {
2822
+ if (!this.setup.enabled) return Result6.ok({ person: null, status: "disabled" });
2823
+ if (!isNonBlankString(externalUserId)) {
2824
+ return Result6.err(new InvalidArgumentError("identifySync() needs a non-blank distinct id"));
2825
+ }
2826
+ const replacement = this.replacement();
2827
+ if (Option13.isSome(replacement)) {
2828
+ return replacement.value.identifySync(externalUserId, options);
2829
+ }
2830
+ return this.enqueueIdentityChange(async () => {
2831
+ const started = this.started();
2832
+ if (started.isErr()) return Result6.err(started.error);
2833
+ return started.value.identifySync(externalUserId, options);
2834
+ }, Option13.some(externalUserId));
2835
+ }
2836
+ /**
2837
+ * Starts a fresh visitor: a new anonymous distinct id and analytics session,
2838
+ * with no groups. When someone is signed in this is exactly `signOut()`;
2839
+ * when nobody is, `signOut()` does nothing and this still starts over, with
2840
+ * no event recorded. Use it for a shared device, or a guest starting over.
2841
+ */
2842
+ async reset() {
2843
+ if (!this.setup.enabled) return Result6.ok(void 0);
2844
+ const replacement = this.replacement();
2845
+ if (Option13.isSome(replacement)) return replacement.value.reset();
2846
+ return this.enqueueIdentityChange(async () => {
2847
+ const started = this.started();
2848
+ if (started.isErr()) return Result6.err(started.error);
2849
+ return this.swallowed("reset", await started.value.reset());
2850
+ });
2851
+ }
2852
+ /**
2853
+ * Signs the current user out: captures the built-in `$sign_out` event
2854
+ * (unless automatic lifecycle events are off or analytics consent is not
2855
+ * granted), flushes it under the signing-out identity, then resets to a
2856
+ * fresh anonymous distinct id and starts a new analytics session. Does
2857
+ * nothing when nobody is signed in, so it is safe to call whenever the app
2858
+ * finds no session; `reset()` is the call for a fresh anonymous visitor.
2859
+ */
2860
+ async signOut() {
2861
+ if (!this.setup.enabled) return Result6.ok(void 0);
2862
+ const replacement = this.replacement();
2863
+ if (Option13.isSome(replacement)) return replacement.value.signOut();
2864
+ return this.enqueueIdentityChange(async () => {
2865
+ const started = this.started();
2866
+ if (started.isErr()) return Result6.err(started.error);
2867
+ return this.swallowed("signOut", await started.value.signOut());
2868
+ });
2869
+ }
2870
+ /**
2871
+ * Puts the end user in a group, such as the company or workspace they use
2872
+ * your app as part of. Every event captured after the returned promise
2873
+ * resolves carries it in `$groups`, until `resetGroups()`, `reset()` or
2874
+ * `signOut()`; the native SDK stores it on the device with the distinct id,
2875
+ * one group per type.
2876
+ *
2877
+ * `properties` set the group's own properties, such as its `name` and
2878
+ * `plan`: strings, numbers or booleans. They are sent as a `$groupidentify`
2879
+ * event when given, or when the end user's group of that type changed.
2880
+ * Groups and their properties are sent whatever the analytics consent;
2881
+ * without it the `$groupidentify` goes out at once, on its own, and is not
2882
+ * retried if it fails.
2883
+ *
2884
+ * A group type is a lower-case letter followed by up to 63 lower-case
2885
+ * letters, digits or underscores, such as `company`, and a key has 1 to 256
2886
+ * characters; a number is kept as text. Any other is an `INVALID_ARGUMENT`
2887
+ * error. `null` properties count as none. Like identity calls, it waits for initialization and runs in call
2888
+ * order with `identify()`, `reset()` and `signOut()`.
2889
+ */
2890
+ async group(groupType, groupKey, properties) {
2891
+ if (!this.setup.enabled) return Result6.ok(void 0);
2892
+ const key = String(groupKey);
2893
+ const replacement = this.replacement();
2894
+ if (Option13.isSome(replacement)) return replacement.value.group(groupType, key, properties);
2895
+ return this.enqueueInIdentityOrder(async () => {
2896
+ const started = this.started();
2897
+ if (started.isErr()) return Result6.err(started.error);
2898
+ return this.swallowed(
2899
+ "group",
2900
+ await started.value.group(groupType, key, Option13.fromNullishOr(properties))
2901
+ );
2902
+ });
2903
+ }
2904
+ /**
2905
+ * Replaces every group the end user is in, in one call: the groups to be in
2906
+ * by type, each an id or `{ id, ...properties }`. A type left out, or given
2907
+ * as `null` or `undefined`, is dropped. Safe to call whenever the groups
2908
+ * might have changed: a `$groupidentify` is sent only for a group whose id
2909
+ * or properties differ from what was last sent, so repeating a call sends
2910
+ * nothing. An empty object behaves like `resetGroups()`.
2911
+ *
2912
+ * An id is a string or a finite number. A group given with any other id, or
2913
+ * with none, is an `INVALID_ARGUMENT` error for the whole call, and nothing
2914
+ * changes. Types and ids otherwise follow the rules of `group()`: a group
2915
+ * whose type or id those refuse is left out. Runs in call order with `identify()`, `reset()` and `signOut()`.
2916
+ */
2917
+ async setGroups(groups) {
2918
+ if (!this.setup.enabled) return Result6.ok(void 0);
2919
+ const replacement = this.replacement();
2920
+ if (Option13.isSome(replacement)) return replacement.value.setGroups(groups);
2921
+ const invalid = invalidGroups(groups);
2922
+ if (Option13.isSome(invalid)) return Result6.err(invalid.value);
2923
+ return this.enqueueInIdentityOrder(async () => {
2924
+ const started = this.started();
2925
+ if (started.isErr()) return Result6.err(started.error);
2926
+ return this.swallowed("setGroups", await started.value.setGroups(groups));
2927
+ });
2928
+ }
2929
+ /** Takes the end user out of every group; later events carry no `$groups`. */
2930
+ async resetGroups() {
2931
+ if (!this.setup.enabled) return Result6.ok(void 0);
2932
+ const replacement = this.replacement();
2933
+ if (Option13.isSome(replacement)) return replacement.value.resetGroups();
2934
+ return this.enqueueInIdentityOrder(async () => {
2935
+ const started = this.started();
2936
+ if (started.isErr()) return Result6.err(started.error);
2937
+ return this.swallowed("resetGroups", await started.value.resetGroups());
2938
+ });
2939
+ }
2940
+ /**
2941
+ * The groups the end user belongs to, by group type, as `group()` set them:
2942
+ * `{}` before `init()` resolves, while disabled, and when they belong to none.
2943
+ */
2944
+ getGroups() {
2945
+ const started = this.started();
2946
+ return this.setup.enabled && started.isOk() ? started.value.getGroups() : {};
2947
+ }
2948
+ /**
2949
+ * Evaluates feature flags for the current person, cache-first: `flagKeys`
2950
+ * (every flag when omitted), each with its enabled state, variant key
2951
+ * (`null` without a variant) and payload. Returns no flags while disabled.
2952
+ */
2953
+ async getFeatureFlags(flagKeys) {
2954
+ if (!this.setup.enabled) return Result6.ok(DISABLED_FEATURE_FLAGS);
2955
+ const started = this.started();
2956
+ if (started.isErr()) return Result6.err(started.error);
2957
+ return started.value.getFeatureFlags(flagKeys);
2958
+ }
2959
+ /**
2960
+ * The value of the variant flag `key` selected for the current person: the
2961
+ * variant's value when the flag is enabled and evaluated, `null` when it is
2962
+ * off, has no variant (or one whose value is not text), is unknown, or was
2963
+ * not evaluated within `featureFlags.maxWaitMs`. Evaluates `key`
2964
+ * cache-first, as `getFeatureFlags([key])` does. Answers `Ok(null)` while
2965
+ * disabled. Typed by the variant values `voidhash.gen.d.ts` lists for the
2966
+ * flag; a variant added since generation is not in that union.
2967
+ */
2968
+ async getVariantValue(key) {
2969
+ const evaluation = await this.getFeatureFlags([key]);
2970
+ return evaluation.map(({ flags }) => {
2971
+ const flag = flags.find((candidate) => candidate.key === key);
2972
+ return flag?.enabled === true && P8.isString(flag.payload) ? flag.payload : null;
2973
+ });
2974
+ }
2975
+ /**
2976
+ * Resolves the currently assigned paywall showing for a location slug.
2977
+ * Answers `Ok(null)` while disabled.
2978
+ */
2979
+ async getPaywallForLocation(locationSlug) {
2980
+ if (!this.setup.enabled) return Result6.ok(null);
2981
+ const started = this.started();
2982
+ if (started.isErr()) return Result6.err(started.error);
2983
+ return started.value.getPaywallForLocation(String(locationSlug));
2984
+ }
2985
+ async getProducts(slugs) {
2986
+ if (!this.setup.enabled) {
2987
+ return Result6.ok(slugs === void 0 ? [] : slugs.map(() => void 0));
2988
+ }
2989
+ const started = this.started();
2990
+ if (started.isErr()) return Result6.err(started.error);
2991
+ return (await started.value.loadProducts()).map(
2992
+ (products) => slugs === void 0 ? products : slugs.map((slug) => products.find((product) => product.slug === slug))
2993
+ );
2994
+ }
2995
+ /**
2996
+ * Buys a product from `getProducts()` or `useProducts()`. By default a
2997
+ * subscription comes with the free trial or introductory price the end
2998
+ * user is eligible for; `options.offer` picks another offer or the regular
2999
+ * price. Resolves to a `Result`: `purchased`, `pending` and `cancelled` are
3000
+ * outcomes, every failure is an `Err` carrying a coded
3001
+ * {@link VoidhashError}. Answers `Ok({ status: "disabled" })` while
3002
+ * disabled.
3003
+ *
3004
+ * Waits for `init()`. One purchase runs at a time: another started while
3005
+ * it runs fails with `PURCHASE_IN_PROGRESS` and buys nothing. Blocked in
3006
+ * observer mode; the mode in effect when the purchase starts decides, so a
3007
+ * `setReadOnly()` landing later doesn't abandon it. Options no store could
3008
+ * honour are an `INVALID_ARGUMENT` error, and nothing is bought.
3009
+ */
3010
+ async purchase(product, options = {}) {
3011
+ if (!this.setup.enabled) return Result6.ok({ status: "disabled" });
3012
+ const slug = P8.hasProperty(product, "slug") ? product.slug : void 0;
3013
+ if (!isNonBlankString(slug)) {
3014
+ return Result6.err(
3015
+ new InvalidArgumentError("purchase() needs a product from getProducts() or useProducts()")
3016
+ );
3017
+ }
3018
+ const nativeOptions = toNativePurchaseOptions(product, options);
3019
+ if (EffectResult2.isFailure(nativeOptions)) return Result6.err(nativeOptions.failure);
3020
+ const replacement = this.replacement();
3021
+ if (Option13.isSome(replacement)) return replacement.value.purchase(product, options);
3022
+ if (Option13.isSome(this.purchaseInFlight)) return Result6.err(new PurchaseInProgressError());
3023
+ const purchased = (async () => {
3024
+ const initialized = await this.whenInitialized();
3025
+ if (initialized.isErr()) return Result6.err(initialized.error);
3026
+ if (this.readOnly) return Result6.err(new ReadOnlyModePurchaseNotAllowedError());
3027
+ return initialized.value.purchase(slug, nativeOptions.success);
3028
+ })().finally(() => {
3029
+ this.purchaseInFlight = Option13.none();
3030
+ });
3031
+ this.purchaseInFlight = Option13.some(purchased);
3032
+ return purchased;
3033
+ }
3034
+ /**
3035
+ * Revalidates restorable purchases for the user who requested the restore,
3036
+ * and answers the refreshed person, `null` when there is none, so a
3037
+ * "nothing to restore" needs no second read: check the person's
3038
+ * entitlements. Call from a user action: iOS may prompt for App Store
3039
+ * authentication. Known consumables are excluded. Waits for `init()`;
3040
+ * answers `Ok(null)` while disabled.
3041
+ */
3042
+ // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.
3043
+ async restorePurchases() {
3044
+ if (!this.setup.enabled) return Result6.ok(null);
3045
+ const replacement = this.replacement();
3046
+ if (Option13.isSome(replacement)) return replacement.value.restorePurchases();
3047
+ const initialized = await this.whenInitialized();
3048
+ if (initialized.isErr()) return Result6.err(initialized.error);
3049
+ const restored = await initialized.value.restorePurchases();
3050
+ return restored.isOk() ? restored : this.swallowed("restorePurchases", Result6.err(restored.error)).map(() => null);
3051
+ }
3052
+ /**
3053
+ * Calls `listener` with each purchase that completes outside `purchase()`:
3054
+ * an approved Ask to Buy, a pending payment that went through, a redeemed
3055
+ * offer code, a promoted purchase, and on iOS a renewal seen on the device
3056
+ * (`transaction.isRenewal`; Google Play does not report renewals to the
3057
+ * device). A purchase or restore made in a flow is not one: `presentFlow()`
3058
+ * answers it. It is called once the SDK handled the purchase; `synced`
3059
+ * says whether Voidhash already accepted it. A signal for the UI, not a
3060
+ * delivery guarantee: access always comes from the person's entitlements,
3061
+ * which hooks re-render with. Returns the function that removes the
3062
+ * listener. Never called while disabled.
3063
+ */
3064
+ addTransactionListener(listener) {
3065
+ const entry = (update2) => listener(update2);
3066
+ MutableHashSet.add(this.transactionListeners, entry);
3067
+ return () => {
3068
+ MutableHashSet.remove(this.transactionListeners, entry);
3069
+ };
3070
+ }
3071
+ /**
3072
+ * Opens the store's subscription management: the App Store's sheet (for
3073
+ * `product`'s subscription group, on iOS 17 and later) or Google Play's
3074
+ * subscriptions page (for `product`, when given). No-op while disabled.
3075
+ */
3076
+ async showManageSubscriptions(product) {
3077
+ if (!this.setup.enabled) return Result6.ok(void 0);
3078
+ const started = this.started();
3079
+ if (started.isErr()) return Result6.err(started.error);
3080
+ return this.swallowed(
3081
+ "showManageSubscriptions",
3082
+ await started.value.showManageSubscriptions(product?.slug)
3083
+ );
3084
+ }
3085
+ /**
3086
+ * Lets the end user redeem an offer code: Apple's redemption sheet (where
3087
+ * they type the code; `code` is ignored), or Google Play's redeem page
3088
+ * filled in with `code`. A redeemed code arrives as a transaction update.
3089
+ * No-op while disabled.
3090
+ */
3091
+ async presentCodeRedemption(code) {
3092
+ if (!this.setup.enabled) return Result6.ok(void 0);
3093
+ const started = this.started();
3094
+ if (started.isErr()) return Result6.err(started.error);
3095
+ return this.swallowed("presentCodeRedemption", await started.value.presentCodeRedemption(code));
3096
+ }
3097
+ /**
3098
+ * The storefront the end user buys from: its ISO 3166-1 alpha-2 country,
3099
+ * and currency where the store says. `undefined` when the store has none to
3100
+ * give, and while disabled.
3101
+ */
3102
+ // oxlint-disable-next-line effect/prefer-option-over-null -- public SDK answer consumed by non-Effect app code.
3103
+ async getStorefront() {
3104
+ if (!this.setup.enabled) return Result6.ok(void 0);
3105
+ const started = this.started();
3106
+ if (started.isErr()) return Result6.err(started.error);
3107
+ return started.value.getStorefront();
3108
+ }
3109
+ /**
3110
+ * Whether this device can make purchases: payments are not restricted (App
3111
+ * Store) and billing is available (Google Play). `false` while disabled.
3112
+ */
3113
+ async canMakePayments() {
3114
+ if (!this.setup.enabled) return Result6.ok(false);
3115
+ const started = this.started();
3116
+ if (started.isErr()) return Result6.err(started.error);
3117
+ return started.value.canMakePayments();
3118
+ }
3119
+ /**
3120
+ * Hands a purchase intent to the listeners, or holds it for the first one
3121
+ * while there is none: the native client sends intents from `init()` on,
3122
+ * possibly before the app added its listener.
3123
+ */
3124
+ receivePurchaseIntent(intent) {
3125
+ if (MutableHashSet.size(this.purchaseIntentListeners) > 0) {
3126
+ this.notify("appStore.addPurchaseIntentListener", this.purchaseIntentListeners, intent);
3127
+ return;
3128
+ }
3129
+ this.heldPurchaseIntents.push(intent);
3130
+ if (this.heldPurchaseIntents.length <= MAX_HELD_PURCHASE_INTENTS) return;
3131
+ const dropped = this.heldPurchaseIntents.shift();
3132
+ this.emitDiagnostic({
3133
+ code: "PURCHASE_INTENT_DROPPED",
3134
+ kind: "eviction",
3135
+ message: `Dropped the purchase intent for "${dropped?.productSlug}": ${MAX_HELD_PURCHASE_INTENTS} are held until a listener is added`,
3136
+ operation: "appStore.addPurchaseIntentListener",
3137
+ retryable: false
3138
+ });
3139
+ }
3140
+ /** App Store actions; see {@link AppStoreActions}. */
3141
+ appStore = {
3142
+ addPurchaseIntentListener: (listener) => {
3143
+ const entry = (intent) => listener(intent);
3144
+ MutableHashSet.add(this.purchaseIntentListeners, entry);
3145
+ const held = this.heldPurchaseIntents.splice(0);
3146
+ held.forEach((intent) => this.notify("appStore.addPurchaseIntentListener", [entry], intent));
3147
+ return () => {
3148
+ MutableHashSet.remove(this.purchaseIntentListeners, entry);
3149
+ };
3150
+ },
3151
+ appTransaction: () => this.storeAction(
3152
+ "appStore",
3153
+ "appTransaction",
3154
+ () => Result6.err(new NotInitializedError()),
3155
+ (native) => native.appStoreAppTransaction()
3156
+ ),
3157
+ beginRefundRequest: (transactionId) => this.storeAction(
3158
+ "appStore",
3159
+ "beginRefundRequest",
3160
+ () => Result6.err(new NotInitializedError()),
3161
+ (native) => native.appStoreBeginRefundRequest(transactionId)
3162
+ ),
3163
+ currentEntitlements: () => this.storeAction(
3164
+ "appStore",
3165
+ "currentEntitlements",
3166
+ () => Result6.ok([]),
3167
+ (native) => native.appStoreCurrentEntitlements()
3168
+ ),
3169
+ subscriptionStatus: (groupId) => this.storeAction(
3170
+ "appStore",
3171
+ "subscriptionStatus",
3172
+ () => Result6.ok([]),
3173
+ (native) => native.appStoreSubscriptionStatus(groupId)
3174
+ )
3175
+ };
3176
+ /** Google Play actions; see {@link GooglePlayActions}. */
3177
+ googlePlay = {
3178
+ isFeatureSupported: (feature) => this.storeAction(
3179
+ "googlePlay",
3180
+ "isFeatureSupported",
3181
+ () => Result6.ok(false),
3182
+ (native) => native.googlePlayIsFeatureSupported(feature)
3183
+ ),
3184
+ queryPurchases: (options = {}) => this.storeAction(
3185
+ "googlePlay",
3186
+ "queryPurchases",
3187
+ () => Result6.ok([]),
3188
+ (native) => native.googlePlayQueryPurchases(options.includeSuspended ?? true)
3189
+ ),
3190
+ showInAppMessages: () => this.storeAction(
3191
+ "googlePlay",
3192
+ "showInAppMessages",
3193
+ () => Result6.ok({ status: "noActionNeeded" }),
3194
+ (native) => native.googlePlayShowInAppMessages()
3195
+ )
3196
+ };
3197
+ /**
3198
+ * Runs an action of one store: `UNSUPPORTED_PLATFORM` on the other
3199
+ * platform, `whileDisabled` on a disabled client, and
3200
+ * `VOIDHASH_CLIENT_NOT_INITIALIZED` before `init()`.
3201
+ */
3202
+ async storeAction(store, operation, whileDisabled, run) {
3203
+ const platform = store === "appStore" ? "ios" : "android";
3204
+ if (this.setup.platform !== platform) {
3205
+ return Result6.err(
3206
+ new UnsupportedPlatformError(
3207
+ this.setup.platform,
3208
+ `${store}.${operation}() is available on ${store === "appStore" ? "iOS" : "Android"} only`
3209
+ )
3210
+ );
3211
+ }
3212
+ if (!this.setup.enabled) return whileDisabled();
3213
+ const started = this.started();
3214
+ if (started.isErr()) return Result6.err(started.error);
3215
+ return run(started.value);
3216
+ }
3217
+ /** Calls every listener with `value`; one that throws is reported and the others still run. */
3218
+ notify(operation, listeners, value3) {
3219
+ Array.from(listeners).forEach((listener) => {
3220
+ try {
3221
+ listener(value3);
3222
+ } catch (error) {
3223
+ this.reportHostCallbackFailure(operation, error);
3224
+ }
3225
+ });
3226
+ }
3227
+ async presentFlow(location, options) {
3228
+ if (!this.setup.enabled) throw flowError("FLOW_DISABLED", "Voidhash is disabled");
3229
+ const replacement = this.replacement();
3230
+ if (Option13.isSome(replacement)) return replacement.value.presentFlow(location, options);
3231
+ const initialized = await this.whenInitialized();
3232
+ if (initialized.isErr()) throw flowError("FLOW_UNAVAILABLE", initialized.error.message);
3233
+ return initialized.value.presentFlow(location, options);
3234
+ }
3235
+ async updateFlowInput(values2) {
3236
+ const started = this.started();
3237
+ if (!this.setup.enabled || started.isErr()) return;
3238
+ await started.value.updateFlowInput(values2);
3239
+ }
3240
+ /**
3241
+ * Closes the flow on screen, if any; its `presentFlow()` resolves as
3242
+ * `dismissed`. No-op while disabled.
3243
+ */
3244
+ async dismissFlow() {
3245
+ const started = this.started();
3246
+ if (!this.setup.enabled || started.isErr()) return;
3247
+ await started.value.dismissFlow();
3248
+ }
3249
+ /**
3250
+ * Reports a purchase your own billing integration completed: its Apple
3251
+ * transaction (ID or JWS) or its Google Play token. Other purchase metadata
3252
+ * is optional and discarded. On iOS, a JWS is sent as the device's proof of
3253
+ * the purchase; with an ID only, the native SDK reads the JWS from the
3254
+ * device's purchase history.
3255
+ *
3256
+ * The report is a purchase the user just made: it goes to the current
3257
+ * user, even when an earlier purchase of the Apple Account or Google account
3258
+ * belongs to another user. Voidhash moves a purchase only when the store
3259
+ * shows it was made in the last 24 hours, and on iOS only with the JWS;
3260
+ * otherwise it is recorded for its current owner. A purchase is claimed
3261
+ * once from a device: reporting it again, also after another user signed
3262
+ * in, cannot move it.
3263
+ *
3264
+ * A report made after an `identify()`, `reset()` or `signOut()` that was
3265
+ * not awaited goes to the user that call switches to: it waits until the
3266
+ * device has switched, not for Voidhash to answer.
3267
+ *
3268
+ * Does not query, finish, acknowledge or consume the purchase. Pending
3269
+ * Android purchases are ignored; report them again when purchased.
3270
+ * Delivery failures remain queued for retry, so success does not imply
3271
+ * server acceptance.
3272
+ */
3273
+ async reportTransaction(transaction, options) {
3274
+ if (!this.setup.enabled) return Result6.ok(void 0);
3275
+ const replacement = this.replacement();
3276
+ if (Option13.isSome(replacement)) {
3277
+ return replacement.value.reportTransaction(transaction, options);
3278
+ }
3279
+ const report = EffectResult2.try({
3280
+ catch: (error) => new VoidhashError(
3281
+ "FAILED_TO_REPORT_TRANSACTION",
3282
+ `FAILED_TO_REPORT_TRANSACTION: ${P8.isError(error) ? error.message : String(error)}`,
3283
+ { cause: error }
3284
+ ),
3285
+ try: () => toNativeReport(fromReportedTransaction(transaction))
3286
+ });
3287
+ if (EffectResult2.isFailure(report)) {
3288
+ return this.swallowed("reportTransaction", Result6.err(report.failure));
3289
+ }
3290
+ await this.afterIdentityChanges();
3291
+ const initialized = await this.whenInitialized();
3292
+ if (initialized.isErr()) return Result6.err(initialized.error);
3293
+ return this.swallowed(
3294
+ "reportTransaction",
3295
+ await initialized.value.reportTransaction(report.success, options?.isRestore === true)
3296
+ );
3297
+ }
3298
+ /**
3299
+ * Reports pending purchases and current store entitlements to Voidhash.
3300
+ * Recovery fallback when a host callback exposes no transaction values. Prefer
3301
+ * reportTransaction for purchase results, especially consumables already finalized.
3302
+ * In observer mode transactions are never finished. Delivery failures stay
3303
+ * queued and emit diagnostics; success does not imply server acceptance.
3304
+ */
3305
+ async syncPurchases() {
3306
+ if (!this.setup.enabled) return Result6.ok(void 0);
3307
+ const replacement = this.replacement();
3308
+ if (Option13.isSome(replacement)) return replacement.value.syncPurchases();
3309
+ await this.afterIdentityChanges();
3310
+ const initialized = await this.whenInitialized();
3311
+ if (initialized.isErr()) return Result6.err(initialized.error);
3312
+ return this.swallowed("syncPurchases", await initialized.value.syncPurchases());
3313
+ }
3314
+ /**
3315
+ * Captures a product analytics event.
3316
+ * Events are batched and delivered on size/time thresholds. Dropped — not
3317
+ * buffered — while disabled or while analytics consent is not granted
3318
+ * (unless `analyticsWhilePending` holds them for a pending one).
3319
+ * Events captured before `init()` resolves are kept and sent once it has,
3320
+ * provided the analytics consent `init()` settles on (the one chosen with
3321
+ * `setAnalyticsConsent()`, else the stored one, else the option) is
3322
+ * `"granted"`; a consent other than `"granted"` chosen meanwhile discards them.
3323
+ *
3324
+ * An event captured after an `identify()`, `reset()` or `signOut()` that
3325
+ * was not awaited is recorded for the person that call switches to: it
3326
+ * waits, in memory, until the device has switched, not for Voidhash to
3327
+ * answer, and keeps the time it was captured at. That is a moment after
3328
+ * `identify()`, and up to about two seconds after a `signOut()` or
3329
+ * `reset()` of a signed-in user, whose last events are sent first. An
3330
+ * identity call runs after the identity, group and person calls made
3331
+ * before it have settled, so behind several of those the wait is as long
3332
+ * as they take, which on a slow network is seconds each. Past 100 events
3333
+ * waiting, the oldest is dropped and reported as `ANALYTICS_EVENT_DROPPED`;
3334
+ * `end()` hands the waiting ones over as they are.
3335
+ *
3336
+ * Property values are copied as the event is captured, into what JSON can
3337
+ * hold: a `bigint` is sent as its decimal string, a `Date` as its ISO
3338
+ * string, a non-finite number as `null`, and functions, symbols,
3339
+ * `undefined` and circular references are left out. An event whose
3340
+ * properties cannot be copied at all (more than 10,000 values, or a getter
3341
+ * that throws) is dropped and reported as `ANALYTICS_EVENT_DROPPED`. Never
3342
+ * throws.
3343
+ */
3344
+ capture(eventName, properties = {}) {
3345
+ if (!this.setup.enabled) return;
3346
+ const normalized = P8.isString(eventName) ? eventName.trim() : "";
3347
+ if (!normalized) return;
3348
+ if (!this.awaitsIdentityChange()) {
3349
+ Option13.map(
3350
+ this.analyticsIntake("capture", normalized),
3351
+ (native2) => native2.capture(normalized, properties)
3352
+ );
3353
+ return;
3354
+ }
3355
+ const native = this.ended ? Option13.none() : this.nativeClient();
3356
+ if (Option13.isNone(native)) {
3357
+ this.analyticsIntake("capture", normalized);
3358
+ return;
3359
+ }
3360
+ Option13.map(
3361
+ native.value.holdEvent("capture", normalized, properties),
3362
+ (send) => this.holdEventForIdentity("capture", normalized, send)
3363
+ );
3364
+ }
3365
+ /**
3366
+ * Reports that the end user opened a notification, as `$push_opened` naming
3367
+ * its send. Call it from your notification library's opened-notification
3368
+ * handler, with the notification's data: the SDK has no notification handling
3369
+ * of its own. A notification not sent through Voidhash is ignored, and so is
3370
+ * one reported again right after its first report, as a handler that reads
3371
+ * the last opened notification on every mount does. Dropped while disabled or
3372
+ * while analytics consent is not granted. Never throws.
3373
+ */
3374
+ trackPushOpened(data) {
3375
+ const sendId = data?.[PUSH_SEND_ID_DATA_KEY];
3376
+ if (!P8.isString(sendId) || sendId.trim() === "") return;
3377
+ if (Option13.contains(this.lastPushOpenedSendId, sendId)) return;
3378
+ this.lastPushOpenedSendId = Option13.some(sendId);
3379
+ this.capture(AUTOMATIC_EVENTS.PUSH_OPENED, { [PUSH_SEND_ID_PROPERTY]: sendId });
3380
+ }
3381
+ /**
3382
+ * The native client an event for `name` can be handed to, or `None` when it
3383
+ * is dropped: without consent (reported once) unless the native client
3384
+ * holds it for a pending one, after `end()`, or without
3385
+ * the native module (each reported).
3386
+ *
3387
+ * Before the client has started only the native client can know the consent
3388
+ * stored on the device, so the event is handed over for it to keep or
3389
+ * discard at start, whatever the `analyticsConsent` option says. A consent
3390
+ * `setAnalyticsConsent()` chose in this process is the exception: it wins
3391
+ * over the stored one, so it decides here already.
3392
+ */
3393
+ analyticsIntake(operation, name) {
3394
+ const known = this._isInitialized ? Option13.some(this.analyticsConsent) : this.chosenAnalyticsConsent;
3395
+ const isRefused = Option13.exists(
3396
+ known,
3397
+ (consent) => consent !== "granted" && !(consent === "pending" && this.setup.analyticsWhilePending === "buffer")
3398
+ );
3399
+ if (isRefused) {
3400
+ this.reportAnalyticsConsentDenied(operation);
3401
+ return Option13.none();
3402
+ }
3403
+ const native = this.ended ? Option13.none() : this.nativeClient();
3404
+ if (Option13.isNone(native)) {
3405
+ this.emitDiagnostic({
3406
+ code: "ANALYTICS_EVENT_DROPPED",
3407
+ kind: "eviction",
3408
+ message: this.ended ? `Dropped "${name}" \u2014 captured after end()` : `Dropped "${name}" \u2014 the Voidhash native module is missing`,
3409
+ operation,
3410
+ retryable: false
3411
+ });
3412
+ }
3413
+ return native;
3414
+ }
3415
+ /**
3416
+ * Captures a `$screen` event for a screen the SDK cannot observe itself
3417
+ * (custom navigation, onboarding steps, pager pages). Every call is a new
3418
+ * screen instance, so calling it twice with the same name emits twice.
3419
+ * No-op while disabled or when `screenTracking.enabled` is `false`. Never
3420
+ * throws: a screen whose name is not a string, or that cannot be read, is
3421
+ * dropped and reported as `ANALYTICS_EVENT_DROPPED`.
3422
+ */
3423
+ screen(name, properties = {}) {
3424
+ this.manualScreenCounter += 1;
3425
+ const identity = `${P8.isString(name) ? name : ""}#${this.manualScreenCounter}`;
3426
+ this.trackScreenView({ identity, name, path: name, source: "manual" }, properties);
3427
+ }
3428
+ /**
3429
+ * Feeds a screen arrival observed by an integration through the screen
3430
+ * tracker and captures `$screen` when it is a new screen instance. Whether
3431
+ * the event may be recorded is settled first: a screen seen without consent
3432
+ * neither runs `mapScreen` nor becomes the previous screen of a later one.
3433
+ * Never throws: it runs inside the host's navigation listeners and effects, so a
3434
+ * screen that cannot be tracked is dropped and reported instead.
3435
+ * @internal
3436
+ */
3437
+ trackScreenView(view, properties = {}) {
3438
+ if (!this.setup.enabled || this.setup.screenTracking.enabled === false) return;
3439
+ const failure = isTrackableScreen(view) ? Option13.map(
3440
+ EffectResult2.getFailure(
3441
+ EffectResult2.try(() => {
3442
+ const native = this.analyticsIntake("screen", view.name);
3443
+ if (Option13.isNone(native)) return;
3444
+ const screenProperties = this.screenTracker.transition(view);
3445
+ if (Option13.isNone(screenProperties)) return;
3446
+ const mappedName = screenProperties.value[SCREEN_PROPERTIES.NAME];
3447
+ const screenName = P8.isString(mappedName) ? mappedName : view.name;
3448
+ const recorded = { ...properties, ...screenProperties.value };
3449
+ if (!this.awaitsIdentityChange()) {
3450
+ native.value.screen(screenName, recorded);
3451
+ return;
3452
+ }
3453
+ Option13.map(
3454
+ native.value.holdEvent("screen", screenName, recorded),
3455
+ (send) => this.holdEventForIdentity("screen", screenName, send)
3456
+ );
3457
+ })
3458
+ ),
3459
+ (error) => P8.isError(error) ? error.message : "it could not be read"
3460
+ ) : Option13.some("its identity, name or path is not a string");
3461
+ if (Option13.isSome(failure)) {
3462
+ this.emitDiagnostic({
3463
+ code: "ANALYTICS_EVENT_DROPPED",
3464
+ kind: "eviction",
3465
+ message: `Dropped a screen: ${failure.value}`,
3466
+ operation: "screen",
3467
+ retryable: false
3468
+ });
3469
+ }
3470
+ }
3471
+ /**
3472
+ * Sends everything queued now: person writes (`identify()` links and
3473
+ * attributes) first, then store receipts and analytics events, and reports
3474
+ * the analytics outcome. Waits at most about two seconds; delivery goes on
3475
+ * past that. Events still waiting for an identity change to switch the
3476
+ * person are sent too: the flush starts once it has. Nothing is ever queued
3477
+ * while disabled, so this no-ops.
3478
+ */
3479
+ async flush() {
3480
+ if (!this.setup.enabled) return Result6.ok({ flushed: 0, pending: 0 });
3481
+ if (this.awaitsIdentityChange()) await this.afterIdentityChanges();
3482
+ if (Option13.isSome(this.flushInFlight)) return this.flushInFlight.value;
3483
+ const started = this.started();
3484
+ if (started.isErr()) return Result6.ok({ flushed: 0, pending: 0 });
3485
+ const inFlight = started.value.flush().finally(() => {
3486
+ this.flushInFlight = Option13.none();
3487
+ });
3488
+ this.flushInFlight = Option13.some(inFlight);
3489
+ return inFlight;
3490
+ }
3491
+ /** Clears the cached person snapshot. The next read refetches from the server. */
3492
+ async resetCache() {
3493
+ if (!this.setup.enabled) return Result6.ok(void 0);
3494
+ const started = this.started();
3495
+ if (started.isErr()) return this.swallowed("resetCache", Result6.err(started.error));
3496
+ return this.swallowed("resetCache", await started.value.resetCache());
3497
+ }
3498
+ /**
3499
+ * Internal surface used by the SDK's React bindings.
3500
+ * Not part of the public API — may change or disappear at any time.
3501
+ */
3502
+ internal = {
3503
+ getAtomRegistry: () => this.atomRegistry,
3504
+ /** What flag `key` reads as while it has no evaluated value: its `featureFlags.defaults` entry, or `false`. */
3505
+ isFeatureEnabledByDefault: (key) => Option13.getOrElse(R7.get(this.setup.featureFlagDefaults, key), () => false),
3506
+ /**
3507
+ * What a purchase of `product` with `options` buys, as text: two
3508
+ * purchases with the same key buy the same product the same way. `None`
3509
+ * for options `purchase()` refuses.
3510
+ */
3511
+ purchaseKey: (product, options) => Option13.flatMap(
3512
+ EffectResult2.getSuccess(toNativePurchaseOptions(product, options)),
3513
+ (native) => encodeJson2({ ...native, productSlug: product.slug })
3514
+ ),
3515
+ getSchema: () => this._isInitialized ? this.atomRegistry.get(schemaAtom) : Option13.none(),
3516
+ getSuccessCallbackBaseUrl: () => `${this.setup.scheme}://voidhash/callback/success`,
3517
+ getErrorCallbackBaseUrl: () => `${this.setup.scheme}://voidhash/callback/error`,
3518
+ reportHostCallbackFailure: (operation, error) => this.reportHostCallbackFailure(operation, error)
3519
+ };
3520
+ /** Reports an exception a callback the app supplied threw; the SDK carried on without it. */
3521
+ reportHostCallbackFailure(operation, error) {
3522
+ this.emitDiagnostic({
3523
+ code: "HOST_CALLBACK_FAILED",
3524
+ kind: "configuration",
3525
+ message: `${operation} threw: ${P8.isError(error) ? error.message : String(error)}`,
3526
+ operation,
3527
+ retryable: false
3528
+ });
3529
+ }
3530
+ /**
3531
+ * Reports, once until consent is granted again, that analytics work was
3532
+ * skipped for lack of consent.
3533
+ */
3534
+ reportAnalyticsConsentDenied(operation) {
3535
+ if (this.analyticsConsentDeniedReported) return;
3536
+ this.analyticsConsentDeniedReported = true;
3537
+ this.emitDiagnostic({
3538
+ code: "ANALYTICS_CONSENT_DENIED",
3539
+ kind: "consent",
3540
+ message: `Skipped ${operation}: analytics consent is "${this.analyticsConsent}", so no analytics are captured or sent until it is granted`,
3541
+ operation,
3542
+ retryable: false
3543
+ });
3544
+ }
3545
+ };
3546
+
3547
+ // ../react-native/src/constants.ts
3548
+ var ANONYMOUS_DISTINCT_ID_PREFIX = "vh_anon_";
3549
+ var LEGACY_ANONYMOUS_DISTINCT_ID_PREFIX = "vh:anon:";
3550
+ var isAnonymousDistinctId = (distinctId) => distinctId.startsWith(ANONYMOUS_DISTINCT_ID_PREFIX) || distinctId.startsWith(LEGACY_ANONYMOUS_DISTINCT_ID_PREFIX);
3551
+
3552
+ // ../react-native/src/core/entities/perk.ts
3553
+ var Perk = class {
3554
+ };
3555
+
3556
+ // src/client-nitro-ui.ts
3557
+ import * as Result8 from "effect/Result";
3558
+ import { Platform } from "nitro-ui-core";
3559
+
3560
+ // ../react-native/src/client-host.ts
3561
+ import * as Arr10 from "effect/Array";
3562
+ import * as Option20 from "effect/Option";
3563
+ import * as P11 from "effect/Predicate";
3564
+ import * as R9 from "effect/Record";
3565
+ import { AtomRegistry } from "effect/reactivity";
3566
+
3567
+ // ../react-native/src/react/hooks/use-person.ts
3568
+ import React3 from "react";
3569
+ import * as Option15 from "effect/Option";
3570
+
3571
+ // ../react-native/src/react/hooks/use-async-function.ts
3572
+ import * as Cause2 from "effect/Cause";
3573
+ import * as Effect7 from "effect/Effect";
3574
+ import * as EffectRuntime from "effect/Effect";
3575
+ import * as Exit2 from "effect/Exit";
3576
+ import * as Option14 from "effect/Option";
3577
+ import * as React from "react";
3578
+ function useAsyncFunction(asyncFn, status) {
3579
+ const latestCall = React.useRef(0);
3580
+ const asyncFnReducer = (state2, action) => {
3581
+ if (action.type === "loading") return { data: state2.data, error: null, isLoading: true };
3582
+ if (action.type === "executed") {
3583
+ return { data: action.payload, error: null, isLoading: false, settledFunction: action.fn };
3584
+ }
3585
+ return {
3586
+ data: state2.data,
3587
+ error: action.payload,
3588
+ isLoading: false,
3589
+ settledFunction: action.fn
3590
+ };
3591
+ };
3592
+ const [state, dispatch] = React.useReducer(asyncFnReducer, { error: null, isLoading: false });
3593
+ const executeAsyncFunction = React.useCallback(async () => {
3594
+ latestCall.current += 1;
3595
+ const call2 = latestCall.current;
3596
+ dispatch({ type: "loading" });
3597
+ const exit2 = await EffectRuntime.runPromise(
3598
+ Effect7.exit(Effect7.tryPromise({ try: () => asyncFn(), catch: (error) => error }))
3599
+ );
3600
+ if (latestCall.current !== call2) {
3601
+ return;
3602
+ }
3603
+ if (Exit2.isSuccess(exit2)) {
3604
+ const result = exit2.value;
3605
+ if (result.isOk()) {
3606
+ dispatch({ fn: asyncFn, payload: result.value, type: "executed" });
3607
+ } else {
3608
+ dispatch({ fn: asyncFn, payload: result.error, type: "error" });
3609
+ }
3610
+ return;
3611
+ }
3612
+ dispatch({
3613
+ fn: asyncFn,
3614
+ payload: new UnknownVoidhashError(Cause2.squash(exit2.cause)),
3615
+ type: "error"
3616
+ });
3617
+ }, [asyncFn]);
3618
+ const refetch = React.useCallback(async () => {
3619
+ await executeAsyncFunction();
3620
+ }, [executeAsyncFunction]);
3621
+ const enabled = Option14.contains(status, "ready");
3622
+ React.useEffect(() => {
3623
+ if (!enabled) {
3624
+ return;
3625
+ }
3626
+ void executeAsyncFunction();
3627
+ return () => {
3628
+ latestCall.current += 1;
3629
+ };
3630
+ }, [executeAsyncFunction, enabled]);
3631
+ return {
3632
+ data: state.data,
3633
+ error: state.error,
3634
+ isLoading: Option14.contains(status, "initializing") || enabled && (state.isLoading || state.settledFunction !== asyncFn),
3635
+ refetch
3636
+ };
3637
+ }
3638
+ var use_async_function_default = useAsyncFunction;
3639
+
3640
+ // ../react-native/src/react/hooks/use-atom-value.ts
3641
+ import React2 from "react";
3642
+ function useAtomValue(registry, atom) {
3643
+ const store = React2.useMemo(
3644
+ () => ({
3645
+ subscribe: (notify) => registry.subscribe(atom, notify),
3646
+ snapshot: () => registry.get(atom)
3647
+ }),
3648
+ [registry, atom]
3649
+ );
3650
+ const value3 = React2.useSyncExternalStore(store.subscribe, store.snapshot);
3651
+ React2.useEffect(() => registry.mount(atom), [registry, atom]);
3652
+ return value3;
3653
+ }
3654
+
3655
+ // ../react-native/src/react/hooks/use-person.ts
3656
+ function currentPersonHookFactory(client, vhContext, hookName = "useCurrentPerson") {
3657
+ function useCurrentPerson() {
3658
+ const status = useProviderStatus(vhContext, hookName);
3659
+ const registry = client.internal.getAtomRegistry();
3660
+ const identityEpoch = useAtomValue(registry, identityEpochAtom);
3661
+ const getPersonCallback = React3.useCallback(
3662
+ () => client.getCurrentPerson(),
3663
+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- identityEpoch is the refetch trigger, not an input of the call.
3664
+ [identityEpoch]
3665
+ );
3666
+ const { isLoading, error, refetch } = use_async_function_default(getPersonCallback, status);
3667
+ const person = useAtomValue(registry, currentPersonAtom);
3668
+ const freshness = useAtomValue(registry, currentPersonFreshnessAtom);
3669
+ return {
3670
+ data: Option15.getOrNull(person),
3671
+ error,
3672
+ isLoading,
3673
+ // Staleness travels with the published snapshot, so a refresh that
3674
+ // lands in the background clears it.
3675
+ isStale: !isLoading && (freshness.isStale || freshness.isExpired),
3676
+ refetch
3677
+ };
3678
+ }
3679
+ return useCurrentPerson;
3680
+ }
3681
+
3682
+ // ../react-native/src/react/hooks/use-feature-flags.ts
3683
+ import React4 from "react";
3684
+ import * as Option16 from "effect/Option";
3685
+ import * as P9 from "effect/Predicate";
3686
+ function featureFlagsHookFactory(client, vhContext) {
3687
+ function useFeatureFlags(flagKeys) {
3688
+ const status = useProviderStatus(vhContext, "useFeatureFlags");
3689
+ const registry = client.internal.getAtomRegistry();
3690
+ const identityEpoch = useAtomValue(registry, identityEpochAtom);
3691
+ const normalizedKeys = normalizeFeatureFlagKeys(flagKeys);
3692
+ const stableFlagKeys = React4.useMemo(
3693
+ () => normalizedKeys === "all" ? void 0 : decodeFeatureFlagKeys(normalizedKeys),
3694
+ [normalizedKeys]
3695
+ );
3696
+ const fetchFlags = React4.useCallback(
3697
+ () => client.getFeatureFlags(stableFlagKeys),
3698
+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- identityEpoch is the refetch trigger, not an input of the call.
3699
+ [stableFlagKeys, identityEpoch]
3700
+ );
3701
+ const { isLoading, error, refetch } = use_async_function_default(fetchFlags, status);
3702
+ const flagsAtom = React4.useMemo(
3703
+ () => featureFlagsForKeysAtom(stableFlagKeys),
3704
+ [stableFlagKeys]
3705
+ );
3706
+ const flags = useAtomValue(registry, flagsAtom);
3707
+ const findFlag = React4.useCallback(
3708
+ (key) => Option16.flatMap(
3709
+ flags,
3710
+ (result) => Option16.fromUndefinedOr(result.flags.find((flag) => flag.key === key))
3711
+ ),
3712
+ [flags]
3713
+ );
3714
+ const isEnabled = React4.useCallback(
3715
+ (key) => Option16.match(findFlag(key), {
3716
+ onNone: () => client.internal.isFeatureEnabledByDefault(key),
3717
+ onSome: (flag) => flag.enabled
3718
+ }),
3719
+ [findFlag]
3720
+ );
3721
+ const getVariantValue = React4.useCallback(
3722
+ // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.
3723
+ (key) => {
3724
+ if (isLoading) return null;
3725
+ const flag = findFlag(key);
3726
+ return Option16.isSome(flag) && flag.value.enabled && P9.isString(flag.value.payload) ? flag.value.payload : null;
3727
+ },
3728
+ [findFlag, isLoading]
3729
+ );
3730
+ const getVariant = React4.useCallback(
3731
+ // oxlint-disable-next-line effect/prefer-option-over-null -- public hook answer consumed by non-Effect app code.
3732
+ (key) => Option16.getOrNull(
3733
+ Option16.map(findFlag(key), (flag) => ({
3734
+ enabled: flag.enabled,
3735
+ payload: flag.payload,
3736
+ variantKey: flag.variantKey
3737
+ }))
3738
+ ),
3739
+ [findFlag]
3740
+ );
3741
+ const data = React4.useMemo(
3742
+ () => ({
3743
+ flags: Option16.match(flags, { onNone: () => [], onSome: (result) => result.flags })
3744
+ }),
3745
+ [flags]
3746
+ );
3747
+ return {
3748
+ data,
3749
+ error,
3750
+ getVariant,
3751
+ getVariantValue,
3752
+ isEnabled,
3753
+ isLoading,
3754
+ refetch
3755
+ };
3756
+ }
3757
+ return useFeatureFlags;
3758
+ }
3759
+
3760
+ // ../react-native/src/react/hooks/use-has-perk.ts
3761
+ import React5 from "react";
3762
+ import * as Option17 from "effect/Option";
3763
+ function hasPerkHookFactory(client, vhContext) {
3764
+ function useHasPerk(perkSlug) {
3765
+ const status = useProviderStatus(vhContext, "useHasPerk");
3766
+ const registry = client.internal.getAtomRegistry();
3767
+ const identityEpoch = useAtomValue(registry, identityEpochAtom);
3768
+ const getPersonCallback = React5.useCallback(
3769
+ () => client.getCurrentPerson(),
3770
+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- identityEpoch is the refetch trigger, not an input of the call.
3771
+ [identityEpoch]
3772
+ );
3773
+ const { isLoading, error, refetch } = use_async_function_default(getPersonCallback, status);
3774
+ const person = useAtomValue(registry, currentPersonAtom);
3775
+ const freshness = useAtomValue(registry, currentPersonFreshnessAtom);
3776
+ const grant = React5.useMemo(() => findActiveGrant(person, perkSlug), [person, perkSlug]);
3777
+ const isStale = !isLoading && (freshness.isStale || freshness.isExpired || error !== null && Option17.isSome(person) && Option17.isSome(grant));
3778
+ return {
3779
+ error,
3780
+ grant: Option17.getOrNull(grant),
3781
+ hasAccess: Option17.isSome(grant),
3782
+ isLoading,
3783
+ isStale,
3784
+ refetch
3785
+ };
3786
+ }
3787
+ return useHasPerk;
3788
+ }
3789
+
3790
+ // ../react-native/src/react/hooks/use-present-flow.ts
3791
+ import * as React6 from "react";
3792
+ function presentFlowHookFactory(client, vhContext) {
3793
+ function usePresentFlow(location) {
3794
+ useProviderStatus(vhContext, "usePresentFlow");
3795
+ const [isPresenting, setIsPresenting] = React6.useState(false);
3796
+ const present = React6.useCallback(
3797
+ (...args) => {
3798
+ setIsPresenting(true);
3799
+ return client.presentFlow(location, ...args).finally(() => setIsPresenting(false));
3800
+ },
3801
+ [location]
3802
+ );
3803
+ const updateInput = React6.useCallback(
3804
+ (values2) => client.updateFlowInput(values2),
3805
+ []
3806
+ );
3807
+ return { isPresenting, present, updateInput };
3808
+ }
3809
+ return usePresentFlow;
3810
+ }
3811
+
3812
+ // ../react-native/src/react/hooks/use-products.ts
3813
+ import * as Option18 from "effect/Option";
3814
+ import * as R8 from "effect/Record";
3815
+ import * as Schema12 from "effect/Schema";
3816
+ import React7 from "react";
3817
+ var encodeSlugs = Schema12.encodeSync(Schema12.fromJsonString(Schema12.Array(Schema12.String)));
3818
+ function productsHookFactory(client, vhContext) {
3819
+ function useProducts(slugs) {
3820
+ const status = useProviderStatus(vhContext, "useProducts");
3821
+ const registry = client.internal.getAtomRegistry();
3822
+ const state = useAtomValue(registry, productsAtom);
3823
+ const run = useAtomValue(registry, clientRunAtom);
3824
+ const ready = Option18.contains(status, "ready");
3825
+ React7.useEffect(() => {
3826
+ if (!ready) return;
3827
+ const current = registry.get(productsAtom);
3828
+ if (Option18.isNone(current.products) && !current.isLoading) void client.getProducts();
3829
+ }, [ready, registry, run]);
3830
+ const refetch = React7.useCallback(async () => {
3831
+ await client.getProducts();
3832
+ }, []);
3833
+ const products = React7.useMemo(
3834
+ () => Option18.getOrElse(state.products, () => []),
3835
+ [state.products]
3836
+ );
3837
+ const slugsKey = slugs === void 0 ? void 0 : encodeSlugs(slugs);
3838
+ const selected = React7.useMemo(
3839
+ () => slugs?.map((slug) => products.find((product) => product.slug === slug)),
3840
+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- the key is the slugs' content; the array identity changes every render.
3841
+ [products, slugsKey]
3842
+ );
3843
+ const data = React7.useMemo(() => {
3844
+ const bySlug = R8.fromIterableWith(products, (product) => [product.slug, product]);
3845
+ function get6(slug) {
3846
+ return bySlug[slug];
3847
+ }
3848
+ return { bySlug, get: get6, toList: () => products };
3849
+ }, [products]);
3850
+ const load = {
3851
+ error: Option18.getOrNull(state.error),
3852
+ isLoading: Option18.contains(status, "initializing") || ready && (state.isLoading || Option18.isNone(state.products) && Option18.isNone(state.error)),
3853
+ refetch
3854
+ };
3855
+ return selected === void 0 ? { ...load, data, products } : { ...load, products: selected };
3856
+ }
3857
+ return useProducts;
3858
+ }
3859
+
3860
+ // ../react-native/src/react/hooks/use-purchase.ts
3861
+ import { Result as Result7 } from "better-result";
3862
+ import * as Option19 from "effect/Option";
3863
+ import * as React8 from "react";
3864
+
3865
+ // ../react-native/src/react/internal/host-callback.ts
3866
+ import * as P10 from "effect/Predicate";
3867
+ function runHostCallback(client, name, callback) {
3868
+ const report = (callbackError) => client.internal.reportHostCallbackFailure(name, callbackError);
3869
+ try {
3870
+ const returned = callback();
3871
+ if (P10.isPromiseLike(returned)) returned.then(void 0, report);
3872
+ } catch (callbackError) {
3873
+ report(callbackError);
3874
+ }
3875
+ }
3876
+
3877
+ // ../react-native/src/react/hooks/use-purchase.ts
3878
+ function purchaseHookFactory(client, vhContext) {
3879
+ function usePurchase(hookOptions) {
3880
+ useProviderStatus(vhContext, "usePurchase");
3881
+ const [pendingProduct, setPendingProduct] = React8.useState(void 0);
3882
+ const [error, setError] = React8.useState(null);
3883
+ const running = React8.useRef(
3884
+ Option19.none()
3885
+ );
3886
+ const purchase = React8.useCallback(
3887
+ (product, options) => {
3888
+ const { onError, onSettled, onSuccess, ...purchaseOptions } = {
3889
+ ...hookOptions,
3890
+ ...options
3891
+ };
3892
+ const runCallbacks = (result) => {
3893
+ if (result.isOk() && result.value.status === "purchased" && onSuccess) {
3894
+ const completed = result.value;
3895
+ runHostCallback(client, "usePurchase.onSuccess", () => onSuccess(completed));
3896
+ }
3897
+ if (result.isErr() && onError) {
3898
+ runHostCallback(client, "usePurchase.onError", () => onError(result.error));
3899
+ }
3900
+ if (onSettled) runHostCallback(client, "usePurchase.onSettled", () => onSettled(result));
3901
+ };
3902
+ const key = client.internal.purchaseKey(product, purchaseOptions);
3903
+ const current = running.current;
3904
+ if (Option19.isSome(current)) {
3905
+ if (Option19.isSome(key) && Option19.contains(current.value.key, key.value)) {
3906
+ return current.value.settled;
3907
+ }
3908
+ const refused = Result7.err(new PurchaseInProgressError());
3909
+ runCallbacks(refused);
3910
+ return Promise.resolve(refused);
3911
+ }
3912
+ setPendingProduct(product);
3913
+ setError(null);
3914
+ const settled = client.purchase(product, purchaseOptions).then((result) => {
3915
+ running.current = Option19.none();
3916
+ setPendingProduct(void 0);
3917
+ if (result.isErr()) setError(result.error);
3918
+ runCallbacks(result);
3919
+ return result;
3920
+ });
3921
+ running.current = Option19.some({ key, settled });
3922
+ return settled;
3923
+ },
3924
+ [hookOptions]
3925
+ );
3926
+ return {
3927
+ /** The error of the last purchase this hook started, or `null`. */
3928
+ error,
3929
+ /** Whether a purchase this hook started is running. */
3930
+ isLoading: pendingProduct !== void 0,
3931
+ /** The product a purchase this hook started is buying, or `undefined`. */
3932
+ pendingProduct,
3933
+ purchase
3934
+ };
3935
+ }
3936
+ return usePurchase;
3937
+ }
3938
+
3939
+ // ../react-native/src/react/hooks/use-restore-purchases.ts
3940
+ import * as React9 from "react";
3941
+ function restorePurchasesHookFactory(client, vhContext) {
3942
+ function useRestorePurchases(hookOptions) {
3943
+ useProviderStatus(vhContext, "useRestorePurchases");
3944
+ const [isLoading, setIsLoading] = React9.useState(false);
3945
+ const [error, setError] = React9.useState(null);
3946
+ const restore = React9.useCallback(() => {
3947
+ setIsLoading(true);
3948
+ setError(null);
3949
+ return client.restorePurchases().then((result) => {
3950
+ setIsLoading(false);
3951
+ if (result.isErr()) setError(result.error);
3952
+ const { onError, onSettled, onSuccess } = hookOptions ?? {};
3953
+ if (result.isOk() && onSuccess) {
3954
+ const person = result.value;
3955
+ runHostCallback(client, "useRestorePurchases.onSuccess", () => onSuccess(person));
3956
+ }
3957
+ if (result.isErr() && onError) {
3958
+ runHostCallback(client, "useRestorePurchases.onError", () => onError(result.error));
3959
+ }
3960
+ if (onSettled) {
3961
+ runHostCallback(client, "useRestorePurchases.onSettled", () => onSettled(result));
3962
+ }
3963
+ return result;
3964
+ });
3965
+ }, [hookOptions]);
3966
+ return {
3967
+ /** The error of the last restore, or `null`. */
3968
+ error,
3969
+ isLoading,
3970
+ restore
3971
+ };
3972
+ }
3973
+ return useRestorePurchases;
3974
+ }
3975
+
3976
+ // ../react-native/src/react/hooks/use-subscriptions.ts
3977
+ var NO_SUBSCRIPTIONS = [];
3978
+ function subscriptionsHookFactory(useCurrentPerson) {
3979
+ function useSubscriptions() {
3980
+ const { data: person, ...state } = useCurrentPerson();
3981
+ return {
3982
+ ...state,
3983
+ all: person?.subscriptions.all ?? NO_SUBSCRIPTIONS,
3984
+ current: person?.subscriptions.current
3985
+ };
3986
+ }
3987
+ return useSubscriptions;
3988
+ }
3989
+
3990
+ // ../react-native/src/client-host.ts
3991
+ var nativeEngineWarningShown = false;
3992
+ var DEFAULT_BASE_URL = "https://api.voidhash.com";
3993
+ var ABSOLUTE_HTTP_URL = /^https?:\/\/[^\s/?#]+(?:[/?#]\S*)?$/i;
3994
+ var resolveOrigin = (option, configured, emitDiagnostic) => {
3995
+ const value3 = Option20.filter(
3996
+ Option20.map(configured, (origin) => origin.trim()),
3997
+ (origin) => origin !== ""
3998
+ );
3999
+ if (Option20.isNone(value3) || ABSOLUTE_HTTP_URL.test(value3.value)) return value3;
4000
+ if (__DEV__) {
4001
+ throw new InvalidArgumentError(
4002
+ `${option} must be an absolute http(s) URL such as "https://api.example.com", got "${value3.value}"`
4003
+ );
4004
+ }
4005
+ emitDiagnostic({
4006
+ code: DIAGNOSTIC_CODES.INVALID_CONFIGURATION,
4007
+ kind: "configuration",
4008
+ message: `Ignored ${option} "${value3.value}": it is not an absolute http(s) URL, so the default origin is used`,
4009
+ operation: "createVoidhashClient",
4010
+ retryable: false
4011
+ });
4012
+ return Option20.none();
4013
+ };
4014
+ var resolveFeatureFlagOptions = (options, emitDiagnostic) => {
4015
+ const refuse = (message, fallback) => {
4016
+ if (__DEV__) throw new InvalidArgumentError(message);
4017
+ emitDiagnostic({
4018
+ code: DIAGNOSTIC_CODES.INVALID_CONFIGURATION,
4019
+ kind: "configuration",
4020
+ message: `Ignored ${message}; ${fallback}`,
4021
+ operation: "createVoidhashClient",
4022
+ retryable: false
4023
+ });
4024
+ };
4025
+ const isValidWait = (wait) => Number.isInteger(wait) && wait >= 0;
4026
+ const maxWaitMs = Option20.fromUndefinedOr(options.maxWaitMs);
4027
+ if (Option20.isSome(maxWaitMs) && !isValidWait(maxWaitMs.value)) {
4028
+ refuse(
4029
+ `featureFlags.maxWaitMs must be zero or a positive integer, got ${String(maxWaitMs.value)}`,
4030
+ "the default wait is used"
4031
+ );
4032
+ }
4033
+ const configuredDefaults = options.defaults ?? {};
4034
+ R9.toEntries(configuredDefaults).forEach(([key, value3]) => {
4035
+ if (P11.isBoolean(value3)) return;
4036
+ refuse(
4037
+ `featureFlags.defaults["${key}"] must be true or false, got ${String(value3)}`,
4038
+ "the flag has no default"
4039
+ );
4040
+ });
4041
+ const defaults = R9.filter(configuredDefaults, P11.isBoolean);
4042
+ return { defaults, maxWaitMs: Option20.filter(maxWaitMs, isValidWait) };
4043
+ };
4044
+ function createVoidhashClientOnHost(host, publishableKey, options = {}) {
4045
+ const key = publishableKey?.trim() ?? "";
4046
+ const emitDiagnostic = makeDiagnosticEmitter(Option20.fromUndefinedOr(options.onDiagnostic));
4047
+ const baseUrl = Option20.getOrElse(
4048
+ resolveOrigin("baseUrl", Option20.fromUndefinedOr(options.baseUrl), emitDiagnostic),
4049
+ () => DEFAULT_BASE_URL
4050
+ );
4051
+ const debug = options.debug ?? false;
4052
+ const dev = options.dev ?? false;
4053
+ const distinctId = Option20.fromUndefinedOr(options.distinctId);
4054
+ const enabled = (options.enabled ?? true) && key !== "" && (host.platform === "ios" || host.platform === "android");
4055
+ const ingestUrl = resolveOrigin(
4056
+ "ingestUrl",
4057
+ Option20.fromUndefinedOr(options.ingestUrl),
4058
+ emitDiagnostic
4059
+ );
4060
+ const readOnly = options.readOnly ?? false;
4061
+ const analyticsConsent = options.analyticsConsent ?? "granted";
4062
+ if (!isAnalyticsConsent(analyticsConsent)) {
4063
+ const message = `analyticsConsent must be "granted", "denied" or "pending", got "${String(analyticsConsent)}"`;
4064
+ if (__DEV__) throw new InvalidArgumentError(message);
4065
+ emitDiagnostic({
4066
+ code: DIAGNOSTIC_CODES.INVALID_CONFIGURATION,
4067
+ kind: "configuration",
4068
+ message: `Ignored ${message}; "granted" is used`,
4069
+ operation: "createVoidhashClient",
4070
+ retryable: false
4071
+ });
4072
+ }
4073
+ const featureFlags = resolveFeatureFlagOptions(options.featureFlags ?? {}, emitDiagnostic);
4074
+ if (options.unstable_nativeEngine === true && __DEV__ && !nativeEngineWarningShown) {
4075
+ nativeEngineWarningShown = true;
4076
+ console.warn(
4077
+ "[voidhash] unstable_nativeEngine no longer has an effect; the SDK always runs on its native client."
4078
+ );
4079
+ }
4080
+ const client = new VoidhashClient({
4081
+ analyticsConsent: isAnalyticsConsent(analyticsConsent) ? analyticsConsent : "granted",
4082
+ analyticsWhilePending: options.analyticsWhilePending === "buffer" ? "buffer" : "drop",
4083
+ appStoreMessages: options.appStoreMessages === "automatic" ? "automatic" : "deferWhileFlowPresented",
4084
+ atomRegistry: AtomRegistry.make(),
4085
+ automaticLifecycleEvents: options.automaticLifecycleEvents ?? true,
4086
+ baseUrl,
4087
+ createNativeClient: host.createNativeClient,
4088
+ debug,
4089
+ developmentMode: __DEV__ && dev,
4090
+ // A blank configured id counts as absent: the SDK keeps (or mints) the
4091
+ // anonymous identity instead of adopting one no request can carry.
4092
+ distinctId: Option20.filter(distinctId, (id) => P11.isString(id) && id.trim() !== ""),
4093
+ enabled,
4094
+ featureFlagDefaults: featureFlags.defaults,
4095
+ featureFlagMaxWaitMs: featureFlags.maxWaitMs,
4096
+ grantConsentOnIdentify: options.grantConsentOnIdentify ?? false,
4097
+ flowCapabilities: Arr10.dedupe(options.flowCapabilities ?? DEFAULT_FLOW_CAPABILITIES),
4098
+ flowRevisions: options.flowRevisions ?? {},
4099
+ flowRuntime: options.flowRuntime === "module" ? "module" : "linked",
4100
+ flowLoading: options.flowLoading === "none" ? "none" : "standard",
4101
+ ingestUrl,
4102
+ installAttribution: options.installAttribution ?? true,
4103
+ internalSchema: Option20.fromUndefinedOr(options.unstable_internalSchema),
4104
+ metaAppId: Option20.fromUndefinedOr(options.metaAppId),
4105
+ oneNativeClientPerProcess: host.platform === "android",
4106
+ onDiagnostic: Option20.fromUndefinedOr(options.onDiagnostic),
4107
+ packageName: host.packageName,
4108
+ platform: host.platform,
4109
+ preloadLocations: options.preloadLocations ?? [],
4110
+ publishableKey: key,
4111
+ purchaseIntents: options.purchaseIntents === "manual" ? "manual" : "purchaseWhenReady",
4112
+ readOnly,
4113
+ scheme: options.scheme ?? "",
4114
+ screenTracking: options.screenTracking ?? {},
4115
+ unstableSwallowErrors: options.unstable_swallowErrors ?? false
4116
+ });
4117
+ const { provider, context, useVoidhash } = voidhashProviderFactory(client);
4118
+ const useCurrentPerson = currentPersonHookFactory(client, context);
4119
+ return {
4120
+ Provider: provider,
4121
+ /** App Store actions, as `client.appStore`. */
4122
+ appStore: client.appStore,
4123
+ client,
4124
+ /** Google Play actions, as `client.googlePlay`. */
4125
+ googlePlay: client.googlePlay,
4126
+ useCurrentPerson,
4127
+ useFeatureFlags: featureFlagsHookFactory(client, context),
4128
+ useHasPerk: hasPerkHookFactory(client, context),
4129
+ usePresentFlow: presentFlowHookFactory(client, context),
4130
+ useProducts: productsHookFactory(client, context),
4131
+ usePurchase: purchaseHookFactory(client, context),
4132
+ useRestorePurchases: restorePurchasesHookFactory(client, context),
4133
+ useSubscriptions: subscriptionsHookFactory(
4134
+ currentPersonHookFactory(client, context, "useSubscriptions")
4135
+ ),
4136
+ useVoidhash
4137
+ };
4138
+ }
4139
+
4140
+ // src/specs/VoidhashNativeClient.nitro.ts
4141
+ var VoidhashNativeClient_nitro_exports = {};
4142
+ __reExport(VoidhashNativeClient_nitro_exports, VoidhashNativeClient_star);
4143
+ import * as VoidhashNativeClient_star from "#nitro/VoidhashNativeClient";
4144
+
4145
+ // src/client-nitro-ui.ts
4146
+ var createVoidhashNativeClient = () => Result8.getSuccess(Result8.try(() => new VoidhashNativeClient_nitro_exports.VoidhashNativeClient()));
4147
+ function createVoidhashClient(publishableKey, options = {}) {
4148
+ return createVoidhashClientOnHost(
4149
+ {
4150
+ createNativeClient: createVoidhashNativeClient,
4151
+ packageName: "@voidhash/nitro-ui",
4152
+ platform: Platform.OS
4153
+ },
4154
+ publishableKey,
4155
+ options
4156
+ );
4157
+ }
4158
+ export {
4159
+ DEFAULT_FLOW_CAPABILITIES,
4160
+ DIAGNOSTIC_CODES,
4161
+ Perk,
4162
+ RuntimeAppleAppStoreProductConfiguration,
4163
+ RuntimeDevelopmentProductConfiguration,
4164
+ RuntimeGooglePlayProductConfiguration,
4165
+ RuntimePaywallLocationDefinition,
4166
+ RuntimePerkDefinition,
4167
+ RuntimeProductDefinition,
4168
+ RuntimeProductDuration,
4169
+ RuntimeProductProviders,
4170
+ RuntimeSchemaValue,
4171
+ RuntimeStoreOffer,
4172
+ VOIDHASH_ERROR_CODES,
4173
+ VoidhashClient,
4174
+ VoidhashError,
4175
+ createEmptyRuntimeSchema,
4176
+ createVoidhashClient,
4177
+ isAnonymousDistinctId,
4178
+ useProviderStatus,
4179
+ useVoidhashClient,
4180
+ voidhashProviderFactory
4181
+ };
4182
+ //# sourceMappingURL=index.js.map