@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
package/src/Adshift.ts CHANGED
@@ -1,355 +1,1148 @@
1
1
  /**
2
- * AdShift SDK for React Native
3
- *
4
- * Main SDK interface providing type-safe access to native AdShift functionality.
2
+ * AdShift SDK for React Native.
5
3
  *
6
4
  * @example
7
5
  * ```typescript
8
- * import { Adshift, AdshiftEventType } from '@adshift/react-native-plugin';
6
+ * import {
7
+ * Adshift,
8
+ * AdshiftEventParam,
9
+ * AdshiftEventType,
10
+ * } from '@adshift/react-native-plugin';
9
11
  *
10
- * // 1. Initialize
11
- * Adshift.initialize({ apiKey: 'your-api-key', isDebug: true });
12
+ * // 1. Register the deep link listener (safe to do before initialize)
13
+ * const subscription = Adshift.onDeepLink((deepLink) => {
14
+ * // route on deepLink.deepLinkValue / deepLink.params
15
+ * });
12
16
  *
13
- * // 2. Start tracking
14
- * await Adshift.start();
17
+ * // 2. Initialize
18
+ * Adshift.initialize({ apiKey: 'your-api-key', isDebug: __DEV__ });
15
19
  *
16
- * // 3. Track events
17
- * await Adshift.trackEvent(AdshiftEventType.Purchase, { price: 9.99 });
20
+ * // 3. Start
21
+ * const result = await Adshift.start();
18
22
  *
19
- * // 4. Listen for deep links
20
- * const subscription = Adshift.onDeepLink((deepLink) => {
21
- * console.log('Deep link received:', deepLink);
23
+ * // 4. Track
24
+ * await Adshift.trackEvent(AdshiftEventType.Purchase, {
25
+ * [AdshiftEventParam.Revenue]: 9.99,
26
+ * [AdshiftEventParam.Currency]: 'USD',
22
27
  * });
28
+ *
23
29
  * // Later: subscription.remove();
24
30
  * ```
25
31
  */
26
32
 
27
- import { NativeEventEmitter, Platform } from 'react-native';
33
+ import { Linking, Platform } from 'react-native';
34
+ import type { EventSubscription } from 'react-native';
28
35
  import NativeAdShiftReactNativePlugin from './NativeAdShiftReactNativePlugin';
29
- import type { AdshiftConfig, AdshiftConsent, AdshiftDeepLink } from './types';
36
+ import type { NativeDeepLinkPayload } from './NativeAdShiftReactNativePlugin';
37
+ import { NATIVE_SDK_VERSIONS } from './nativeSdkVersions';
38
+ import type {
39
+ AdRevenueParams,
40
+ AdshiftConfig,
41
+ AdshiftConsent,
42
+ AdshiftDeepLink,
43
+ AdshiftError,
44
+ AdshiftEventTypeValue,
45
+ AdshiftThirdPartySharing,
46
+ ConsentSnapshot,
47
+ } from './types';
30
48
  import {
49
+ AdshiftDeepLink as AdshiftDeepLinkHelpers,
50
+ AdshiftErrorCode,
51
+ AdshiftEventParam,
52
+ AdshiftMediationNetwork,
31
53
  configToMap,
54
+ getAllEventParams,
55
+ consentSnapshotFromMap,
32
56
  consentToMap,
33
- AdshiftDeepLink as AdshiftDeepLinkHelpers,
57
+ createAdshiftError,
58
+ thirdPartySharingToMap,
59
+ toAdshiftError,
34
60
  } from './types';
61
+ import { PLUGIN_VERSION } from './version';
35
62
 
36
- // ============ Types ============
63
+ // ============ Public types ============
37
64
 
38
65
  /**
39
- * Result returned from Adshift.start()
66
+ * Result of `Adshift.start()`.
67
+ *
68
+ * `success` reports whether the SDK started locally. Backend validation of
69
+ * the API key continues in the background; a rejected key is reported through
70
+ * `config.onError` as `INVALID_API_KEY`.
40
71
  */
41
72
  export interface StartResult {
42
- /** Whether start was successful */
43
73
  success: boolean;
44
- /** Optional message from native SDK */
45
- message?: string;
74
+ /**
75
+ * Outcome of the API key check at the time `start()` resolved.
76
+ * `pending` means the answer had not arrived yet when `start()` resolved; it
77
+ * changes nothing you have to do, since the SDK keeps the data either way.
78
+ */
79
+ apiKeyValidationStatus?: ApiKeyValidationStatus;
80
+ /** Platform error number behind `errorCode`, for support requests. */
81
+ nativeCode?: number | string;
82
+ /** Platform error domain behind `errorCode`. @platform ios */
83
+ nativeDomain?: string;
84
+ /** Set when `success` is false. */
85
+ errorCode?: AdshiftErrorCode;
86
+ /** Set when `success` is false. */
87
+ errorMessage?: string;
46
88
  }
47
89
 
48
- /**
49
- * Values that can be passed to trackEvent
50
- */
90
+ /** How far the API key check had got when `start()` resolved. */
91
+ export type ApiKeyValidationStatus = 'pending' | 'valid' | 'invalid';
92
+
51
93
  export type EventValues = Record<string, string | number | boolean>;
52
94
 
53
95
  /**
54
- * Parameters for trackPurchase
96
+ * Parameters for `Adshift.trackPurchase()`.
55
97
  */
56
98
  export interface PurchaseParams {
57
- /** Product identifier */
99
+ /** Product identifier. */
58
100
  productId: string;
59
- /** Purchase amount (revenue) */
101
+ /** Purchase amount in `currency`. */
60
102
  revenue: number;
61
- /** ISO currency code (e.g., "USD") */
103
+ /** ISO 4217 currency code, e.g. `USD`. */
62
104
  currency: string;
63
- /** Transaction ID / purchase receipt token */
105
+ /** Transaction id or purchase token. */
64
106
  transactionId: string;
65
107
  }
66
108
 
67
109
  /**
68
- * Subscription returned from onDeepLink
110
+ * Subscription returned by `Adshift.onDeepLink()`.
69
111
  */
70
112
  export interface DeepLinkSubscription {
71
- /** Removes the deep link listener */
113
+ /** Removes the listener. Safe to call more than once. */
72
114
  remove(): void;
73
115
  }
74
116
 
117
+ export type DeepLinkCallback = (deepLink: AdshiftDeepLink) => void;
118
+
75
119
  /**
76
- * Callback for deep link events
120
+ * Native SDK versions bundled with this plugin release.
77
121
  */
78
- export type DeepLinkCallback = (deepLink: AdshiftDeepLink) => void;
122
+ export interface NativeSdkVersions {
123
+ android: string;
124
+ ios: string;
125
+ }
79
126
 
80
- // ============ Internal State ============
127
+ /**
128
+ * Plugin information returned by `Adshift.getInfo()`.
129
+ */
130
+ export interface AdshiftInfo {
131
+ /** `Platform.OS`; the SDK only supports `ios` and `android`. */
132
+ platform: 'ios' | 'android' | (string & {});
133
+ /** Plugin version. */
134
+ version: string;
135
+ /** Native SDK versions this plugin depends on. */
136
+ nativeSdkVersions: NativeSdkVersions;
137
+ }
81
138
 
82
- let _isInitialized = false;
83
- let _eventEmitter: NativeEventEmitter | null = null;
139
+ // ============ Constants ============
84
140
 
85
- // ============ Internal Helpers ============
141
+ const DEEP_LINK_BUFFER_LIMIT = 20;
142
+ const PENDING_CALL_LIMIT = 100;
143
+ /** Bounds how long `start()` waits for the URL the app was opened with. */
144
+ const INITIAL_URL_WAIT_MS = 3000;
145
+ /** How long one URL counts as the same link, whoever passed it in first. */
146
+ const AUTO_FORWARD_DEDUP_MS = 2000;
147
+ /**
148
+ * Mirrors a limit the SDK applies, so the warning below can name it. Raising it
149
+ * there without raising it here makes the warning wrong, not the behaviour.
150
+ */
151
+ const MAX_AD_REVENUE_PER_IMPRESSION = 10;
152
+ const MEDIATION_NETWORKS: ReadonlySet<string> = new Set(
153
+ Object.values(AdshiftMediationNetwork)
154
+ );
155
+ /**
156
+ * Event names the SDK sends on its own. Sending them by hand would mix
157
+ * hand-made records into install and session counts, which cannot be undone
158
+ * once they are reported.
159
+ */
160
+ const RESERVED_EVENT_NAMES: ReadonlySet<string> = new Set([
161
+ 'app_install',
162
+ 'app_open',
163
+ ]);
164
+
165
+ type LifecycleState =
166
+ | 'uninitialized'
167
+ | 'initialized'
168
+ | 'starting'
169
+ | 'started'
170
+ | 'stopped';
171
+
172
+ interface ListenerEntry {
173
+ callback: DeepLinkCallback;
174
+ }
175
+
176
+ interface PendingCall {
177
+ run: () => Promise<unknown>;
178
+ resolve: (value: unknown) => void;
179
+ reject: (error: AdshiftError) => void;
180
+ }
181
+
182
+ /**
183
+ * Configuration received before `initialize()`. Each entry holds the latest
184
+ * value for one setter, so the memory is bounded by the number of setters.
185
+ */
186
+ interface PendingSettings {
187
+ customerUserId?: string;
188
+ debugEnabled?: boolean;
189
+ appOpenDebounceMs?: number;
190
+ brandedDomains?: string[];
191
+ metaAppId?: string;
192
+ oaid?: string;
193
+ consent?: AdshiftConsent;
194
+ tcfEnabled?: boolean;
195
+ gppEnabled?: boolean;
196
+ /**
197
+ * Absent means neither sharing call was made; `null` means the last one was
198
+ * `clearThirdPartySharing()`. Two calls share this slot, so the distinction
199
+ * has to survive here or a clear before `initialize()` would be dropped and
200
+ * the set it was meant to undo would still be applied.
201
+ */
202
+ thirdPartySharing?: AdshiftThirdPartySharing | null;
203
+ pushDeepLinkPaths: string[][];
204
+ }
205
+
206
+ // ============ Internal state ============
207
+
208
+ let state: LifecycleState = 'uninitialized';
209
+ let frozenConfig: Readonly<AdshiftConfig> | null = null;
210
+ let startInFlight: Promise<StartResult> | null = null;
211
+ /** Incremented per start attempt so a superseded attempt cannot touch the state. */
212
+ let startEpoch = 0;
213
+
214
+ let nativeSubscription: EventSubscription | null = null;
215
+ const listeners = new Set<ListenerEntry>();
216
+ const deepLinkBuffer: AdshiftDeepLink[] = [];
217
+ let replayScheduled = false;
218
+
219
+ const pendingCalls: PendingCall[] = [];
86
220
 
87
- function ensureInitialized(): void {
88
- if (!_isInitialized) {
89
- throw new Error(
90
- 'AdShift SDK not initialized. Call Adshift.initialize(config) first.'
221
+ let linkingSubscription: EventSubscription | null = null;
222
+ let initialUrlForward: Promise<void> | null = null;
223
+ const autoForwarded = new Map<string, number>();
224
+
225
+ let pendingSettings: PendingSettings = { pushDeepLinkPaths: [] };
226
+ let errorHandler: ((error: AdshiftError) => void) | null = null;
227
+ /** Kept so `start()` can answer with the reason `initialize()` was refused. */
228
+ let configError: AdshiftError | null = null;
229
+
230
+ // ============ Logging ============
231
+
232
+ function devWarn(message: string): void {
233
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
234
+ console.warn(`[AdShift] ${message}`);
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Reports a call the plugin declined to make.
240
+ *
241
+ * Public methods that return nothing have no channel to answer through, so
242
+ * they never raise: raising would unwind a stack the caller did not choose,
243
+ * and React Native treats an error escaping an event handler or a native
244
+ * callback as fatal. The call is skipped and reported here instead.
245
+ */
246
+ function reportDeclined(error: AdshiftError): void {
247
+ devWarn(`${error.message} (${error.code})`);
248
+ if (!errorHandler) return;
249
+ try {
250
+ errorHandler(error);
251
+ } catch {
252
+ devWarn('config.onError threw; ignoring it.');
253
+ }
254
+ }
255
+
256
+ // ============ Errors ============
257
+
258
+ function notInitializedError(): AdshiftError {
259
+ return createAdshiftError(
260
+ AdshiftErrorCode.NotInitialized,
261
+ 'AdShift SDK is not initialized. Call Adshift.initialize(config) first.'
262
+ );
263
+ }
264
+
265
+ function notStartedError(): AdshiftError {
266
+ return createAdshiftError(
267
+ AdshiftErrorCode.NotStarted,
268
+ 'AdShift SDK is stopped. Call Adshift.start() first.'
269
+ );
270
+ }
271
+
272
+ function invalidArgument(message: string): AdshiftError {
273
+ return createAdshiftError(AdshiftErrorCode.InvalidArgument, message);
274
+ }
275
+
276
+ function isNonEmptyString(value: unknown): value is string {
277
+ return typeof value === 'string' && value.trim().length > 0;
278
+ }
279
+
280
+ function isFiniteNumber(value: unknown): value is number {
281
+ return typeof value === 'number' && Number.isFinite(value);
282
+ }
283
+
284
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
285
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
286
+ }
287
+
288
+ function isStringArray(value: unknown): value is string[] {
289
+ return Array.isArray(value) && value.every(isNonEmptyString);
290
+ }
291
+
292
+ /**
293
+ * Plain names a caller is likely to invent, mapped onto the standard constant
294
+ * that carries the same meaning. Built from the constants so there is one list
295
+ * to keep, not two.
296
+ */
297
+ const STANDARD_PARAM_BY_PLAIN_NAME: ReadonlyMap<
298
+ string,
299
+ keyof typeof AdshiftEventParam
300
+ > = (() => {
301
+ const index = new Map<string, keyof typeof AdshiftEventParam>();
302
+ const standard = new Set<string>(getAllEventParams());
303
+ for (const [key, value] of Object.entries(AdshiftEventParam)) {
304
+ const bare = value.slice('as_'.length);
305
+ const aliases = [
306
+ bare,
307
+ bare.replace(/_([a-z0-9])/g, (_match, char: string) =>
308
+ char.toUpperCase()
309
+ ),
310
+ key.charAt(0).toLowerCase() + key.slice(1),
311
+ ];
312
+ for (const alias of aliases) {
313
+ if (!standard.has(alias) && !index.has(alias)) {
314
+ index.set(alias, key as keyof typeof AdshiftEventParam);
315
+ }
316
+ }
317
+ }
318
+ return index;
319
+ })();
320
+
321
+ const reportedPlainParamNames = new Set<string>();
322
+
323
+ /**
324
+ * Warns once per name when a value carries a plain name instead of the
325
+ * standard one. Sending it is allowed — it just stays a custom parameter.
326
+ */
327
+ function warnAboutPlainParamNames(values: EventValues | undefined): void {
328
+ if (values === undefined) return;
329
+ for (const key of Object.keys(values)) {
330
+ const standard = STANDARD_PARAM_BY_PLAIN_NAME.get(key);
331
+ if (standard === undefined || reportedPlainParamNames.has(key)) continue;
332
+ reportedPlainParamNames.add(key);
333
+ devWarn(
334
+ `"${key}" is kept as a custom parameter. Use AdshiftEventParam.${standard} ` +
335
+ `("${AdshiftEventParam[standard]}") for a value reports should count.`
91
336
  );
92
337
  }
93
338
  }
94
339
 
95
- function getEventEmitter(): NativeEventEmitter {
96
- if (!_eventEmitter) {
97
- _eventEmitter = new NativeEventEmitter(NativeAdShiftReactNativePlugin);
340
+ function validateEventValues(values: unknown, name: string): void {
341
+ if (values === undefined || values === null) return;
342
+ if (!isPlainObject(values)) {
343
+ throw invalidArgument(`AdShift SDK: ${name} must be an object`);
344
+ }
345
+ for (const [key, value] of Object.entries(values)) {
346
+ const type = typeof value;
347
+ if (type !== 'string' && type !== 'number' && type !== 'boolean') {
348
+ throw invalidArgument(
349
+ `AdShift SDK: ${name}.${key} must be a string, number or boolean`
350
+ );
351
+ }
352
+ if (type === 'number' && !Number.isFinite(value)) {
353
+ throw invalidArgument(`AdShift SDK: ${name}.${key} must be finite`);
354
+ }
98
355
  }
99
- return _eventEmitter;
100
356
  }
101
357
 
102
- // ============ Main SDK API ============
358
+ // ============ Configuration received before initialize() ============
359
+
360
+ /**
361
+ * Folds settings received before `initialize()` into the config.
362
+ *
363
+ * The config wins for anything it states, because it is the later and more
364
+ * explicit declaration. Push key paths are additive, so they are merged.
365
+ * Settings that reach the SDK through a setter only are applied by
366
+ * `applyPendingSettings()` right after the native module is initialized.
367
+ */
368
+ function withPendingSettings(config: AdshiftConfig): AdshiftConfig {
369
+ const merged: AdshiftConfig = { ...config };
370
+ const pending = pendingSettings;
371
+ if (merged.isDebug === undefined && pending.debugEnabled !== undefined) {
372
+ merged.isDebug = pending.debugEnabled;
373
+ }
374
+ if (
375
+ merged.appOpenDebounceMs === undefined &&
376
+ pending.appOpenDebounceMs !== undefined
377
+ ) {
378
+ merged.appOpenDebounceMs = pending.appOpenDebounceMs;
379
+ }
380
+ if (merged.brandedDomains === undefined && pending.brandedDomains) {
381
+ merged.brandedDomains = pending.brandedDomains;
382
+ }
383
+ if (merged.metaAppId === undefined && pending.metaAppId !== undefined) {
384
+ merged.metaAppId = pending.metaAppId;
385
+ }
386
+ if (pending.pushDeepLinkPaths.length > 0) {
387
+ merged.pushDeepLinkPaths = [
388
+ ...(merged.pushDeepLinkPaths ?? []),
389
+ ...pending.pushDeepLinkPaths,
390
+ ];
391
+ }
392
+ return merged;
393
+ }
394
+
395
+ function applyPendingSettings(): void {
396
+ const pending = pendingSettings;
397
+ pendingSettings = { pushDeepLinkPaths: [] };
398
+ if (pending.customerUserId !== undefined) {
399
+ NativeAdShiftReactNativePlugin.setCustomerUserId(pending.customerUserId);
400
+ }
401
+ if (pending.oaid !== undefined) {
402
+ NativeAdShiftReactNativePlugin.setOaidData(pending.oaid);
403
+ }
404
+ if (pending.consent !== undefined) {
405
+ NativeAdShiftReactNativePlugin.setConsentData(
406
+ consentToMap(pending.consent)
407
+ );
408
+ }
409
+ if (pending.tcfEnabled !== undefined) {
410
+ NativeAdShiftReactNativePlugin.enableTCFDataCollection(pending.tcfEnabled);
411
+ }
412
+ if (pending.gppEnabled !== undefined) {
413
+ NativeAdShiftReactNativePlugin.enableGPPDataCollection(pending.gppEnabled);
414
+ }
415
+ if (pending.thirdPartySharing !== undefined) {
416
+ if (pending.thirdPartySharing === null) {
417
+ NativeAdShiftReactNativePlugin.clearThirdPartySharing();
418
+ } else {
419
+ NativeAdShiftReactNativePlugin.setThirdPartySharing(
420
+ thirdPartySharingToMap(pending.thirdPartySharing)
421
+ );
422
+ }
423
+ }
424
+ }
425
+
426
+ // ============ Deep link delivery ============
427
+
428
+ function ensureNativeSubscription(): void {
429
+ if (nativeSubscription) return;
430
+ nativeSubscription = NativeAdShiftReactNativePlugin.onDeepLink(
431
+ (payload: NativeDeepLinkPayload) => {
432
+ dispatchDeepLink(
433
+ AdshiftDeepLinkHelpers.fromMap(payload as Record<string, unknown>)
434
+ );
435
+ }
436
+ );
437
+ }
438
+
439
+ function dispatchDeepLink(deepLink: AdshiftDeepLink): void {
440
+ // A result must never overtake one already waiting in the buffer: a deferred
441
+ // link delivered after a link tapped later would attribute the install to
442
+ // the wrong click.
443
+ if (listeners.size === 0 || deepLinkBuffer.length > 0) {
444
+ bufferDeepLink(deepLink);
445
+ scheduleReplay();
446
+ return;
447
+ }
448
+ deliver(deepLink);
449
+ }
450
+
451
+ function deliver(deepLink: AdshiftDeepLink): void {
452
+ for (const entry of Array.from(listeners)) {
453
+ if (!listeners.has(entry)) continue;
454
+ try {
455
+ entry.callback(deepLink);
456
+ } catch (error) {
457
+ devWarn(
458
+ `onDeepLink listener threw: ${
459
+ error instanceof Error ? error.message : String(error)
460
+ }`
461
+ );
462
+ }
463
+ }
464
+ }
465
+
466
+ function bufferDeepLink(deepLink: AdshiftDeepLink): void {
467
+ if (deepLinkBuffer.length >= DEEP_LINK_BUFFER_LIMIT) {
468
+ const evictable = deepLinkBuffer.findIndex((item) => !item.isDeferred);
469
+ if (evictable >= 0) {
470
+ deepLinkBuffer.splice(evictable, 1);
471
+ } else if (deepLink.isDeferred) {
472
+ deepLinkBuffer.shift();
473
+ } else {
474
+ devWarn('Deep link buffer is full; dropping a direct deep link.');
475
+ return;
476
+ }
477
+ }
478
+ deepLinkBuffer.push(deepLink);
479
+ }
480
+
481
+ function scheduleReplay(): void {
482
+ if (replayScheduled) return;
483
+ replayScheduled = true;
484
+ Promise.resolve().then(() => {
485
+ replayScheduled = false;
486
+ if (listeners.size === 0 || deepLinkBuffer.length === 0) return;
487
+ const items = deepLinkBuffer.splice(0, deepLinkBuffer.length);
488
+ for (const item of items) {
489
+ deliver(item);
490
+ }
491
+ });
492
+ }
493
+
494
+ // ============ Automatic URL forwarding (iOS) ============
495
+
496
+ function autoForwardEnabled(): boolean {
497
+ return (
498
+ Platform.OS === 'ios' &&
499
+ frozenConfig !== null &&
500
+ frozenConfig.autoHandleDeepLinks !== false
501
+ );
502
+ }
503
+
504
+ function startLinkingAutoForward(): void {
505
+ if (linkingSubscription) return;
506
+ linkingSubscription = Linking.addEventListener('url', ({ url }) => {
507
+ if (state === 'uninitialized' || !autoForwardEnabled()) return;
508
+ // An app that handles `url` itself and calls handleDeepLink() sees the same
509
+ // event here, and the two are indistinguishable from a second tap. The
510
+ // short window treats them as one link; a tap that comes later is a
511
+ // separate click and is forwarded.
512
+ if (wasAutoForwardedRecently(url)) return;
513
+ forwardUrl(url, false).catch(() => undefined);
514
+ });
515
+ // The launch URL is read on every initialize(), so it comes back after a
516
+ // JavaScript reload as well. It is marked as such, and the native side keeps
517
+ // it for the lifetime of the process, so the link is booked once.
518
+ initialUrlForward = Linking.getInitialURL()
519
+ .then((url) => (url ? forwardUrl(url, true) : undefined))
520
+ .catch(() => undefined)
521
+ .finally(() => {
522
+ initialUrlForward = null;
523
+ });
524
+ }
525
+
526
+ async function forwardUrl(url: string, fromLaunch: boolean): Promise<void> {
527
+ if (!isNonEmptyString(url)) return;
528
+ pruneAutoForwarded();
529
+ autoForwarded.set(url, Date.now());
530
+ try {
531
+ await NativeAdShiftReactNativePlugin.handleDeepLink(url, fromLaunch);
532
+ } catch (error) {
533
+ const mapped = toAdshiftError(error);
534
+ if (mapped.code !== AdshiftErrorCode.OptedOut) {
535
+ devWarn(`Automatic deep link forwarding failed: ${mapped.code}`);
536
+ }
537
+ }
538
+ }
539
+
540
+ function pruneAutoForwarded(): void {
541
+ const cutoff = Date.now() - AUTO_FORWARD_DEDUP_MS;
542
+ for (const [url, timestamp] of autoForwarded) {
543
+ if (timestamp < cutoff) {
544
+ autoForwarded.delete(url);
545
+ }
546
+ }
547
+ }
548
+
549
+ function wasAutoForwardedRecently(url: string): boolean {
550
+ pruneAutoForwarded();
551
+ return autoForwarded.has(url);
552
+ }
553
+
554
+ async function waitForInitialUrlForward(): Promise<void> {
555
+ const pending = initialUrlForward;
556
+ if (!pending) return;
557
+ let timer: ReturnType<typeof setTimeout> | undefined;
558
+ const timeout = new Promise<void>((resolve) => {
559
+ timer = setTimeout(resolve, INITIAL_URL_WAIT_MS);
560
+ });
561
+ try {
562
+ await Promise.race([pending, timeout]);
563
+ } finally {
564
+ if (timer !== undefined) clearTimeout(timer);
565
+ }
566
+ }
567
+
568
+ // ============ Start gating ============
569
+
570
+ function runWhenStarted<T>(run: () => Promise<T>): Promise<T> {
571
+ switch (state) {
572
+ case 'uninitialized':
573
+ return Promise.reject(notInitializedError());
574
+ case 'stopped':
575
+ return Promise.reject(notStartedError());
576
+ case 'started':
577
+ return run().catch((error) => {
578
+ throw toAdshiftError(error);
579
+ });
580
+ case 'initialized':
581
+ case 'starting':
582
+ if (pendingCalls.length >= PENDING_CALL_LIMIT) {
583
+ return Promise.reject(
584
+ createAdshiftError(
585
+ AdshiftErrorCode.QueueFull,
586
+ 'AdShift SDK: too many calls are waiting for start().'
587
+ )
588
+ );
589
+ }
590
+ if (startEpoch === 0 && pendingCalls.length === 0) {
591
+ devWarn(
592
+ 'Call queued until start() runs; it settles when the first start attempt finishes.'
593
+ );
594
+ }
595
+ return new Promise<T>((resolve, reject) => {
596
+ pendingCalls.push({
597
+ run,
598
+ resolve: resolve as (value: unknown) => void,
599
+ reject,
600
+ });
601
+ });
602
+ }
603
+ }
604
+
605
+ function flushPendingCalls(): void {
606
+ const calls = pendingCalls.splice(0, pendingCalls.length);
607
+ for (const call of calls) {
608
+ call
609
+ .run()
610
+ .then(call.resolve)
611
+ .catch((error) => call.reject(toAdshiftError(error)));
612
+ }
613
+ }
614
+
615
+ function rejectPendingCalls(error: AdshiftError): void {
616
+ const calls = pendingCalls.splice(0, pendingCalls.length);
617
+ for (const call of calls) {
618
+ call.reject(error);
619
+ }
620
+ }
621
+
622
+ /**
623
+ * Warns when the native SDK on the device is not the one this release was built
624
+ * against. Only iOS reports its version, so on Android the pin is guarded by a
625
+ * build-time test instead.
626
+ */
627
+ function checkNativeSdkVersion(reported: unknown): void {
628
+ if (typeof reported !== 'string' || reported.length === 0) return;
629
+ const expected =
630
+ Platform.OS === 'ios'
631
+ ? NATIVE_SDK_VERSIONS.ios
632
+ : Platform.OS === 'android'
633
+ ? NATIVE_SDK_VERSIONS.android
634
+ : null;
635
+ if (expected !== null && reported !== expected) {
636
+ devWarn(
637
+ `Native SDK ${reported} differs from the version this plugin was built for (${expected}).`
638
+ );
639
+ }
640
+ }
641
+
642
+ function readStartResult(raw: unknown): StartResult {
643
+ const map = isPlainObject(raw) ? raw : {};
644
+ checkNativeSdkVersion(map.sdkVersion);
645
+ const result: StartResult = { success: map.success === true };
646
+ const validation = map.apiKeyValidationStatus;
647
+ if (
648
+ validation === 'pending' ||
649
+ validation === 'valid' ||
650
+ validation === 'invalid'
651
+ ) {
652
+ result.apiKeyValidationStatus = validation;
653
+ }
654
+ if (!result.success) {
655
+ const code = map.errorCode;
656
+ result.errorCode =
657
+ typeof code === 'string' &&
658
+ (Object.values(AdshiftErrorCode) as string[]).includes(code)
659
+ ? (code as AdshiftErrorCode)
660
+ : AdshiftErrorCode.Unknown;
661
+ result.errorMessage =
662
+ typeof map.errorMessage === 'string'
663
+ ? map.errorMessage
664
+ : 'AdShift SDK failed to start.';
665
+ if (
666
+ typeof map.nativeCode === 'number' ||
667
+ typeof map.nativeCode === 'string'
668
+ ) {
669
+ result.nativeCode = map.nativeCode;
670
+ }
671
+ if (typeof map.nativeDomain === 'string') {
672
+ result.nativeDomain = map.nativeDomain;
673
+ }
674
+ }
675
+ return result;
676
+ }
677
+
678
+ async function performStart(): Promise<StartResult> {
679
+ const previous = state;
680
+ const epoch = ++startEpoch;
681
+ state = 'starting';
682
+ try {
683
+ await waitForInitialUrlForward();
684
+ const result = readStartResult(
685
+ await NativeAdShiftReactNativePlugin.start()
686
+ );
687
+ if (epoch !== startEpoch) {
688
+ // A newer start() owns the lifecycle now; report what native said and
689
+ // leave the state to the newer attempt.
690
+ return result;
691
+ }
692
+ if (state !== 'starting') {
693
+ // stop() was called while start() was in flight; honour the last call.
694
+ if (result.success) {
695
+ NativeAdShiftReactNativePlugin.stop();
696
+ }
697
+ const error = notStartedError();
698
+ return {
699
+ success: false,
700
+ errorCode: error.code,
701
+ errorMessage: error.message,
702
+ };
703
+ }
704
+ if (result.success) {
705
+ state = 'started';
706
+ flushPendingCalls();
707
+ if (result.apiKeyValidationStatus === 'invalid') {
708
+ // The SDK started locally, but nothing it sends will be accepted.
709
+ reportDeclined(
710
+ createAdshiftError(
711
+ AdshiftErrorCode.InvalidApiKey,
712
+ 'AdShift SDK: the backend rejected this API key; no data will be reported.'
713
+ )
714
+ );
715
+ }
716
+ return result;
717
+ }
718
+ state = previous;
719
+ const error = createAdshiftError(
720
+ result.errorCode ?? AdshiftErrorCode.Unknown,
721
+ result.errorMessage ?? 'AdShift SDK failed to start.'
722
+ );
723
+ reportDeclined(error);
724
+ if (isTerminalStartFailure(error.code)) {
725
+ rejectPendingCalls(error);
726
+ }
727
+ return result;
728
+ } catch (error) {
729
+ const mapped = toAdshiftError(error);
730
+ if (epoch === startEpoch && state === 'starting') {
731
+ state = previous;
732
+ }
733
+ const result: StartResult = {
734
+ success: false,
735
+ errorCode: mapped.code,
736
+ errorMessage: mapped.message,
737
+ };
738
+ // What the platform said travels with the result, the same way it does
739
+ // when the native side answers with a failure instead of rejecting.
740
+ if (mapped.userInfo.nativeCode !== undefined) {
741
+ result.nativeCode = mapped.userInfo.nativeCode;
742
+ }
743
+ if (mapped.userInfo.nativeDomain !== undefined) {
744
+ result.nativeDomain = mapped.userInfo.nativeDomain;
745
+ }
746
+ return result;
747
+ }
748
+ }
103
749
 
104
750
  /**
105
- * AdShift SDK main interface.
751
+ * Whether a failed start rules out the calls waiting for it.
106
752
  *
107
- * Provides type-safe access to all SDK functionality.
753
+ * A rejected key, an excluded device and a missing configuration cannot be
754
+ * fixed by trying again, so the waiting calls are answered. Anything else can
755
+ * be, and holding the calls is worth more than answering them quickly: the
756
+ * data survives until the app starts the SDK again.
108
757
  */
758
+ function isTerminalStartFailure(code: AdshiftErrorCode): boolean {
759
+ return (
760
+ code === AdshiftErrorCode.InvalidApiKey ||
761
+ code === AdshiftErrorCode.OptedOut ||
762
+ code === AdshiftErrorCode.NotInitialized
763
+ );
764
+ }
765
+
766
+ // ============ Main SDK API ============
767
+
109
768
  export const Adshift = {
110
769
  // ============ Lifecycle ============
111
770
 
112
771
  /**
113
- * Initializes the SDK with configuration.
114
- *
115
- * Must be called before any other SDK methods.
116
- * Call this early in your app's lifecycle (e.g., in App.tsx or index.js).
772
+ * Initializes the SDK.
117
773
  *
118
- * @param config - SDK configuration
774
+ * Call once, as early as possible (e.g. at module scope of `App.tsx`).
775
+ * The configuration is fixed on the first call; later calls are ignored.
119
776
  *
120
- * @example
121
- * ```typescript
122
- * Adshift.initialize({
123
- * apiKey: 'your-api-key',
124
- * isDebug: __DEV__,
125
- * // iOS only
126
- * waitForATTBeforeStart: true,
127
- * // Android only
128
- * collectOaid: true,
129
- * });
130
- * ```
777
+ * Never raises, because it is meant to run at module scope, where an error
778
+ * would stop the bundle from evaluating. An unusable config is reported
779
+ * through `config.onError` and answered by `start()`.
131
780
  */
132
781
  initialize(config: AdshiftConfig): void {
133
- if (!config.apiKey) {
134
- throw new Error('AdShift SDK: apiKey is required in config');
782
+ if (state !== 'uninitialized') {
783
+ devWarn('initialize() called more than once; the first config is kept.');
784
+ return;
135
785
  }
786
+ errorHandler =
787
+ isPlainObject(config) && typeof config.onError === 'function'
788
+ ? config.onError
789
+ : null;
136
790
 
137
- const configMap = configToMap(config);
138
- NativeAdShiftReactNativePlugin.initialize(configMap);
139
- _isInitialized = true;
791
+ const refuse = (message: string): void => {
792
+ configError = invalidArgument(message);
793
+ reportDeclined(configError);
794
+ };
795
+ if (!isPlainObject(config) || !isNonEmptyString(config.apiKey)) {
796
+ refuse('AdShift SDK: apiKey is required in config');
797
+ return;
798
+ }
799
+ if (
800
+ config.brandedDomains !== undefined &&
801
+ !isStringArray(config.brandedDomains)
802
+ ) {
803
+ refuse(
804
+ 'AdShift SDK: brandedDomains must be an array of non-empty strings'
805
+ );
806
+ return;
807
+ }
808
+ if (
809
+ config.pushDeepLinkPaths !== undefined &&
810
+ !(
811
+ Array.isArray(config.pushDeepLinkPaths) &&
812
+ config.pushDeepLinkPaths.every(isStringArray)
813
+ )
814
+ ) {
815
+ refuse(
816
+ 'AdShift SDK: pushDeepLinkPaths must be an array of string arrays'
817
+ );
818
+ return;
819
+ }
820
+
821
+ configError = null;
822
+ frozenConfig = Object.freeze(withPendingSettings(config));
823
+ try {
824
+ ensureNativeSubscription();
825
+ NativeAdShiftReactNativePlugin.initialize(configToMap(frozenConfig));
826
+ state = 'initialized';
827
+ applyPendingSettings();
828
+ } catch (error) {
829
+ configError = toAdshiftError(error);
830
+ state = 'uninitialized';
831
+ frozenConfig = null;
832
+ reportDeclined(configError);
833
+ return;
834
+ }
835
+
836
+ if (autoForwardEnabled()) {
837
+ startLinkingAutoForward();
838
+ }
140
839
  },
141
840
 
142
841
  /**
143
842
  * Starts the SDK.
144
843
  *
145
- * Validates API key, sends install event (if first launch), and begins tracking.
146
- * Call this after initialize().
147
- *
148
- * @returns Promise resolving to start result
149
- *
150
- * @example
151
- * ```typescript
152
- * try {
153
- * const result = await Adshift.start();
154
- * console.log('SDK started:', result);
155
- * } catch (error) {
156
- * console.error('SDK start failed:', error);
157
- * }
158
- * ```
844
+ * Resolves once the SDK has started locally. Never rejects; inspect
845
+ * `result.success` and `result.errorCode`. Calls to `trackEvent`,
846
+ * `trackPurchase` and `logAdRevenue` made before this resolves are queued
847
+ * and dispatched afterwards. A start that fails with a reason retrying
848
+ * cannot fix rejects them instead; any other failure keeps them waiting for
849
+ * the next attempt.
159
850
  */
160
- async start(): Promise<StartResult> {
161
- ensureInitialized();
162
-
163
- try {
164
- const result = (await NativeAdShiftReactNativePlugin.start()) as Record<
165
- string,
166
- unknown
167
- >;
168
- return {
169
- success: true,
170
- message: result?.message as string | undefined,
171
- };
172
- } catch (error) {
173
- const message = error instanceof Error ? error.message : 'Unknown error';
174
- return {
851
+ start(): Promise<StartResult> {
852
+ if (state === 'uninitialized') {
853
+ const error = configError ?? notInitializedError();
854
+ return Promise.resolve({
175
855
  success: false,
176
- message,
177
- };
856
+ errorCode: error.code,
857
+ errorMessage: error.message,
858
+ });
859
+ }
860
+ if (state === 'started') {
861
+ return Promise.resolve({ success: true });
178
862
  }
863
+ if (startInFlight) {
864
+ return startInFlight;
865
+ }
866
+ const attempt = performStart().finally(() => {
867
+ if (startInFlight === attempt) {
868
+ startInFlight = null;
869
+ }
870
+ });
871
+ startInFlight = attempt;
872
+ return attempt;
179
873
  },
180
874
 
181
875
  /**
182
- * Stops the SDK.
876
+ * Stops the SDK. Tracking calls reject with `NOT_STARTED` until the next
877
+ * successful `start()`.
183
878
  *
184
- * Pauses all tracking. Can be restarted with start().
185
- *
186
- * @example
187
- * ```typescript
188
- * Adshift.stop();
189
- * ```
879
+ * Before `initialize()` there is nothing to stop: the call is reported and
880
+ * skipped.
190
881
  */
191
882
  stop(): void {
192
- ensureInitialized();
883
+ if (state === 'uninitialized') {
884
+ reportDeclined(notInitializedError());
885
+ return;
886
+ }
887
+ state = 'stopped';
888
+ // A later start() must not receive the promise of the attempt this stop cancels.
889
+ startInFlight = null;
890
+ rejectPendingCalls(notStartedError());
193
891
  NativeAdShiftReactNativePlugin.stop();
194
892
  },
195
893
 
196
894
  /**
197
- * Checks if SDK is currently started.
198
- *
199
- * @returns true if SDK is running
200
- *
201
- * @example
202
- * ```typescript
203
- * if (Adshift.isStarted()) {
204
- * // SDK is tracking
205
- * }
206
- * ```
895
+ * Whether `start()` has completed successfully and `stop()` has not been
896
+ * called since. Safe to call before `initialize()`.
207
897
  */
208
898
  isStarted(): boolean {
209
- ensureInitialized();
210
- return NativeAdShiftReactNativePlugin.isStarted();
899
+ return state === 'started';
211
900
  },
212
901
 
213
902
  // ============ Configuration ============
214
903
 
215
904
  /**
216
- * Sets custom user identifier for attribution.
217
- *
218
- * Associate events with your own user ID. Can be called before or after start().
219
- *
220
- * @param userId - Your user identifier
905
+ * Sets your own user identifier. Can be called before or after `start()`.
221
906
  *
222
- * @example
223
- * ```typescript
224
- * Adshift.setCustomerUserId('user_123');
225
- * ```
907
+ * Called before `initialize()`, the value is kept and applied afterwards.
908
+ * An empty identifier is reported and skipped; nothing is raised.
226
909
  */
227
910
  setCustomerUserId(userId: string): void {
228
- ensureInitialized();
229
-
230
- if (!userId || typeof userId !== 'string') {
231
- throw new Error('AdShift SDK: userId must be a non-empty string');
911
+ if (!isNonEmptyString(userId)) {
912
+ reportDeclined(
913
+ invalidArgument('AdShift SDK: userId must be a non-empty string')
914
+ );
915
+ return;
916
+ }
917
+ if (state === 'uninitialized') {
918
+ pendingSettings.customerUserId = userId;
919
+ return;
232
920
  }
233
-
234
921
  NativeAdShiftReactNativePlugin.setCustomerUserId(userId);
235
922
  },
236
923
 
237
924
  /**
238
- * Enables/disables debug logging at runtime.
239
- *
240
- * Note: Can also be set via config.isDebug during initialize().
241
- *
242
- * @param enabled - true to enable debug logs
925
+ * Enables or disables verbose SDK logging at runtime.
243
926
  *
244
- * @example
245
- * ```typescript
246
- * // Enable debug in production for troubleshooting
247
- * Adshift.setDebugEnabled(true);
248
- * ```
927
+ * Called before `initialize()`, the value is kept and applied afterwards.
249
928
  */
250
929
  setDebugEnabled(enabled: boolean): void {
251
- ensureInitialized();
252
- NativeAdShiftReactNativePlugin.setDebugEnabled(enabled);
930
+ if (state === 'uninitialized') {
931
+ pendingSettings.debugEnabled = enabled === true;
932
+ return;
933
+ }
934
+ NativeAdShiftReactNativePlugin.setDebugEnabled(enabled === true);
253
935
  },
254
936
 
255
937
  /**
256
- * Sets app open debounce time in milliseconds.
257
- *
258
- * Used to deduplicate rapid app open events.
259
- * Note: Can also be set via config.appOpenDebounceMs during initialize().
260
- *
261
- * @param ms - Debounce time in milliseconds (e.g., 5000 for 5 seconds)
938
+ * Sets the debounce interval for automatic `app_open` events.
262
939
  *
263
- * @example
264
- * ```typescript
265
- * Adshift.setAppOpenDebounceMs(5000);
266
- * ```
940
+ * Called before `initialize()`, the value is kept and applied afterwards.
941
+ * A negative interval is reported and skipped; nothing is raised.
267
942
  */
268
943
  setAppOpenDebounceMs(ms: number): void {
269
- ensureInitialized();
944
+ if (!isFiniteNumber(ms) || ms < 0) {
945
+ reportDeclined(
946
+ invalidArgument('AdShift SDK: ms must be a non-negative number')
947
+ );
948
+ return;
949
+ }
950
+ if (state === 'uninitialized') {
951
+ pendingSettings.appOpenDebounceMs = ms;
952
+ return;
953
+ }
954
+ NativeAdShiftReactNativePlugin.setAppOpenDebounceMs(ms);
955
+ },
956
+
957
+ /**
958
+ * Sets branded attribution domains. Must be called before `start()`.
959
+ *
960
+ * Called before `initialize()`, the domains are kept and applied with the
961
+ * config, so they are in place before the first link is processed.
962
+ */
963
+ setBrandedDomains(domains: string[]): void {
964
+ if (!isStringArray(domains)) {
965
+ reportDeclined(
966
+ invalidArgument(
967
+ 'AdShift SDK: domains must be an array of non-empty strings'
968
+ )
969
+ );
970
+ return;
971
+ }
972
+ if (state === 'uninitialized') {
973
+ pendingSettings.brandedDomains = [...domains];
974
+ return;
975
+ }
976
+ NativeAdShiftReactNativePlugin.setBrandedDomains(domains);
977
+ },
270
978
 
271
- if (typeof ms !== 'number' || ms < 0) {
272
- throw new Error('AdShift SDK: ms must be a non-negative number');
979
+ /**
980
+ * Sets the Meta app id used to parse Meta App Links. No-op on iOS.
981
+ *
982
+ * Called before `initialize()`, the value is kept and applied afterwards.
983
+ */
984
+ setMetaAppId(appId: string): void {
985
+ if (!isNonEmptyString(appId)) {
986
+ reportDeclined(
987
+ invalidArgument('AdShift SDK: appId must be a non-empty string')
988
+ );
989
+ return;
273
990
  }
991
+ if (state === 'uninitialized') {
992
+ pendingSettings.metaAppId = appId;
993
+ return;
994
+ }
995
+ NativeAdShiftReactNativePlugin.setMetaAppId(appId);
996
+ },
274
997
 
275
- NativeAdShiftReactNativePlugin.setAppOpenDebounceMs(ms);
998
+ /**
999
+ * Hands over an OAID the app obtained itself, for Android devices without
1000
+ * Google Play services. Set `collectOaid: false` when you supply it this
1001
+ * way. No-op on iOS.
1002
+ *
1003
+ * Called before `initialize()`, the value is kept and applied afterwards.
1004
+ */
1005
+ setOaidData(oaid: string): void {
1006
+ if (!isNonEmptyString(oaid)) {
1007
+ reportDeclined(
1008
+ invalidArgument('AdShift SDK: oaid must be a non-empty string')
1009
+ );
1010
+ return;
1011
+ }
1012
+ if (state === 'uninitialized') {
1013
+ pendingSettings.oaid = oaid;
1014
+ return;
1015
+ }
1016
+ NativeAdShiftReactNativePlugin.setOaidData(oaid);
276
1017
  },
277
1018
 
278
1019
  // ============ Consent (GDPR/DMA) ============
279
1020
 
280
1021
  /**
281
- * Sets user consent data manually.
1022
+ * Sets consent collected by your own UI. Use `AdshiftConsent.forGDPRUser()`
1023
+ * or `AdshiftConsent.forNonGDPRUser()`.
282
1024
  *
283
- * Use this for manual consent collection (not CMP).
284
- * Use AdshiftConsent.forGDPRUser() or AdshiftConsent.forNonGDPRUser() helpers.
1025
+ * Called before `initialize()`, the consent is kept and applied afterwards.
1026
+ */
1027
+ setConsentData(consent: AdshiftConsent): void {
1028
+ if (
1029
+ !isPlainObject(consent) ||
1030
+ typeof consent.isUserSubjectToGDPR !== 'boolean'
1031
+ ) {
1032
+ reportDeclined(
1033
+ invalidArgument(
1034
+ 'AdShift SDK: consent.isUserSubjectToGDPR must be a boolean'
1035
+ )
1036
+ );
1037
+ return;
1038
+ }
1039
+ if (state === 'uninitialized') {
1040
+ pendingSettings.consent = consent;
1041
+ return;
1042
+ }
1043
+ NativeAdShiftReactNativePlugin.setConsentData(consentToMap(consent));
1044
+ },
1045
+
1046
+ /**
1047
+ * Enables or disables reading IAB TCF v2.2 consent from the CMP on device.
1048
+ * Call before `start()`.
285
1049
  *
286
- * @param consent - Consent data
1050
+ * Called before `initialize()`, the value is kept and applied afterwards.
1051
+ */
1052
+ enableTCFDataCollection(enabled: boolean): void {
1053
+ if (state === 'uninitialized') {
1054
+ pendingSettings.tcfEnabled = enabled === true;
1055
+ return;
1056
+ }
1057
+ NativeAdShiftReactNativePlugin.enableTCFDataCollection(enabled === true);
1058
+ },
1059
+
1060
+ /**
1061
+ * Enables reading an IAB GPP string written by the CMP on device, used for US
1062
+ * state privacy signals. Off until called with `true`.
287
1063
  *
288
- * @example
289
- * ```typescript
290
- * // GDPR user who accepted all
291
- * Adshift.setConsentData(
292
- * AdshiftConsent.forGDPRUser({
293
- * hasConsentForDataUsage: true,
294
- * hasConsentForAdsPersonalization: true,
295
- * hasConsentForAdStorage: true,
296
- * })
297
- * );
1064
+ * The GPP string rides on its own axis: it is forwarded alongside whatever
1065
+ * decides the GDPR axis, including a consent set through `setConsentData()`,
1066
+ * and it does not gate the advertising identifier on the device.
298
1067
  *
299
- * // Non-GDPR user
300
- * Adshift.setConsentData(AdshiftConsent.forNonGDPRUser());
301
- * ```
1068
+ * Call before `start()`. Called before `initialize()`, the value is kept and
1069
+ * applied afterwards.
302
1070
  */
303
- setConsentData(consent: AdshiftConsent): void {
304
- ensureInitialized();
305
- const consentMap = consentToMap(consent);
306
- NativeAdShiftReactNativePlugin.setConsentData(consentMap);
1071
+ enableGPPDataCollection(enabled: boolean): void {
1072
+ if (state === 'uninitialized') {
1073
+ pendingSettings.gppEnabled = enabled === true;
1074
+ return;
1075
+ }
1076
+ NativeAdShiftReactNativePlugin.enableGPPDataCollection(enabled === true);
307
1077
  },
308
1078
 
309
1079
  /**
310
- * Enables/disables automatic TCF v2.2 data collection from CMP.
311
- *
312
- * When enabled, SDK reads IAB TCF consent strings from device storage
313
- * (set by CMPs like Google Funding Choices, Didomi, etc.)
1080
+ * States what the app collected about passing this user's data on to
1081
+ * advertising partners. Use `AdshiftThirdPartySharing.optedOut()` or
1082
+ * `AdshiftThirdPartySharing.allowed()`.
314
1083
  *
315
- * Call this BEFORE start().
1084
+ * This is the answer to a different question than `setConsentData()`, and it
1085
+ * has the opposite default: nothing said here means sharing is allowed, so
1086
+ * only call it once the user has actually been asked. Setting `allowed()` at
1087
+ * startup as a default records a declaration the user never made, and events
1088
+ * already sent cannot be recalled when a real answer arrives.
316
1089
  *
317
- * @param enabled - true to enable TCF collection
1090
+ * Nothing is gated on the device either way — this travels with the events for
1091
+ * the backend to act on.
318
1092
  *
319
- * @example
320
- * ```typescript
321
- * Adshift.enableTCFDataCollection(true);
322
- * await Adshift.start();
323
- * ```
1093
+ * Called before `initialize()`, the answer is kept and applied afterwards.
324
1094
  */
325
- enableTCFDataCollection(enabled: boolean): void {
326
- ensureInitialized();
327
- NativeAdShiftReactNativePlugin.enableTCFDataCollection(enabled);
1095
+ setThirdPartySharing(sharing: AdshiftThirdPartySharing): void {
1096
+ if (!isPlainObject(sharing) || typeof sharing.optOut !== 'boolean') {
1097
+ reportDeclined(
1098
+ invalidArgument('AdShift SDK: sharing.optOut must be a boolean')
1099
+ );
1100
+ return;
1101
+ }
1102
+ if (state === 'uninitialized') {
1103
+ pendingSettings.thirdPartySharing = sharing;
1104
+ return;
1105
+ }
1106
+ NativeAdShiftReactNativePlugin.setThirdPartySharing(
1107
+ thirdPartySharingToMap(sharing)
1108
+ );
328
1109
  },
329
1110
 
330
1111
  /**
331
- * Refreshes consent state from TCF/CMP or manual sources.
1112
+ * Withdraws the answer set by `setThirdPartySharing()`.
332
1113
  *
333
- * Call this after CMP dialog closes to pick up updated consent.
334
- * Priority: Manual > TCF > None
1114
+ * Subsequent events state nothing on this axis, which is not the same as
1115
+ * stating that sharing is allowed: the first leaves the decision to your
1116
+ * dashboard configuration, the second is the app's own declaration and is
1117
+ * recorded as such.
335
1118
  *
336
- * @returns Promise resolving to consent snapshot
1119
+ * Called before `initialize()`, this cancels a `setThirdPartySharing()` that
1120
+ * was also queued.
1121
+ */
1122
+ clearThirdPartySharing(): void {
1123
+ if (state === 'uninitialized') {
1124
+ pendingSettings.thirdPartySharing = null;
1125
+ return;
1126
+ }
1127
+ NativeAdShiftReactNativePlugin.clearThirdPartySharing();
1128
+ },
1129
+
1130
+ /**
1131
+ * Re-reads consent from the CMP or manual source and returns the snapshot.
1132
+ * Call after the CMP dialog closes.
337
1133
  *
338
- * @example
339
- * ```typescript
340
- * // After CMP dialog closes
341
- * const snapshot = await Adshift.refreshConsent();
342
- * console.log('Consent source:', snapshot.source);
343
- * ```
1134
+ * @returns Rejects with `AdshiftError` (`NOT_INITIALIZED`).
344
1135
  */
345
- async refreshConsent(): Promise<Record<string, unknown>> {
346
- ensureInitialized();
347
- const result =
348
- (await NativeAdShiftReactNativePlugin.refreshConsent()) as Record<
349
- string,
350
- unknown
351
- >;
352
- return result;
1136
+ async refreshConsent(): Promise<ConsentSnapshot> {
1137
+ if (state === 'uninitialized') {
1138
+ throw notInitializedError();
1139
+ }
1140
+ try {
1141
+ const raw = await NativeAdShiftReactNativePlugin.refreshConsent();
1142
+ return consentSnapshotFromMap(isPlainObject(raw) ? raw : {});
1143
+ } catch (error) {
1144
+ throw toAdshiftError(error);
1145
+ }
353
1146
  },
354
1147
 
355
1148
  // ============ Event Tracking ============
@@ -357,183 +1150,321 @@ export const Adshift = {
357
1150
  /**
358
1151
  * Tracks an in-app event.
359
1152
  *
360
- * Use AdshiftEventType constants for predefined events, or custom strings.
361
- * Events are queued until SDK is started.
362
- *
363
- * @param eventName - Event name (use AdshiftEventType or custom string)
364
- * @param values - Optional event parameters
365
- * @returns Promise resolving on success
1153
+ * `app_install` and `app_open` are reserved: the SDK sends them itself and
1154
+ * passing them here rejects with `INVALID_ARGUMENT`.
366
1155
  *
367
- * @example
368
- * ```typescript
369
- * // Predefined event
370
- * await Adshift.trackEvent(AdshiftEventType.AddToCart, {
371
- * product_id: 'SKU123',
372
- * price: 29.99,
373
- * });
1156
+ * Resolves once the SDK has accepted the event. A call made between
1157
+ * `initialize()` and a successful `start()` waits for the start: it is sent
1158
+ * when the SDK starts, and rejects when the start fails for a reason
1159
+ * retrying cannot fix (rejected key, excluded device) or after `stop()`.
1160
+ * A start that failed for any other reason keeps the call waiting for the
1161
+ * next attempt, so `start()` belongs on every launch path.
374
1162
  *
375
- * // Custom event
376
- * await Adshift.trackEvent('custom_event', { key: 'value' });
377
- * ```
1163
+ * @returns Rejects with `AdshiftError` (`NOT_INITIALIZED`, `NOT_STARTED`,
1164
+ * `INVALID_API_KEY`, `OPTED_OUT`, `QUEUE_FULL`, `INVALID_ARGUMENT`).
378
1165
  */
379
- async trackEvent(eventName: string, values?: EventValues): Promise<void> {
380
- ensureInitialized();
381
-
382
- if (!eventName || typeof eventName !== 'string') {
383
- throw new Error('AdShift SDK: eventName must be a non-empty string');
1166
+ trackEvent(
1167
+ eventName: AdshiftEventTypeValue | (string & {}),
1168
+ values?: EventValues
1169
+ ): Promise<void> {
1170
+ if (!isNonEmptyString(eventName)) {
1171
+ return Promise.reject(
1172
+ invalidArgument('AdShift SDK: eventName must be a non-empty string')
1173
+ );
384
1174
  }
385
-
386
- await NativeAdShiftReactNativePlugin.trackEvent(eventName, values ?? null);
1175
+ if (RESERVED_EVENT_NAMES.has(eventName.trim().toLowerCase())) {
1176
+ return Promise.reject(
1177
+ invalidArgument(
1178
+ `AdShift SDK: "${eventName}" is reserved and sent by the SDK; use your own event name`
1179
+ )
1180
+ );
1181
+ }
1182
+ try {
1183
+ validateEventValues(values, 'values');
1184
+ } catch (error) {
1185
+ return Promise.reject(error);
1186
+ }
1187
+ warnAboutPlainParamNames(values);
1188
+ return runWhenStarted(() =>
1189
+ NativeAdShiftReactNativePlugin.trackEvent(eventName, values ?? null)
1190
+ );
387
1191
  },
388
1192
 
389
1193
  /**
390
- * Tracks a purchase event.
391
- *
392
- * Use for revenue tracking and SKAdNetwork conversion value calculation.
393
- *
394
- * @param params - Purchase parameters
395
- * @returns Promise resolving on success
1194
+ * Tracks a purchase.
396
1195
  *
397
- * @example
398
- * ```typescript
399
- * await Adshift.trackPurchase({
400
- * productId: 'premium_subscription',
401
- * revenue: 9.99,
402
- * currency: 'USD',
403
- * transactionId: 'TXN_123456',
404
- * });
405
- * ```
1196
+ * @returns Rejects with `AdshiftError` (see `trackEvent`).
406
1197
  */
407
- async trackPurchase(params: PurchaseParams): Promise<void> {
408
- ensureInitialized();
409
-
1198
+ trackPurchase(params: PurchaseParams): Promise<void> {
1199
+ if (!isPlainObject(params)) {
1200
+ return Promise.reject(
1201
+ invalidArgument('AdShift SDK: params must be an object')
1202
+ );
1203
+ }
410
1204
  const { productId, revenue, currency, transactionId } = params;
411
-
412
- if (!productId) {
413
- throw new Error('AdShift SDK: productId is required');
1205
+ if (!isNonEmptyString(productId)) {
1206
+ return Promise.reject(
1207
+ invalidArgument('AdShift SDK: productId is required')
1208
+ );
414
1209
  }
415
- if (typeof revenue !== 'number' || revenue < 0) {
416
- throw new Error('AdShift SDK: revenue must be a non-negative number');
1210
+ if (!isFiniteNumber(revenue) || revenue < 0) {
1211
+ return Promise.reject(
1212
+ invalidArgument('AdShift SDK: revenue must be a non-negative number')
1213
+ );
417
1214
  }
418
- if (!currency) {
419
- throw new Error('AdShift SDK: currency is required');
1215
+ if (!isNonEmptyString(currency)) {
1216
+ return Promise.reject(
1217
+ invalidArgument('AdShift SDK: currency is required')
1218
+ );
420
1219
  }
421
- if (!transactionId) {
422
- throw new Error('AdShift SDK: transactionId is required');
1220
+ if (!isNonEmptyString(transactionId)) {
1221
+ return Promise.reject(
1222
+ invalidArgument('AdShift SDK: transactionId is required')
1223
+ );
423
1224
  }
1225
+ return runWhenStarted(() =>
1226
+ NativeAdShiftReactNativePlugin.trackPurchase(
1227
+ productId,
1228
+ revenue,
1229
+ currency,
1230
+ transactionId
1231
+ )
1232
+ );
1233
+ },
424
1234
 
425
- // Native SDK uses price/token naming internally
426
- await NativeAdShiftReactNativePlugin.trackPurchase(
427
- productId,
1235
+ /**
1236
+ * Logs ad revenue for a single impression.
1237
+ *
1238
+ * @returns Rejects with `AdshiftError` (see `trackEvent`).
1239
+ */
1240
+ logAdRevenue(params: AdRevenueParams): Promise<void> {
1241
+ if (!isPlainObject(params)) {
1242
+ return Promise.reject(
1243
+ invalidArgument('AdShift SDK: params must be an object')
1244
+ );
1245
+ }
1246
+ const {
1247
+ monetizationNetwork,
1248
+ mediationNetwork,
1249
+ currency,
428
1250
  revenue,
1251
+ adUnitId,
1252
+ precision,
1253
+ additionalParameters,
1254
+ } = params;
1255
+ if (!isNonEmptyString(monetizationNetwork)) {
1256
+ return Promise.reject(
1257
+ invalidArgument('AdShift SDK: monetizationNetwork is required')
1258
+ );
1259
+ }
1260
+ if (
1261
+ !isNonEmptyString(mediationNetwork) ||
1262
+ !MEDIATION_NETWORKS.has(mediationNetwork)
1263
+ ) {
1264
+ return Promise.reject(
1265
+ invalidArgument(
1266
+ 'AdShift SDK: mediationNetwork must be an AdshiftMediationNetwork value'
1267
+ )
1268
+ );
1269
+ }
1270
+ if (!isNonEmptyString(currency)) {
1271
+ return Promise.reject(
1272
+ invalidArgument('AdShift SDK: currency is required')
1273
+ );
1274
+ }
1275
+ if (currency.length !== 3) {
1276
+ return Promise.reject(
1277
+ invalidArgument(
1278
+ 'AdShift SDK: currency must be a 3-letter ISO 4217 code'
1279
+ )
1280
+ );
1281
+ }
1282
+ if (!isFiniteNumber(revenue) || revenue <= 0) {
1283
+ return Promise.reject(
1284
+ invalidArgument('AdShift SDK: revenue must be a positive number')
1285
+ );
1286
+ }
1287
+ if (revenue > MAX_AD_REVENUE_PER_IMPRESSION) {
1288
+ devWarn(
1289
+ `logAdRevenue: revenue above ${MAX_AD_REVENUE_PER_IMPRESSION} is not recorded. ` +
1290
+ 'Pass the revenue of a single impression, not an aggregate.'
1291
+ );
1292
+ }
1293
+ if (adUnitId !== undefined && typeof adUnitId !== 'string') {
1294
+ return Promise.reject(
1295
+ invalidArgument('AdShift SDK: adUnitId must be a string')
1296
+ );
1297
+ }
1298
+ if (precision !== undefined && typeof precision !== 'string') {
1299
+ return Promise.reject(
1300
+ invalidArgument('AdShift SDK: precision must be a string')
1301
+ );
1302
+ }
1303
+ try {
1304
+ validateEventValues(additionalParameters, 'additionalParameters');
1305
+ } catch (error) {
1306
+ return Promise.reject(error);
1307
+ }
1308
+ warnAboutPlainParamNames(additionalParameters);
1309
+ const data: Record<string, unknown> = {
1310
+ monetizationNetwork,
1311
+ mediationNetwork,
429
1312
  currency,
430
- transactionId
1313
+ revenue,
1314
+ };
1315
+ if (adUnitId !== undefined) data.adUnitId = adUnitId;
1316
+ if (precision !== undefined) data.precision = precision;
1317
+ if (additionalParameters !== undefined) {
1318
+ data.additionalParameters = additionalParameters;
1319
+ }
1320
+ return runWhenStarted(() =>
1321
+ NativeAdShiftReactNativePlugin.logAdRevenue(data)
431
1322
  );
432
1323
  },
433
1324
 
1325
+ // ============ Identity ============
1326
+
1327
+ /**
1328
+ * Returns the AdShift device id, or `null` before `initialize()`.
1329
+ */
1330
+ async getAdShiftDeviceId(): Promise<string | null> {
1331
+ if (state === 'uninitialized') {
1332
+ return null;
1333
+ }
1334
+ try {
1335
+ const value = await NativeAdShiftReactNativePlugin.getAdShiftDeviceId();
1336
+ return typeof value === 'string' && value.length > 0 ? value : null;
1337
+ } catch (error) {
1338
+ throw toAdshiftError(error);
1339
+ }
1340
+ },
1341
+
434
1342
  // ============ Deep Links ============
435
1343
 
436
1344
  /**
437
- * Handles a deep link URL.
438
- *
439
- * Call this when your app receives a deep link (e.g., from Linking API).
440
- * Extracts campaign parameters for attribution.
441
- *
442
- * @param url - Deep link URL string
443
- * @returns Promise resolving to deep link response
1345
+ * Passes a URL to the SDK.
444
1346
  *
445
- * @example
446
- * ```typescript
447
- * import { Linking } from 'react-native';
1347
+ * Not needed when `autoHandleDeepLinks` is on (the default). The result is
1348
+ * delivered through `onDeepLink()`; the promise resolves once the SDK has
1349
+ * finished processing the URL.
448
1350
  *
449
- * Linking.addEventListener('url', async ({ url }) => {
450
- * const deepLink = await Adshift.handleDeepLink(url);
451
- * if (deepLink.status === AdshiftDeepLinkStatus.Found) {
452
- * // Navigate based on deepLink.params
453
- * }
454
- * });
455
- * ```
1351
+ * @returns Rejects with `AdshiftError` (`NOT_INITIALIZED`,
1352
+ * `INVALID_ARGUMENT`).
456
1353
  */
457
- async handleDeepLink(url: string): Promise<AdshiftDeepLink> {
458
- ensureInitialized();
459
-
460
- if (!url || typeof url !== 'string') {
461
- return AdshiftDeepLinkHelpers.error('Invalid URL');
1354
+ async handleDeepLink(url: string): Promise<void> {
1355
+ if (state === 'uninitialized') {
1356
+ throw notInitializedError();
462
1357
  }
463
-
1358
+ if (!isNonEmptyString(url)) {
1359
+ throw invalidArgument('AdShift SDK: url must be a non-empty string');
1360
+ }
1361
+ if (wasAutoForwardedRecently(url)) {
1362
+ return;
1363
+ }
1364
+ // Recorded here as well, so automatic forwarding does not repeat a URL the
1365
+ // app passed in first.
1366
+ pruneAutoForwarded();
1367
+ autoForwarded.set(url, Date.now());
464
1368
  try {
465
- const result = (await NativeAdShiftReactNativePlugin.handleDeepLink(
466
- url
467
- )) as Record<string, unknown>;
468
- return AdshiftDeepLinkHelpers.fromMap(result);
1369
+ await NativeAdShiftReactNativePlugin.handleDeepLink(url, false);
469
1370
  } catch (error) {
470
- const message = error instanceof Error ? error.message : 'Unknown error';
471
- return AdshiftDeepLinkHelpers.error(message);
1371
+ const mapped = toAdshiftError(error);
1372
+ if (mapped.code === AdshiftErrorCode.OptedOut) {
1373
+ return;
1374
+ }
1375
+ throw mapped;
472
1376
  }
473
1377
  },
474
1378
 
475
1379
  /**
476
- * Registers a listener for deep link events.
477
- *
478
- * Called when:
479
- * - Deferred deep links are resolved (after first install)
480
- * - App links are received while app is running
1380
+ * Adds a key path inside push payloads that carries an AdShift deep link.
481
1381
  *
482
- * If a deep link was received before listener was set (cold start),
483
- * the callback is called immediately with the cached deep link.
484
- *
485
- * @param callback - Function called when deep link is received
486
- * @returns Subscription object with remove() method
1382
+ * Called before `initialize()`, the path is kept and registered afterwards.
1383
+ * The first path you register takes over from the top-level `as_push_link`
1384
+ * the SDK reads on its own, so register that key too if you still need it.
1385
+ */
1386
+ addPushNotificationDeepLinkPath(path: string[]): void {
1387
+ if (!isStringArray(path) || path.length === 0) {
1388
+ reportDeclined(
1389
+ invalidArgument(
1390
+ 'AdShift SDK: path must be a non-empty array of strings'
1391
+ )
1392
+ );
1393
+ return;
1394
+ }
1395
+ if (state === 'uninitialized') {
1396
+ pendingSettings.pushDeepLinkPaths.push([...path]);
1397
+ return;
1398
+ }
1399
+ NativeAdShiftReactNativePlugin.addPushNotificationDeepLinkPath(path);
1400
+ },
1401
+
1402
+ /**
1403
+ * Passes a push notification payload to the SDK. Resolves to `true` when
1404
+ * the payload carried an AdShift deep link; the result then arrives
1405
+ * through `onDeepLink()`.
487
1406
  *
488
- * @example
489
- * ```typescript
490
- * useEffect(() => {
491
- * const subscription = Adshift.onDeepLink((deepLink) => {
492
- * if (deepLink.status === AdshiftDeepLinkStatus.Found) {
493
- * console.log('Deep link:', deepLink.deepLink);
494
- * console.log('Params:', deepLink.params);
495
- * // Navigate to appropriate screen
496
- * }
497
- * });
1407
+ * @returns Rejects with `AdshiftError` (`NOT_INITIALIZED`,
1408
+ * `INVALID_ARGUMENT`).
1409
+ */
1410
+ async handlePushNotification(
1411
+ payload: Record<string, unknown>
1412
+ ): Promise<boolean> {
1413
+ if (state === 'uninitialized') {
1414
+ throw notInitializedError();
1415
+ }
1416
+ if (!isPlainObject(payload)) {
1417
+ throw invalidArgument('AdShift SDK: payload must be an object');
1418
+ }
1419
+ try {
1420
+ return (
1421
+ (await NativeAdShiftReactNativePlugin.handlePushNotification(
1422
+ payload
1423
+ )) === true
1424
+ );
1425
+ } catch (error) {
1426
+ throw toAdshiftError(error);
1427
+ }
1428
+ },
1429
+
1430
+ /**
1431
+ * Registers a deep link listener.
498
1432
  *
499
- * return () => subscription.remove();
500
- * }, []);
501
- * ```
1433
+ * Safe to call before `initialize()`. Results that arrive while no
1434
+ * listener is registered are buffered and delivered to the first listener.
1435
+ * Every link that reaches the SDK (direct, deferred, push) is delivered.
502
1436
  */
503
1437
  onDeepLink(callback: DeepLinkCallback): DeepLinkSubscription {
504
- ensureInitialized();
505
-
506
- const eventEmitter = getEventEmitter();
507
-
508
- const subscription = eventEmitter.addListener(
509
- 'onDeepLink',
510
- (event: unknown) => {
511
- const deepLink = AdshiftDeepLinkHelpers.fromMap(
512
- event as Record<string, unknown>
513
- );
514
- callback(deepLink);
515
- }
516
- );
517
-
1438
+ if (typeof callback !== 'function') {
1439
+ reportDeclined(
1440
+ invalidArgument('AdShift SDK: callback must be a function')
1441
+ );
1442
+ return { remove: () => {} };
1443
+ }
1444
+ const entry: ListenerEntry = { callback };
1445
+ const wasEmpty = listeners.size === 0;
1446
+ listeners.add(entry);
1447
+ if (wasEmpty && deepLinkBuffer.length > 0) {
1448
+ scheduleReplay();
1449
+ }
518
1450
  return {
519
1451
  remove: () => {
520
- subscription.remove();
1452
+ listeners.delete(entry);
521
1453
  },
522
1454
  };
523
1455
  },
524
1456
 
525
- // ============ Debug ============
1457
+ // ============ Info ============
526
1458
 
527
- /**
528
- * Returns SDK version and platform info.
529
- * Useful for debugging.
530
- */
531
- getInfo(): { platform: string; version: string } {
1459
+ getInfo(): AdshiftInfo {
532
1460
  return {
533
1461
  platform: Platform.OS,
534
- version: '1.0.0', // TODO: Get from package.json
1462
+ version: PLUGIN_VERSION,
1463
+ nativeSdkVersions: { ...NATIVE_SDK_VERSIONS },
535
1464
  };
536
1465
  },
537
- };
1466
+ } as const;
1467
+
1468
+ Object.freeze(Adshift);
538
1469
 
539
1470
  export default Adshift;