@advenue/react-native 0.9.0 → 1.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 (94) hide show
  1. package/README.md +8 -7
  2. package/android/src/main/java/expo/modules/advenue/AdvenueAndroidModule.kt +118 -368
  3. package/android/src/main/kotlin/io/advenue/Advenue.kt +549 -0
  4. package/android/src/main/kotlin/io/advenue/AdvenueConfig.kt +114 -0
  5. package/android/src/main/kotlin/io/advenue/core/Backoff.kt +28 -0
  6. package/android/src/main/kotlin/io/advenue/core/ClientEvent.kt +136 -0
  7. package/android/src/main/kotlin/io/advenue/core/CommandPipe.kt +186 -0
  8. package/android/src/main/kotlin/io/advenue/core/Consent.kt +52 -0
  9. package/android/src/main/kotlin/io/advenue/core/Contracts.kt +80 -0
  10. package/android/src/main/kotlin/io/advenue/core/Conversion.kt +69 -0
  11. package/android/src/main/kotlin/io/advenue/core/Engine.kt +414 -0
  12. package/android/src/main/kotlin/io/advenue/core/EventQueue.kt +89 -0
  13. package/android/src/main/kotlin/io/advenue/core/HmacSigner.kt +31 -0
  14. package/android/src/main/kotlin/io/advenue/core/InstallReferrer.kt +146 -0
  15. package/android/src/main/kotlin/io/advenue/core/Json.kt +272 -0
  16. package/android/src/main/kotlin/io/advenue/core/Limits.kt +47 -0
  17. package/android/src/main/kotlin/io/advenue/core/MetaReferrer.kt +80 -0
  18. package/android/src/main/kotlin/io/advenue/core/SessionTracker.kt +189 -0
  19. package/android/src/main/kotlin/io/advenue/core/SystemServices.kt +58 -0
  20. package/android/src/main/kotlin/io/advenue/core/Tcf.kt +48 -0
  21. package/android/src/main/kotlin/io/advenue/core/Time.kt +56 -0
  22. package/android/src/main/kotlin/io/advenue/platform/Collectors.kt +149 -0
  23. package/android/src/main/kotlin/io/advenue/platform/CompositeStore.kt +33 -0
  24. package/android/src/main/kotlin/io/advenue/platform/ConversionFetcher.kt +68 -0
  25. package/android/src/main/kotlin/io/advenue/platform/ForegroundTracker.kt +90 -0
  26. package/android/src/main/kotlin/io/advenue/platform/HttpUrlTransport.kt +101 -0
  27. package/android/src/main/kotlin/io/advenue/platform/Identity.kt +79 -0
  28. package/android/src/main/kotlin/io/advenue/platform/InstallEnrichment.kt +197 -0
  29. package/android/src/main/kotlin/io/advenue/platform/InstallScopedStore.kt +91 -0
  30. package/android/src/main/kotlin/io/advenue/platform/LifecycleBridge.kt +72 -0
  31. package/android/src/main/kotlin/io/advenue/platform/PreferencesStore.kt +32 -0
  32. package/android/src/main/kotlin/io/advenue/plugin/Contracts.kt +67 -0
  33. package/android/src/main/kotlin/io/advenue/plugin/FirebaseAppInstanceIdSource.kt +73 -0
  34. package/android/src/main/kotlin/io/advenue/plugin/PlayAdvertisingIdSource.kt +47 -0
  35. package/android/src/main/kotlin/io/advenue/plugin/PlayInstallReferrerSource.kt +85 -0
  36. package/android/src/main/kotlin/io/advenue/plugin/PlayIntegritySource.kt +86 -0
  37. package/android/src/main/kotlin/io/advenue/plugin/PluginRegistry.kt +61 -0
  38. package/dist/index.cjs +183 -675
  39. package/dist/index.d.cts +199 -336
  40. package/dist/index.d.ts +199 -336
  41. package/dist/index.js +182 -681
  42. package/ios/AdvenueIosModule.swift +144 -446
  43. package/ios/vendor/Advenue/Advenue.swift +596 -0
  44. package/ios/vendor/Advenue/AdvenueConfig.swift +77 -0
  45. package/ios/vendor/AdvenueCore/AdvenueValue.swift +103 -0
  46. package/ios/vendor/AdvenueCore/Attestation.swift +52 -0
  47. package/ios/vendor/AdvenueCore/Backoff.swift +28 -0
  48. package/ios/vendor/AdvenueCore/ClientEvent.swift +154 -0
  49. package/ios/vendor/AdvenueCore/Consent.swift +40 -0
  50. package/ios/vendor/AdvenueCore/Contracts.swift +59 -0
  51. package/ios/vendor/AdvenueCore/Conversion.swift +74 -0
  52. package/ios/vendor/AdvenueCore/ConversionValue.swift +217 -0
  53. package/ios/vendor/AdvenueCore/Engine.swift +587 -0
  54. package/ios/vendor/AdvenueCore/EventQueue.swift +89 -0
  55. package/ios/vendor/AdvenueCore/Limits.swift +41 -0
  56. package/ios/vendor/AdvenueCore/PIIScrub.swift +102 -0
  57. package/ios/vendor/AdvenueCore/SessionTracker.swift +139 -0
  58. package/ios/vendor/AdvenueCore/SkanConfig.swift +76 -0
  59. package/ios/vendor/AdvenueCore/SkanReporter.swift +25 -0
  60. package/ios/vendor/AdvenueCore/SkanState.swift +258 -0
  61. package/ios/vendor/AdvenueCore/Tcf.swift +48 -0
  62. package/ios/vendor/AdvenueCore/Transport.swift +14 -0
  63. package/ios/vendor/AdvenueFirebase/FirebaseAppInstanceId.swift +33 -0
  64. package/ios/vendor/AdvenuePlatform/AdvertisingIdentity.swift +87 -0
  65. package/ios/vendor/AdvenuePlatform/ChallengeFetcher.swift +42 -0
  66. package/ios/vendor/AdvenuePlatform/ConversionFetcher.swift +63 -0
  67. package/ios/vendor/AdvenuePlatform/CryptoKitSigner.swift +19 -0
  68. package/ios/vendor/AdvenuePlatform/DeviceCheckAttestation.swift +91 -0
  69. package/ios/vendor/AdvenuePlatform/DeviceInfo.swift +65 -0
  70. package/ios/vendor/AdvenuePlatform/ForegroundTracker.swift +55 -0
  71. package/ios/vendor/AdvenuePlatform/HttpTransport.swift +96 -0
  72. package/ios/vendor/AdvenuePlatform/Identity.swift +52 -0
  73. package/ios/vendor/AdvenuePlatform/InstallEnrichment.swift +143 -0
  74. package/ios/vendor/AdvenuePlatform/KeychainStore.swift +95 -0
  75. package/ios/vendor/AdvenuePlatform/SearchAdsToken.swift +76 -0
  76. package/ios/vendor/AdvenuePlatform/SkanConfigFetcher.swift +70 -0
  77. package/ios/vendor/AdvenuePlatform/StoreKitSkanReporter.swift +140 -0
  78. package/ios/vendor/AdvenuePlatform/SystemServices.swift +55 -0
  79. package/ios/vendor/AdvenuePlatform/TcfReader.swift +18 -0
  80. package/ios/vendor/AdvenuePlatform/UserDefaultsStore.swift +26 -0
  81. package/package.json +9 -11
  82. package/scripts/check-dist.mjs +17 -0
  83. package/scripts/check-vendored-swift.mjs +148 -0
  84. package/scripts/vendor-natives.mjs +149 -0
  85. package/scripts/vendor-natives.test.mjs +112 -0
  86. package/src/deep-links.ts +19 -1
  87. package/src/index.ts +266 -830
  88. package/src/native-types.ts +74 -181
  89. package/src/native.ts +0 -23
  90. package/src/types.ts +81 -0
  91. package/src/aem.ts +0 -33
  92. package/src/mmkv-storage.ts +0 -21
  93. package/src/native-storage.ts +0 -63
  94. package/src/secure-store.ts +0 -26
package/dist/index.js CHANGED
@@ -51,174 +51,10 @@ var require_native_require = __commonJS({
51
51
  }
52
52
  });
53
53
 
54
- // src/index.ts
55
- import {
56
- extractReferrerProperties,
57
- parseInstallReferrer,
58
- parseMetaInstallReferrer
59
- } from "@advenue/install-referrer";
60
- import {
61
- AdvenueClient,
62
- DEFAULT_ENDPOINT,
63
- DEVICE_ID_KEY,
64
- MemoryStorage,
65
- resolveDurableDeviceId,
66
- tcfToConsent
67
- } from "@advenue/sdk-core";
68
-
69
- // ../signing/src/index.ts
70
- var K = new Uint32Array([
71
- 1116352408,
72
- 1899447441,
73
- 3049323471,
74
- 3921009573,
75
- 961987163,
76
- 1508970993,
77
- 2453635748,
78
- 2870763221,
79
- 3624381080,
80
- 310598401,
81
- 607225278,
82
- 1426881987,
83
- 1925078388,
84
- 2162078206,
85
- 2614888103,
86
- 3248222580,
87
- 3835390401,
88
- 4022224774,
89
- 264347078,
90
- 604807628,
91
- 770255983,
92
- 1249150122,
93
- 1555081692,
94
- 1996064986,
95
- 2554220882,
96
- 2821834349,
97
- 2952996808,
98
- 3210313671,
99
- 3336571891,
100
- 3584528711,
101
- 113926993,
102
- 338241895,
103
- 666307205,
104
- 773529912,
105
- 1294757372,
106
- 1396182291,
107
- 1695183700,
108
- 1986661051,
109
- 2177026350,
110
- 2456956037,
111
- 2730485921,
112
- 2820302411,
113
- 3259730800,
114
- 3345764771,
115
- 3516065817,
116
- 3600352804,
117
- 4094571909,
118
- 275423344,
119
- 430227734,
120
- 506948616,
121
- 659060556,
122
- 883997877,
123
- 958139571,
124
- 1322822218,
125
- 1537002063,
126
- 1747873779,
127
- 1955562222,
128
- 2024104815,
129
- 2227730452,
130
- 2361852424,
131
- 2428436474,
132
- 2756734187,
133
- 3204031479,
134
- 3329325298
135
- ]);
136
- function rotr(x, n) {
137
- return x >>> n | x << 32 - n;
138
- }
139
- function sha256Bytes(msg) {
140
- const h = new Uint32Array([
141
- 1779033703,
142
- 3144134277,
143
- 1013904242,
144
- 2773480762,
145
- 1359893119,
146
- 2600822924,
147
- 528734635,
148
- 1541459225
149
- ]);
150
- const l = msg.length;
151
- const bitLen = l * 8;
152
- const withOne = l + 1;
153
- const padTo = (56 - withOne % 64 + 64) % 64;
154
- const padded = new Uint8Array(withOne + padTo + 8);
155
- padded.set(msg);
156
- padded[l] = 128;
157
- const dv = new DataView(padded.buffer);
158
- dv.setUint32(padded.length - 8, Math.floor(bitLen / 4294967296));
159
- dv.setUint32(padded.length - 4, bitLen >>> 0);
160
- const w = new Uint32Array(64);
161
- for (let i = 0; i < padded.length; i += 64) {
162
- for (let t = 0; t < 16; t++) w[t] = dv.getUint32(i + t * 4);
163
- for (let t = 16; t < 64; t++) {
164
- const w15 = w[t - 15];
165
- const w2 = w[t - 2];
166
- const s0 = rotr(w15, 7) ^ rotr(w15, 18) ^ w15 >>> 3;
167
- const s1 = rotr(w2, 17) ^ rotr(w2, 19) ^ w2 >>> 10;
168
- w[t] = w[t - 16] + s0 + w[t - 7] + s1 >>> 0;
169
- }
170
- let a = h[0];
171
- let b = h[1];
172
- let c = h[2];
173
- let d = h[3];
174
- let e = h[4];
175
- let f = h[5];
176
- let g = h[6];
177
- let hh = h[7];
178
- for (let t = 0; t < 64; t++) {
179
- const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
180
- const ch = e & f ^ ~e & g;
181
- const temp1 = hh + S1 + ch + K[t] + w[t] >>> 0;
182
- const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
183
- const maj = a & b ^ a & c ^ b & c;
184
- const temp2 = S0 + maj >>> 0;
185
- hh = g;
186
- g = f;
187
- f = e;
188
- e = d + temp1 >>> 0;
189
- d = c;
190
- c = b;
191
- b = a;
192
- a = temp1 + temp2 >>> 0;
193
- }
194
- h[0] = h[0] + a >>> 0;
195
- h[1] = h[1] + b >>> 0;
196
- h[2] = h[2] + c >>> 0;
197
- h[3] = h[3] + d >>> 0;
198
- h[4] = h[4] + e >>> 0;
199
- h[5] = h[5] + f >>> 0;
200
- h[6] = h[6] + g >>> 0;
201
- h[7] = h[7] + hh >>> 0;
202
- }
203
- const out = new Uint8Array(32);
204
- const odv = new DataView(out.buffer);
205
- for (let i = 0; i < 8; i++) odv.setUint32(i * 4, h[i]);
206
- return out;
207
- }
208
- function toHex(bytes) {
209
- let s = "";
210
- for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
211
- return s;
212
- }
213
- var enc = new TextEncoder();
214
- function sha256Hex(message) {
215
- return toHex(sha256Bytes(enc.encode(message)));
216
- }
217
-
218
54
  // package.json
219
55
  var package_default = {
220
56
  name: "@advenue/react-native",
221
- version: "0.9.0",
57
+ version: "1.0.0",
222
58
  description: "Advenue MMP React Native SDK \u2014 attribution, install tracking, and deep links (bundled iOS/Android Expo native modules)",
223
59
  type: "module",
224
60
  license: "MIT",
@@ -241,20 +77,20 @@ var package_default = {
241
77
  "ios",
242
78
  "android",
243
79
  "expo-module.config.json",
244
- "!**/*.test.ts"
80
+ "!**/*.test.ts",
81
+ "ios/vendor",
82
+ "android/src/main/kotlin"
245
83
  ],
246
84
  publishConfig: {
247
85
  access: "public"
248
86
  },
249
87
  scripts: {
250
- build: "tsup && node scripts/check-dist.mjs",
88
+ build: "node scripts/vendor-natives.mjs && node scripts/check-vendored-swift.mjs && tsup && node scripts/check-dist.mjs",
251
89
  typecheck: "tsc --noEmit",
252
- test: "vitest run"
253
- },
254
- dependencies: {
255
- "@advenue/install-referrer": "workspace:*",
256
- "@advenue/sdk-core": "workspace:*"
90
+ test: "vitest run --minWorkers=1 --maxWorkers=2 && node --test scripts/vendor-natives.test.mjs && node scripts/vendor-natives.mjs && node scripts/check-vendored-swift.mjs",
91
+ vendor: "node scripts/vendor-natives.mjs"
257
92
  },
93
+ dependencies: {},
258
94
  peerDependencies: {
259
95
  "@expo/config-plugins": ">=8",
260
96
  react: ">=18.2",
@@ -270,8 +106,6 @@ var package_default = {
270
106
  }
271
107
  },
272
108
  devDependencies: {
273
- "@advenue/shared": "workspace:*",
274
- "@advenue/signing": "workspace:*",
275
109
  tsup: "^8.5.1",
276
110
  typescript: "^5.7.2",
277
111
  vitest: "^2.1.8"
@@ -279,18 +113,15 @@ var package_default = {
279
113
  "react-native": "./dist/index.cjs"
280
114
  };
281
115
 
282
- // src/aem.ts
283
- function extractAemCampaignIds(alApplinkData) {
284
- try {
285
- const parsed = JSON.parse(alApplinkData);
286
- const value = typeof parsed.campaign_ids === "string" && parsed.campaign_ids ? parsed.campaign_ids : typeof parsed.extras?.campaign_ids === "string" && parsed.extras.campaign_ids ? parsed.extras.campaign_ids : null;
287
- return value && value.length <= 2048 ? value : null;
288
- } catch {
289
- return null;
290
- }
291
- }
292
-
293
116
  // src/deep-links.ts
117
+ var ALLOWED_QUERY_KEYS = /* @__PURE__ */ new Set([
118
+ "ref",
119
+ "campaign",
120
+ "network",
121
+ "influencer_id",
122
+ "influencerId",
123
+ "al_applink_data"
124
+ ]);
294
125
  function parseDirectLink(url) {
295
126
  let deepLinkValue = "";
296
127
  let params;
@@ -300,6 +131,7 @@ function parseDirectLink(url) {
300
131
  const isHttp = parsed.protocol === "http:" || parsed.protocol === "https:";
301
132
  deepLinkValue = isHttp ? path : [parsed.host, path].filter(Boolean).join("/");
302
133
  parsed.searchParams.forEach((v, k) => {
134
+ if (!ALLOWED_QUERY_KEYS.has(k)) return;
303
135
  params ??= {};
304
136
  params[k] = v;
305
137
  });
@@ -335,15 +167,6 @@ function setupDeepLinks(setup) {
335
167
  return { remove: () => listener.remove(), ready };
336
168
  }
337
169
 
338
- // src/mmkv-storage.ts
339
- function createMMKVStorage(mmkv) {
340
- return {
341
- getItem: (key) => mmkv.getString(key) ?? null,
342
- setItem: (key, value) => mmkv.set(key, value),
343
- removeItem: (key) => mmkv.delete(key)
344
- };
345
- }
346
-
347
170
  // src/native.ts
348
171
  var import_native_require = __toESM(require_native_require(), 1);
349
172
  function getIosNative() {
@@ -370,27 +193,6 @@ function getPlatformOS() {
370
193
  return null;
371
194
  }
372
195
  }
373
- function getOsVersion() {
374
- try {
375
- const rn = (0, import_native_require.requireReactNative)();
376
- if (!rn) return null;
377
- if (rn.Platform.OS === "android") {
378
- const release = rn.Platform.constants?.Release;
379
- return release != null ? String(release) : null;
380
- }
381
- return rn.Platform.Version != null ? String(rn.Platform.Version) : null;
382
- } catch {
383
- return null;
384
- }
385
- }
386
- function getAppState() {
387
- try {
388
- const rn = (0, import_native_require.requireReactNative)();
389
- return rn?.AppState ?? null;
390
- } catch {
391
- return null;
392
- }
393
- }
394
196
  function getLinking() {
395
197
  try {
396
198
  const rn = (0, import_native_require.requireReactNative)();
@@ -400,509 +202,208 @@ function getLinking() {
400
202
  }
401
203
  }
402
204
 
403
- // src/native-storage.ts
404
- function createNativeStorage(mod) {
405
- const m = mod;
406
- if (!m || typeof m.storageGetItem !== "function" || typeof m.storageSetItem !== "function" || typeof m.storageRemoveItem !== "function") {
407
- return null;
408
- }
409
- return {
410
- getItem: (key) => m.storageGetItem?.(key) ?? null,
411
- setItem: (key, value) => m.storageSetItem?.(key, value),
412
- removeItem: (key) => m.storageRemoveItem?.(key)
413
- };
414
- }
415
- function createNativeSecureStore(mod) {
416
- const m = mod;
417
- if (!m || typeof m.secureGetItem !== "function" || typeof m.secureSetItem !== "function" || typeof m.secureRemoveItem !== "function") {
418
- return null;
419
- }
420
- return {
421
- getItemAsync: async (key) => m.secureGetItem?.(key) ?? null,
422
- setItemAsync: async (key, value) => m.secureSetItem?.(key, value),
423
- deleteItemAsync: async (key) => m.secureRemoveItem?.(key)
424
- };
425
- }
426
-
427
- // src/secure-store.ts
428
- function createSecureStore(secureStore2) {
429
- return {
430
- getItemAsync: async (key) => await secureStore2.getItemAsync(key) ?? null,
431
- setItemAsync: (key, value) => secureStore2.setItemAsync(key, value),
432
- ...secureStore2.deleteItemAsync ? {
433
- deleteItemAsync: (key) => secureStore2.deleteItemAsync?.(key) ?? Promise.resolve()
434
- } : {}
435
- };
436
- }
437
-
438
205
  // src/index.ts
439
- async function resolveAdvertisingId() {
440
- const client = active();
441
- const consent = client.getConsentData();
442
- if (client.getRequireConsent() && consent == null) {
443
- client.setAdvertisingId({});
444
- return;
445
- }
446
- if (consent?.isUserSubjectToGDPR === true && consent.hasConsentForDataUsage !== true) {
447
- client.setAdvertisingId({});
448
- return;
449
- }
450
- const ios = getIosNative();
451
- if (ios) {
452
- const idfa = ios.getTrackingAuthorizationStatus() === "authorized" ? await ios.getAdvertisingId() : null;
453
- const vendorId = typeof ios.getIdentifierForVendor === "function" ? ios.getIdentifierForVendor() : null;
454
- client.setAdvertisingId({ ...idfa ? { idfa } : {}, ...vendorId ? { vendorId } : {} });
455
- return;
456
- }
457
- const android = getAndroidNative();
458
- if (android && typeof android.getAdvertisingId === "function") {
459
- const r = await android.getAdvertisingId();
460
- const vendorId = typeof android.getAppSetId === "function" ? await android.getAppSetId() : null;
461
- const adFields = r ? r.limitAdTracking ? { limitAdTracking: true } : { gaid: r.id } : {};
462
- const hasUsableGaid = !!r && !r.limitAdTracking;
463
- const rawAndroidId = !hasUsableGaid && typeof android.getAndroidId === "function" ? android.getAndroidId() : null;
464
- const androidId = rawAndroidId && /^[0-9a-fA-F]{8,32}$/.test(rawAndroidId) ? rawAndroidId : null;
465
- client.setAdvertisingId({
466
- ...adFields,
467
- ...vendorId ? { vendorId } : {},
468
- ...androidId ? { androidId } : {}
469
- });
470
- return;
471
- }
472
- client.setAdvertisingId({});
473
- }
474
- function consentEquals(a, b) {
475
- return a.isUserSubjectToGDPR === b.isUserSubjectToGDPR && a.hasConsentForDataUsage === b.hasConsentForDataUsage && a.hasConsentForAdsPersonalization === b.hasConsentForAdsPersonalization && a.hasConsentForAdStorage === b.hasConsentForAdStorage;
206
+ var IGNORED_OPTIONS = ["mmkv", "secureStore", "sdkConfigFetcher", "tcfDataCollection"];
207
+ var started = false;
208
+ var deepLinkSub = null;
209
+ var errorSub = null;
210
+ var onErrorHook;
211
+ var consentCache = false;
212
+ function bridge() {
213
+ return { ios: getIosNative(), android: getAndroidNative() };
476
214
  }
477
- function resolveDmaConsent() {
478
- if (manualConsentSet) return null;
479
- const native = getIosNative() ?? getAndroidNative();
480
- if (!native || typeof native.getTcfData !== "function") return null;
481
- let consent = null;
482
- try {
483
- consent = tcfToConsent(native.getTcfData());
484
- } catch (err) {
485
- reportError("consent.tcfRead", err);
486
- return null;
215
+ function call(name, ...args) {
216
+ const { ios, android } = bridge();
217
+ for (const mod of [ios, android]) {
218
+ const fn = mod?.[name];
219
+ if (typeof fn === "function") {
220
+ try {
221
+ return fn(...args);
222
+ } catch (error) {
223
+ report(`bridge.${name}`, error);
224
+ return void 0;
225
+ }
226
+ }
487
227
  }
488
- if (!consent) return null;
489
- const client = active();
490
- const current = client.getConsentData();
491
- if (current && consentEquals(current, consent)) return null;
492
- client.setConsentData(consent);
493
- void resolveAdvertisingId().catch((err) => reportError("enrich.advertisingId", err));
494
- return consent;
228
+ return void 0;
495
229
  }
496
- function readNativeDeviceInfo(natives) {
230
+ function report(context, cause) {
497
231
  try {
498
- if (natives.platform === "android" && natives.android?.getDeviceInfo) {
499
- return natives.android.getDeviceInfo();
500
- }
501
- if (natives.platform === "ios" && natives.ios?.getDeviceInfo) {
502
- return natives.ios.getDeviceInfo();
503
- }
232
+ onErrorHook?.(context, cause);
504
233
  } catch {
505
234
  }
506
- return {};
507
- }
508
- function collectDeviceInfo(natives) {
509
- const { shortVersion: _shortVersion, ...info } = readNativeDeviceInfo(natives);
510
- return info;
511
- }
512
- function applyAppState(client, status) {
513
- if (status === "active") {
514
- client.notifyAppActive();
515
- } else if (status === "background") {
516
- client.notifyAppBackground();
517
- }
518
- }
519
- var instance = null;
520
- var appStateSub = null;
521
- var deepLinkSub = null;
522
- var secureStore = null;
523
- var installFlagStore = null;
524
- var INSTALL_SENT_KEY = "advenue.install_sent";
525
- var installInFlight = false;
526
- var autoInstallPending = false;
527
- var autoInstallEnabled = true;
528
- var manualConsentSet = false;
529
- var tcfCollectionEnabled = false;
530
- var ATTEST_CHALLENGE_TIMEOUT_MS = 5e3;
531
- var configuredApiKey = null;
532
- var configuredEndpoint = DEFAULT_ENDPOINT;
533
- var aemSeenUrlHashes = /* @__PURE__ */ new Set();
534
- function active() {
535
- if (!instance) {
536
- throw new Error("Advenue.initialize() must be called before tracking events.");
537
- }
538
- return instance;
539
- }
540
- function reportError(context, cause) {
541
- instance?.report(context, cause);
542
- }
543
- function fireAutoInstall() {
544
- void trackInstall().catch((err) => reportError("install.auto", err));
545
- }
546
- function resolvePlatform(explicit) {
547
- if (explicit) {
548
- return explicit;
549
- }
550
- const os = getPlatformOS();
551
- if (os === "ios" || os === "android") {
552
- return os;
553
- }
554
- if (os) {
555
- return "web";
556
- }
557
- throw new Error(
558
- "Advenue.initialize(): platform could not be detected (react-native unavailable) \u2014 pass platform: 'ios' | 'android' | 'web'."
559
- );
560
235
  }
561
- function fireAutoInstallIfPending() {
562
- if (!autoInstallPending) {
563
- return;
564
- }
565
- autoInstallPending = false;
566
- fireAutoInstall();
236
+ function requireStarted() {
237
+ if (started) return true;
238
+ report("sdk.notInitialized", new Error("Advenue.initialize() has not been called"));
239
+ return false;
567
240
  }
568
241
  var Advenue = {
242
+ /**
243
+ * Starts the SDK. Safe to call from the app's entry point, and safe to call
244
+ * twice: the native side replaces its previous instance.
245
+ */
569
246
  async initialize(config) {
570
- const {
571
- mmkv,
572
- secureStore: secureMod,
573
- onDeepLink,
574
- autoTrackInstall,
575
- tcfDataCollection,
576
- ...rest
577
- } = config;
578
- autoInstallPending = false;
579
- manualConsentSet = false;
580
- tcfCollectionEnabled = tcfDataCollection === true;
581
- autoInstallEnabled = autoTrackInstall !== false;
582
- const platform = resolvePlatform(rest.platform);
583
- configuredApiKey = config.apiKey;
584
- configuredEndpoint = config.endpoint ?? DEFAULT_ENDPOINT;
585
- appStateSub?.remove();
586
- appStateSub = null;
587
- deepLinkSub?.remove();
588
- deepLinkSub = null;
589
- instance?.shutdown();
590
- const iosMod = getIosNative();
591
- const androidMod = getAndroidNative();
592
- const storage = mmkv ? createMMKVStorage(mmkv) : createNativeStorage(iosMod ?? androidMod) ?? new MemoryStorage();
593
- installFlagStore = storage;
594
- secureStore = secureMod ? createSecureStore(secureMod) : createNativeSecureStore(iosMod);
595
- const deviceId = rest.deviceId ?? await resolveDurableDeviceId(storage, secureStore ?? void 0);
596
- const osVersion = rest.osVersion ?? getOsVersion() ?? void 0;
597
- const nativeDeviceInfo = readNativeDeviceInfo({
598
- platform,
599
- ios: getIosNative(),
600
- android: getAndroidNative()
601
- });
602
- const { shortVersion, ...deviceInfo } = nativeDeviceInfo;
603
- const appVersion = rest.appVersion ?? shortVersion ?? void 0;
604
- instance = new AdvenueClient({
605
- ...rest,
606
- platform,
607
- deviceId,
608
- storage,
609
- ...osVersion ? { osVersion } : {},
610
- ...appVersion ? { appVersion } : {},
611
- // Stamped by the SDK, never by the host app — see AdvenueConfig.sdkVersion.
612
- sdkVersion: package_default.version
613
- });
614
- instance.debugLog(`SDK v${package_default.version} \u2014 events -> ${configuredEndpoint}`);
615
- if (tcfCollectionEnabled) resolveDmaConsent();
616
- void resolveAdvertisingId().catch((err) => reportError("enrich.advertisingId", err));
617
- if (Object.keys(deviceInfo).length > 0) instance.setDeviceInfo(deviceInfo);
618
- if (!config.disableAutoSessions) {
619
- const appState = getAppState();
620
- if (appState) {
621
- appStateSub?.remove();
622
- let seenBackground = false;
623
- const handler = (status) => {
624
- if (!instance) return;
625
- if (status === "background") {
626
- seenBackground = true;
627
- if (tcfCollectionEnabled) resolveDmaConsent();
628
- applyAppState(instance, status);
629
- } else if (status === "active") {
630
- if (!seenBackground) return;
631
- seenBackground = false;
632
- if (tcfCollectionEnabled) resolveDmaConsent();
633
- applyAppState(instance, status);
634
- void resolveAdvertisingId().catch((err) => reportError("enrich.advertisingId", err));
635
- }
636
- };
637
- appStateSub = appState.addEventListener("change", handler);
638
- instance.notifyAppActive();
639
- } else {
640
- instance.notifyAppActive();
247
+ onErrorHook = config.onError;
248
+ for (const option of IGNORED_OPTIONS) {
249
+ if (config[option] !== void 0) {
250
+ report(
251
+ `config.ignored:${option}`,
252
+ new Error(`${option} is decided by the native SDK and has no effect`)
253
+ );
641
254
  }
642
255
  }
643
- {
644
- const linking = getLinking();
645
- if (linking) {
646
- const client = instance;
647
- deepLinkSub = setupDeepLinks({
648
- getInitialURL: () => linking.getInitialURL(),
649
- addUrlListener: (handler) => linking.addEventListener("url", (e) => handler(e.url)),
650
- // Deferred deep link: server-side conversion poll (deterministic ids
651
- // where available, probabilistic otherwise).
652
- resolveDeferred: () => client.resolveDeferredDeepLink(),
653
- onDeepLink: onDeepLink ?? (() => {
654
- }),
655
- onDirectUrl: (url, link) => {
656
- const raw = link.params?.al_applink_data;
657
- if (typeof raw !== "string") return;
658
- const campaignIds = extractAemCampaignIds(raw);
659
- if (!campaignIds) return;
660
- const sourceUrlHash = sha256Hex(url);
661
- if (aemSeenUrlHashes.has(sourceUrlHash)) return;
662
- if (client.getRequireConsent() && !client.getTrackingConsent()) return;
663
- client.track("adv_meta_aem", { campaignIds, sourceUrlHash });
664
- aemSeenUrlHashes.add(sourceUrlHash);
665
- }
256
+ Advenue.shutdown();
257
+ call("bridgeInitialize", {
258
+ apiKey: config.apiKey,
259
+ endpoint: config.endpoint,
260
+ appVersion: config.appVersion,
261
+ requireConsent: config.requireConsent ?? false,
262
+ batchSize: config.batchSize,
263
+ flushIntervalMs: config.flushIntervalMs,
264
+ signingSecret: config.signingSecret,
265
+ fbAppId: config.fbAppId,
266
+ autoTrackInstall: config.autoTrackInstall !== false,
267
+ sdkVersion: package_default.version
268
+ });
269
+ started = true;
270
+ const { ios: iosForErrors, android: androidForErrors } = bridge();
271
+ const emitter = iosForErrors ?? androidForErrors;
272
+ if (typeof emitter?.addListener === "function") {
273
+ try {
274
+ errorSub = emitter.addListener("onAdvenueError", (event) => {
275
+ report(event.context, new Error(event.message));
666
276
  });
667
- deepLinkSub.ready.catch((err) => reportError("deepLink.resolve", err));
277
+ } catch (error) {
278
+ report("diagnostics.subscribe", error);
668
279
  }
669
280
  }
670
- if (autoTrackInstall !== false) {
671
- if (instance.getRequireConsent() && !instance.getTrackingConsent()) {
672
- autoInstallPending = true;
673
- instance.debugLog("install deferred until consent is granted");
674
- } else {
675
- fireAutoInstall();
281
+ consentCache = call("bridgeGetConsent") ?? false;
282
+ if (config.appInstanceIdProvider) {
283
+ try {
284
+ const id = await config.appInstanceIdProvider();
285
+ if (id) call("bridgeSetAppInstanceId", id);
286
+ } catch (error) {
287
+ report("enrich.appInstanceId", error);
676
288
  }
677
289
  }
678
- return instance;
290
+ const linking = getLinking();
291
+ if (linking) {
292
+ deepLinkSub = setupDeepLinks({
293
+ getInitialURL: () => linking.getInitialURL(),
294
+ addUrlListener: (handler) => linking.addEventListener("url", (e) => handler(e.url)),
295
+ resolveDeferred: () => Advenue.resolveDeferredDeepLink(),
296
+ onDeepLink: config.onDeepLink ?? (() => {
297
+ }),
298
+ onDirectUrl: (url) => {
299
+ call("bridgeProcessDeepLink", url);
300
+ }
301
+ });
302
+ deepLinkSub.ready.catch((error) => report("deepLink.resolve", error));
303
+ }
304
+ },
305
+ track(name, properties) {
306
+ if (!requireStarted()) return;
307
+ call("bridgeTrack", name, properties ?? null);
308
+ },
309
+ /** Adds exact local revenue to Apple's conversion-value state. iOS only. */
310
+ async recordSkanRevenue(input) {
311
+ if (!requireStarted()) return;
312
+ call("bridgeRecordSkanRevenue", input.amount, input.currency);
313
+ },
314
+ setAppInstanceId(id) {
315
+ if (!requireStarted()) return;
316
+ call("bridgeSetAppInstanceId", id);
317
+ },
318
+ /**
319
+ * Cross-device linking: associates subsequent events with your user id.
320
+ * Pass null to clear.
321
+ *
322
+ * New on this object. The previous release reached it through the client
323
+ * `initialize()` resolved to, and that client no longer exists — so it is
324
+ * promoted here rather than dropped, which is what an app following the
325
+ * documented cross-device recipe would otherwise hit at runtime.
326
+ */
327
+ setUserId(id) {
328
+ if (!requireStarted()) return;
329
+ call("bridgeSetUserId", id);
330
+ },
331
+ /**
332
+ * Registers the device's push token for uninstall measurement.
333
+ *
334
+ * Advenue never requests the notification permission and never displays
335
+ * anything: pass the token your push library already produced, on every
336
+ * launch and from its refresh listener. A stale token is the one thing that
337
+ * makes uninstall measurement report churn that did not happen.
338
+ */
339
+ setPushToken(token, provider) {
340
+ if (!requireStarted()) return;
341
+ call("bridgeSetPushToken", token, provider ?? null);
679
342
  },
680
- track: (name, properties, opts) => active().track(name, properties, opts),
681
343
  /**
682
- * Shows the iOS ATT prompt (resolves 'authorized' immediately on Android/web,
683
- * where ATT doesn't exist) and forwards the result to the consent gate.
344
+ * Shows the iOS ATT prompt. Where ATT does not exist (non-iOS, or the iOS
345
+ * module is absent) there is no prompt to show and no signal to read, so
346
+ * consent is left untouched and the call resolves 'unavailable'.
684
347
  */
685
348
  async requestTrackingAuthorization() {
686
- const ios = getIosNative();
687
- const status = ios ? await ios.requestTrackingAuthorization() : "authorized";
688
- active().setTrackingConsent(status === "authorized");
689
- void resolveAdvertisingId().catch((err) => reportError("enrich.advertisingId", err));
690
- if (status === "authorized") {
691
- fireAutoInstallIfPending();
692
- }
349
+ const { ios } = bridge();
350
+ if (!ios) return "unavailable";
351
+ const status = await ios.requestTrackingAuthorization();
352
+ Advenue.setTrackingConsent(status === "authorized");
693
353
  return status;
694
354
  },
695
355
  setTrackingConsent(granted) {
696
- active().setTrackingConsent(granted);
697
- if (granted) {
698
- fireAutoInstallIfPending();
699
- }
356
+ if (!requireStarted()) return;
357
+ consentCache = granted;
358
+ call("bridgeSetConsent", granted);
359
+ },
360
+ getTrackingConsent: () => consentCache,
361
+ setConsentData(consent) {
362
+ if (!requireStarted()) return;
363
+ call("bridgeSetConsentData", consent);
700
364
  },
701
- getTrackingConsent: () => active().getTrackingConsent(),
702
- /** GDPR/CCPA erasure: stop tracking and wipe local identifiers/queue. */
365
+ getConsentData: () => call("bridgeGetConsentData") ?? null,
366
+ /** GDPR/CCPA erasure: stops tracking and wipes local identifiers and queue. */
703
367
  forgetMe() {
704
- active().forgetMe();
705
- try {
706
- installFlagStore?.removeItem(INSTALL_SENT_KEY);
707
- } catch (err) {
708
- reportError("forget.wipe", err);
709
- }
710
- const secure = secureStore;
711
- if (secure?.deleteItemAsync) {
712
- for (const key of [DEVICE_ID_KEY, INSTALL_SENT_KEY]) {
713
- void secure.deleteItemAsync(key).catch((err) => reportError("forget.secureWipe", err));
714
- }
715
- }
368
+ if (!requireStarted()) return;
369
+ call("bridgeForgetMe");
370
+ consentCache = false;
716
371
  },
717
- setConsentData(consent) {
718
- manualConsentSet = true;
719
- active().setConsentData(consent);
720
- void resolveAdvertisingId().catch((err) => reportError("enrich.advertisingId", err));
372
+ flush() {
373
+ if (!requireStarted()) return;
374
+ call("bridgeFlush");
375
+ },
376
+ getDeviceId: () => Promise.resolve(
377
+ call("bridgeDeviceId") ?? null
378
+ ),
379
+ /** The Advenue ID — alias of `getDeviceId`. */
380
+ getAdvenueId: () => Advenue.getDeviceId(),
381
+ /** Which app the server resolved this API key to; null until a batch lands. */
382
+ getResolvedAppId: () => call("bridgeResolvedAppId") ?? null,
383
+ /**
384
+ * Resolves the deferred deep link for this install, or null for an organic
385
+ * one — which is most of them.
386
+ */
387
+ async resolveDeferredDeepLink() {
388
+ if (!requireStarted()) return null;
389
+ const result = call("bridgeResolveDeferredDeepLink");
390
+ return await result ?? null;
721
391
  },
722
- getConsentData: () => active().getConsentData(),
723
- flush: () => active().flush(),
724
- getDeviceId: () => active().getDeviceId(),
725
- /** The Advenue ID — alias of getDeviceId (see AdvenueClient.getAdvenueId). */
726
- getAdvenueId: () => active().getAdvenueId(),
727
- /** Which app the server resolved this API key to; null until a batch lands
728
- * (see AdvenueClient.getResolvedAppId). */
729
- getResolvedAppId: () => active().getResolvedAppId(),
730
392
  shutdown() {
731
- appStateSub?.remove();
732
- appStateSub = null;
733
393
  deepLinkSub?.remove();
734
394
  deepLinkSub = null;
735
- instance?.shutdown();
736
- instance = null;
737
- secureStore = null;
738
- installInFlight = false;
739
- autoInstallPending = false;
740
- autoInstallEnabled = true;
741
- manualConsentSet = false;
742
- tcfCollectionEnabled = false;
743
- configuredApiKey = null;
744
- configuredEndpoint = DEFAULT_ENDPOINT;
745
- aemSeenUrlHashes.clear();
395
+ errorSub?.remove();
396
+ errorSub = null;
397
+ if (started) call("bridgeShutdown");
398
+ started = false;
399
+ consentCache = false;
746
400
  }
747
401
  };
748
- async function trackInstall() {
749
- const client = active();
750
- if (client.getRequireConsent() && !client.getTrackingConsent()) {
751
- return;
752
- }
753
- let sent = installFlagStore?.getItem(INSTALL_SENT_KEY) === "1";
754
- if (!sent && secureStore) {
755
- try {
756
- sent = await secureStore.getItemAsync(INSTALL_SENT_KEY) === "1";
757
- } catch (err) {
758
- reportError("install.guardRead", err);
759
- }
760
- }
761
- if (sent) {
762
- client.debugLog("install skipped (already sent on this device)");
763
- return;
764
- }
765
- if (installInFlight) {
766
- return;
767
- }
768
- installInFlight = true;
769
- const opts = {};
770
- const props = {};
771
- const android = getAndroidNative();
772
- if (android) {
773
- try {
774
- const result = await android.getInstallReferrer();
775
- if (result) {
776
- const parsed = parseInstallReferrer(result.referrer);
777
- if (parsed.network) opts.network = parsed.network;
778
- if (parsed.campaign) opts.campaign = parsed.campaign;
779
- if (parsed.gclid) props.gclid = parsed.gclid;
780
- if (parsed.fbclid) props.fbclid = parsed.fbclid;
781
- Object.assign(props, extractReferrerProperties(result));
782
- }
783
- } catch (err) {
784
- reportError("enrich.installReferrer", err);
785
- }
786
- try {
787
- const meta = await android.getMetaInstallReferrer();
788
- const parsedMeta = meta ? parseMetaInstallReferrer(meta) : null;
789
- if (parsedMeta) {
790
- props.metaInstallReferrer = parsedMeta.raw;
791
- if (parsedMeta.encryptedData) props.metaReferrerData = parsedMeta.encryptedData;
792
- if (parsedMeta.nonce) props.metaReferrerNonce = parsedMeta.nonce;
793
- if (!opts.network && parsedMeta.isClickThrough) {
794
- opts.network = "meta";
795
- if (parsedMeta.campaign) opts.campaign = parsedMeta.campaign;
796
- }
797
- }
798
- } catch (err) {
799
- reportError("enrich.metaReferrer", err);
800
- }
801
- }
802
- const ios = getIosNative();
803
- if (ios) {
804
- try {
805
- ios.registerAppForAttribution();
806
- } catch (err) {
807
- reportError("enrich.skanRegister", err);
808
- }
809
- try {
810
- const asaToken = await ios.getAttributionToken();
811
- if (asaToken) {
812
- opts.adservicesToken = asaToken;
813
- }
814
- } catch (err) {
815
- reportError("enrich.adservicesToken", err);
816
- }
817
- }
818
- await resolveAdvertisingId();
819
- const trackOpts = { type: "install", ...opts };
820
- if (android && typeof android.getIntegrityToken === "function") {
821
- try {
822
- const deviceId = client.getDeviceId();
823
- const requestHash = sha256Hex(deviceId);
824
- const token = await android.getIntegrityToken(requestHash);
825
- if (token) {
826
- trackOpts.attestationToken = token;
827
- trackOpts.attestationType = "play-integrity";
828
- }
829
- } catch (err) {
830
- reportError("attest.playIntegrity", err);
831
- }
832
- }
833
- if (configuredApiKey && ios && typeof ios.attestKey === "function") {
834
- try {
835
- const deviceId = client.getDeviceId();
836
- const challengeUrl = `${configuredEndpoint}/v1/attest/challenge?deviceId=${encodeURIComponent(deviceId)}`;
837
- const ac = new AbortController();
838
- const timer = setTimeout(
839
- () => ac.abort(new Error("attest challenge timed out")),
840
- ATTEST_CHALLENGE_TIMEOUT_MS
841
- );
842
- let challengeRes;
843
- try {
844
- challengeRes = await fetch(challengeUrl, {
845
- headers: { "x-api-key": configuredApiKey },
846
- signal: ac.signal
847
- });
848
- } finally {
849
- clearTimeout(timer);
850
- }
851
- if (!challengeRes.ok) throw new Error(`challenge HTTP ${challengeRes.status}`);
852
- const { challenge } = await challengeRes.json();
853
- const { keyId, attestationObject } = await ios.attestKey(challenge);
854
- trackOpts.attestationToken = attestationObject;
855
- trackOpts.attestationType = "app-attest";
856
- trackOpts.attestationKeyId = keyId;
857
- trackOpts.attestationChallenge = challenge;
858
- } catch (err) {
859
- reportError("attest.appAttest", err);
860
- }
861
- }
862
- if (ios && typeof ios.getDeviceCheckToken === "function") {
863
- try {
864
- const token = await ios.getDeviceCheckToken();
865
- if (token) {
866
- trackOpts.deviceCheckToken = token;
867
- }
868
- } catch (err) {
869
- reportError("attest.deviceCheck", err);
870
- }
871
- }
872
- const pendingBefore = client.pendingCount;
873
- client.track("install", props, trackOpts);
874
- if (client.pendingCount === pendingBefore) {
875
- installInFlight = false;
876
- client.debugLog("install dropped (consent revoked mid-flight)");
877
- if (autoInstallEnabled && client.getRequireConsent() && !client.getTrackingConsent()) {
878
- autoInstallPending = true;
879
- }
880
- return;
881
- }
882
- client.debugLog("install fired");
883
- try {
884
- installFlagStore?.setItem(INSTALL_SENT_KEY, "1");
885
- } catch (err) {
886
- reportError("install.flagPersist", err);
887
- }
888
- if (secureStore) {
889
- try {
890
- await secureStore.setItemAsync(INSTALL_SENT_KEY, "1");
891
- } catch (err) {
892
- reportError("install.flagPersistSecure", err);
893
- }
894
- }
895
- }
402
+ var platform = getPlatformOS;
896
403
  export {
897
404
  Advenue,
898
- applyAppState,
899
- collectDeviceInfo,
900
- createMMKVStorage,
901
- createSecureStore,
902
405
  getAndroidNative,
903
406
  getIosNative,
904
407
  parseDirectLink,
905
- resolveAdvertisingId,
906
- resolveDmaConsent,
907
- trackInstall
408
+ platform
908
409
  };