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