react-native-genius-sdk 1.0.11 → 1.2.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 (65) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +130 -107
  3. package/android/build.gradle +3 -5
  4. package/android/gradle.properties +3 -3
  5. package/android/src/main/java/com/geniussdk/GeniusSdkModule.kt +66 -125
  6. package/android/src/main/java/com/geniussdk/JsValues.kt +19 -0
  7. package/ios/GeniusSdk.mm +17 -12
  8. package/ios/GeniusSdk.swift +65 -69
  9. package/lib/commonjs/bridgeValue.js +20 -0
  10. package/lib/commonjs/bridgeValue.js.map +1 -0
  11. package/lib/commonjs/dynamicLink.js +28 -0
  12. package/lib/commonjs/dynamicLink.js.map +1 -0
  13. package/lib/commonjs/events.js +33 -0
  14. package/lib/commonjs/events.js.map +1 -0
  15. package/lib/commonjs/index.js +84 -136
  16. package/lib/commonjs/index.js.map +1 -1
  17. package/lib/commonjs/native.js +17 -0
  18. package/lib/commonjs/native.js.map +1 -0
  19. package/lib/commonjs/queryString.js +29 -0
  20. package/lib/commonjs/queryString.js.map +1 -0
  21. package/lib/module/bridgeValue.js +15 -0
  22. package/lib/module/bridgeValue.js.map +1 -0
  23. package/lib/module/dynamicLink.js +24 -0
  24. package/lib/module/dynamicLink.js.map +1 -0
  25. package/lib/module/events.js +28 -0
  26. package/lib/module/events.js.map +1 -0
  27. package/lib/module/index.js +66 -135
  28. package/lib/module/index.js.map +1 -1
  29. package/lib/module/native.js +13 -0
  30. package/lib/module/native.js.map +1 -0
  31. package/lib/module/queryString.js +24 -0
  32. package/lib/module/queryString.js.map +1 -0
  33. package/lib/typescript/commonjs/src/bridgeValue.d.ts +3 -0
  34. package/lib/typescript/commonjs/src/bridgeValue.d.ts.map +1 -0
  35. package/lib/typescript/commonjs/src/dynamicLink.d.ts +2 -0
  36. package/lib/typescript/commonjs/src/dynamicLink.d.ts.map +1 -0
  37. package/lib/typescript/commonjs/src/events.d.ts +21 -0
  38. package/lib/typescript/commonjs/src/events.d.ts.map +1 -0
  39. package/lib/typescript/commonjs/src/index.d.ts +29 -50
  40. package/lib/typescript/commonjs/src/index.d.ts.map +1 -1
  41. package/lib/typescript/commonjs/src/native.d.ts +20 -0
  42. package/lib/typescript/commonjs/src/native.d.ts.map +1 -0
  43. package/lib/typescript/commonjs/src/queryString.d.ts +3 -0
  44. package/lib/typescript/commonjs/src/queryString.d.ts.map +1 -0
  45. package/lib/typescript/module/src/bridgeValue.d.ts +3 -0
  46. package/lib/typescript/module/src/bridgeValue.d.ts.map +1 -0
  47. package/lib/typescript/module/src/dynamicLink.d.ts +2 -0
  48. package/lib/typescript/module/src/dynamicLink.d.ts.map +1 -0
  49. package/lib/typescript/module/src/events.d.ts +21 -0
  50. package/lib/typescript/module/src/events.d.ts.map +1 -0
  51. package/lib/typescript/module/src/index.d.ts +29 -50
  52. package/lib/typescript/module/src/index.d.ts.map +1 -1
  53. package/lib/typescript/module/src/native.d.ts +20 -0
  54. package/lib/typescript/module/src/native.d.ts.map +1 -0
  55. package/lib/typescript/module/src/queryString.d.ts +3 -0
  56. package/lib/typescript/module/src/queryString.d.ts.map +1 -0
  57. package/package.json +6 -8
  58. package/react-native-genius-sdk.podspec +3 -7
  59. package/src/bridgeValue.ts +16 -0
  60. package/src/dynamicLink.ts +43 -0
  61. package/src/events.ts +32 -0
  62. package/src/index.tsx +85 -174
  63. package/src/native.ts +32 -0
  64. package/src/queryString.ts +35 -0
  65. package/ios/GeniusSdk-Bridging-Header.h +0 -2
package/CHANGELOG.md ADDED
@@ -0,0 +1,22 @@
1
+ ## 1.2.0
2
+
3
+ - `setCustomerUserId(id)` and `setPushToken(token)`. Over the 1.2.0 native SDKs, events also carry event ids,
4
+ timezone, the Meta install referrer (Android) and the Apple Search Ads token (iOS).
5
+ - Android: the Meta install referrer is collected only when the app declares its Facebook App ID (see the README).
6
+ - 1.1.0 was not published to npm: when upgrading from 1.0.x, read 1.1.0 as well.
7
+
8
+ ## 1.1.0
9
+
10
+ - Thin bridge over the 1.1.0 native Genius SDKs. Adds `stop(isStopped)` / `isStopped()`, `setDebugLogging`,
11
+ `setMinTimeBetweenSessions`, `setCollectAndroidId`, `setRequestsTrackingAuthorization`, `setReadsPasteboard` and
12
+ `EVENT_PARAM`.
13
+ - Upgrading from 1.0.x:
14
+ - The `@react-native-async-storage/async-storage`, `react-native-device-info` and `react-native-url-polyfill`
15
+ dependencies are removed: apps that use them must list them in their own dependencies.
16
+ - Android apps must compile against SDK 33 or later.
17
+ - `buildDynamicLink` form-encodes keys and values and sorts keys: callers that pre-encoded values must stop.
18
+ - On the install launch (unless stopped), `dynamicLinkInit` delivers the install attribution and then, if a link
19
+ opened the app, that link's parameters.
20
+ - `onLink` keeps a single subscription: a new call replaces the previous callback.
21
+ - `session` events are logged after 5 seconds in the background (`setMinTimeBetweenSessions(0)` disables them),
22
+ and `event_time` is sent in UTC.
package/README.md CHANGED
@@ -1,146 +1,169 @@
1
1
  # react-native-genius-sdk
2
2
 
3
- A react native package for GeniusSDK
3
+ React Native wrapper for the Genius attribution SDK. It bridges the native SDKs (Android
4
+ [`GeniusSDK`](https://github.com/socal-ltd/GeniusSDK), Apple
5
+ [`GeniusSDKFramework`](https://github.com/socal-ltd/GeniusSDKFramework)) and adds deep-link handling on top of
6
+ React Native's `Linking`.
4
7
 
5
- # Installation
8
+ Supports Android 5.0+ (API 21), iOS 13+, tvOS 14+ and macOS 12+.
9
+
10
+ ## Installation
6
11
 
7
12
  ```sh
8
13
  npm install react-native-genius-sdk
14
+ cd ios && pod install
9
15
  ```
10
16
 
11
- # Configuration
12
-
13
- ## Android:
17
+ ### Android
14
18
 
15
- First of all go to your android folder and in there go to your project's build.gradle and in the repositories block add:
19
+ The native SDK (`com.github.socal-ltd:GeniusSDK:1.2.0`) is served by JitPack. React Native 0.71+ adds the
20
+ JitPack repository for you; on older setups add it to the app's repositories:
16
21
 
17
- ```js
18
- maven {
19
- url=uri("https://jitpack.io")
20
- }
22
+ ```groovy
23
+ maven { url "https://www.jitpack.io" }
21
24
  ```
22
25
 
23
- For deep links to be configured you need to first associate your website domain with your app and then add an intent filter in the app's AndroidManifest.xml:
26
+ The app must compile against Android SDK 33 or later (required by the native SDK's AndroidX Lifecycle 2.6).
27
+
28
+ For deep links, add an intent filter to the activity that hosts React Native (keep `launchMode="singleTask"`):
24
29
 
25
30
  ```xml
26
- <intent-filter android:autoVerify="true" >
27
- <data android:host="your-apps-domain"
28
- android:scheme="https" />
31
+ <intent-filter android:autoVerify="true">
32
+ <action android:name="android.intent.action.VIEW" />
29
33
  <category android:name="android.intent.category.DEFAULT" />
30
34
  <category android:name="android.intent.category.BROWSABLE" />
31
- <action android:name="android.intent.action.VIEW" />
35
+ <data android:scheme="https" android:host="your-apps-domain" />
32
36
  </intent-filter>
33
37
  ```
34
38
 
35
- (For development)
36
- To add local GeniusSDK add to build.gradle
37
-
38
- ```groovy
39
- implementation(project(":GeniusSDK"))
40
- ```
41
-
42
- and to the example project's settings.gradle:
43
- ```groovy
44
- include ':GeniusSDK'
45
- project(':GeniusSDK').projectDir = new File('Path-To -> .../Projects/GeniusSDK/Android/TestProjectAndroid/GeniusSDK')
46
- ```
47
-
39
+ For the Meta install referrer, declare the app's Facebook App ID inside `<application>`; apps that use the
40
+ Facebook SDK already do. Reference a string resource: Android stores a bare numeric value as a number, which
41
+ the SDK does not read. Without the ID, the Meta referrer is not collected.
48
42
 
49
- ## iOS:
50
- (For development)
51
- To add local GeniusSDKFramework add to react-native-genius-sdk.podspec:
52
-
53
- ```ruby
54
- s.dependency 'GeniusSDKFramework'
55
- ```
56
-
57
- and to example project's Podfile:
58
-
59
- ```ruby
60
- pod 'GeniusSDKFramework', :path => '../../../IOS/GeniusSDKFrameworkPod'
43
+ ```xml
44
+ <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id" />
61
45
  ```
62
46
 
63
- # Usage
64
-
65
- To only use the install attribution and data extraction, add the following in App.tsx:
47
+ ### iOS
66
48
 
67
- ```js
68
- import geniusSdk from 'react-native-genius-sdk';
69
- import React, { useEffect, useRef } from 'react';
49
+ The pod depends on `GeniusSDKFramework` 1.2.0.
70
50
 
71
- // ...
51
+ - Add `NSUserTrackingUsageDescription` to `Info.plist` if the App Tracking Transparency prompt should be shown;
52
+ without it the prompt is skipped.
53
+ - For deep links, forward opened URLs to `RCTLinkingManager` in the `AppDelegate`, as described in
54
+ React Native's [Linking guide](https://reactnative.dev/docs/linking#enabling-deep-links).
55
+ - Sandboxed macOS apps need the `com.apple.security.network.client` entitlement.
72
56
 
73
- const initialData = useRef<{ [key: string]: any }>({});
74
- useEffect(() => {
75
- const initializeSdk = async () => {
76
- initialData.current = await geniusSdk.connect();
77
- };
57
+ ## Usage
78
58
 
79
- initializeSdk();
80
- }, []);
81
- ```
59
+ ```tsx
60
+ import { useEffect } from 'react';
61
+ import geniusSdk, { EVENT_NAME, EVENT_PARAM } from 'react-native-genius-sdk';
82
62
 
83
- To use dynamic links aswell, add the following:
63
+ useEffect(() => {
64
+ // Optional, before connect(): turn off what the app doesn't want.
65
+ // geniusSdk.setReadsPasteboard(false);
66
+ // geniusSdk.setRequestsTrackingAuthorization(false);
84
67
 
85
- ```js
86
- import geniusSdk from 'react-native-genius-sdk';
87
- import React, { useEffect, useRef } from 'react';
68
+ geniusSdk.connect().then((launch) => {
69
+ // The launch payload (install or open), or {}.
70
+ });
88
71
 
89
- // ...
72
+ // On the install launch (unless stopped), the install attribution, then the opening link's
73
+ // parameters if any; otherwise the opening link's parameters. Then those of every later link.
74
+ geniusSdk.dynamicLinkInit((data) => {
75
+ // navigate with data
76
+ });
77
+ }, []);
90
78
 
91
- const initialData = useRef<{ [key: string]: any }>({});
92
- useEffect(() => {
93
- const initializeSdk = async () => {
94
- initialData.current = await geniusSdk.connect();
79
+ // Resolves once the event is saved; it is sent in the background, with retries.
80
+ geniusSdk.logEvent(EVENT_NAME.DEPOSIT, {
81
+ [EVENT_PARAM.REVENUE]: 9.99,
82
+ [EVENT_PARAM.CURRENCY]: 'USD',
83
+ });
95
84
 
96
- await geniusSdk.dynamicLinkInit((data) => {
97
- console.log('Callback triggered');
98
- console.log(data);
99
- console.log(geniusSdk.dynamicLinkData);
100
- });
101
-
102
- // // Or request the dynamic link data directly on the lifecycle methods
103
- // let data = await geniusSdk.getDynamicLinkData();
104
- // console.log(data);
105
- };
106
-
107
- initializeSdk();
108
- }, []);
85
+ const link = geniusSdk.buildDynamicLink('https://your-apps-domain/open', { leagueId: 42 });
86
+ // https://your-apps-domain/open?leagueId=42
109
87
  ```
110
88
 
111
- To log an event along with all data:
89
+ ## API
90
+
91
+ | Member | Description |
92
+ | --- | --- |
93
+ | `connect()` | Resolves attribution and logs the launch event (`install` or `open`). Runs once per process; later calls await the same run. Resolves to the launch payload, or `{}` while stopped or when the app launched in background (the launch is then logged on the first foreground). |
94
+ | `logEvent(eventName, eventValue = {})` | Stores the event durably and resolves; it is sent in order, with retries. Events logged before `connect()` are sent after it, behind the launch event; after a background launch they are sent right away and the launch follows on the first foreground. A value that isn't a map (`null`, an array or a primitive) is sent as `{}`. |
95
+ | `isFirstOpen()` | Whether this process is the app's install launch. Valid before `connect()` finishes; no side effects. Stays true until the install is recorded, so it is true on every launch while the SDK has been stopped since the install. |
96
+ | `getDeferredData()` | Install attribution as string values, once resolved (Android: Play Install Referrer, waits at most about 17.5 s; iOS: pasteboard, at most 61 s). |
97
+ | `getDynamicLinkData()` | `getDeferredData()` on the install launch unless stopped, otherwise `getInitialLinkParams()`; `{}` when there is nothing. Also sets `dynamicLinkData`. |
98
+ | `dynamicLinkInit(callback)` | Calls `callback` with `getDynamicLinkData()`; when that was the install attribution, then with `getInitialLinkParams()` if the app was opened from a link; then `onLink(callback)`. |
99
+ | `getInitialLinkParams()` | Query parameters of the link that opened the app, or `null`. |
100
+ | `onLink(callback)` | Calls `callback` with the query parameters of every link opened from now on. One subscription: a new call replaces the previous callback. |
101
+ | `dynamicLinkData` | The last link or attribution data delivered. |
102
+ | `buildDynamicLink(url, params)` | Appends `params` form-encoded and sorted by key, before any `#fragment`. |
103
+ | `stop(isStopped)` / `isStopped()` | Persisted. Stopping clears pending events and drops new ones; a `connect()` made while stopped runs on `stop(false)`. |
104
+ | `setMinTimeBetweenSessions(seconds)` | Returning to the app after at least this long in background logs a `session` event. |
105
+ | `setDebugLogging(enabled)` | Native logs, payloads included: Logcat tag `GeniusSDK`, os_log subsystem `com.eshkol.genius`. |
106
+ | `setCollectAndroidId(enabled)` | Persisted. Android only: sends `android_id` while enabled; `setCollectAndroidId(false)` stops it. |
107
+ | `setRequestsTrackingAuthorization(enabled)` | Apple only, before `connect()`: whether `connect()` shows the App Tracking Transparency prompt. |
108
+ | `setReadsPasteboard(enabled)` | iOS only, before `connect()`: whether the install launch reads attribution copied by the Genius landing page (iOS 16+ may show the "Allow Paste" alert). |
109
+ | `setCustomerUserId(id)` | Persisted. Your own user id (for example after login), sent with every event logged after the call; `null` clears it. |
110
+ | `setPushToken(token)` | Persisted. The FCM / APNs token as a string, sent with every event; `null` clears it. |
111
+ | `addListener(eventName, callback)` / `triggerTestEvent()` | Test hook: `triggerTestEvent()` sends a `GENIUS_EVENTS.FIRST_EVENT` event to listeners. |
112
+ | `EVENT_NAME`, `EVENT_PARAM`, `GENIUS_EVENTS` | Predefined event names (`EVENT_NAME.CUSTOM(name)` for others), `revenue` / `currency` value keys, test event names. |
113
+
114
+ ### Defaults
115
+
116
+ | Setting | Default |
117
+ | --- | --- |
118
+ | App Tracking Transparency prompt during `connect()` | on (Apple; only when `NSUserTrackingUsageDescription` is declared) |
119
+ | Pasteboard read on the install launch | on (iOS) |
120
+ | `session` events | after 5 seconds in background; `setMinTimeBetweenSessions(0)` disables them |
121
+ | `android_id` | off |
122
+ | Debug logging | off |
123
+
124
+ ## Behavior
125
+
126
+ - One native engine per process serves every caller; calls apply in call order, except that on Apple platforms a
127
+ call made right after `connect()` may apply before it.
128
+ - Events are queued on disk and survive restarts. Network errors and HTTP 408, 425, 429 and 5xx are retried with
129
+ backoff (4 s doubling up to 5 minutes); an event is dropped after 10 failed responses or on any other status.
130
+ Being offline never drops events. The queue keeps the latest 200 events.
131
+ - Link parameters follow the query rules shared by every Genius SDK: `+` is a space, keys and values are
132
+ percent-decoded separately (a malformed escape is kept as written), the last repeated key wins and the
133
+ `#fragment` is ignored. Values are always strings.
134
+ - While stopped, `getDynamicLinkData()` and `dynamicLinkInit()` don't wait for install attribution, which only
135
+ `connect()` resolves; they use the opening link. Apps that ask for consent before tracking should call
136
+ `dynamicLinkInit` after the decision to receive the attribution on the install launch.
137
+ - `buildDynamicLink` uses `application/x-www-form-urlencoded` encoding, writes `null` as an empty value and objects
138
+ or arrays as JSON, and joins with `&` when the URL already has a query.
139
+
140
+ ## Backend notes
141
+
142
+ - The backend (`neuron.eshkol.io/app_sdk` → BigQuery `appsdk_log`) rejects a whole insert batch when a row carries
143
+ an unknown non-null key, so the SDKs send exactly the existing columns.
144
+ - Since 1.1.0, `event_time` is UTC (same `yyyy-MM-dd HH:mm:ss.SSS` format, no offset) and `session` is a new event
145
+ name; `open` still means a cold start.
146
+ - Delivery is at least once: a response lost after the server stored a row produces a duplicate row.
147
+ - Device fields are collected once per session; an event sent later carries those of the session that sends it.
148
+ - Since 1.2.0, events also carry `event_id` (server-side dedupe), `timezone`, `customer_user_id` and
149
+ `push_token`, plus `meta_install_referrer` on Android and `asa_token` on iOS and macOS.
150
+
151
+ ## Development
112
152
 
113
- ```js
114
- <Button
115
- title="Send Event"
116
- onPress={() => {
117
- geniusSdk.logEvent(EVENT_NAME.CUSTOM('Custom Event'), { username: "bob" })
118
- // geniusSdk.logEvent(EVENT_NAME.INSTALL, { username: "bob" })
119
- }}
120
- />
153
+ ```sh
154
+ yarn # install (Yarn 3, from .yarn/releases)
155
+ yarn typecheck
156
+ yarn lint
157
+ yarn test
121
158
  ```
122
159
 
123
- To add an event listener to listen to events invoked by the Genius:
124
-
125
- ```js
126
- useEffect(() => {
127
- let eventListener = geniusSdk.addListener(GENIUS_EVENTS.FIRST_EVENT, (data) => {
128
- console.log('Event triggered');
129
- for (const key in data) {
130
- console.log(`Key: ${key}, Value: ${data[key]}`);
131
- }
132
- });
133
-
134
- return () => {
135
- eventListener.remove();
136
- };
137
- }, []);
138
- ```
160
+ - Android bridge unit tests: `cd example/android && ./gradlew :react-native-genius-sdk:testDebugUnitTest`.
161
+ - The fixtures in `src/__fixtures__` are shared with the other Genius SDKs; keep them identical.
162
+ - To build the example against unpublished native SDKs: on Android, publish the SDK with `publishToMavenLocal` and
163
+ pass Gradle an `--init-script` that adds `mavenLocal()` for the `com.github.socal-ltd` group; on iOS, add
164
+ `pod 'GeniusSDKFramework', :path => '<path to the pod repo>'` to `example/ios/Podfile` before `pod install`, and
165
+ revert the Podfile and `Podfile.lock` afterwards.
139
166
 
140
- # License
167
+ ## License
141
168
 
142
169
  MIT
143
-
144
- ---
145
-
146
- Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
@@ -1,5 +1,4 @@
1
1
  buildscript {
2
- // Buildscript is evaluated before everything else so we can't use getExtOrDefault
3
2
  def kotlin_version = rootProject.ext.has("kotlinVersion") ? rootProject.ext.get("kotlinVersion") : project.properties["GeniusSdk_kotlinVersion"]
4
3
 
5
4
  repositories {
@@ -43,7 +42,6 @@ def supportsNamespace() {
43
42
  def major = parsed[0].toInteger()
44
43
  def minor = parsed[1].toInteger()
45
44
 
46
- // Namespace support was added in 7.3.0
47
45
  return (major == 7 && minor >= 3) || major >= 8
48
46
  }
49
47
 
@@ -93,11 +91,11 @@ repositories {
93
91
  def kotlin_version = getExtOrDefault("kotlinVersion")
94
92
 
95
93
  dependencies {
96
- // For < 0.71, this will be from the local maven repo
97
- // For > 0.71, this will be replaced by `com.facebook.react:react-android:$version` by react gradle plugin
98
94
  //noinspection GradleDynamicVersion
99
95
  implementation "com.facebook.react:react-native:+"
100
96
  implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
101
- implementation("com.github.socal-ltd:GeniusSDK:1.0.23")
97
+ implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3"
98
+ implementation "com.github.socal-ltd:GeniusSDK:1.2.0"
99
+ testImplementation "junit:junit:4.13.2"
102
100
  }
103
101
 
@@ -1,5 +1,5 @@
1
- GeniusSdk_kotlinVersion=1.7.0
1
+ GeniusSdk_kotlinVersion=1.9.0
2
2
  GeniusSdk_minSdkVersion=21
3
- GeniusSdk_targetSdkVersion=31
4
- GeniusSdk_compileSdkVersion=31
3
+ GeniusSdk_targetSdkVersion=34
4
+ GeniusSdk_compileSdkVersion=34
5
5
  GeniusSdk_ndkversion=21.4.7075529
@@ -1,165 +1,106 @@
1
1
  package com.geniussdk
2
2
 
3
+ import com.eshkol.geniussdk.GeniusSDK
4
+ import com.facebook.react.bridge.Arguments
5
+ import com.facebook.react.bridge.Promise
3
6
  import com.facebook.react.bridge.ReactApplicationContext
4
- import com.facebook.react.bridge.ReactContext
5
7
  import com.facebook.react.bridge.ReactContextBaseJavaModule
6
8
  import com.facebook.react.bridge.ReactMethod
7
- import com.facebook.react.bridge.Promise
8
9
  import com.facebook.react.bridge.ReadableMap
9
- import com.facebook.react.bridge.ReadableArray
10
- import com.facebook.react.bridge.ReadableType
11
- import com.facebook.react.bridge.WritableMap
12
- import com.facebook.react.bridge.Arguments
13
10
  import com.facebook.react.modules.core.DeviceEventManagerModule
14
- import com.eshkol.geniussdk.GeniusSDK
11
+ import kotlinx.coroutines.CancellationException
12
+ import kotlinx.coroutines.CoroutineStart
15
13
  import kotlinx.coroutines.Dispatchers
16
- import kotlinx.coroutines.CoroutineScope
17
- import kotlinx.coroutines.SupervisorJob
14
+ import kotlinx.coroutines.MainScope
15
+ import kotlinx.coroutines.cancel
18
16
  import kotlinx.coroutines.launch
19
17
  import kotlinx.coroutines.withContext
20
18
 
21
- class GeniusSdkModule(reactContext: ReactApplicationContext) :
22
- ReactContextBaseJavaModule(reactContext) {
23
-
24
- private val reactContext: ReactContext = reactContext
25
- private val geniusSdk = GeniusSDK(reactContext)
26
- private var listenerCount = 0
27
-
28
- private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
19
+ class GeniusSdkModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
20
+ private val sdk = GeniusSDK(reactContext).apply { sendEvent = ::emit }
21
+ private val scope = MainScope()
29
22
 
23
+ override fun getName() = NAME
30
24
 
31
- override fun getName(): String {
32
- return NAME
25
+ override fun invalidate() {
26
+ scope.cancel()
27
+ super.invalidate()
33
28
  }
34
29
 
35
- // Example method
36
- // See https://reactnative.dev/docs/native-modules-android
37
30
  @ReactMethod
38
- fun connect(promise: Promise) {
39
- scope.launch {
40
- try {
41
- // Set the callback for sending events
42
- geniusSdk.sendEvent = ::sendEvent
43
-
44
- // Run the suspend connect() function
45
- geniusSdk.connect() // runs on IO thread
46
-
47
- // Switch to main thread to resolve the JS promise
48
- withContext(Dispatchers.Main) {
49
- promise.resolve(geniusSdk.dataString)
50
- }
51
- } catch (e: Exception) {
52
- // Switch to main thread to reject the JS promise
53
- withContext(Dispatchers.Main) {
54
- promise.reject("connect_ERROR", e)
55
- }
56
- }
57
- }
31
+ fun connect(promise: Promise) = settle(promise) {
32
+ sdk.connect()
33
+ sdk.dataString
58
34
  }
59
35
 
60
- @ReactMethod
61
- fun logEvent(eventName: String, eventValue: ReadableMap, promise: Promise) {
62
- val dataMap = readableMapToMap(eventValue)
36
+ // These getters block until the SDK state loads; keep them off the shared native-modules thread.
37
+ @ReactMethod
38
+ fun isFirstOpen(promise: Promise) = settle(promise) { withContext(Dispatchers.IO) { sdk.isFirstOpen } }
63
39
 
64
- // Run logging asynchronously on IO thread
65
- scope.launch {
66
- try {
67
- geniusSdk.logEvent(eventName = GeniusSDK.EventName.Custom(eventName), eventValue = dataMap)
40
+ @ReactMethod
41
+ fun isStopped(promise: Promise) = settle(promise) { withContext(Dispatchers.IO) { sdk.isStopped } }
68
42
 
69
- // Resolve the JS promise on Main thread
70
- withContext(Dispatchers.Main) {
71
- promise.resolve(true)
72
- }
73
- } catch (e: Exception) {
74
- // Reject the JS promise on Main thread if an error occurs
75
- withContext(Dispatchers.Main) {
76
- promise.reject("logEvent_ERROR", e)
77
- }
43
+ @ReactMethod
44
+ fun logEvent(eventName: String, eventValue: ReadableMap, promise: Promise) {
45
+ val value = JsValues.map(eventValue.toHashMap())
46
+ settle(promise) {
47
+ sdk.logEvent(GeniusSDK.EventName.Custom(eventName), value)
48
+ null
78
49
  }
79
50
  }
80
- }
81
51
 
82
52
  @ReactMethod
83
- fun getDeferredDeepLinkData(promise: Promise) {
84
- val data = geniusSdk.deferredData
85
-
86
- val writableMap = Arguments.createMap()
87
- for ((key, value) in data) {
88
- when (value) {
89
- is String -> writableMap.putString(key, value)
90
- is Int -> writableMap.putInt(key, value)
91
- is Boolean -> writableMap.putBoolean(key, value)
92
- is Double -> writableMap.putDouble(key, value)
93
- else -> writableMap.putString(key, value.toString())
94
- }
95
- }
96
-
97
- promise.resolve(writableMap);
53
+ fun getDeferredDeepLinkData(promise: Promise) = settle(promise) {
54
+ Arguments.makeNativeMap(sdk.awaitDeferredData())
98
55
  }
99
56
 
100
57
  @ReactMethod
101
- fun addListener(eventName: String) {
102
- if (listenerCount == 0) {
103
- // Set up any upstream listeners or background tasks as necessary
104
- }
58
+ fun stop(isStopped: Boolean) = sdk.stop(isStopped)
105
59
 
106
- listenerCount += 1
107
- }
60
+ @ReactMethod
61
+ fun setDebugLogging(enabled: Boolean) = GeniusSDK.setDebugLogging(enabled)
108
62
 
109
63
  @ReactMethod
110
- fun removeListeners(count: Int) {
111
- listenerCount -= count
112
- if (listenerCount == 0) {
113
- // Remove upstream listeners, stop unnecessary background tasks
114
- }
115
- }
64
+ fun setCollectAndroidId(enabled: Boolean) = sdk.setCollectAndroidId(enabled)
116
65
 
117
66
  @ReactMethod
118
- fun triggerTestEvent() {
119
- geniusSdk.triggerEvent(
120
- "FirstEvent",
121
- mutableMapOf<String,Any?>("data" to "SomeData", "id" to 172638)
122
- )
123
- }
67
+ fun setMinTimeBetweenSessions(seconds: Int) = sdk.setMinTimeBetweenSessions(seconds)
124
68
 
125
- private fun sendEvent(eventName: String, params: String) {
126
- reactContext
127
- .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
128
- .emit(eventName, params)
129
- }
69
+ @ReactMethod
70
+ fun setCustomerUserId(id: String?) = sdk.setCustomerUserId(id)
130
71
 
131
- fun readableMapToMap(readableMap: ReadableMap): Map<String, Any?> {
132
- val map = mutableMapOf<String, Any?>()
133
- val iterator = readableMap.keySetIterator()
134
-
135
- while (iterator.hasNextKey()) {
136
- val key = iterator.nextKey()
137
- when (readableMap.getType(key)) {
138
- ReadableType.Null -> map[key] = null
139
- ReadableType.Boolean -> map[key] = readableMap.getBoolean(key)
140
- ReadableType.Number -> map[key] = readableMap.getDouble(key)
141
- ReadableType.String -> map[key] = readableMap.getString(key)
142
- ReadableType.Map -> map[key] = readableMapToMap(readableMap.getMap(key)!!)
143
- ReadableType.Array -> map[key] = readableArrayToList(readableMap.getArray(key)!!)
144
- }
145
- }
72
+ @ReactMethod
73
+ fun setPushToken(token: String?) = sdk.setPushToken(token)
146
74
 
147
- return map
148
- }
75
+ @ReactMethod
76
+ fun triggerEvent(eventName: String, data: ReadableMap) = sdk.triggerEvent(eventName, JsValues.map(data.toHashMap()))
149
77
 
150
- fun readableArrayToList(readableArray: com.facebook.react.bridge.ReadableArray): List<Any?> {
151
- val list = mutableListOf<Any?>()
152
- for (i in 0 until readableArray.size()) {
153
- when (readableArray.getType(i)) {
154
- ReadableType.Null -> list.add(null)
155
- ReadableType.Boolean -> list.add(readableArray.getBoolean(i))
156
- ReadableType.Number -> list.add(readableArray.getDouble(i))
157
- ReadableType.String -> list.add(readableArray.getString(i))
158
- ReadableType.Map -> list.add(readableMapToMap(readableArray.getMap(i)!!))
159
- ReadableType.Array -> list.add(readableArrayToList(readableArray.getArray(i)!!))
160
- }
78
+ @Suppress("UNUSED_PARAMETER")
79
+ @ReactMethod
80
+ fun addListener(eventName: String) = Unit
81
+
82
+ @Suppress("UNUSED_PARAMETER")
83
+ @ReactMethod
84
+ fun removeListeners(count: Int) = Unit
85
+
86
+ // Starts block on the calling thread, so the SDK captures calls in JS call order.
87
+ private fun settle(promise: Promise, block: suspend () -> Any?) {
88
+ scope.launch(start = CoroutineStart.UNDISPATCHED) {
89
+ val value = try {
90
+ block()
91
+ } catch (e: CancellationException) {
92
+ throw e
93
+ } catch (e: Exception) {
94
+ return@launch promise.reject(NAME, e)
161
95
  }
162
- return list
96
+ promise.resolve(value)
97
+ }
98
+ }
99
+
100
+ private fun emit(eventName: String, json: String) {
101
+ reactApplicationContext
102
+ .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
103
+ .emit(eventName, json)
163
104
  }
164
105
 
165
106
  companion object {
@@ -0,0 +1,19 @@
1
+ package com.geniussdk
2
+
3
+ import kotlin.math.abs
4
+
5
+ internal object JsValues {
6
+ private const val MAX_EXACT_INTEGER = 9_007_199_254_740_992.0
7
+
8
+ fun number(value: Double): Number =
9
+ if (value % 1.0 == 0.0 && abs(value) <= MAX_EXACT_INTEGER) value.toLong() else value
10
+
11
+ fun map(map: Map<String, Any?>): Map<String, Any?> = map.mapValues { (_, value) -> convert(value) }
12
+
13
+ private fun convert(value: Any?): Any? = when (value) {
14
+ is Double -> number(value)
15
+ is Map<*, *> -> value.entries.associate { (key, item) -> key.toString() to convert(item) }
16
+ is List<*> -> value.map(::convert)
17
+ else -> value
18
+ }
19
+ }
package/ios/GeniusSdk.mm CHANGED
@@ -1,18 +1,23 @@
1
1
  #import <React/RCTBridgeModule.h>
2
2
  #import <React/RCTEventEmitter.h>
3
3
 
4
- @interface RCT_EXTERN_MODULE (GeniusSDK, RCTEventEmitter)
4
+ @interface RCT_EXTERN_MODULE(GeniusSDK, RCTEventEmitter)
5
5
 
6
- RCT_EXTERN_METHOD(connect : (RCTPromiseResolveBlock)
7
- resolve withRejecter : (RCTPromiseRejectBlock)reject)
8
-
9
- RCT_EXTERN_METHOD(getDeferredDeepLinkData : (RCTPromiseResolveBlock)
10
- resolve withRejecter : (RCTPromiseRejectBlock)reject)
11
-
12
- RCT_EXTERN_METHOD(logEvent : (NSString *)eventName withEventValue : (
13
- NSDictionary *)eventValue withResolver : (RCTPromiseResolveBlock)
14
- resolve withRejecter : (RCTPromiseRejectBlock)reject)
15
-
16
- RCT_EXTERN_METHOD(triggerTestEvent)
6
+ RCT_EXTERN_METHOD(connect:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
7
+ RCT_EXTERN_METHOD(isFirstOpen:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
8
+ RCT_EXTERN_METHOD(isStopped:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
9
+ RCT_EXTERN_METHOD(logEvent:(NSString *)eventName
10
+ eventValue:(NSDictionary *)eventValue
11
+ resolver:(RCTPromiseResolveBlock)resolve
12
+ rejecter:(RCTPromiseRejectBlock)reject)
13
+ RCT_EXTERN_METHOD(getDeferredDeepLinkData:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
14
+ RCT_EXTERN_METHOD(stop:(BOOL)isStopped)
15
+ RCT_EXTERN_METHOD(setDebugLogging:(BOOL)enabled)
16
+ RCT_EXTERN_METHOD(setMinTimeBetweenSessions:(NSInteger)seconds)
17
+ RCT_EXTERN_METHOD(setRequestsTrackingAuthorization:(BOOL)enabled)
18
+ RCT_EXTERN_METHOD(setReadsPasteboard:(BOOL)enabled)
19
+ RCT_EXTERN_METHOD(setCustomerUserId:(NSString *)customerUserId)
20
+ RCT_EXTERN_METHOD(setPushToken:(NSString *)pushToken)
21
+ RCT_EXTERN_METHOD(triggerEvent:(NSString *)eventName data:(NSDictionary *)data)
17
22
 
18
23
  @end