@amplytools/react-native-amply-sdk 0.13.0 → 0.15.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 (45) hide show
  1. package/AmplyReactNative.podspec +1 -1
  2. package/README.md +47 -0
  3. package/android/build.gradle +1 -1
  4. package/android/src/main/java/tools/amply/sdk/reactnative/AmplyModule.kt +30 -0
  5. package/android/src/main/java/tools/amply/sdk/reactnative/core/AmplyClient.kt +13 -0
  6. package/android/src/main/java/tools/amply/sdk/reactnative/core/DefaultAmplyClient.kt +46 -0
  7. package/android/src/main/java/tools/amply/sdk/reactnative/model/AmplyInitializationOptions.kt +2 -0
  8. package/android/src/main/java/tools/amply/sdk/reactnative/model/CampaignTouchPayload.kt +12 -0
  9. package/android/src/newarch/java/tools/amply/sdk/reactnative/NativeAmplyModuleSpec.java +12 -0
  10. package/android/src/newarch/jni/AmplyReactNative-generated.cpp +18 -0
  11. package/dist/src/__tests__/appLanguage.test.d.ts +2 -0
  12. package/dist/src/__tests__/appLanguage.test.d.ts.map +1 -0
  13. package/dist/src/__tests__/appLanguage.test.js +211 -0
  14. package/dist/src/__tests__/handleUrl.test.d.ts +2 -0
  15. package/dist/src/__tests__/handleUrl.test.d.ts.map +1 -0
  16. package/dist/src/__tests__/handleUrl.test.js +114 -0
  17. package/dist/src/__tests__/lastCampaignTouch.test.d.ts +2 -0
  18. package/dist/src/__tests__/lastCampaignTouch.test.d.ts.map +1 -0
  19. package/dist/src/__tests__/lastCampaignTouch.test.js +119 -0
  20. package/dist/src/__tests__/systemEventUtils.test.js +16 -0
  21. package/dist/src/campaignTouch.d.ts +36 -0
  22. package/dist/src/campaignTouch.d.ts.map +1 -0
  23. package/dist/src/campaignTouch.js +39 -0
  24. package/dist/src/index.d.ts +50 -0
  25. package/dist/src/index.d.ts.map +1 -1
  26. package/dist/src/index.js +198 -1
  27. package/dist/src/nativeSpecs/NativeAmplyModule.d.ts +40 -0
  28. package/dist/src/nativeSpecs/NativeAmplyModule.d.ts.map +1 -1
  29. package/dist/src/systemEventUtils.d.ts.map +1 -1
  30. package/dist/src/systemEventUtils.js +3 -1
  31. package/dist/tsconfig.tsbuildinfo +1 -1
  32. package/docs/ARCHITECTURE.md +4 -0
  33. package/docs/DEVELOPMENT.md +2 -1
  34. package/ios/Sources/AmplyReactNative/AmplyModule.mm +81 -0
  35. package/ios/Sources/AmplyReactNative/AmplyReactNative/AmplyReactNative-generated.mm +21 -0
  36. package/ios/Sources/AmplyReactNative/AmplyReactNative/AmplyReactNative.h +11 -0
  37. package/package.json +1 -1
  38. package/src/__tests__/appLanguage.test.ts +298 -0
  39. package/src/__tests__/handleUrl.test.ts +155 -0
  40. package/src/__tests__/lastCampaignTouch.test.ts +151 -0
  41. package/src/__tests__/systemEventUtils.test.ts +22 -0
  42. package/src/campaignTouch.ts +74 -0
  43. package/src/index.ts +223 -1
  44. package/src/nativeSpecs/NativeAmplyModule.ts +41 -0
  45. package/src/systemEventUtils.ts +3 -1
@@ -42,6 +42,28 @@ describe('formatSystemEventLabel', () => {
42
42
  );
43
43
  });
44
44
 
45
+ it('names the campaign in CampaignShown when the SDK sends campaignName', () => {
46
+ const event = makeEvent('CampaignShown', {
47
+ campaignId: 'abc',
48
+ campaignName: 'Spring offer',
49
+ source: 'click',
50
+ });
51
+ expect(formatSystemEventLabel(event)).toBe(
52
+ 'Campaign shown "Spring offer" (abc) via click',
53
+ );
54
+ });
55
+
56
+ it('ignores an empty campaignName in CampaignShown', () => {
57
+ const event = makeEvent('CampaignShown', {
58
+ campaignId: 'abc',
59
+ campaignName: '',
60
+ source: 'click',
61
+ });
62
+ expect(formatSystemEventLabel(event)).toBe(
63
+ 'Campaign shown (abc) via click',
64
+ );
65
+ });
66
+
45
67
  it('formats EventTriggered with source event', () => {
46
68
  const event = makeEvent('EventTriggered', {sourceEvent: 'purchase'});
47
69
  expect(formatSystemEventLabel(event)).toBe('Event triggered (purchase)');
@@ -0,0 +1,74 @@
1
+ import type {CampaignTouchPayload} from './nativeSpecs/NativeAmplyModule';
2
+
3
+ /**
4
+ * - `'shown'`: the campaign was shown (`CampaignShown`).
5
+ * - `'engaged'`: the campaign resolved `Completed` (`CampaignResolved` with `result: 'Completed'`).
6
+ */
7
+ export type CampaignTouchKind = 'shown' | 'engaged';
8
+
9
+ /**
10
+ * The most recent moment a campaign reached the user, as answered by `getLastCampaignTouch`.
11
+ *
12
+ * Meant for your own analytics: attach `campaignId` / `campaignName` to a purchase (or any
13
+ * conversion) that happens shortly after a campaign, even when it did not start from the
14
+ * campaign's own link.
15
+ */
16
+ export type CampaignTouch = {
17
+ /**
18
+ * The id the SDK reports in `CampaignShown`. Inside an experiment that is the arm's own id —
19
+ * the same value `{@campaign.id}` resolves to, so it is also the right value for an explicit
20
+ * `amply_campaign_id` mark.
21
+ */
22
+ campaignId: string;
23
+ /** The campaign's name when the touch was recorded. Empty if the event carried no name. */
24
+ campaignName: string;
25
+ /** One touch per campaign: the newer of a show and a completion wins. */
26
+ kind: CampaignTouchKind;
27
+ /** When it happened, epoch milliseconds in the SDK's server-corrected clock. */
28
+ atMs: number;
29
+ };
30
+
31
+ /** Thrown (as a rejection) by `getLastCampaignTouch` for a window that is not a usable number. */
32
+ export function assertValidWithinMs(withinMs: unknown): asserts withinMs is number {
33
+ if (typeof withinMs !== 'number' || !Number.isFinite(withinMs) || withinMs < 0) {
34
+ throw new RangeError(
35
+ `[Amply] getLastCampaignTouch: withinMs must be a finite number >= 0, got ${String(withinMs)}`,
36
+ );
37
+ }
38
+ }
39
+
40
+ function toKind(raw: unknown): CampaignTouchKind | null {
41
+ if (typeof raw !== 'string') {
42
+ return null;
43
+ }
44
+ const lowered = raw.toLowerCase();
45
+ return lowered === 'shown' || lowered === 'engaged' ? lowered : null;
46
+ }
47
+
48
+ /**
49
+ * Narrows what the native bridge resolved to the public type. Anything it cannot read as a
50
+ * touch becomes null with a warning: the caller asked "was there a campaign", and a payload this
51
+ * bridge does not understand is not one it can vouch for.
52
+ */
53
+ export function toCampaignTouch(payload: CampaignTouchPayload | null | undefined): CampaignTouch | null {
54
+ if (payload == null) {
55
+ return null;
56
+ }
57
+ const kind = toKind(payload.kind);
58
+ const isReadable =
59
+ kind !== null &&
60
+ typeof payload.campaignId === 'string' &&
61
+ payload.campaignId.length > 0 &&
62
+ typeof payload.atMs === 'number' &&
63
+ Number.isFinite(payload.atMs);
64
+ if (!isReadable) {
65
+ console.warn('[Amply] getLastCampaignTouch: ignoring an unreadable native payload', payload);
66
+ return null;
67
+ }
68
+ return {
69
+ campaignId: payload.campaignId,
70
+ campaignName: typeof payload.campaignName === 'string' ? payload.campaignName : '',
71
+ kind,
72
+ atMs: payload.atMs,
73
+ };
74
+ }
package/src/index.ts CHANGED
@@ -3,6 +3,9 @@ import {addSystemEventListenerRaw, addSystemEventListener as addSystemEventListe
3
3
  export {useAmplySystemEvents} from './hooks/useAmplySystemEvents';
4
4
  export {formatSystemEventLabel} from './systemEventUtils';
5
5
  export type {FormatOptions} from './systemEventUtils';
6
+ import {assertValidWithinMs, toCampaignTouch} from './campaignTouch';
7
+ import type {CampaignTouch} from './campaignTouch';
8
+ export type {CampaignTouch, CampaignTouchKind} from './campaignTouch';
6
9
  import type {
7
10
  CampaignResult,
8
11
  GateDecision,
@@ -232,11 +235,198 @@ export async function initialize(config: AmplyInitializationConfig): Promise<voi
232
235
  if (config.debug || config.logLevel) {
233
236
  ensureDebugLogListener();
234
237
  }
235
- await getNativeModule().initialize(config);
238
+ // Taken now, synchronously: a call made after this point is later than the config and must
239
+ // stay parked so it is applied after it.
240
+ const parked = takeParkedAppLanguage();
241
+ try {
242
+ await getNativeModule().initialize(withParkedAppLanguage(config, parked));
243
+ } catch (error) {
244
+ // A debug link parked for a failed start has nothing to open; replaying it later would
245
+ // surprise a retry that the user did not scan for.
246
+ parkedDebugUrl = null;
247
+ // Nothing reached the SDK, so the call still has to — unless a newer one replaced it.
248
+ if (parkedAppLanguage == null && isLatestLanguageWrite(parked)) {
249
+ parkedAppLanguage = parked;
250
+ }
251
+ throw error;
252
+ }
253
+ // A parked clear cannot travel in the config, where null means "leave it alone". Replayed only
254
+ // if nothing newer came in while initialize was in flight: the native SDK reports itself up
255
+ // before this promise settles, and a call made in that window has already reached it.
256
+ if (parked?.tag === null && !hasText(config.appLanguage) && isLatestLanguageWrite(parked)) {
257
+ getNativeModule().setAppLanguage(null);
258
+ }
259
+ flushParkedAppLanguage();
260
+ flushParkedDebugUrl();
236
261
  // Anything the host registered before this point was parked rather than lost.
237
262
  replayPendingRegistrations();
238
263
  }
239
264
 
265
+ /**
266
+ * A {@link setAppLanguage} call made before the SDK was up. Boxed so that a parked `null` — a
267
+ * request to return to automatic detection — is distinguishable from nothing parked.
268
+ *
269
+ * The native bridges buffer such calls too, but replay them AFTER building the SDK, which applies
270
+ * the config's `appLanguage` first. An earlier call would then overwrite a later config value,
271
+ * the opposite of "last write wins". Parking it here lets {@link initialize} put the two in the
272
+ * order they were made.
273
+ */
274
+ let parkedAppLanguage: LanguageWrite | null = null;
275
+
276
+ /**
277
+ * One {@link setAppLanguage} call. `seq` orders it against every other call, forwarded or held:
278
+ * a held value is applied only while it is still the latest write, so one taken before
279
+ * initialize cannot be replayed over a call the native SDK received while initialize was in
280
+ * flight.
281
+ */
282
+ interface LanguageWrite {
283
+ readonly tag: string | null;
284
+ readonly seq: number;
285
+ }
286
+
287
+ /** Bumped by every {@link setAppLanguage} call, whether it is forwarded or held. */
288
+ let languageWriteSeq = 0;
289
+
290
+ function isLatestLanguageWrite(write: LanguageWrite | null): write is LanguageWrite {
291
+ return write != null && write.seq === languageWriteSeq;
292
+ }
293
+
294
+ function hasText(value: string | null | undefined): value is string {
295
+ return typeof value === 'string' && value.trim().length > 0;
296
+ }
297
+
298
+ function takeParkedAppLanguage(): LanguageWrite | null {
299
+ const parked = parkedAppLanguage;
300
+ parkedAppLanguage = null;
301
+ return parked;
302
+ }
303
+
304
+ /** The config's own appLanguage wins: initialize was called after the parked call. */
305
+ function withParkedAppLanguage(
306
+ config: AmplyInitializationConfig,
307
+ parked: LanguageWrite | null,
308
+ ): AmplyInitializationConfig {
309
+ if (hasText(config.appLanguage) || parked == null || parked.tag === null) {
310
+ return config;
311
+ }
312
+ return {...config, appLanguage: parked.tag};
313
+ }
314
+
315
+ function flushParkedAppLanguage(): void {
316
+ const parked = takeParkedAppLanguage();
317
+ if (isLatestLanguageWrite(parked)) {
318
+ getNativeModule().setAppLanguage(parked.tag);
319
+ }
320
+ }
321
+
322
+ /**
323
+ * Tell Amply the language your app's UI is in, so sheets, stories and mini-apps show in the
324
+ * matching language and campaigns can target it. Use this when the app chooses its language
325
+ * itself (an in-app language picker, i18next, …) rather than following the device.
326
+ *
327
+ * Any common tag format works — `'pt_BR'`, `'pt-BR'`, `'zh-TW'`, `'fr'`, any case. A value that
328
+ * is not a language tag is ignored by the SDK with a warning log. The value is persisted across
329
+ * launches; pass `null` to return to automatic detection. The device language is never changed.
330
+ *
331
+ * Safe to call before {@link initialize}: the value is held and applied at initialization, and
332
+ * an `appLanguage` passed to a later `initialize` call wins over it.
333
+ * @param tag The language tag, or null to clear
334
+ */
335
+ export function setAppLanguage(tag: string | null): void {
336
+ languageWriteSeq += 1;
337
+ if (isSdkUp()) {
338
+ getNativeModule().setAppLanguage(tag);
339
+ return;
340
+ }
341
+ parkedAppLanguage = {tag, seq: languageWriteSeq};
342
+ }
343
+
344
+ /** A debug link that arrived before the SDK was up. At most one: a newer link replaces it. */
345
+ let parkedDebugUrl: string | null = null;
346
+
347
+ const URL_SCHEME_PREFIX = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//;
348
+ const DEBUG_LINK_HOST = 'amply-debug';
349
+ const DEBUG_LINK_PATH = '/campaign';
350
+ const DEBUG_LINK_TOKEN_PARAM = 't';
351
+
352
+ /**
353
+ * True for `<any scheme>://amply-debug/campaign?t=<non-empty>`. Parsed by hand, without decoding,
354
+ * so a malformed string is just "not a debug link" and can never throw.
355
+ */
356
+ function isDebugLink(url: string): boolean {
357
+ const scheme = URL_SCHEME_PREFIX.exec(url);
358
+ if (scheme == null) {
359
+ return false;
360
+ }
361
+ const rest = url.slice(scheme[0].length).split('#')[0];
362
+ const queryStart = rest.indexOf('?');
363
+ if (queryStart < 0) {
364
+ return false;
365
+ }
366
+ const target = rest.slice(0, queryStart);
367
+ const slash = target.indexOf('/');
368
+ if (slash < 0 || target.slice(0, slash) !== DEBUG_LINK_HOST) {
369
+ return false;
370
+ }
371
+ if (target.slice(slash).replace(/\/+$/, '') !== DEBUG_LINK_PATH) {
372
+ return false;
373
+ }
374
+ return rest
375
+ .slice(queryStart + 1)
376
+ .split('&')
377
+ .some(pair => {
378
+ const eq = pair.indexOf('=');
379
+ return eq > 0 && pair.slice(0, eq) === DEBUG_LINK_TOKEN_PARAM && eq < pair.length - 1;
380
+ });
381
+ }
382
+
383
+ function flushParkedDebugUrl(): void {
384
+ const url = parkedDebugUrl;
385
+ parkedDebugUrl = null;
386
+ if (url == null) {
387
+ return;
388
+ }
389
+ try {
390
+ getNativeModule().handleUrl?.(url);
391
+ } catch (error) {
392
+ console.warn('[Amply] Failed to replay a debug link parked until initialize', error);
393
+ }
394
+ }
395
+
396
+ /**
397
+ * Hand an incoming URL to Amply. Call it for every link your app is opened with — cold start
398
+ * and while running — before your own routing; when it returns `true` Amply recognised the
399
+ * link as its own and took it over, so your app should not route it.
400
+ *
401
+ * Safe to call before {@link initialize}, which is how a cold-start link arrives: an Amply debug
402
+ * link is held (the newest one) and opened once initialization succeeds, and `true` is returned.
403
+ *
404
+ * Synchronous. Returns `false` for any other URL, for a non-string, and when the installed
405
+ * native SDK predates this method; it never throws.
406
+ * @param url The full incoming URL
407
+ */
408
+ export function handleUrl(url: string): boolean {
409
+ if (typeof url !== 'string') {
410
+ return false;
411
+ }
412
+ try {
413
+ if (!isSdkUp()) {
414
+ if (!isDebugLink(url)) {
415
+ return false;
416
+ }
417
+ parkedDebugUrl = url;
418
+ return true;
419
+ }
420
+ const nativeModule = getNativeModule();
421
+ if (typeof nativeModule.handleUrl !== 'function') {
422
+ return false;
423
+ }
424
+ return nativeModule.handleUrl(url) === true;
425
+ } catch {
426
+ return false;
427
+ }
428
+ }
429
+
240
430
  /**
241
431
  * Set the user ID for analytics. Pass null to clear.
242
432
  * @param userId The user ID to set, or null to clear
@@ -515,6 +705,35 @@ export async function getRecentEvents(limit: number): Promise<EventRecord[]> {
515
705
  return getNativeModule().getRecentEvents(limit);
516
706
  }
517
707
 
708
+ /**
709
+ * The campaign the user was most recently touched by — shown, or completed — at most `withinMs`
710
+ * ago, or `null` if there was none.
711
+ *
712
+ * Use it to attribute a purchase (or any conversion) in your own analytics to the campaign that
713
+ * preceded it, including one made from somewhere other than the campaign's link:
714
+ *
715
+ * ```ts
716
+ * const touch = await Amply.getLastCampaignTouch(30 * 60 * 1000);
717
+ * analytics.track('Purchase', {sku, amply_campaign_id: touch?.campaignId});
718
+ * ```
719
+ *
720
+ * One touch per campaign, the newer of a show and a completion. `withinMs` is inclusive and
721
+ * capped at 30 days by the SDK. Resolves `null` before {@link initialize}, while the SDK's storage
722
+ * is off, and if the native call fails — it rejects only for a `withinMs` that is not a finite
723
+ * number >= 0, which is a bug at the call site.
724
+ */
725
+ export async function getLastCampaignTouch(withinMs: number): Promise<CampaignTouch | null> {
726
+ assertValidWithinMs(withinMs);
727
+ try {
728
+ return toCampaignTouch(await getNativeModule().getLastCampaignTouch(withinMs));
729
+ } catch (error) {
730
+ // The SDK answers null for every state it can be in; a rejection here is the bridge itself
731
+ // failing, and an analytics lookup must never break the purchase flow that asked.
732
+ console.warn('[Amply] getLastCampaignTouch failed; resolving null', error);
733
+ return null;
734
+ }
735
+ }
736
+
518
737
  export async function getDataSetSnapshot(type: DataSetType): Promise<DataSetSnapshot> {
519
738
  return getNativeModule().getDataSetSnapshot(type);
520
739
  }
@@ -636,12 +855,15 @@ export default {
636
855
  trackGated,
637
856
  registerGate,
638
857
  getRecentEvents,
858
+ getLastCampaignTouch,
639
859
  getDataSetSnapshot,
640
860
  addDeepLinkListener,
641
861
  addSystemEventListener,
642
862
  addSystemEventsListener,
643
863
  removeAllListeners,
644
864
  setUserId,
865
+ setAppLanguage,
866
+ handleUrl,
645
867
  setLogLevel,
646
868
  getLogLevel,
647
869
  setCustomProperty,
@@ -46,6 +46,12 @@ export type AmplyInitializationConfig = {
46
46
  * Takes precedence over `debug` if both are specified.
47
47
  */
48
48
  logLevel?: LogLevel | null;
49
+ /**
50
+ * The language the app's UI is in, in any common format (`'pt_BR'`, `'zh-TW'`, `'fr'`).
51
+ * The same as calling `setAppLanguage` right after initialization, and persisted the same
52
+ * way. Omitted, null or blank leaves the current setting alone.
53
+ */
54
+ appLanguage?: string | null;
49
55
  };
50
56
 
51
57
  export type EventType = 'custom' | 'system';
@@ -63,8 +69,24 @@ export type EventRecord = {
63
69
  properties: JsonMap;
64
70
  };
65
71
 
72
+ /**
73
+ * A system event from the SDK. `CampaignShown` and `CampaignResolved` carry `campaignId` and,
74
+ * from SDK 0.15.0, `campaignName` in `properties`.
75
+ */
66
76
  export type SystemEventPayload = EventRecord;
67
77
 
78
+ /**
79
+ * Wire shape of a campaign touch as the native bridges send it. `kind` is `'shown'` or
80
+ * `'engaged'`; the public `CampaignTouch` type narrows it. Kept a plain string here so the
81
+ * codegen contract does not change if the SDK ever adds a kind.
82
+ */
83
+ export type CampaignTouchPayload = {
84
+ campaignId: string;
85
+ campaignName: string;
86
+ kind: string;
87
+ atMs: number;
88
+ };
89
+
68
90
  export type TriggeredEventCountStrategy = 'global' | 'session';
69
91
 
70
92
  export type TriggeredEventParam = {
@@ -195,6 +217,12 @@ export interface Spec extends TurboModule {
195
217
  */
196
218
  unregisterGate(baseUrl: string): void;
197
219
  getRecentEvents(limit: number): Promise<EventRecord[]>;
220
+ /**
221
+ * The campaign the user was most recently touched by (shown, or completed) at most `withinMs`
222
+ * ago, or null. Never rejects for "not initialised" — that resolves null, as in the SDK.
223
+ * `withinMs` is clamped natively to [0, 30 days].
224
+ */
225
+ getLastCampaignTouch(withinMs: number): Promise<CampaignTouchPayload | null>;
198
226
  getDataSetSnapshot(type: DataSetType): Promise<DataSetSnapshot>;
199
227
  registerDeepLinkListener(): void;
200
228
  /**
@@ -202,6 +230,19 @@ export interface Spec extends TurboModule {
202
230
  * @param userId The user ID to set, or null to clear
203
231
  */
204
232
  setUserId(userId: string | null): void;
233
+ /**
234
+ * Set the language the app's UI is in. Any common tag format; null returns to automatic
235
+ * detection. Persisted by the SDK across launches.
236
+ * @param tag The language tag, or null to clear
237
+ */
238
+ setAppLanguage(tag: string | null): void;
239
+ /**
240
+ * Hand an incoming URL to the SDK. Returns true when the SDK recognised it as its own
241
+ * (a test-launch link) and took it over; false for any other URL, or when the SDK is not
242
+ * initialized.
243
+ * @param url The full incoming URL
244
+ */
245
+ handleUrl(url: string): boolean;
205
246
  /**
206
247
  * Set the log level at runtime.
207
248
  * @param level The log level to set
@@ -27,8 +27,10 @@ export function formatSystemEventLabel(
27
27
  }
28
28
  if (event.name === 'CampaignShown') {
29
29
  const campaignId = event.properties.campaignId as string | undefined;
30
+ // Sent by SDK 0.15.0 and later (on CampaignShown and CampaignResolved alike).
31
+ const campaignName = event.properties.campaignName as string | undefined;
30
32
  const source = event.properties.source as string | undefined;
31
- return `Campaign shown${campaignId ? ` (${campaignId})` : ''}${
33
+ return `Campaign shown${campaignName ? ` "${campaignName}"` : ''}${campaignId ? ` (${campaignId})` : ''}${
32
34
  source ? ` via ${source}` : ''
33
35
  }`;
34
36
  }