@adshift/react-native-plugin 1.0.0 → 2.0.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 (180) hide show
  1. package/AdShiftReactNativePlugin.podspec +11 -7
  2. package/CHANGELOG.md +122 -0
  3. package/README.md +506 -542
  4. package/android/build.gradle +17 -3
  5. package/android/consumer-rules.pro +21 -0
  6. package/android/src/main/java/com/adshift/reactnativeplugin/AdShiftReactNativePluginModule.kt +786 -229
  7. package/android/src/test/java/com/adshift/reactnativeplugin/ConsentSnapshotTest.kt +180 -0
  8. package/android/src/test/java/com/adshift/reactnativeplugin/DeepLinkDeliveryTest.kt +146 -0
  9. package/android/src/test/java/com/adshift/reactnativeplugin/InitializeOrderingTest.kt +111 -0
  10. package/android/src/test/java/com/adshift/reactnativeplugin/IntentLinkDedupTest.kt +168 -0
  11. package/android/src/test/java/com/adshift/reactnativeplugin/LaunchIntentForwardingTest.kt +106 -0
  12. package/android/src/test/java/com/adshift/reactnativeplugin/ModuleTestSupport.kt +167 -0
  13. package/android/src/test/java/com/adshift/reactnativeplugin/StartVerdictTest.kt +164 -0
  14. package/ios/AdShiftReactNativePlugin.h +7 -7
  15. package/ios/AdShiftReactNativePlugin.mm +200 -181
  16. package/ios/AdShiftReactNativePluginHelper.swift +584 -286
  17. package/ios/Core/BridgeRules.swift +82 -0
  18. package/lib/commonjs/Adshift.js +1135 -0
  19. package/lib/commonjs/Adshift.js.map +1 -0
  20. package/lib/commonjs/NativeAdShiftReactNativePlugin.js +22 -0
  21. package/lib/commonjs/NativeAdShiftReactNativePlugin.js.map +1 -0
  22. package/lib/commonjs/index.js +94 -0
  23. package/lib/commonjs/index.js.map +1 -0
  24. package/lib/commonjs/jest/index.js +164 -0
  25. package/lib/commonjs/jest/index.js.map +1 -0
  26. package/lib/commonjs/nativeSdkVersions.js +17 -0
  27. package/lib/commonjs/nativeSdkVersions.js.map +1 -0
  28. package/lib/commonjs/package.json +1 -0
  29. package/lib/commonjs/types/AdshiftAdRevenue.js +47 -0
  30. package/lib/commonjs/types/AdshiftAdRevenue.js.map +1 -0
  31. package/lib/commonjs/types/AdshiftConfig.js +45 -0
  32. package/lib/commonjs/types/AdshiftConfig.js.map +1 -0
  33. package/lib/commonjs/types/AdshiftConsent.js +113 -0
  34. package/lib/commonjs/types/AdshiftConsent.js.map +1 -0
  35. package/lib/commonjs/types/AdshiftConsentSnapshot.js +69 -0
  36. package/lib/commonjs/types/AdshiftConsentSnapshot.js.map +1 -0
  37. package/lib/commonjs/types/AdshiftDeepLink.js +154 -0
  38. package/lib/commonjs/types/AdshiftDeepLink.js.map +1 -0
  39. package/lib/commonjs/types/AdshiftError.js +91 -0
  40. package/lib/commonjs/types/AdshiftError.js.map +1 -0
  41. package/lib/commonjs/types/AdshiftEventParam.js +140 -0
  42. package/lib/commonjs/types/AdshiftEventParam.js.map +1 -0
  43. package/lib/commonjs/types/AdshiftEventType.js +88 -0
  44. package/lib/commonjs/types/AdshiftEventType.js.map +1 -0
  45. package/lib/commonjs/types/AdshiftThirdPartySharing.js +70 -0
  46. package/lib/commonjs/types/AdshiftThirdPartySharing.js.map +1 -0
  47. package/lib/commonjs/types/index.js +123 -0
  48. package/lib/commonjs/types/index.js.map +1 -0
  49. package/lib/commonjs/version.js +9 -0
  50. package/lib/commonjs/version.js.map +1 -0
  51. package/lib/module/Adshift.js +959 -296
  52. package/lib/module/Adshift.js.map +1 -1
  53. package/lib/module/NativeAdShiftReactNativePlugin.js +10 -7
  54. package/lib/module/NativeAdShiftReactNativePlugin.js.map +1 -1
  55. package/lib/module/index.js +26 -25
  56. package/lib/module/index.js.map +1 -1
  57. package/lib/module/jest/index.js +144 -0
  58. package/lib/module/jest/index.js.map +1 -0
  59. package/lib/module/nativeSdkVersions.js +13 -0
  60. package/lib/module/nativeSdkVersions.js.map +1 -0
  61. package/lib/module/types/AdshiftAdRevenue.js +43 -0
  62. package/lib/module/types/AdshiftAdRevenue.js.map +1 -0
  63. package/lib/module/types/AdshiftConfig.js +23 -26
  64. package/lib/module/types/AdshiftConfig.js.map +1 -1
  65. package/lib/module/types/AdshiftConsent.js +57 -50
  66. package/lib/module/types/AdshiftConsent.js.map +1 -1
  67. package/lib/module/types/AdshiftConsentSnapshot.js +65 -0
  68. package/lib/module/types/AdshiftConsentSnapshot.js.map +1 -0
  69. package/lib/module/types/AdshiftDeepLink.js +97 -67
  70. package/lib/module/types/AdshiftDeepLink.js.map +1 -1
  71. package/lib/module/types/AdshiftError.js +87 -0
  72. package/lib/module/types/AdshiftError.js.map +1 -0
  73. package/lib/module/types/AdshiftEventParam.js +135 -0
  74. package/lib/module/types/AdshiftEventParam.js.map +1 -0
  75. package/lib/module/types/AdshiftEventType.js +11 -36
  76. package/lib/module/types/AdshiftEventType.js.map +1 -1
  77. package/lib/module/types/AdshiftThirdPartySharing.js +65 -0
  78. package/lib/module/types/AdshiftThirdPartySharing.js.map +1 -0
  79. package/lib/module/types/index.js +9 -7
  80. package/lib/module/types/index.js.map +1 -1
  81. package/lib/module/version.js +5 -0
  82. package/lib/module/version.js.map +1 -0
  83. package/lib/typescript/commonjs/package.json +1 -0
  84. package/lib/typescript/commonjs/src/Adshift.d.ts +311 -0
  85. package/lib/typescript/commonjs/src/Adshift.d.ts.map +1 -0
  86. package/lib/typescript/commonjs/src/NativeAdShiftReactNativePlugin.d.ts +102 -0
  87. package/lib/typescript/commonjs/src/NativeAdShiftReactNativePlugin.d.ts.map +1 -0
  88. package/lib/typescript/commonjs/src/index.d.ts +51 -0
  89. package/lib/typescript/commonjs/src/index.d.ts.map +1 -0
  90. package/lib/typescript/commonjs/src/jest/index.d.ts +103 -0
  91. package/lib/typescript/commonjs/src/jest/index.d.ts.map +1 -0
  92. package/lib/typescript/commonjs/src/nativeSdkVersions.d.ts +11 -0
  93. package/lib/typescript/commonjs/src/nativeSdkVersions.d.ts.map +1 -0
  94. package/lib/typescript/commonjs/src/types/AdshiftAdRevenue.d.ts +56 -0
  95. package/lib/typescript/commonjs/src/types/AdshiftAdRevenue.d.ts.map +1 -0
  96. package/lib/typescript/commonjs/src/types/AdshiftConfig.d.ts +104 -0
  97. package/lib/typescript/commonjs/src/types/AdshiftConfig.d.ts.map +1 -0
  98. package/lib/typescript/commonjs/src/types/AdshiftConsent.d.ts +76 -0
  99. package/lib/typescript/commonjs/src/types/AdshiftConsent.d.ts.map +1 -0
  100. package/lib/typescript/commonjs/src/types/AdshiftConsentSnapshot.d.ts +56 -0
  101. package/lib/typescript/commonjs/src/types/AdshiftConsentSnapshot.d.ts.map +1 -0
  102. package/lib/typescript/commonjs/src/types/AdshiftDeepLink.d.ts +89 -0
  103. package/lib/typescript/commonjs/src/types/AdshiftDeepLink.d.ts.map +1 -0
  104. package/lib/typescript/commonjs/src/types/AdshiftError.d.ts +57 -0
  105. package/lib/typescript/commonjs/src/types/AdshiftError.d.ts.map +1 -0
  106. package/lib/typescript/commonjs/src/types/AdshiftEventParam.d.ts +111 -0
  107. package/lib/typescript/commonjs/src/types/AdshiftEventParam.d.ts.map +1 -0
  108. package/lib/typescript/{src → commonjs/src}/types/AdshiftEventType.d.ts +12 -35
  109. package/lib/typescript/commonjs/src/types/AdshiftEventType.d.ts.map +1 -0
  110. package/lib/typescript/commonjs/src/types/AdshiftThirdPartySharing.d.ts +53 -0
  111. package/lib/typescript/commonjs/src/types/AdshiftThirdPartySharing.d.ts.map +1 -0
  112. package/lib/typescript/commonjs/src/types/index.d.ts +17 -0
  113. package/lib/typescript/commonjs/src/types/index.d.ts.map +1 -0
  114. package/lib/typescript/commonjs/src/version.d.ts +2 -0
  115. package/lib/typescript/commonjs/src/version.d.ts.map +1 -0
  116. package/lib/typescript/module/src/Adshift.d.ts +311 -0
  117. package/lib/typescript/module/src/Adshift.d.ts.map +1 -0
  118. package/lib/typescript/module/src/NativeAdShiftReactNativePlugin.d.ts +102 -0
  119. package/lib/typescript/module/src/NativeAdShiftReactNativePlugin.d.ts.map +1 -0
  120. package/lib/typescript/module/src/index.d.ts +51 -0
  121. package/lib/typescript/module/src/index.d.ts.map +1 -0
  122. package/lib/typescript/module/src/jest/index.d.ts +103 -0
  123. package/lib/typescript/module/src/jest/index.d.ts.map +1 -0
  124. package/lib/typescript/module/src/nativeSdkVersions.d.ts +11 -0
  125. package/lib/typescript/module/src/nativeSdkVersions.d.ts.map +1 -0
  126. package/lib/typescript/module/src/types/AdshiftAdRevenue.d.ts +56 -0
  127. package/lib/typescript/module/src/types/AdshiftAdRevenue.d.ts.map +1 -0
  128. package/lib/typescript/module/src/types/AdshiftConfig.d.ts +104 -0
  129. package/lib/typescript/module/src/types/AdshiftConfig.d.ts.map +1 -0
  130. package/lib/typescript/module/src/types/AdshiftConsent.d.ts +76 -0
  131. package/lib/typescript/module/src/types/AdshiftConsent.d.ts.map +1 -0
  132. package/lib/typescript/module/src/types/AdshiftConsentSnapshot.d.ts +56 -0
  133. package/lib/typescript/module/src/types/AdshiftConsentSnapshot.d.ts.map +1 -0
  134. package/lib/typescript/module/src/types/AdshiftDeepLink.d.ts +89 -0
  135. package/lib/typescript/module/src/types/AdshiftDeepLink.d.ts.map +1 -0
  136. package/lib/typescript/module/src/types/AdshiftError.d.ts +57 -0
  137. package/lib/typescript/module/src/types/AdshiftError.d.ts.map +1 -0
  138. package/lib/typescript/module/src/types/AdshiftEventParam.d.ts +111 -0
  139. package/lib/typescript/module/src/types/AdshiftEventParam.d.ts.map +1 -0
  140. package/lib/typescript/module/src/types/AdshiftEventType.d.ts +64 -0
  141. package/lib/typescript/module/src/types/AdshiftEventType.d.ts.map +1 -0
  142. package/lib/typescript/module/src/types/AdshiftThirdPartySharing.d.ts +53 -0
  143. package/lib/typescript/module/src/types/AdshiftThirdPartySharing.d.ts.map +1 -0
  144. package/lib/typescript/module/src/types/index.d.ts +17 -0
  145. package/lib/typescript/module/src/types/index.d.ts.map +1 -0
  146. package/lib/typescript/module/src/version.d.ts +2 -0
  147. package/lib/typescript/module/src/version.d.ts.map +1 -0
  148. package/package.json +49 -10
  149. package/src/Adshift.ts +1273 -342
  150. package/src/NativeAdShiftReactNativePlugin.ts +81 -115
  151. package/src/index.tsx +40 -25
  152. package/src/jest/index.ts +224 -0
  153. package/src/nativeSdkVersions.ts +10 -0
  154. package/src/types/AdshiftAdRevenue.ts +58 -0
  155. package/src/types/AdshiftConfig.ts +101 -53
  156. package/src/types/AdshiftConsent.ts +75 -72
  157. package/src/types/AdshiftConsentSnapshot.ts +103 -0
  158. package/src/types/AdshiftDeepLink.ts +123 -102
  159. package/src/types/AdshiftError.ts +107 -0
  160. package/src/types/AdshiftEventParam.ts +216 -0
  161. package/src/types/AdshiftEventType.ts +13 -35
  162. package/src/types/AdshiftThirdPartySharing.ts +63 -0
  163. package/src/types/index.ts +38 -6
  164. package/src/version.ts +2 -0
  165. package/lib/typescript/src/Adshift.d.ts +0 -335
  166. package/lib/typescript/src/Adshift.d.ts.map +0 -1
  167. package/lib/typescript/src/NativeAdShiftReactNativePlugin.d.ts +0 -143
  168. package/lib/typescript/src/NativeAdShiftReactNativePlugin.d.ts.map +0 -1
  169. package/lib/typescript/src/index.d.ts +0 -47
  170. package/lib/typescript/src/index.d.ts.map +0 -1
  171. package/lib/typescript/src/types/AdshiftConfig.d.ts +0 -74
  172. package/lib/typescript/src/types/AdshiftConfig.d.ts.map +0 -1
  173. package/lib/typescript/src/types/AdshiftConsent.d.ts +0 -88
  174. package/lib/typescript/src/types/AdshiftConsent.d.ts.map +0 -1
  175. package/lib/typescript/src/types/AdshiftDeepLink.d.ts +0 -93
  176. package/lib/typescript/src/types/AdshiftDeepLink.d.ts.map +0 -1
  177. package/lib/typescript/src/types/AdshiftEventType.d.ts.map +0 -1
  178. package/lib/typescript/src/types/index.d.ts +0 -5
  179. package/lib/typescript/src/types/index.d.ts.map +0 -1
  180. /package/lib/typescript/{package.json → module/package.json} +0 -0
@@ -1,132 +1,352 @@
1
1
  package com.adshift.reactnativeplugin
2
2
 
3
+ import android.app.Activity
3
4
  import android.content.Intent
4
5
  import android.net.Uri
6
+ import android.os.Bundle
5
7
  import android.os.Handler
6
8
  import android.os.Looper
9
+ import android.util.Log
10
+ import com.adshift.sdk.core.ASAdRevenueData
11
+ import com.adshift.sdk.core.ASInAppEventParameterName
12
+ import com.adshift.sdk.core.ASMediationNetwork
13
+ import com.adshift.sdk.core.AdShiftConsent
14
+ import com.adshift.sdk.core.AdShiftLib
15
+ import com.adshift.sdk.core.AdShiftRequestListener
16
+ import com.adshift.sdk.core.AdShiftThirdPartySharing
17
+ import com.adshift.sdk.core.ConsentSnapshot
18
+ import com.adshift.sdk.core.deeplink.DeepLinkListener
19
+ import com.adshift.sdk.core.deeplink.DeepLinkResult
20
+ import com.adshift.sdk.core.deeplink.DeepLinkStatus
21
+ import com.facebook.react.bridge.ActivityEventListener
7
22
  import com.facebook.react.bridge.Arguments
23
+ import com.facebook.react.bridge.CxxCallbackImpl
24
+ import com.facebook.react.bridge.LifecycleEventListener
8
25
  import com.facebook.react.bridge.Promise
9
26
  import com.facebook.react.bridge.ReactApplicationContext
27
+ import com.facebook.react.bridge.ReadableArray
10
28
  import com.facebook.react.bridge.ReadableMap
29
+ import com.facebook.react.bridge.ReadableType
11
30
  import com.facebook.react.bridge.WritableMap
12
31
  import com.facebook.react.module.annotations.ReactModule
13
- import com.facebook.react.modules.core.DeviceEventManagerModule
14
- import com.adshift.sdk.core.AdShiftLib
15
- import com.adshift.sdk.core.AdShiftConsent
16
- import com.adshift.sdk.core.AdShiftRequestListener
17
- import com.adshift.sdk.core.deeplink.DeepLinkListener
18
- import com.adshift.sdk.core.deeplink.DeepLinkResult
19
- import com.adshift.sdk.core.deeplink.DeepLinkStatus
32
+ import java.lang.ref.WeakReference
33
+ import java.security.MessageDigest
34
+ import java.util.Collections
35
+ import java.util.WeakHashMap
36
+ import java.util.concurrent.atomic.AtomicBoolean
37
+ import org.json.JSONObject
20
38
 
21
39
  /**
22
- * AdShift React Native Turbo Module for Android.
40
+ * AdShift TurboModule for Android.
23
41
  *
24
- * Bridges React Native JavaScript to native AdShift Android SDK.
25
- * Implements NativeAdShiftReactNativePluginSpec generated by Codegen.
42
+ * Bridges the JavaScript contract (`NativeAdShiftReactNativePlugin.ts`) to the
43
+ * AdShift Android SDK. Deep link results are delivered exclusively through the
44
+ * `onDeepLink` event; the SDK listener is registered once per process and
45
+ * forwards to whichever module instance is current, so results keep flowing
46
+ * across JavaScript reloads.
26
47
  */
27
48
  @ReactModule(name = AdShiftReactNativePluginModule.NAME)
28
49
  class AdShiftReactNativePluginModule(private val reactContext: ReactApplicationContext) :
29
- NativeAdShiftReactNativePluginSpec(reactContext) {
50
+ NativeAdShiftReactNativePluginSpec(reactContext), ActivityEventListener, LifecycleEventListener {
51
+
52
+ /** Error codes surfaced to JavaScript as the rejection `code`. */
53
+ private object ErrorCode {
54
+ const val NOT_INITIALIZED = "NOT_INITIALIZED"
55
+ const val NOT_STARTED = "NOT_STARTED"
56
+ const val INVALID_API_KEY = "INVALID_API_KEY"
57
+ const val OPTED_OUT = "OPTED_OUT"
58
+ const val QUEUE_FULL = "QUEUE_FULL"
59
+ const val INVALID_ARGUMENT = "INVALID_ARGUMENT"
60
+ const val UNKNOWN = "UNKNOWN"
61
+ }
62
+
63
+ /** Values passed to `AdShiftRequestListener.onError` (SDK `RequestError` codes). */
64
+ private object SdkErrorCode {
65
+ const val STOP_TRACKING = 12
66
+ const val NO_DEV_KEY = 41
67
+ const val QUEUE_FULL = 51
68
+ }
69
+
70
+ /** An Intent received before `initialize`, kept until the SDK can process it. */
71
+ private class StoredIntent(val intent: Intent, val fromLaunchPath: Boolean)
30
72
 
31
73
  companion object {
32
74
  const val NAME = "AdShiftReactNativePlugin"
33
- private const val EVENT_DEEP_LINK = "onDeepLink"
75
+
76
+ private const val TAG = "AdShiftRN"
77
+ private const val AUTO_FORWARD_DEDUP_WINDOW_MS = 2_000L
78
+ private const val META_APP_LINK_EXTRA = "al_applink_data"
79
+
80
+ /** Deep link results kept while no JavaScript listener can receive them. */
81
+ private const val PENDING_DEEP_LINK_LIMIT = 20
82
+
83
+ /** How deep to look for links inside JSON carried by Intent extras. */
84
+ private const val EXTRAS_URL_SEARCH_DEPTH = 3
85
+
86
+ private const val LAUNCH_URL_MEMORY_LIMIT = 20
87
+
88
+ /** How long `start` waits for the SDK listener before answering optimistically. */
89
+ private const val START_VERDICT_TIMEOUT_MS = 5_000L
90
+
91
+ /** Keys the SDK sets itself when building the ad revenue event. */
92
+ private val RESERVED_AD_REVENUE_KEYS = setOf(
93
+ ASInAppEventParameterName.REVENUE,
94
+ ASInAppEventParameterName.CURRENCY,
95
+ ASInAppEventParameterName.AD_REVENUE_SOURCE,
96
+ ASInAppEventParameterName.AD_REVENUE_NETWORK_NAME,
97
+ )
98
+
99
+ /** Single main-thread queue shared by `start` and `stop` so call order is preserved. */
100
+ private val mainHandler = Handler(Looper.getMainLooper())
101
+
102
+ private val lock = Any()
103
+
104
+ @Volatile private var currentModule: WeakReference<AdShiftReactNativePluginModule>? = null
105
+ @Volatile private var sdkInitialized = false
106
+
107
+ /** Set once the SDK is initialised *and* the `initialize` options have been applied. */
108
+ @Volatile private var readyForIntents = false
109
+ @Volatile private var deepLinkListenerRegistered = false
110
+ @Volatile private var autoHandleDeepLinks = true
111
+ @Volatile private var collectOaidApplied = false
112
+
113
+ // Guarded by [lock].
114
+ private var pendingIntent: StoredIntent? = null
115
+ private var lastLaunchIntentFingerprint: String? = null
116
+ private val processedIntents: MutableSet<Intent> =
117
+ Collections.newSetFromMap(WeakHashMap<Intent, Boolean>())
118
+ private val autoForwardedUrls = HashMap<String, Long>()
119
+
120
+ /**
121
+ * URLs that opened this process, kept until it dies. Reloading JavaScript replays the
122
+ * launch URL, and that replay can arrive long after the two second window has closed.
123
+ * A new tap arrives as a new Intent, so it is unaffected.
124
+ */
125
+ private val launchForwardedUrls = LinkedHashSet<String>()
126
+
127
+ private val registeredPushPaths = HashSet<String>()
128
+ private val pendingDeepLinks = ArrayDeque<DeepLinkResult>()
129
+
130
+ /**
131
+ * Forwards an SDK deep link result to the current module instance, keeping it for the
132
+ * next one when JavaScript cannot receive it yet — a result is delivered once, and a
133
+ * reload must not consume it.
134
+ */
135
+ private fun dispatchDeepLink(result: DeepLinkResult) {
136
+ if (currentModule?.get()?.emitDeepLink(result) == true) return
137
+ synchronized(lock) {
138
+ while (pendingDeepLinks.size >= PENDING_DEEP_LINK_LIMIT) {
139
+ pendingDeepLinks.removeFirst()
140
+ }
141
+ pendingDeepLinks.addLast(result)
142
+ }
143
+ Log.d(TAG, "onDeepLink kept for the next listener")
144
+ }
145
+
146
+ private fun mapSdkErrorCode(code: Int): String = when (code) {
147
+ SdkErrorCode.STOP_TRACKING -> ErrorCode.OPTED_OUT
148
+ SdkErrorCode.NO_DEV_KEY -> ErrorCode.INVALID_API_KEY
149
+ SdkErrorCode.QUEUE_FULL -> ErrorCode.QUEUE_FULL
150
+ else -> ErrorCode.UNKNOWN
151
+ }
152
+
153
+ private fun mapThrowable(e: Throwable): String = when (e) {
154
+ is IllegalStateException -> ErrorCode.NOT_INITIALIZED
155
+ is IllegalArgumentException -> ErrorCode.INVALID_ARGUMENT
156
+ else -> ErrorCode.UNKNOWN
157
+ }
34
158
  }
35
159
 
36
- // Handler for main thread operations
37
- private val mainHandler = Handler(Looper.getMainLooper())
38
-
39
- // Track if we have listeners
40
- private var listenerCount = 0
41
- private var deepLinkListenerRegistered = false
42
-
43
- // Pending promise for handleDeepLink() one-shot calls
44
- private var pendingDeepLinkPromise: Promise? = null
160
+ @Volatile private var invalidated = false
161
+
162
+ /**
163
+ * The emitter callback of the generated base class is not volatile, and deep links arrive on an
164
+ * SDK thread. This flag publishes the callback to that thread, so a result is buffered rather
165
+ * than read against a stale null and lost.
166
+ */
167
+ @Volatile private var emitterAttached = false
168
+
169
+ init {
170
+ synchronized(lock) { currentModule = WeakReference(this) }
171
+ reactContext.addActivityEventListener(this)
172
+ reactContext.addLifecycleEventListener(this)
173
+ }
45
174
 
46
175
  override fun getName(): String = NAME
47
176
 
48
- // ============ Lifecycle Methods ============
177
+ override fun invalidate() {
178
+ invalidated = true
179
+ reactContext.removeActivityEventListener(this)
180
+ reactContext.removeLifecycleEventListener(this)
181
+ synchronized(lock) {
182
+ if (currentModule?.get() === this) currentModule = null
183
+ }
184
+ super.invalidate()
185
+ }
186
+
187
+ // ============ Lifecycle ============
49
188
 
50
189
  override fun initialize(config: ReadableMap) {
51
- val context = reactContext.applicationContext ?: return
52
-
53
- val apiKey = config.getString("apiKey")
190
+ val apiKey = optString(config, "apiKey")
54
191
  if (apiKey.isNullOrBlank()) {
55
- logError("initialize", "apiKey is required")
192
+ Log.e(TAG, "initialize: apiKey is required")
56
193
  return
57
194
  }
58
195
 
59
196
  try {
60
- // Initialize SDK with API key
61
- AdShiftLib.initSdk(context, apiKey)
62
-
63
- // Apply optional configuration
64
- if (config.hasKey("isDebug")) {
65
- AdShiftLib.setDebugLog(config.getBoolean("isDebug"))
197
+ if (!sdkInitialized) {
198
+ AdShiftLib.initSdk(reactContext.applicationContext ?: reactContext, apiKey)
199
+ sdkInitialized = true
66
200
  }
67
-
68
- if (config.hasKey("appOpenDebounceMs")) {
69
- AdShiftLib.setAppOpenDebounceMs(config.getDouble("appOpenDebounceMs").toLong())
201
+ if (!deepLinkListenerRegistered) {
202
+ AdShiftLib.setDeepLinkListener(object : DeepLinkListener {
203
+ override fun onDeepLinking(result: DeepLinkResult) {
204
+ try {
205
+ dispatchDeepLink(result)
206
+ } catch (e: Exception) {
207
+ Log.d(TAG, "onDeepLink dispatch failed: ${e.javaClass.simpleName}")
208
+ }
209
+ }
210
+ })
211
+ deepLinkListenerRegistered = true
70
212
  }
213
+ } catch (e: Exception) {
214
+ logFailure("initialize", e)
215
+ return
216
+ }
71
217
 
72
- // Android only: OAID collection
73
- if (config.hasKey("collectOaid")) {
74
- AdShiftLib.setCollectOaid(config.getBoolean("collectOaid"))
75
- }
218
+ applyOptions(config)
219
+ autoHandleDeepLinks = optBoolean(config, "autoHandleDeepLinks") ?: true
220
+ // Only now may an Intent be forwarded: branded domains and push paths are in place.
221
+ readyForIntents = true
222
+
223
+ val stored = synchronized(lock) { pendingIntent.also { pendingIntent = null } }
224
+ if (!autoHandleDeepLinks) return
225
+ stored?.let { processIntent(it.intent, it.fromLaunchPath) }
226
+ processIntent(reactContext.currentActivity?.intent, fromLaunchPath = true)
227
+ }
76
228
 
77
- // iOS only options are ignored on Android (disableSKAN, waitForATT, attTimeout)
78
-
79
- logInfo("SDK initialized successfully")
229
+ /** Applies the optional `initialize` keys; absent keys leave SDK defaults untouched. */
230
+ private fun applyOptions(config: ReadableMap) {
231
+ try {
232
+ optBoolean(config, "isDebug")?.let { AdShiftLib.setDebugLog(it) }
233
+ optDouble(config, "appOpenDebounceMs")?.let { AdShiftLib.setAppOpenDebounceMs(it.toLong()) }
234
+ optBoolean(config, "collectOaid")?.let {
235
+ if (!collectOaidApplied) {
236
+ collectOaidApplied = true
237
+ AdShiftLib.setCollectOaid(it)
238
+ }
239
+ }
240
+ optArray(config, "brandedDomains")?.let { AdShiftLib.setBrandedDomains(stringList(it)) }
241
+ optString(config, "metaAppId")?.takeIf { it.isNotBlank() }?.let { AdShiftLib.setMetaAppId(it) }
242
+ optArray(config, "pushDeepLinkPaths")?.let { paths ->
243
+ for (i in 0 until paths.size()) {
244
+ if (paths.getType(i) != ReadableType.Array) continue
245
+ val path = paths.getArray(i)?.let(::stringList) ?: continue
246
+ if (path.isNotEmpty()) registerPushPath(path)
247
+ }
248
+ }
80
249
  } catch (e: Exception) {
81
- logError("initialize", e.message)
250
+ logFailure("initialize options", e)
82
251
  }
83
252
  }
84
253
 
254
+ /**
255
+ * Answers from the SDK listener rather than from the call returning, so a device that opted
256
+ * out is reported as such instead of looking like a successful start. The listener answers on
257
+ * the main thread, and [START_VERDICT_TIMEOUT_MS] bounds the promise in case the answer comes
258
+ * later than the call.
259
+ */
85
260
  override fun start(promise: Promise) {
86
- try {
87
- AdShiftLib.start(object : AdShiftRequestListener {
261
+ if (!sdkInitialized) {
262
+ promise.resolve(startFailure(ErrorCode.NOT_INITIALIZED, "SDK not initialized"))
263
+ return
264
+ }
265
+ mainHandler.post {
266
+ val answered = AtomicBoolean(false)
267
+ val listener = object : AdShiftRequestListener {
88
268
  override fun onSuccess() {
89
- val result = Arguments.createMap().apply {
90
- putBoolean("success", true)
269
+ if (answered.compareAndSet(false, true)) {
270
+ Log.d(TAG, "start: SDK started")
271
+ promise.resolve(startSucceeded("valid"))
91
272
  }
92
- promise.resolve(result)
93
273
  }
94
274
 
95
275
  override fun onError(code: Int, error: String) {
96
- promise.reject("START_ERROR", error)
276
+ if (!answered.compareAndSet(false, true)) return
277
+ when (code) {
278
+ SdkErrorCode.NO_DEV_KEY -> Log.w(TAG, "start: API key rejected")
279
+ SdkErrorCode.STOP_TRACKING -> Log.d(TAG, "start: tracking disabled for this device")
280
+ else -> Log.d(TAG, "start: listener error code=$code")
281
+ }
282
+ val failure = startFailure(mapSdkErrorCode(code), error, nativeCode = code)
283
+ if (code == SdkErrorCode.NO_DEV_KEY) {
284
+ failure.putString("apiKeyValidationStatus", "invalid")
285
+ }
286
+ promise.resolve(failure)
97
287
  }
98
- })
99
- } catch (e: Exception) {
100
- promise.reject("START_ERROR", e.message, e)
288
+ }
289
+ try {
290
+ AdShiftLib.start(listener)
291
+ } catch (e: IllegalStateException) {
292
+ if (answered.compareAndSet(false, true)) {
293
+ promise.resolve(startFailure(ErrorCode.NOT_INITIALIZED, e.message ?: "not initialized"))
294
+ }
295
+ return@post
296
+ } catch (e: Exception) {
297
+ if (answered.compareAndSet(false, true)) {
298
+ promise.resolve(startFailure(ErrorCode.UNKNOWN, e.message ?: e.javaClass.simpleName))
299
+ }
300
+ return@post
301
+ }
302
+ mainHandler.postDelayed({
303
+ if (answered.compareAndSet(false, true)) {
304
+ Log.d(TAG, "start: no verdict yet, reporting as started")
305
+ promise.resolve(startSucceeded("pending"))
306
+ }
307
+ }, START_VERDICT_TIMEOUT_MS)
308
+ }
309
+ }
310
+
311
+ /**
312
+ * The listener answers only once the SDK holds a usable key, so a success
313
+ * callback is itself the verdict. Silence within the window below means the
314
+ * answer is still outstanding, which is what `pending` reports.
315
+ */
316
+ private fun startSucceeded(apiKeyValidationStatus: String): WritableMap =
317
+ Arguments.createMap().apply {
318
+ putBoolean("success", true)
319
+ putString("apiKeyValidationStatus", apiKeyValidationStatus)
101
320
  }
321
+
322
+ private fun startFailure(
323
+ code: String,
324
+ message: String,
325
+ nativeCode: Int? = null,
326
+ ): WritableMap = Arguments.createMap().apply {
327
+ putBoolean("success", false)
328
+ putString("errorCode", code)
329
+ putString("errorMessage", message)
330
+ nativeCode?.let { putInt("nativeCode", it) }
102
331
  }
103
332
 
104
333
  override fun stop() {
105
- // Must run on main thread due to Android SDK requirements
106
334
  mainHandler.post {
107
335
  try {
108
336
  AdShiftLib.stop()
109
337
  } catch (e: Exception) {
110
- logError("stop", e.message)
338
+ logFailure("stop", e)
111
339
  }
112
340
  }
113
341
  }
114
342
 
115
- override fun isStarted(): Boolean {
116
- return try {
117
- AdShiftLib.isStarted()
118
- } catch (e: Exception) {
119
- false
120
- }
121
- }
122
-
123
- // ============ Configuration Methods ============
343
+ // ============ Configuration ============
124
344
 
125
345
  override fun setCustomerUserId(userId: String) {
126
346
  try {
127
347
  AdShiftLib.setCustomerUserId(userId)
128
348
  } catch (e: Exception) {
129
- logError("setCustomerUserId", e.message)
349
+ logFailure("setCustomerUserId", e)
130
350
  }
131
351
  }
132
352
 
@@ -134,7 +354,7 @@ class AdShiftReactNativePluginModule(private val reactContext: ReactApplicationC
134
354
  try {
135
355
  AdShiftLib.setDebugLog(enabled)
136
356
  } catch (e: Exception) {
137
- logError("setDebugEnabled", e.message)
357
+ logFailure("setDebugEnabled", e)
138
358
  }
139
359
  }
140
360
 
@@ -142,18 +362,51 @@ class AdShiftReactNativePluginModule(private val reactContext: ReactApplicationC
142
362
  try {
143
363
  AdShiftLib.setAppOpenDebounceMs(ms.toLong())
144
364
  } catch (e: Exception) {
145
- logError("setAppOpenDebounceMs", e.message)
365
+ logFailure("setAppOpenDebounceMs", e)
146
366
  }
147
367
  }
148
368
 
149
- // ============ Consent Methods ============
369
+ override fun setBrandedDomains(domains: ReadableArray) {
370
+ try {
371
+ AdShiftLib.setBrandedDomains(stringList(domains))
372
+ } catch (e: Exception) {
373
+ logFailure("setBrandedDomains", e)
374
+ }
375
+ }
376
+
377
+ override fun setMetaAppId(appId: String) {
378
+ try {
379
+ AdShiftLib.setMetaAppId(appId)
380
+ } catch (e: Exception) {
381
+ logFailure("setMetaAppId", e)
382
+ }
383
+ }
384
+
385
+ override fun setOaidData(oaid: String) {
386
+ try {
387
+ AdShiftLib.setOaidData(oaid)
388
+ } catch (e: Exception) {
389
+ logFailure("setOaidData", e)
390
+ }
391
+ }
392
+
393
+ // ============ Consent ============
150
394
 
151
395
  override fun setConsentData(consent: ReadableMap) {
152
396
  try {
153
- val adShiftConsent = mapToAdShiftConsent(consent)
397
+ val subjectToGdpr = optBoolean(consent, "isUserSubjectToGDPR") ?: false
398
+ val adShiftConsent = if (subjectToGdpr) {
399
+ AdShiftConsent.forGDPRUser(
400
+ hasConsentForDataUsage = triState(consent, "hasConsentForDataUsage"),
401
+ hasConsentForAdsPersonalization = triState(consent, "hasConsentForAdsPersonalization"),
402
+ hasConsentForAdStorage = triState(consent, "hasConsentForAdStorage"),
403
+ )
404
+ } else {
405
+ AdShiftConsent.forNonGDPRUser()
406
+ }
154
407
  AdShiftLib.setConsentData(adShiftConsent)
155
408
  } catch (e: Exception) {
156
- logError("setConsentData", e.message)
409
+ logFailure("setConsentData", e)
157
410
  }
158
411
  }
159
412
 
@@ -161,7 +414,46 @@ class AdShiftReactNativePluginModule(private val reactContext: ReactApplicationC
161
414
  try {
162
415
  AdShiftLib.enableTCFDataCollection(enabled)
163
416
  } catch (e: Exception) {
164
- logError("enableTCFDataCollection", e.message)
417
+ logFailure("enableTCFDataCollection", e)
418
+ }
419
+ }
420
+
421
+ override fun enableGPPDataCollection(enabled: Boolean) {
422
+ try {
423
+ AdShiftLib.enableGPPDataCollection(enabled)
424
+ } catch (e: Exception) {
425
+ logFailure("enableGPPDataCollection", e)
426
+ }
427
+ }
428
+
429
+ /**
430
+ * A missing or non-boolean `optOut` is dropped rather than defaulted.
431
+ *
432
+ * This axis has the opposite polarity to consent: `false` is the app
433
+ * declaring that sharing is allowed, not the absence of an answer. Guessing
434
+ * either way from a malformed call would record a declaration the user never
435
+ * made, and the wrong guess cannot be undone for events already sent.
436
+ */
437
+ override fun setThirdPartySharing(sharing: ReadableMap) {
438
+ try {
439
+ val optOut = optBoolean(sharing, "optOut")
440
+ if (optOut == null) {
441
+ logFailure("setThirdPartySharing", IllegalArgumentException("optOut must be a boolean"))
442
+ return
443
+ }
444
+ AdShiftLib.setThirdPartySharing(
445
+ if (optOut) AdShiftThirdPartySharing.optedOut() else AdShiftThirdPartySharing.allowed()
446
+ )
447
+ } catch (e: Exception) {
448
+ logFailure("setThirdPartySharing", e)
449
+ }
450
+ }
451
+
452
+ override fun clearThirdPartySharing() {
453
+ try {
454
+ AdShiftLib.clearThirdPartySharing()
455
+ } catch (e: Exception) {
456
+ logFailure("clearThirdPartySharing", e)
165
457
  }
166
458
  }
167
459
 
@@ -173,44 +465,46 @@ class AdShiftReactNativePluginModule(private val reactContext: ReactApplicationC
173
465
  snapshot.gdprApplies?.let { putInt("gdprApplies", it) }
174
466
  putBoolean("tcStringPresent", snapshot.tcStringPresent)
175
467
  putBoolean("gppPresent", snapshot.gppPresent)
468
+ putBoolean("cmpDetected", snapshot.cmpDetected)
176
469
  snapshot.adUserDataEnabled?.let { putBoolean("adUserDataEnabled", it) }
177
470
  snapshot.adPersonalizationEnabled?.let { putBoolean("adPersonalizationEnabled", it) }
178
471
  snapshot.adStorageEnabled?.let { putBoolean("adStorageEnabled", it) }
179
472
  putDouble("appliedAtMillis", snapshot.appliedAtMillis.toDouble())
180
- // Convenience field for JS
181
- putBoolean("hasConsent", snapshot.adStorageEnabled == true || snapshot.adUserDataEnabled == true)
473
+ putBoolean("adIdentifiersAllowed", adIdentifiersAllowed(snapshot))
182
474
  }
183
475
  promise.resolve(result)
184
476
  } catch (e: Exception) {
185
- promise.reject("CONSENT_ERROR", e.message, e)
477
+ rejectWith(promise, e)
478
+ }
479
+ }
480
+
481
+ /**
482
+ * Whether consent lets the SDK use the advertising identifier.
483
+ *
484
+ * Storage and data usage both have to be allowed. Under GDPR an undecided
485
+ * flag counts as a refusal; outside it, only an explicit denial does.
486
+ */
487
+ private fun adIdentifiersAllowed(snapshot: ConsentSnapshot): Boolean {
488
+ val storage = snapshot.adStorageEnabled
489
+ val dataUsage = snapshot.adUserDataEnabled
490
+ return if (snapshot.gdprApplies == 1) {
491
+ storage == true && dataUsage == true
492
+ } else {
493
+ storage != false && dataUsage != false
186
494
  }
187
495
  }
188
496
 
189
- // ============ Event Tracking Methods ============
497
+ // ============ Event Tracking ============
190
498
 
191
499
  override fun trackEvent(eventName: String, values: ReadableMap?, promise: Promise) {
192
500
  try {
193
- // Filter out null values and cast to Map<String, Any>
194
- val eventValues: Map<String, Any> = values?.toHashMap()
195
- ?.filterValues { it != null }
196
- ?.mapValues { it.value as Any }
197
- ?: emptyMap()
198
-
199
501
  AdShiftLib.trackEvent(
200
502
  eventName = eventName,
201
- eventValue = eventValues,
202
- listener = object : AdShiftRequestListener {
203
- override fun onSuccess() {
204
- promise.resolve(null)
205
- }
206
-
207
- override fun onError(code: Int, error: String) {
208
- promise.reject("TRACK_ERROR", error)
209
- }
210
- }
503
+ eventValue = values?.let(::nonNullValues) ?: emptyMap(),
504
+ listener = promiseListener(promise),
211
505
  )
212
506
  } catch (e: Exception) {
213
- promise.reject("TRACK_ERROR", e.message, e)
507
+ rejectWith(promise, e)
214
508
  }
215
509
  }
216
510
 
@@ -219,7 +513,7 @@ class AdShiftReactNativePluginModule(private val reactContext: ReactApplicationC
219
513
  price: Double,
220
514
  currency: String,
221
515
  token: String,
222
- promise: Promise
516
+ promise: Promise,
223
517
  ) {
224
518
  try {
225
519
  AdShiftLib.trackPurchase(
@@ -227,194 +521,457 @@ class AdShiftReactNativePluginModule(private val reactContext: ReactApplicationC
227
521
  price = price,
228
522
  currency = currency,
229
523
  token = token,
230
- listener = object : AdShiftRequestListener {
231
- override fun onSuccess() {
232
- promise.resolve(null)
233
- }
524
+ listener = promiseListener(promise),
525
+ )
526
+ } catch (e: Exception) {
527
+ rejectWith(promise, e)
528
+ }
529
+ }
234
530
 
235
- override fun onError(code: Int, error: String) {
236
- promise.reject("TRACK_ERROR", error)
237
- }
238
- }
531
+ override fun logAdRevenue(data: ReadableMap, promise: Promise) {
532
+ val monetizationNetwork = optString(data, "monetizationNetwork")
533
+ val mediationNetworkName = optString(data, "mediationNetwork")
534
+ val currency = optString(data, "currency")
535
+ val revenue = optDouble(data, "revenue")
536
+ if (monetizationNetwork.isNullOrBlank() || mediationNetworkName.isNullOrBlank() ||
537
+ currency.isNullOrBlank() || revenue == null
538
+ ) {
539
+ rejectWith(
540
+ promise,
541
+ ErrorCode.INVALID_ARGUMENT,
542
+ "monetizationNetwork, mediationNetwork, currency and revenue are required",
543
+ null,
544
+ null,
239
545
  )
546
+ return
547
+ }
548
+ if (!revenue.isFinite() || revenue <= 0.0) {
549
+ rejectWith(promise, ErrorCode.INVALID_ARGUMENT, "revenue must be a positive number", null, null)
550
+ return
551
+ }
552
+ if (currency.length != 3) {
553
+ rejectWith(promise, ErrorCode.INVALID_ARGUMENT, "currency must be a 3-letter ISO 4217 code", null, null)
554
+ return
555
+ }
556
+
557
+ val mediationNetwork = ASMediationNetwork.entries.firstOrNull { it.networkName == mediationNetworkName }
558
+ ?: ASMediationNetwork.OTHER.also { Log.d(TAG, "logAdRevenue: unknown mediation network, using other") }
559
+
560
+ val additionalParameters = LinkedHashMap<String, Any>()
561
+ optMap(data, "additionalParameters")?.let { extra ->
562
+ for ((key, value) in nonNullValues(extra)) {
563
+ if (key !in RESERVED_AD_REVENUE_KEYS) additionalParameters[key] = value
564
+ }
565
+ }
566
+ optString(data, "adUnitId")?.let { additionalParameters[ASInAppEventParameterName.AD_REVENUE_AD_UNIT_ID] = it }
567
+ optString(data, "precision")?.let { additionalParameters[ASInAppEventParameterName.AD_REVENUE_PRECISION] = it }
568
+
569
+ try {
570
+ AdShiftLib.logAdRevenue(
571
+ ASAdRevenueData(
572
+ monetizationNetwork = monetizationNetwork,
573
+ mediationNetwork = mediationNetwork,
574
+ currencyIso4217Code = currency,
575
+ revenue = revenue,
576
+ ),
577
+ additionalParameters.takeIf { it.isNotEmpty() },
578
+ )
579
+ promise.resolve(null)
240
580
  } catch (e: Exception) {
241
- promise.reject("TRACK_ERROR", e.message, e)
581
+ rejectWith(promise, e)
242
582
  }
243
583
  }
244
584
 
245
- // ============ Deep Link Methods ============
585
+ // ============ Identity ============
246
586
 
247
- override fun handleDeepLink(url: String, promise: Promise) {
587
+ override fun getAdShiftDeviceId(promise: Promise) {
248
588
  try {
249
- val uri = Uri.parse(url)
250
- val intent = Intent(Intent.ACTION_VIEW, uri)
589
+ promise.resolve(AdShiftLib.getAdShiftDeviceId())
590
+ } catch (e: Exception) {
591
+ rejectWith(promise, e)
592
+ }
593
+ }
251
594
 
252
- // Store promise to resolve when deep link callback fires
253
- pendingDeepLinkPromise = promise
254
-
255
- // Ensure unified listener is registered
256
- ensureDeepLinkListenerRegistered()
595
+ // ============ Deep Links ============
257
596
 
258
- AdShiftLib.handleAppLinkIntent(intent)
597
+ override fun handleDeepLink(url: String, fromLaunch: Boolean, promise: Promise) {
598
+ val uri = Uri.parse(url)
599
+ val scheme = uri.scheme
600
+ val isWeb = scheme.equals("http", ignoreCase = true) || scheme.equals("https", ignoreCase = true)
601
+ if (scheme.isNullOrEmpty() || (isWeb && uri.host.isNullOrEmpty())) {
602
+ rejectWith(promise, ErrorCode.INVALID_ARGUMENT, "url must be an absolute URL", null, null)
603
+ return
604
+ }
605
+ if (!sdkInitialized) {
606
+ rejectWith(promise, ErrorCode.NOT_INITIALIZED, "SDK not initialized", null, null)
607
+ return
608
+ }
609
+
610
+ val now = System.currentTimeMillis()
611
+ val alreadyForwarded = synchronized(lock) {
612
+ pruneAutoForwarded(now)
613
+ autoForwardedUrls.containsKey(url) ||
614
+ (fromLaunch && launchForwardedUrls.contains(url))
615
+ }
616
+ if (alreadyForwarded) {
617
+ Log.d(TAG, "handleDeepLink: url already forwarded from Intent")
618
+ promise.resolve(null)
619
+ return
620
+ }
621
+ if (fromLaunch) {
622
+ synchronized(lock) { rememberLaunchUrls(setOf(url)) }
623
+ }
624
+
625
+ try {
626
+ AdShiftLib.handleAppLinkIntent(Intent(Intent.ACTION_VIEW, uri))
627
+ promise.resolve(null)
259
628
  } catch (e: Exception) {
260
- pendingDeepLinkPromise = null
261
- val errorResult = Arguments.createMap().apply {
262
- putString("status", "error")
263
- putString("errorMessage", e.message ?: "Unknown error")
264
- putBoolean("isDeferred", false)
265
- }
266
- promise.resolve(errorResult)
629
+ rejectWith(promise, e)
267
630
  }
268
631
  }
269
632
 
270
- // ============ Event Emitter Methods ============
633
+ override fun addPushNotificationDeepLinkPath(path: ReadableArray) {
634
+ val keys = stringList(path)
635
+ if (keys.isEmpty()) {
636
+ Log.e(TAG, "addPushNotificationDeepLinkPath: path must contain at least one key")
637
+ return
638
+ }
639
+ registerPushPath(keys)
640
+ }
271
641
 
272
- override fun addListener(eventType: String) {
273
- listenerCount++
274
-
275
- // Register deep link listener when first listener is added
276
- if (listenerCount == 1) {
277
- ensureDeepLinkListenerRegistered()
642
+ /** Registers a push payload key path once per process. */
643
+ private fun registerPushPath(path: List<String>) {
644
+ val id = path.joinToString("\u001F")
645
+ synchronized(lock) {
646
+ if (!registeredPushPaths.add(id)) return
647
+ }
648
+ try {
649
+ AdShiftLib.addPushNotificationDeepLinkPath(*path.toTypedArray())
650
+ } catch (e: Exception) {
651
+ synchronized(lock) { registeredPushPaths.remove(id) }
652
+ logFailure("addPushNotificationDeepLinkPath", e)
278
653
  }
279
654
  }
280
655
 
281
- override fun removeListeners(count: Double) {
282
- listenerCount -= count.toInt()
283
- if (listenerCount < 0) listenerCount = 0
656
+ override fun handlePushNotification(payload: ReadableMap, promise: Promise) {
657
+ try {
658
+ promise.resolve(AdShiftLib.handlePushNotification(payload.toHashMap()))
659
+ } catch (e: Exception) {
660
+ rejectWith(promise, e)
661
+ }
284
662
  }
285
663
 
286
664
  /**
287
- * Ensures single unified deep link listener is registered.
288
- * Handles both one-shot Promise (handleDeepLink) and EventEmitter (onDeepLink) callbacks.
665
+ * Returns false when JavaScript could not receive the result, so the caller can keep it.
289
666
  */
290
- private fun ensureDeepLinkListenerRegistered() {
291
- if (deepLinkListenerRegistered) return
292
-
293
- try {
294
- AdShiftLib.setDeepLinkListener(object : DeepLinkListener {
295
- override fun onDeepLinking(deepLinkResult: DeepLinkResult) {
296
- val resultMap = mapDeepLinkResultToWritableMap(deepLinkResult)
297
-
298
- mainHandler.post {
299
- // First: resolve any pending Promise from handleDeepLink()
300
- pendingDeepLinkPromise?.let { promise ->
301
- promise.resolve(resultMap)
302
- pendingDeepLinkPromise = null
303
- }
304
-
305
- // Second: emit to EventEmitter subscribers (if any)
306
- if (listenerCount > 0) {
307
- // Create a copy since we may have already used resultMap for promise
308
- val eventMap = mapDeepLinkResultToWritableMap(deepLinkResult)
309
- sendEvent(EVENT_DEEP_LINK, eventMap)
310
- }
311
- }
312
- }
313
- })
314
- deepLinkListenerRegistered = true
667
+ private fun emitDeepLink(result: DeepLinkResult): Boolean {
668
+ if (invalidated || !emitterAttached || mEventEmitterCallback == null) return false
669
+ return try {
670
+ emitOnDeepLink(toWritableMap(result))
671
+ true
315
672
  } catch (e: Exception) {
316
- // SDK might not be initialized yet
317
- logError("ensureDeepLinkListenerRegistered", e.message)
673
+ Log.d(TAG, "onDeepLink emit failed: ${e.javaClass.simpleName}")
674
+ false
675
+ }
676
+ }
677
+
678
+ override fun setEventEmitterCallback(eventEmitterCallback: CxxCallbackImpl) {
679
+ super.setEventEmitterCallback(eventEmitterCallback)
680
+ emitterAttached = true
681
+ flushPendingDeepLinks()
682
+ }
683
+
684
+ /** Delivers results that arrived while no JavaScript listener was reachable, oldest first. */
685
+ private fun flushPendingDeepLinks() {
686
+ val pending = synchronized(lock) {
687
+ if (pendingDeepLinks.isEmpty()) return
688
+ pendingDeepLinks.toList().also { pendingDeepLinks.clear() }
689
+ }
690
+ pending.forEach { result ->
691
+ if (!emitDeepLink(result)) {
692
+ synchronized(lock) { pendingDeepLinks.addLast(result) }
693
+ }
318
694
  }
319
695
  }
320
696
 
697
+ // ============ Intent forwarding ============
698
+
321
699
  /**
322
- * Sends event to JavaScript via DeviceEventEmitter.
700
+ * Forwards an Intent to the SDK once. Intents that arrive before `initialize`
701
+ * are kept (newest wins) and processed when the SDK becomes available.
323
702
  */
324
- private fun sendEvent(eventName: String, params: WritableMap) {
325
- mainHandler.post {
326
- reactContext
327
- .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
328
- ?.emit(eventName, params)
703
+ private fun processIntent(intent: Intent?, fromLaunchPath: Boolean) {
704
+ if (intent == null) return
705
+ if (!readyForIntents) {
706
+ synchronized(lock) { pendingIntent = StoredIntent(intent, fromLaunchPath) }
707
+ return
708
+ }
709
+ if (!autoHandleDeepLinks) return
710
+ if ((intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
711
+ Log.d(TAG, "intent skipped (history)")
712
+ return
713
+ }
714
+ val firstSeen = synchronized(lock) { processedIntents.add(intent) }
715
+ if (!firstSeen) {
716
+ Log.d(TAG, "intent skipped (duplicate)")
717
+ return
718
+ }
719
+ if (fromLaunchPath) {
720
+ val fingerprint = fingerprintOf(intent)
721
+ val alreadySeen = synchronized(lock) {
722
+ (lastLaunchIntentFingerprint == fingerprint).also { seen ->
723
+ if (!seen) lastLaunchIntentFingerprint = fingerprint
724
+ }
725
+ }
726
+ if (alreadySeen) {
727
+ Log.d(TAG, "intent skipped (launch)")
728
+ return
729
+ }
730
+ }
731
+
732
+ try {
733
+ AdShiftLib.handlePushNotification(intent.extras)
734
+ AdShiftLib.handleAppLinkIntent(intent)
735
+ } catch (e: Exception) {
736
+ Log.d(TAG, "intent processing failed: ${e.javaClass.simpleName}")
329
737
  }
738
+
739
+ val forwarded = linkedSetOf<String>()
740
+ intent.dataString?.let { forwarded += it }
741
+ forwarded += urlsIn(intent.extras)
742
+ if (forwarded.isNotEmpty()) {
743
+ val now = System.currentTimeMillis()
744
+ synchronized(lock) {
745
+ pruneAutoForwarded(now)
746
+ forwarded.forEach { autoForwardedUrls[it] = now }
747
+ rememberLaunchUrls(forwarded)
748
+ }
749
+ }
750
+ Log.d(TAG, "intent processed")
330
751
  }
331
752
 
332
- // ============ Mappers ============
753
+ /** Guarded by [lock]. Keeps the newest entries so the set cannot grow without bound. */
754
+ private fun rememberLaunchUrls(urls: Set<String>) {
755
+ for (url in urls) {
756
+ launchForwardedUrls.remove(url)
757
+ launchForwardedUrls.add(url)
758
+ }
759
+ while (launchForwardedUrls.size > LAUNCH_URL_MEMORY_LIMIT) {
760
+ val oldest = launchForwardedUrls.iterator()
761
+ oldest.next()
762
+ oldest.remove()
763
+ }
764
+ }
333
765
 
334
766
  /**
335
- * Maps ReadableMap consent to native AdShiftConsent.
767
+ * Identifies a single Intent delivery, so an Activity recreated with the same Intent is
768
+ * recognised while a genuinely new delivery is not. Covers the data URI, the Meta App Link
769
+ * payload and the extras, because notification taps carry no data URI and are told apart
770
+ * only by their extras.
336
771
  */
337
- private fun mapToAdShiftConsent(consent: ReadableMap): AdShiftConsent {
338
- val isGDPR = consent.getBooleanOrDefault("isUserSubjectToGDPR", false)
339
- val dataUsage = consent.getBooleanOrDefault("hasConsentForDataUsage", false)
340
- val personalization = consent.getBooleanOrDefault("hasConsentForAdsPersonalization", false)
341
- val storage = consent.getBooleanOrDefault("hasConsentForAdStorage", false)
342
-
343
- return if (isGDPR) {
344
- AdShiftConsent.forGDPRUser(
345
- hasConsentForDataUsage = dataUsage,
346
- hasConsentForAdsPersonalization = personalization,
347
- hasConsentForAdStorage = storage
348
- )
349
- } else {
350
- AdShiftConsent.forNonGDPRUser()
351
- }
772
+ private fun fingerprintOf(intent: Intent): String {
773
+ val data = intent.dataString ?: ""
774
+ val appLink = runCatching {
775
+ @Suppress("DEPRECATION")
776
+ when (val extra = intent.extras?.get(META_APP_LINK_EXTRA)) {
777
+ is String -> extra
778
+ is android.os.Bundle -> extra.getString("target_url") ?: ""
779
+ else -> ""
780
+ }
781
+ }.getOrDefault("")
782
+ val payload = "$data|$appLink|${extrasFingerprint(intent)}"
783
+ val digest = MessageDigest.getInstance("SHA-256").digest(payload.toByteArray())
784
+ return digest.joinToString("") { "%02x".format(it) }
352
785
  }
353
786
 
354
787
  /**
355
- * Maps native DeepLinkResult to WritableMap for React Native.
788
+ * Extras rendered in a stable order. Only values whose textual form survives re-parcelling
789
+ * are included, so the digest stays equal for the same delivery.
356
790
  */
357
- private fun mapDeepLinkResultToWritableMap(result: DeepLinkResult): WritableMap {
358
- return Arguments.createMap().apply {
359
- // Deep link URL
360
- result.uri?.toString()?.let { putString("deepLink", it) }
361
-
362
- // Deep link value - extract from queryParams if present
363
- // Note: Android SDK doesn't have deepLinkValue as separate field like iOS
364
- result.queryParams?.get("deep_link_value")?.let { putString("deepLinkValue", it) }
365
-
366
- // Sub parameters
367
- result.sub1?.let { putString("deepLinkSub1", it) }
368
- result.sub2?.let { putString("deepLinkSub2", it) }
369
- result.sub3?.let { putString("deepLinkSub3", it) }
370
- result.sub4?.let { putString("deepLinkSub4", it) }
371
- result.sub5?.let { putString("deepLinkSub5", it) }
372
-
373
- // Query params (build combined map)
374
- val paramsMap = Arguments.createMap()
375
- result.queryParams?.forEach { (key, value) ->
376
- paramsMap.putString(key, value)
791
+ private fun extrasFingerprint(intent: Intent): String = runCatching {
792
+ val extras = intent.extras ?: return@runCatching ""
793
+ extras.keySet()
794
+ .filter { it != META_APP_LINK_EXTRA }
795
+ .sorted()
796
+ .mapNotNull { key ->
797
+ @Suppress("DEPRECATION")
798
+ when (val value = extras.get(key)) {
799
+ is CharSequence, is Boolean, is Int, is Long, is Float, is Double -> "$key=$value"
800
+ else -> null
801
+ }
377
802
  }
378
- // Also add sub params to params for consistency with iOS
379
- result.sub1?.let { paramsMap.putString("deep_link_sub1", it) }
380
- result.sub2?.let { paramsMap.putString("deep_link_sub2", it) }
381
- result.sub3?.let { paramsMap.putString("deep_link_sub3", it) }
382
- result.sub4?.let { paramsMap.putString("deep_link_sub4", it) }
383
- result.sub5?.let { paramsMap.putString("deep_link_sub5", it) }
384
-
385
- if (paramsMap.toHashMap().isNotEmpty()) {
386
- putMap("params", paramsMap)
803
+ .joinToString("&")
804
+ }.getOrDefault("")
805
+
806
+ /**
807
+ * URLs carried by the extras, including those nested in JSON payloads. A tapped notification
808
+ * holds its link there, so recording them lets `handleDeepLink` recognise a link the SDK has
809
+ * already received with the Intent.
810
+ */
811
+ private fun urlsIn(extras: Bundle?): Set<String> {
812
+ if (extras == null) return emptySet()
813
+ val found = linkedSetOf<String>()
814
+ runCatching {
815
+ extras.keySet().forEach { key ->
816
+ @Suppress("DEPRECATION")
817
+ collectUrls(extras.get(key), EXTRAS_URL_SEARCH_DEPTH, found)
387
818
  }
819
+ }
820
+ return found
821
+ }
822
+
823
+ private fun collectUrls(node: Any?, depth: Int, into: MutableSet<String>) {
824
+ when (node) {
825
+ is String ->
826
+ if (Uri.parse(node).host?.isNotEmpty() == true) {
827
+ into += node
828
+ } else if (depth > 0) {
829
+ runCatching { JSONObject(node) }.getOrNull()
830
+ ?.let { collectUrls(it, depth - 1, into) }
831
+ }
832
+ is JSONObject ->
833
+ if (depth > 0) {
834
+ node.keys().forEach { key -> collectUrls(node.opt(key), depth - 1, into) }
835
+ }
836
+ }
837
+ }
838
+
839
+ /** Must be called with [lock] held. */
840
+ private fun pruneAutoForwarded(now: Long) {
841
+ val iterator = autoForwardedUrls.values.iterator()
842
+ while (iterator.hasNext()) {
843
+ if (now - iterator.next() > AUTO_FORWARD_DEDUP_WINDOW_MS) iterator.remove()
844
+ }
845
+ }
846
+
847
+ // ============ ActivityEventListener / LifecycleEventListener ============
848
+
849
+ override fun onNewIntent(intent: Intent) {
850
+ if (invalidated) return
851
+ try {
852
+ processIntent(intent, fromLaunchPath = false)
853
+ } catch (e: Exception) {
854
+ Log.d(TAG, "onNewIntent failed: ${e.javaClass.simpleName}")
855
+ }
856
+ }
857
+
858
+ override fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) = Unit
388
859
 
389
- // Is deferred
390
- putBoolean("isDeferred", result.isDeferred)
860
+ override fun onHostResume() {
861
+ if (invalidated) return
862
+ try {
863
+ processIntent(reactContext.currentActivity?.intent, fromLaunchPath = true)
864
+ } catch (e: Exception) {
865
+ Log.d(TAG, "onHostResume failed: ${e.javaClass.simpleName}")
866
+ }
867
+ }
868
+
869
+ override fun onHostPause() = Unit
870
+
871
+ override fun onHostDestroy() = Unit
872
+
873
+ // ============ Error model ============
874
+
875
+ private fun rejectWith(promise: Promise, code: String, message: String, throwable: Throwable?, nativeCode: Any?) {
876
+ val userInfo = Arguments.createMap()
877
+ when (nativeCode) {
878
+ null -> Unit
879
+ is Int -> userInfo.putInt("nativeCode", nativeCode)
880
+ else -> userInfo.putString("nativeCode", nativeCode.toString())
881
+ }
882
+ promise.reject(code, message, throwable, userInfo)
883
+ }
884
+
885
+ private fun rejectWith(promise: Promise, e: Throwable) {
886
+ rejectWith(promise, mapThrowable(e), e.message ?: e.javaClass.simpleName, e, null)
887
+ }
888
+
889
+ private fun promiseListener(promise: Promise) = object : AdShiftRequestListener {
890
+ override fun onSuccess() {
891
+ promise.resolve(null)
892
+ }
893
+
894
+ override fun onError(code: Int, error: String) {
895
+ rejectWith(promise, mapSdkErrorCode(code), error, null, code)
896
+ }
897
+ }
898
+
899
+ // ============ Mappers ============
391
900
 
392
- // Status
393
- val statusString = when (result.status) {
901
+ private fun toWritableMap(result: DeepLinkResult): WritableMap = Arguments.createMap().apply {
902
+ val query = result.queryParams ?: emptyMap()
903
+
904
+ result.uri?.toString()?.let { putString("deepLink", it) }
905
+ query["deep_link_value"]?.let { putString("deepLinkValue", it) }
906
+ result.sub1?.let { putString("deepLinkSub1", it) }
907
+ result.sub2?.let { putString("deepLinkSub2", it) }
908
+ result.sub3?.let { putString("deepLinkSub3", it) }
909
+ result.sub4?.let { putString("deepLinkSub4", it) }
910
+ result.sub5?.let { putString("deepLinkSub5", it) }
911
+
912
+ val params = Arguments.createMap()
913
+ for ((key, value) in query) params.putString(key, value)
914
+ result.sub1?.let { params.putString("deep_link_sub1", it) }
915
+ result.sub2?.let { params.putString("deep_link_sub2", it) }
916
+ result.sub3?.let { params.putString("deep_link_sub3", it) }
917
+ result.sub4?.let { params.putString("deep_link_sub4", it) }
918
+ result.sub5?.let { params.putString("deep_link_sub5", it) }
919
+ putMap("params", params)
920
+
921
+ putBoolean("isDeferred", result.isDeferred)
922
+ putBoolean("isFirstSession", result.isFirstSession)
923
+ putString(
924
+ "status",
925
+ when (result.status) {
394
926
  DeepLinkStatus.FOUND -> "found"
395
927
  DeepLinkStatus.NOT_FOUND -> "notFound"
396
928
  DeepLinkStatus.ERROR -> "error"
397
- }
398
- putString("status", statusString)
399
-
400
- // Error message
401
- result.error?.let { error ->
402
- putString("errorMessage", error.name.lowercase().replace("_", " "))
403
- }
404
- }
929
+ },
930
+ )
931
+ result.error?.let { putString("errorMessage", it.name.lowercase().replace('_', ' ')) }
405
932
  }
406
933
 
407
- // ============ Utilities ============
934
+ // ============ ReadableMap helpers ============
935
+
936
+ private fun optString(map: ReadableMap, key: String): String? =
937
+ if (map.hasKey(key) && map.getType(key) == ReadableType.String) map.getString(key) else null
408
938
 
409
- private fun ReadableMap.getBooleanOrDefault(key: String, default: Boolean): Boolean {
410
- return if (hasKey(key)) getBoolean(key) else default
939
+ private fun optBoolean(map: ReadableMap, key: String): Boolean? =
940
+ if (map.hasKey(key) && map.getType(key) == ReadableType.Boolean) map.getBoolean(key) else null
941
+
942
+ private fun optDouble(map: ReadableMap, key: String): Double? =
943
+ if (map.hasKey(key) && map.getType(key) == ReadableType.Number) map.getDouble(key) else null
944
+
945
+ private fun optMap(map: ReadableMap, key: String): ReadableMap? =
946
+ if (map.hasKey(key) && map.getType(key) == ReadableType.Map) map.getMap(key) else null
947
+
948
+ private fun optArray(map: ReadableMap, key: String): ReadableArray? =
949
+ if (map.hasKey(key) && map.getType(key) == ReadableType.Array) map.getArray(key) else null
950
+
951
+ private fun triState(map: ReadableMap, key: String): Boolean? =
952
+ if (!map.hasKey(key) || map.isNull(key)) null else map.getBoolean(key)
953
+
954
+ private fun nonNullValues(map: ReadableMap): Map<String, Any> {
955
+ val out = LinkedHashMap<String, Any>()
956
+ for ((key, value) in map.toHashMap()) {
957
+ if (value != null) out[key] = value
958
+ }
959
+ return out
411
960
  }
412
961
 
413
- private fun logInfo(message: String) {
414
- android.util.Log.i("AdShiftRN", message)
962
+ private fun stringList(array: ReadableArray): List<String> {
963
+ val out = ArrayList<String>(array.size())
964
+ for (i in 0 until array.size()) {
965
+ if (array.getType(i) != ReadableType.String) continue
966
+ val value = array.getString(i) ?: continue
967
+ if (value.isNotBlank()) out.add(value)
968
+ }
969
+ return out
415
970
  }
416
971
 
417
- private fun logError(method: String, message: String?) {
418
- android.util.Log.e("AdShiftRN", "[$method] Error: $message")
972
+ // ============ Logging ============
973
+
974
+ private fun logFailure(method: String, e: Exception) {
975
+ Log.e(TAG, "$method failed: ${e.javaClass.simpleName}: ${e.message}")
419
976
  }
420
977
  }