@altcraft/react-native-sdk 0.0.2 → 0.0.4

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 (36) hide show
  1. package/LICENSE +20 -20
  2. package/README.md +119 -27
  3. package/Sdk.podspec +2 -2
  4. package/android/build.gradle +3 -4
  5. package/android/src/main/java/com/altcraft/sdk/SdkEventEmitter.kt +50 -0
  6. package/android/src/main/java/com/altcraft/sdk/SdkModule.kt +663 -480
  7. package/android/src/main/java/com/altcraft/sdk/SdkPackage.kt +16 -8
  8. package/android/src/main/java/com/altcraft/sdk/utilities/Converter.kt +164 -0
  9. package/android/src/main/java/com/altcraft/sdk/utilities/Extension.kt +72 -0
  10. package/ios/Converter.swift +485 -48
  11. package/ios/Sdk.mm +195 -270
  12. package/ios/SdkModule.swift +456 -507
  13. package/lib/module/NativeSdk.js +35 -0
  14. package/lib/module/NativeSdk.js.map +1 -1
  15. package/lib/module/Utilities.js +178 -0
  16. package/lib/module/Utilities.js.map +1 -0
  17. package/lib/module/index.js +335 -245
  18. package/lib/module/index.js.map +1 -1
  19. package/lib/typescript/src/NativeSdk.d.ts +125 -33
  20. package/lib/typescript/src/NativeSdk.d.ts.map +1 -1
  21. package/lib/typescript/src/Utilities.d.ts +47 -0
  22. package/lib/typescript/src/Utilities.d.ts.map +1 -0
  23. package/lib/typescript/src/index.d.ts +218 -94
  24. package/lib/typescript/src/index.d.ts.map +1 -1
  25. package/package.json +1 -1
  26. package/src/NativeSdk.ts +169 -46
  27. package/src/Utilities.ts +180 -0
  28. package/src/index.tsx +410 -312
  29. package/android/src/main/java/com/altcraft/sdk/interfaces/RnFCMProvider.kt +0 -26
  30. package/android/src/main/java/com/altcraft/sdk/interfaces/RnHMSProvider.kt +0 -32
  31. package/android/src/main/java/com/altcraft/sdk/interfaces/RnJWTProvider.kt +0 -21
  32. package/android/src/main/java/com/altcraft/sdk/interfaces/RnRustoreProvider.kt +0 -53
  33. package/ios/protocols/RNAPNSProvider.swift +0 -15
  34. package/ios/protocols/RNFCMProvider.swift +0 -24
  35. package/ios/protocols/RNHMSProvider.swift +0 -24
  36. package/ios/protocols/RNJWTProvider.swift +0 -15
@@ -1,16 +1,27 @@
1
1
  package com.altcraft.sdk
2
2
 
3
+ // Created by Andrey Pogodin.
4
+ //
5
+ // Copyright © 2025 Altcraft. All rights reserved.
6
+
3
7
  import androidx.activity.ComponentActivity
4
8
  import com.altcraft.sdk.config.AltcraftConfiguration
5
9
  import com.altcraft.sdk.data.DataClasses
6
- import com.altcraft.sdk.mob_events.PublicMobileEventFunction
10
+ import com.altcraft.sdk.mob_events.PublicMobileEventFunctions
7
11
  import com.altcraft.sdk.push.events.PublicPushEventFunctions
8
12
  import com.altcraft.sdk.push.subscribe.PublicPushSubscriptionFunctions
13
+ import com.altcraft.sdk.profile.PublicProfileFunctions
9
14
  import com.altcraft.sdk.push.token.PublicPushTokenFunctions
10
- import com.altcraft.sdk.rn.providers.RnFCMProvider
11
- import com.altcraft.sdk.rn.providers.RnHMSProvider
12
- import com.altcraft.sdk.rn.providers.RnJWTProvider
13
- import com.altcraft.sdk.rn.providers.RnRuStoreProvider
15
+ import com.altcraft.sdk.rn.getArrayOrNull
16
+ import com.altcraft.sdk.rn.getBooleanOrNull
17
+ import com.altcraft.sdk.rn.getIntOrNull
18
+ import com.altcraft.sdk.rn.getMapOrNull
19
+ import com.altcraft.sdk.rn.getStringOrNull
20
+ import com.altcraft.sdk.rn.hasNonNullKey
21
+ import com.altcraft.sdk.rn.putNullableBoolean
22
+ import com.altcraft.sdk.rn.putNullableInt
23
+ import com.altcraft.sdk.rn.putNullableString
24
+ import com.altcraft.sdk.rn.toStringList
14
25
  import com.altcraft.sdk.sdk_events.Events
15
26
  import com.altcraft.sdk.utilities.Converter
16
27
  import com.facebook.react.bridge.Arguments
@@ -21,99 +32,131 @@ import com.facebook.react.bridge.ReadableMap
21
32
  import com.facebook.react.bridge.UiThreadUtil
22
33
  import com.facebook.react.bridge.WritableMap
23
34
  import com.facebook.react.module.annotations.ReactModule
24
- import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter
35
+
25
36
  import kotlinx.coroutines.CoroutineScope
26
37
  import kotlinx.coroutines.Dispatchers
27
38
  import kotlinx.coroutines.SupervisorJob
28
39
  import kotlinx.coroutines.launch
29
40
 
30
- @ReactModule(name = SdkModule.NAME)
31
- class SdkModule(
32
- reactContext: ReactApplicationContext
33
- ) : NativeSdkSpec(reactContext) {
34
-
35
- private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
36
-
37
- override fun getName(): String = NAME
38
-
39
- // ---------------------- init / auth / providers ----------------------
40
-
41
- override fun initialize(config: ReadableMap, promise: Promise) {
42
- AltcraftRnInitializer.initialize(
43
- reactApplicationContext,
44
- config,
45
- promise
46
- )
47
- }
48
-
49
- override fun setJwt(token: String?) {
50
- if (token.isNullOrBlank()) {
51
- RnJWTProvider.clear()
52
- AltcraftSDK.setJWTProvider(null)
53
- } else {
54
- RnJWTProvider.setToken(token)
55
- AltcraftSDK.setJWTProvider(RnJWTProvider)
56
- }
57
- }
58
-
59
- override fun setAndroidFcmToken(token: String?) {
60
- if (token.isNullOrBlank()) {
61
- RnFCMProvider.clear()
62
- PublicPushTokenFunctions.setFCMTokenProvider(null)
63
- } else {
64
- RnFCMProvider.setToken(token)
65
- PublicPushTokenFunctions.setFCMTokenProvider(RnFCMProvider)
66
- }
67
- }
68
-
69
- override fun setIosFcmToken(token: String?) {
70
- // no-op on Android
71
- }
72
-
73
- override fun setAndroidHmsToken(token: String?) {
74
- if (token.isNullOrBlank()) {
75
- RnHMSProvider.clear()
76
- PublicPushTokenFunctions.setHMSTokenProvider(null)
77
- } else {
78
- RnHMSProvider.setToken(token)
79
- PublicPushTokenFunctions.setHMSTokenProvider(RnHMSProvider)
80
- }
81
- }
82
-
83
- override fun setIosHmsToken(token: String?) {
84
- // no-op on Android
85
- }
86
-
87
- override fun setApnsToken(token: String?) {
88
- // no-op on Android
89
- }
41
+ // ---------------------- Constants ----------------------
42
+
43
+ private object RnConstants {
44
+ // Module
45
+ const val MODULE_NAME: String = "Sdk"
46
+
47
+ // JS event emitter
48
+ const val JS_EVENT_NAME: String = "AltcraftSdkEvent"
49
+
50
+ // Promise reject codes
51
+ const val ERR_INIT_INVALID_CONFIG: String = "ALTCRAFT_INIT_INVALID_CONFIG"
52
+ const val ERR_INIT_ERROR: String = "ALTCRAFT_INIT_ERROR"
53
+ const val ERR_GET_PUSH_TOKEN: String = "getPushToken"
54
+ const val ERR_SET_PUSH_TOKEN: String = "setPushToken"
55
+ const val ERR_CLEAR: String = "clear"
56
+ const val ERR_UNSUSPEND: String = "unSuspendPushSubscription"
57
+ const val ERR_GET_LATEST_STATUS: String = "getStatusOfLatestSubscription"
58
+ const val ERR_GET_CURRENT_STATUS: String = "getStatusForCurrentSubscription"
59
+ const val ERR_GET_LATEST_STATUS_PROVIDER: String = "getStatusOfLatestSubscriptionForProvider"
60
+ const val ERR_UPDATE_PROFILE_FIELDS: String = "updateProfileFields"
61
+ const val ERR_FORCED_TOKEN_UPDATE: String = "forcedTokenUpdate"
62
+ const val ERR_DELETE_DEVICE_TOKEN: String = "deleteDeviceToken"
63
+ const val ERR_CHANGE_PROVIDER_PRIORITY: String = "changePushProviderPriorityList"
64
+
65
+ // Promise reject messages
66
+ const val MSG_PROVIDER_IS_BLANK: String = "provider is blank"
67
+ const val MSG_INIT_UNKNOWN: String = "Altcraft initialization failed with unknown error"
68
+ const val MSG_INIT_ERROR: String = "Altcraft initialization error"
69
+
70
+ // Keys: TokenData map
71
+ const val KEY_PROVIDER: String = "provider"
72
+ const val KEY_TOKEN: String = "token"
73
+
74
+ // Keys: SDK event map
75
+ const val KEY_FUNCTION: String = "function"
76
+ const val KEY_CODE: String = "code"
77
+ const val KEY_MESSAGE: String = "message"
78
+ const val KEY_TYPE: String = "type"
79
+ const val KEY_VALUE: String = "value"
80
+
81
+ // Event types for JS
82
+ const val TYPE_EVENT: String = "event"
83
+ const val TYPE_ERROR: String = "error"
84
+ const val TYPE_RETRY_ERROR: String = "retryError"
85
+
86
+ // Keys: ResponseWithHttpCode -> JS map
87
+ const val KEY_HTTP_CODE: String = "httpCode"
88
+ const val KEY_RESPONSE: String = "response"
89
+ const val KEY_ERROR: String = "error"
90
+ const val KEY_ERROR_TEXT: String = "errorText"
91
+ const val KEY_PROFILE: String = "profile"
92
+ const val KEY_ID: String = "id"
93
+ const val KEY_STATUS: String = "status"
94
+ const val KEY_IS_TEST: String = "isTest"
95
+ const val KEY_SUBSCRIPTION: String = "subscription"
96
+ const val KEY_SUBSCRIPTION_ID: String = "subscriptionId"
97
+ const val KEY_HASH_ID: String = "hashId"
98
+
99
+ // Fields not mapped yet (kept for parity with TS)
100
+ const val KEY_FIELDS: String = "fields"
101
+ const val KEY_CATS: String = "cats"
102
+ }
90
103
 
91
- override fun setUserDefaultsValue(suiteName: String?, key: String, value: String?) {
92
- // no-op on Android
93
- }
104
+ @ReactModule(name = RnConstants.MODULE_NAME)
105
+ class SdkModule(reactContext: ReactApplicationContext) : NativeSdkSpec(reactContext) {
94
106
 
95
- override fun setRustoreToken(token: String?) {
96
- if (token.isNullOrBlank()) {
97
- RnRuStoreProvider.clear()
98
- PublicPushTokenFunctions.setRuStoreTokenProvider(null)
99
- } else {
100
- RnRuStoreProvider.setToken(token)
101
- PublicPushTokenFunctions.setRuStoreTokenProvider(RnRuStoreProvider)
102
- }
103
- }
107
+ private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
104
108
 
105
- // ---------------------- required for NativeEventEmitter ----------------------
109
+ override fun getName(): String = RnConstants.MODULE_NAME
106
110
 
111
+ /**
112
+ * Required by NativeEventEmitter (no-op on Android).
113
+ *
114
+ * @param eventName Event name from JS side.
115
+ */
107
116
  override fun addListener(eventName: String) {
108
117
  // no-op
109
118
  }
110
119
 
120
+ /**
121
+ * Required by NativeEventEmitter (no-op on Android).
122
+ *
123
+ * @param count Number of JS listeners removed.
124
+ */
111
125
  override fun removeListeners(count: Double) {
112
126
  // no-op
113
127
  }
114
128
 
115
- // ---------------------- token-API for RN ----------------------
129
+ // ---------------------- init ----------------------
130
+
131
+ /**
132
+ * Initializes the native Altcraft SDK using RN config map.
133
+ *
134
+ * @param config React Native configuration object.
135
+ * ```
136
+ * Required: `apiUrl`.
137
+ * Optional: `rToken`, `appInfo`, `providerPriorityList`, `enableLogging`,
138
+ * Android-only: `android_icon`, `android_usingService`, `android_serviceMessage`,
139
+ * `android_pushReceiverModules`, `android_pushChannelName`, `android_pushChannelDescription`.
140
+ * @param promise
141
+ * ```
142
+ * Promise resolved on success; rejected on invalid config or initialization failure.
143
+ */
144
+ override fun initialize(config: ReadableMap, promise: Promise) {
145
+ AltcraftRnInitializer.initialize(
146
+ reactContext = reactApplicationContext,
147
+ config = config,
148
+ promise = promise
149
+ )
150
+ }
151
+
152
+ // ---------------------- token-API for RN (ONLY getPushToken / setPushToken)
153
+ // ----------------------
116
154
 
155
+ /**
156
+ * Returns current push token data from native side.
157
+ *
158
+ * @param promise Resolves to `{ provider, token }` or `null` if token is not available.
159
+ */
117
160
  override fun getPushToken(promise: Promise) {
118
161
  coroutineScope.launch {
119
162
  try {
@@ -122,165 +165,143 @@ class SdkModule(
122
165
  promise.resolve(null)
123
166
  } else {
124
167
  val map = Arguments.createMap()
125
- map.putString("provider", tokenData.provider)
126
- map.putString("token", tokenData.token)
168
+ map.putString(RnConstants.KEY_PROVIDER, tokenData.provider)
169
+ map.putString(RnConstants.KEY_TOKEN, tokenData.token)
127
170
  promise.resolve(map)
128
171
  }
129
172
  } catch (e: Exception) {
130
- promise.reject("getPushToken", e)
131
- }
132
- }
133
- }
134
-
135
- override fun deleteDeviceToken(provider: String?, promise: Promise) {
136
- val p: String = provider ?: run {
137
- promise.reject("deleteDeviceToken", "provider is null")
138
- return
139
- }
140
-
141
- coroutineScope.launch {
142
- try {
143
- PublicPushTokenFunctions.deleteDeviceToken(reactApplicationContext, p)
144
- promise.resolve(null)
145
- } catch (e: Exception) {
146
- promise.reject("deleteDeviceToken", e)
147
- }
148
- }
149
- }
150
-
151
- override fun forcedTokenUpdate(promise: Promise) {
152
- coroutineScope.launch {
153
- try {
154
- PublicPushTokenFunctions.forcedTokenUpdate(reactApplicationContext) {
155
- promise.resolve(null)
156
- }
157
- } catch (e: Exception) {
158
- promise.reject("forcedTokenUpdate", e)
159
- }
160
- }
161
- }
162
-
163
- override fun changePushProviderPriorityList(priorityList: ReadableArray?, promise: Promise) {
164
- val list = Converter.toStringList(priorityList)
165
- coroutineScope.launch {
166
- try {
167
- PublicPushTokenFunctions.changePushProviderPriorityList(
168
- context = reactApplicationContext,
169
- priorityList = list
170
- )
171
- promise.resolve(null)
172
- } catch (e: Exception) {
173
- promise.reject("changePushProviderPriorityList", e)
173
+ promise.reject(RnConstants.ERR_GET_PUSH_TOKEN, e)
174
174
  }
175
175
  }
176
176
  }
177
177
 
178
+ /**
179
+ * Sets or clears push token for the given provider.
180
+ *
181
+ * @param provider Provider identifier (must be non-blank).
182
+ * @param token Token string or `null` to clear (native expects String; `null` is converted to
183
+ * empty string).
184
+ * @param promise Resolves when the token is saved on native side.
185
+ */
178
186
  override fun setPushToken(provider: String, token: String?, promise: Promise) {
179
187
  if (provider.isBlank()) {
180
- promise.reject("setPushToken", "provider is blank")
188
+ promise.reject(RnConstants.ERR_SET_PUSH_TOKEN, RnConstants.MSG_PROVIDER_IS_BLANK)
181
189
  return
182
190
  }
183
191
 
184
192
  coroutineScope.launch {
185
193
  try {
186
- if (token == null) {
187
- PublicPushTokenFunctions.deleteDeviceToken(
188
- context = reactApplicationContext,
189
- provider = provider
190
- )
191
- promise.resolve(null)
192
- return@launch
193
- }
194
+ val tokenToPass: String = token ?: ""
194
195
 
195
196
  PublicPushTokenFunctions.setPushToken(
196
- context = reactApplicationContext,
197
- provider = provider,
198
- token = token
197
+ context = reactApplicationContext,
198
+ provider = provider,
199
+ token = tokenToPass
199
200
  )
200
201
  promise.resolve(null)
201
202
  } catch (e: Exception) {
202
- promise.reject("setPushToken", e)
203
+ promise.reject(RnConstants.ERR_SET_PUSH_TOKEN, e)
203
204
  }
204
205
  }
205
206
  }
206
207
 
207
- // ---------------------- AltcraftSDK: clear / initial ops / permission ----------------------
208
+ // ---------------------- AltcraftSDK: clear / permission ----------------------
208
209
 
210
+ /**
211
+ * Clears SDK local state and stored data (native).
212
+ *
213
+ * @param promise Resolves after cleanup is finished.
214
+ */
209
215
  override fun clear(promise: Promise) {
210
216
  try {
211
- AltcraftSDK.clear(reactApplicationContext) {
212
- promise.resolve(null)
213
- }
217
+ AltcraftSDK.clear(reactApplicationContext) { promise.resolve(null) }
214
218
  } catch (e: Exception) {
215
- promise.reject("clear", e)
216
- }
217
- }
218
-
219
- override fun unlockInitOperationsInThisSession() {
220
- try {
221
- AltcraftSDK.unlockInitOperationsInThisSession()
222
- } catch (_: Exception) {
219
+ promise.reject(RnConstants.ERR_CLEAR, e)
223
220
  }
224
221
  }
225
222
 
223
+ /**
224
+ * Requests notification permission (Android-only runtime behavior). Safe no-op if current
225
+ * Activity is not a ComponentActivity.
226
+ */
226
227
  override fun requestNotificationPermission() {
227
228
  val activity = currentActivity
228
- if (activity !is ComponentActivity) {
229
- return
230
- }
229
+ if (activity !is ComponentActivity) return
230
+
231
231
  UiThreadUtil.runOnUiThread {
232
232
  try {
233
- AltcraftSDK.requestNotificationPermission(
234
- reactApplicationContext,
235
- activity
236
- )
233
+ AltcraftSDK.requestNotificationPermission(reactApplicationContext, activity)
237
234
  } catch (_: Exception) {
235
+ // ignore
238
236
  }
239
237
  }
240
238
  }
241
239
 
242
240
  // ---------------------- MobileEvent bridge ----------------------
243
241
 
242
+ /**
243
+ * Sends a mobile event to the server (fire-and-forget).
244
+ *
245
+ * @param sid Pixel identifier.
246
+ * @param eventName Event name.
247
+ * @param sendMessageId Optional message identifier to link the event.
248
+ * @param payload Optional event payload (string-only map).
249
+ * @param matching Optional matching parameters (string-only map).
250
+ * @param matchingType Optional matching mode/type.
251
+ * @param profileFields Optional profile fields (string-only map).
252
+ * @param subscription Optional subscription info (email/sms/push/cc_data), converted on native
253
+ * side.
254
+ * @param utm Optional UTM tags for attribution.
255
+ */
244
256
  override fun mobileEvent(
245
- sid: String,
246
- eventName: String,
247
- sendMessageId: String?,
248
- payload: ReadableMap?,
249
- matching: ReadableMap?,
250
- matchingType: String?,
251
- profileFields: ReadableMap?,
252
- utm: ReadableMap?
257
+ sid: String,
258
+ eventName: String,
259
+ sendMessageId: String?,
260
+ payload: ReadableMap?,
261
+ matching: ReadableMap?,
262
+ matchingType: String?,
263
+ profileFields: ReadableMap?,
264
+ subscription: ReadableMap?,
265
+ utm: ReadableMap?
253
266
  ) {
254
267
  try {
255
- val utmData = utm?.let {
256
- DataClasses.UTM(
257
- campaign = it.getString("campaign"),
258
- content = it.getString("content"),
259
- keyword = it.getString("keyword"),
260
- medium = it.getString("medium"),
261
- source = it.getString("source"),
262
- temp = it.getString("temp")
263
- )
264
- }
268
+ val utmData =
269
+ utm?.let {
270
+ DataClasses.UTM(
271
+ campaign = it.getString("campaign"),
272
+ content = it.getString("content"),
273
+ keyword = it.getString("keyword"),
274
+ medium = it.getString("medium"),
275
+ source = it.getString("source"),
276
+ temp = it.getString("temp")
277
+ )
278
+ }
265
279
 
266
- PublicMobileEventFunction.mobileEvent(
267
- context = reactApplicationContext,
268
- sid = sid,
269
- eventName = eventName,
270
- sendMessageId = sendMessageId,
271
- payload = Converter.toKotlinMap(payload),
272
- matching = Converter.toKotlinMap(matching),
273
- matchingType = matchingType,
274
- profileFields = Converter.toKotlinMap(profileFields),
275
- subscription = null,
276
- utm = utmData
280
+ PublicMobileEventFunctions.mobileEvent(
281
+ context = reactApplicationContext,
282
+ sid = sid,
283
+ eventName = eventName,
284
+ sendMessageId = sendMessageId,
285
+ payload = Converter.toKotlinMap(payload),
286
+ matching = Converter.toKotlinMap(matching),
287
+ matchingType = matchingType,
288
+ profileFields = Converter.toKotlinMap(profileFields),
289
+ subscription = Converter.toSubscriptionOrNull(subscription),
290
+ utm = utmData
277
291
  )
278
- } catch (_: Exception) {
292
+ } catch (e: Exception) {
293
+ // Log error but don't crash bridge
294
+ e.printStackTrace()
279
295
  }
280
296
  }
281
297
 
282
298
  // ---------------------- push payload bridge ----------------------
283
299
 
300
+ /**
301
+ * Forwards a push payload to native SDK (Android-only behavior).
302
+ *
303
+ * @param message Push payload map (string-only).
304
+ */
284
305
  override fun takePush(message: ReadableMap?) {
285
306
  if (message == null) return
286
307
  val map = Converter.toStringMapOrNull(message) ?: return
@@ -289,53 +310,72 @@ class SdkModule(
289
310
  }
290
311
  }
291
312
 
313
+ // ---------------------- manual push events ----------------------
314
+
315
+ /**
316
+ * Reports a push delivery event (Android-only behavior).
317
+ *
318
+ * @param message Optional push payload (string-only map).
319
+ * @param messageUID Optional Altcraft message UID.
320
+ */
292
321
  override fun deliveryEvent(message: ReadableMap?, messageUID: String?) {
293
322
  try {
294
323
  val map = Converter.toStringMapOrNull(message)
295
324
  PublicPushEventFunctions.deliveryEvent(
296
- context = reactApplicationContext,
297
- message = map,
298
- messageUID = messageUID
325
+ context = reactApplicationContext,
326
+ message = map,
327
+ messageUID = messageUID
299
328
  )
300
329
  } catch (_: Exception) {
330
+ // ignore
301
331
  }
302
332
  }
303
333
 
334
+ /**
335
+ * Reports a push open event (Android-only behavior).
336
+ *
337
+ * @param message Optional push payload (string-only map).
338
+ * @param messageUID Optional Altcraft message UID.
339
+ */
304
340
  override fun openEvent(message: ReadableMap?, messageUID: String?) {
305
341
  try {
306
342
  val map = Converter.toStringMapOrNull(message)
307
343
  PublicPushEventFunctions.openEvent(
308
- context = reactApplicationContext,
309
- message = map,
310
- messageUID = messageUID
344
+ context = reactApplicationContext,
345
+ message = map,
346
+ messageUID = messageUID
311
347
  )
312
348
  } catch (_: Exception) {
349
+ // ignore
313
350
  }
314
351
  }
315
352
 
316
353
  // --------------------- Events bridge for RN ---------------------
317
354
 
355
+ /**
356
+ * Subscribes native SDK events stream and forwards events to JS via DeviceEventEmitter. Calling
357
+ * from JS multiple times replaces handler on JS side (native always emits to the same event
358
+ * name).
359
+ */
318
360
  override fun subscribeToEvents() {
319
361
  Events.subscribe { event -> sendEventToJs(event) }
320
362
  }
321
363
 
364
+ /** Unsubscribes native SDK events stream. */
322
365
  override fun unsubscribeFromEvent() {
323
366
  Events.unsubscribe()
324
367
  }
325
368
 
326
369
  private fun sendEventToJs(event: DataClasses.Event) {
327
370
  val eventMap = Arguments.createMap()
328
- eventMap.putString("function", event.function)
371
+ eventMap.putString(RnConstants.KEY_FUNCTION, event.function)
329
372
 
330
373
  val code = event.eventCode
331
- if (code != null) {
332
- eventMap.putInt("code", code)
333
- } else {
334
- eventMap.putNull("code")
335
- }
374
+ if (code != null) eventMap.putInt(RnConstants.KEY_CODE, code)
375
+ else eventMap.putNull(RnConstants.KEY_CODE)
336
376
 
337
377
  val message = event.eventMessage ?: event.toString()
338
- eventMap.putString("message", message)
378
+ eventMap.putString(RnConstants.KEY_MESSAGE, message)
339
379
 
340
380
  val value = event.eventValue
341
381
  if (value != null) {
@@ -352,275 +392,465 @@ class SdkModule(
352
392
  else -> valueMap.putString(key, anyValue.toString())
353
393
  }
354
394
  }
355
- eventMap.putMap("value", valueMap)
395
+ eventMap.putMap(RnConstants.KEY_VALUE, valueMap)
356
396
  } else {
357
- eventMap.putNull("value")
358
- }
359
-
360
- val type = when (event) {
361
- is DataClasses.Error -> "error"
362
- is DataClasses.RetryError -> "retryError"
363
- else -> "event"
397
+ eventMap.putNull(RnConstants.KEY_VALUE)
364
398
  }
365
- eventMap.putString("type", type)
399
+ val type =
400
+ when (event) {
401
+ is DataClasses.Error -> RnConstants.TYPE_ERROR
402
+ is DataClasses.RetryError -> RnConstants.TYPE_RETRY_ERROR
403
+ else -> RnConstants.TYPE_EVENT
404
+ }
405
+ eventMap.putString(RnConstants.KEY_TYPE, type)
366
406
 
367
- reactApplicationContext
368
- .getJSModule(RCTDeviceEventEmitter::class.java)
369
- .emit("AltcraftSdkEvent", eventMap)
407
+ SdkEventEmitter.emit(RnConstants.JS_EVENT_NAME, eventMap)
370
408
  }
371
409
 
372
410
  // --------------------- subscription bridge ---------------------
373
411
 
412
+ /**
413
+ * Sends a push subscribe request.
414
+ *
415
+ * @param sync Execution mode:
416
+ * ```
417
+ * `true` — synchronous server request returning the operation result.
418
+ * `false` — asynchronous server request returning enqueue result.
419
+ * `null` — defaults to `true` on Android bridge.
420
+ * @param profileFields
421
+ * ```
422
+ * Optional profile fields (string-only map).
423
+ * @param customFields Optional custom fields (string-only map).
424
+ * @param cats Optional categories list.
425
+ * @param replace Optional flag to replace an existing subscription.
426
+ * @param skipTriggers Optional flag to skip trigger execution on the server.
427
+ */
374
428
  override fun pushSubscribe(
375
- sync: Boolean?,
376
- profileFields: ReadableMap?,
377
- customFields: ReadableMap?,
378
- cats: ReadableArray?,
379
- replace: Boolean?,
380
- skipTriggers: Boolean?
429
+ sync: Boolean?,
430
+ profileFields: ReadableMap?,
431
+ customFields: ReadableMap?,
432
+ cats: ReadableArray?,
433
+ replace: Boolean?,
434
+ skipTriggers: Boolean?
381
435
  ) {
382
436
  val isSync = sync ?: true
383
437
  PublicPushSubscriptionFunctions.pushSubscribe(
384
- context = reactApplicationContext,
385
- sync = isSync,
386
- profileFields = Converter.toKotlinMap(profileFields),
387
- customFields = Converter.toKotlinMap(customFields),
388
- cats = Converter.toCategoryListOrNull(cats),
389
- replace = replace,
390
- skipTriggers = skipTriggers
438
+ context = reactApplicationContext,
439
+ sync = isSync,
440
+ profileFields = Converter.toKotlinMap(profileFields),
441
+ customFields = Converter.toKotlinMap(customFields),
442
+ cats = Converter.toCategoryListOrNull(cats),
443
+ replace = replace,
444
+ skipTriggers = skipTriggers
391
445
  )
392
446
  }
393
447
 
448
+ /**
449
+ * Sends a push suspend request.
450
+ *
451
+ * @param sync Execution mode (see [pushSubscribe]).
452
+ * @param profileFields Optional profile fields (string-only map).
453
+ * @param customFields Optional custom fields (string-only map).
454
+ * @param cats Optional categories list.
455
+ * @param replace Optional flag to replace an existing subscription.
456
+ * @param skipTriggers Optional flag to skip trigger execution on the server.
457
+ */
394
458
  override fun pushSuspend(
395
- sync: Boolean?,
396
- profileFields: ReadableMap?,
397
- customFields: ReadableMap?,
398
- cats: ReadableArray?,
399
- replace: Boolean?,
400
- skipTriggers: Boolean?
459
+ sync: Boolean?,
460
+ profileFields: ReadableMap?,
461
+ customFields: ReadableMap?,
462
+ cats: ReadableArray?,
463
+ replace: Boolean?,
464
+ skipTriggers: Boolean?
401
465
  ) {
402
466
  val isSync = sync ?: true
403
467
  PublicPushSubscriptionFunctions.pushSuspend(
404
- context = reactApplicationContext,
405
- sync = isSync,
406
- profileFields = Converter.toKotlinMap(profileFields),
407
- customFields = Converter.toKotlinMap(customFields),
408
- cats = Converter.toCategoryListOrNull(cats),
409
- replace = replace,
410
- skipTriggers = skipTriggers
468
+ context = reactApplicationContext,
469
+ sync = isSync,
470
+ profileFields = Converter.toKotlinMap(profileFields),
471
+ customFields = Converter.toKotlinMap(customFields),
472
+ cats = Converter.toCategoryListOrNull(cats),
473
+ replace = replace,
474
+ skipTriggers = skipTriggers
411
475
  )
412
476
  }
413
477
 
478
+ /**
479
+ * Sends a push unsubscribe request.
480
+ *
481
+ * @param sync Execution mode (see [pushSubscribe]).
482
+ * @param profileFields Optional profile fields (string-only map).
483
+ * @param customFields Optional custom fields (string-only map).
484
+ * @param cats Optional categories list.
485
+ * @param replace Optional flag to replace an existing subscription.
486
+ * @param skipTriggers Optional flag to skip trigger execution on the server.
487
+ */
414
488
  override fun pushUnSubscribe(
415
- sync: Boolean?,
416
- profileFields: ReadableMap?,
417
- customFields: ReadableMap?,
418
- cats: ReadableArray?,
419
- replace: Boolean?,
420
- skipTriggers: Boolean?
489
+ sync: Boolean?,
490
+ profileFields: ReadableMap?,
491
+ customFields: ReadableMap?,
492
+ cats: ReadableArray?,
493
+ replace: Boolean?,
494
+ skipTriggers: Boolean?
421
495
  ) {
422
496
  val isSync = sync ?: true
423
497
  PublicPushSubscriptionFunctions.pushUnSubscribe(
424
- context = reactApplicationContext,
425
- sync = isSync,
426
- profileFields = Converter.toKotlinMap(profileFields),
427
- customFields = Converter.toKotlinMap(customFields),
428
- cats = Converter.toCategoryListOrNull(cats),
429
- replace = replace,
430
- skipTriggers = skipTriggers
498
+ context = reactApplicationContext,
499
+ sync = isSync,
500
+ profileFields = Converter.toKotlinMap(profileFields),
501
+ customFields = Converter.toKotlinMap(customFields),
502
+ cats = Converter.toCategoryListOrNull(cats),
503
+ replace = replace,
504
+ skipTriggers = skipTriggers
431
505
  )
432
506
  }
433
507
 
434
508
  // --------------------- async status bridges ---------------------
435
509
 
510
+ /**
511
+ * Unsuspends push subscriptions based on native matching rules.
512
+ *
513
+ * @param promise Resolves to response with HTTP code or `null` if unavailable.
514
+ */
436
515
  override fun unSuspendPushSubscription(promise: Promise) {
437
516
  coroutineScope.launch {
438
517
  try {
439
- val res = PublicPushSubscriptionFunctions.unSuspendPushSubscription(
440
- reactApplicationContext
441
- )
518
+ val res =
519
+ PublicPushSubscriptionFunctions.unSuspendPushSubscription(
520
+ reactApplicationContext
521
+ )
442
522
  promise.resolve(responseWithHttpCodeToWritableMap(res))
443
523
  } catch (e: Exception) {
444
- promise.reject("unSuspendPushSubscription", e)
524
+ promise.reject(RnConstants.ERR_UNSUSPEND, e)
445
525
  }
446
526
  }
447
527
  }
448
528
 
529
+ /**
530
+ * Returns the status of the latest subscription in profile.
531
+ *
532
+ * @param promise Resolves to response with HTTP code or `null` if unavailable.
533
+ */
449
534
  override fun getStatusOfLatestSubscription(promise: Promise) {
450
535
  coroutineScope.launch {
451
536
  try {
452
- val res = PublicPushSubscriptionFunctions.getStatusOfLatestSubscription(
453
- reactApplicationContext
454
- )
537
+ val res =
538
+ PublicPushSubscriptionFunctions.getStatusOfLatestSubscription(
539
+ reactApplicationContext
540
+ )
455
541
  promise.resolve(responseWithHttpCodeToWritableMap(res))
456
542
  } catch (e: Exception) {
457
- promise.reject("getStatusOfLatestSubscription", e)
543
+ promise.reject(RnConstants.ERR_GET_LATEST_STATUS, e)
458
544
  }
459
545
  }
460
546
  }
461
547
 
462
- override fun getStatusOfLatestSubscriptionForProvider(
463
- provider: String?,
464
- promise: Promise
465
- ) {
548
+ /**
549
+ * Returns the status of the latest subscription for the given provider.
550
+ *
551
+ * @param provider Optional provider identifier (may be null).
552
+ * @param promise Resolves to response with HTTP code or `null` if unavailable.
553
+ */
554
+ override fun getStatusOfLatestSubscriptionForProvider(provider: String?, promise: Promise) {
466
555
  coroutineScope.launch {
467
556
  try {
468
- val res = PublicPushSubscriptionFunctions.getStatusOfLatestSubscriptionForProvider(
469
- context = reactApplicationContext,
470
- provider = provider
471
- )
557
+ val res =
558
+ PublicPushSubscriptionFunctions.getStatusOfLatestSubscriptionForProvider(
559
+ context = reactApplicationContext,
560
+ provider = provider
561
+ )
472
562
  promise.resolve(responseWithHttpCodeToWritableMap(res))
473
563
  } catch (e: Exception) {
474
- promise.reject("getStatusOfLatestSubscriptionForProvider", e)
564
+ promise.reject(RnConstants.ERR_GET_LATEST_STATUS_PROVIDER, e)
475
565
  }
476
566
  }
477
567
  }
478
568
 
569
+ /**
570
+ * Returns the status for current subscription (by current provider/token context).
571
+ *
572
+ * @param promise Resolves to response with HTTP code or `null` if unavailable.
573
+ */
479
574
  override fun getStatusForCurrentSubscription(promise: Promise) {
480
575
  coroutineScope.launch {
481
576
  try {
482
- val res = PublicPushSubscriptionFunctions.getStatusForCurrentSubscription(
483
- reactApplicationContext
484
- )
577
+ val res =
578
+ PublicPushSubscriptionFunctions.getStatusForCurrentSubscription(
579
+ reactApplicationContext
580
+ )
485
581
  promise.resolve(responseWithHttpCodeToWritableMap(res))
486
582
  } catch (e: Exception) {
487
- promise.reject("getStatusForCurrentSubscription", e)
583
+ promise.reject(RnConstants.ERR_GET_CURRENT_STATUS, e)
488
584
  }
489
585
  }
490
586
  }
491
587
 
492
- private fun responseWithHttpCodeToWritableMap(
493
- data: DataClasses.ResponseWithHttpCode?
494
- ): WritableMap? {
495
- if (data == null) return null
496
-
497
- val root = Arguments.createMap()
588
+ // ---------------------- Profile API ----------------------
498
589
 
499
- val httpCode = data.httpCode
500
- if (httpCode != null) {
501
- root.putInt("httpCode", httpCode)
502
- } else {
503
- root.putNull("httpCode")
590
+ /**
591
+ * Updates profile fields on the server.
592
+ *
593
+ * @param profileFields Optional profile fields (string-only map).
594
+ * @param skipTriggers Optional flag to skip trigger execution on the server.
595
+ */
596
+ override fun updateProfileFields(
597
+ profileFields: ReadableMap?,
598
+ skipTriggers: Boolean?
599
+ ) {
600
+ try {
601
+ PublicProfileFunctions.updateProfileFields(
602
+ context = reactApplicationContext,
603
+ profileFields = Converter.toKotlinMap(profileFields),
604
+ skipTriggers = skipTriggers
605
+ )
606
+ } catch (e: Exception) {
607
+ e.printStackTrace()
504
608
  }
609
+ }
505
610
 
506
- val resp = data.response
507
- if (resp == null) {
508
- root.putNull("response")
509
- return root
510
- }
611
+ // ---------------------- Token management API ----------------------
511
612
 
512
- val respMap = Arguments.createMap()
613
+ /**
614
+ * Forces a push token refresh (delete + re-register).
615
+ *
616
+ * @param promise Resolves when the token update flow completes.
617
+ */
618
+ override fun forcedTokenUpdate(promise: Promise) {
619
+ coroutineScope.launch {
620
+ try {
621
+ PublicPushTokenFunctions.forcedTokenUpdate(reactApplicationContext) {
622
+ promise.resolve(null)
623
+ }
624
+ } catch (e: Exception) {
625
+ promise.reject(RnConstants.ERR_FORCED_TOKEN_UPDATE, e)
626
+ }
627
+ }
628
+ }
513
629
 
514
- val error = resp.error
515
- if (error != null) {
516
- respMap.putInt("error", error)
517
- } else {
518
- respMap.putNull("error")
630
+ /**
631
+ * Deletes the device token for a given provider.
632
+ *
633
+ * @param provider Provider identifier (e.g. `android-firebase`).
634
+ * @param promise Resolves when the delete call is dispatched.
635
+ */
636
+ override fun deleteDeviceToken(provider: String, promise: Promise) {
637
+ try {
638
+ PublicPushTokenFunctions.deleteDeviceToken(
639
+ context = reactApplicationContext,
640
+ provider = provider
641
+ ) {
642
+ promise.resolve(null)
643
+ }
644
+ } catch (e: Exception) {
645
+ promise.reject(RnConstants.ERR_DELETE_DEVICE_TOKEN, e)
519
646
  }
647
+ }
520
648
 
521
- val errorText = resp.errorText
522
- if (errorText != null) {
523
- respMap.putString("errorText", errorText)
524
- } else {
525
- respMap.putNull("errorText")
649
+ /**
650
+ * Changes the push provider priority list at runtime.
651
+ *
652
+ * @param priorityList Ordered list of provider identifiers.
653
+ * @param promise Resolves when the priority list is updated and token update is triggered.
654
+ */
655
+ override fun changePushProviderPriorityList(priorityList: ReadableArray, promise: Promise) {
656
+ coroutineScope.launch {
657
+ try {
658
+ val list = priorityList.toStringList()
659
+ PublicPushTokenFunctions.changePushProviderPriorityList(
660
+ context = reactApplicationContext,
661
+ priorityList = list
662
+ )
663
+ promise.resolve(null)
664
+ } catch (e: Exception) {
665
+ promise.reject(RnConstants.ERR_CHANGE_PROVIDER_PRIORITY, e)
666
+ }
526
667
  }
668
+ }
527
669
 
528
- val profile = resp.profile
529
- if (profile == null) {
530
- respMap.putNull("profile")
531
- } else {
532
- val profileMap = Arguments.createMap()
670
+ // ---------------------- PushReceiver helpers ----------------------
533
671
 
534
- val profileId = profile.id
535
- if (profileId != null) {
536
- profileMap.putString("id", profileId)
537
- } else {
538
- profileMap.putNull("id")
539
- }
672
+ /**
673
+ * Checks whether a push payload belongs to Altcraft.
674
+ *
675
+ * @param message Push payload map (string-only).
676
+ * @return `true` if the message contains the Altcraft marker key.
677
+ */
678
+ override fun isAltcraftPush(message: ReadableMap?): Boolean {
679
+ if (message == null) return false
680
+ val map = Converter.toStringMapOrNull(message) ?: return false
681
+ return AltcraftSDK.PushReceiver.isAltcraftPush(map)
682
+ }
540
683
 
541
- val status = profile.status
542
- if (status != null) {
543
- profileMap.putString("status", status)
544
- } else {
545
- profileMap.putNull("status")
546
- }
684
+ // ---------------------- SDK lifecycle ----------------------
547
685
 
548
- val isTest = profile.isTest
549
- if (isTest != null) {
550
- profileMap.putBoolean("isTest", isTest)
551
- } else {
552
- profileMap.putNull("isTest")
686
+ /**
687
+ * Allows re-running initial retry/scheduling/token-check logic
688
+ * in this process on the next [initialization].
689
+ */
690
+ override fun unlockInitialOperationsInThisSession() {
691
+ AltcraftSDK.unlockInitialOperationsInThisSession()
692
+ }
693
+
694
+ /**
695
+ * Sets the App Group name (iOS-only, no-op on Android).
696
+ */
697
+ override fun setAppGroup(groupName: String?) {
698
+ // no-op on Android
699
+ }
700
+
701
+ /**
702
+ * Maps {@link DataClasses.ResponseWithHttpCode} to a RN {@link WritableMap}. Returns `null` if
703
+ * input is `null`. Unmapped fields (`fields`, `cats`) are set to `null`.
704
+ */
705
+ private fun responseWithHttpCodeToWritableMap(
706
+ data: DataClasses.ResponseWithHttpCode?
707
+ ): WritableMap? {
708
+ if (data == null) return null
709
+
710
+ val resp = data.response
711
+
712
+ return Arguments.createMap().apply root@{
713
+ putNullableInt(RnConstants.KEY_HTTP_CODE, data.httpCode)
714
+
715
+ if (resp == null) {
716
+ putNull(RnConstants.KEY_RESPONSE)
717
+ return@root
553
718
  }
554
719
 
555
- val sub = profile.subscription
556
- if (sub == null) {
557
- profileMap.putNull("subscription")
558
- } else {
559
- val subMap = Arguments.createMap()
720
+ val respMap =
721
+ Arguments.createMap().apply resp@{
722
+ putNullableInt(RnConstants.KEY_ERROR, resp.error)
723
+ putNullableString(RnConstants.KEY_ERROR_TEXT, resp.errorText)
560
724
 
561
- val subscriptionId = sub.subscriptionId
562
- if (subscriptionId != null) {
563
- subMap.putString("subscriptionId", subscriptionId)
564
- } else {
565
- subMap.putNull("subscriptionId")
566
- }
725
+ val profile = resp.profile
726
+ if (profile == null) {
727
+ putNull(RnConstants.KEY_PROFILE)
728
+ return@resp
729
+ }
567
730
 
568
- val hashId = sub.hashId
569
- if (hashId != null) {
570
- subMap.putString("hashId", hashId)
571
- } else {
572
- subMap.putNull("hashId")
573
- }
731
+ val profileMap =
732
+ Arguments.createMap().apply profile@{
733
+ putNullableString(RnConstants.KEY_ID, profile.id)
734
+ putNullableString(RnConstants.KEY_STATUS, profile.status)
735
+ putNullableBoolean(RnConstants.KEY_IS_TEST, profile.isTest)
736
+
737
+ val sub = profile.subscription
738
+ if (sub == null) {
739
+ putNull(RnConstants.KEY_SUBSCRIPTION)
740
+ return@profile
741
+ }
742
+
743
+ val subMap =
744
+ Arguments.createMap().apply sub@{
745
+ putNullableString(
746
+ RnConstants.KEY_SUBSCRIPTION_ID,
747
+ sub.subscriptionId
748
+ )
749
+ putNullableString(
750
+ RnConstants.KEY_HASH_ID,
751
+ sub.hashId
752
+ )
753
+ putNullableString(
754
+ RnConstants.KEY_PROVIDER,
755
+ sub.provider
756
+ )
757
+ putNullableString(
758
+ RnConstants.KEY_STATUS,
759
+ sub.status
760
+ )
761
+
762
+ putNull(RnConstants.KEY_FIELDS)
763
+ putNull(RnConstants.KEY_CATS)
764
+ }
765
+
766
+ putMap(RnConstants.KEY_SUBSCRIPTION, subMap)
767
+ }
768
+
769
+ putMap(RnConstants.KEY_PROFILE, profileMap)
770
+ }
574
771
 
575
- val provider = sub.provider
576
- if (provider != null) {
577
- subMap.putString("provider", provider)
578
- } else {
579
- subMap.putNull("provider")
580
- }
772
+ putMap(RnConstants.KEY_RESPONSE, respMap)
773
+ }
774
+ }
775
+
776
+ /**
777
+ * Stores a key-value pair in native persistent storage.
778
+ *
779
+ * Platform behavior:
780
+ * - iOS: uses UserDefaults (optionally scoped by `suiteName` / App Group).
781
+ * - Android: uses SharedPreferences; `suiteName` is used as preferences name.
782
+ *
783
+ * Supported value types:
784
+ * - primitives (Boolean, Number, String)
785
+ * - complex structures serialized as JSON string
786
+ * - `null` removes the stored value
787
+ *
788
+ * @param suiteName Storage namespace / suite name (platform-dependent).
789
+ * @param key Storage key.
790
+ * @param value Value to store or `null` to remove.
791
+ */
792
+ override fun setUserDefaultsValue(suiteName: String?, key: String, value: String?) {
793
+ val k = key.trim()
794
+ if (k.isEmpty()) return
581
795
 
582
- val subStatus = sub.status
583
- if (subStatus != null) {
584
- subMap.putString("status", subStatus)
585
- } else {
586
- subMap.putNull("status")
587
- }
796
+ val prefsName =
797
+ suiteName?.trim().takeUnless { it.isNullOrEmpty() }
798
+ ?: reactApplicationContext.packageName
588
799
 
589
- subMap.putNull("fields")
590
- subMap.putNull("cats")
800
+ val prefs =
801
+ reactApplicationContext.getSharedPreferences(
802
+ prefsName,
803
+ android.content.Context.MODE_PRIVATE
804
+ )
591
805
 
592
- profileMap.putMap("subscription", subMap)
593
- }
806
+ if (value == null) {
807
+ prefs.edit().remove(k).apply()
808
+ return
809
+ }
810
+
811
+ val v = value.trim()
812
+
813
+ // Store JSON as String (SharedPreferences has no native JSON type)
814
+ if ((v.startsWith("{") && v.endsWith("}")) || (v.startsWith("[") && v.endsWith("]"))) {
815
+ prefs.edit().putString(k, v).apply()
816
+ return
817
+ }
818
+
819
+ // Boolean
820
+ if (v.equals("true", ignoreCase = true) || v.equals("false", ignoreCase = true)) {
821
+ prefs.edit().putBoolean(k, v.equals("true", ignoreCase = true)).apply()
822
+ return
823
+ }
824
+
825
+ // Integer (Long)
826
+ v.toLongOrNull()?.let { asLong ->
827
+ prefs.edit().putLong(k, asLong).apply()
828
+ return
829
+ }
594
830
 
595
- respMap.putMap("profile", profileMap)
831
+ // Double -> keep precision as String
832
+ v.toDoubleOrNull()?.let {
833
+ prefs.edit().putString(k, v).apply()
834
+ return
596
835
  }
597
836
 
598
- root.putMap("response", respMap)
599
- return root
837
+ // Fallback: String
838
+ prefs.edit().putString(k, value).apply()
600
839
  }
601
840
 
602
841
  companion object {
603
- const val NAME: String = "Sdk"
842
+ const val NAME: String = RnConstants.MODULE_NAME
604
843
  }
605
844
  }
606
845
 
607
- /**
608
- * Internal RN initializer entry point.
609
- */
846
+ /** Internal RN initializer entry point. */
610
847
  internal object AltcraftRnInitializer {
611
848
 
612
- fun initialize(
613
- reactContext: ReactApplicationContext,
614
- config: ReadableMap,
615
- promise: Promise
616
- ) {
849
+ fun initialize(reactContext: ReactApplicationContext, config: ReadableMap, promise: Promise) {
617
850
  try {
618
851
  val configuration = AltcraftRnConfigMapper.buildConfiguration(config)
619
852
 
620
- AltcraftSDK.initialization(
621
- reactContext,
622
- configuration
623
- ) { result ->
853
+ AltcraftSDK.initialization(reactContext, configuration) { result ->
624
854
  reactContext.runOnUiQueueThread {
625
855
  if (result.isSuccess) {
626
856
  promise.resolve(null)
@@ -628,139 +858,92 @@ internal object AltcraftRnInitializer {
628
858
  val throwable = result.exceptionOrNull()
629
859
  if (throwable != null) {
630
860
  promise.reject(
631
- "ALTCRAFT_INIT_ERROR",
632
- throwable.message ?: "Altcraft initialization error",
633
- throwable
861
+ RnConstants.ERR_INIT_ERROR,
862
+ throwable.message ?: RnConstants.MSG_INIT_ERROR,
863
+ throwable
634
864
  )
635
865
  } else {
636
- promise.reject(
637
- "ALTCRAFT_INIT_ERROR",
638
- "Altcraft initialization failed with unknown error"
639
- )
866
+ promise.reject(RnConstants.ERR_INIT_ERROR, RnConstants.MSG_INIT_UNKNOWN)
640
867
  }
641
868
  }
642
869
  }
643
870
  }
644
871
  } catch (e: Exception) {
645
872
  promise.reject(
646
- "ALTCRAFT_INIT_INVALID_CONFIG",
647
- e.message ?: "Invalid Altcraft configuration",
648
- e
873
+ RnConstants.ERR_INIT_INVALID_CONFIG,
874
+ e.message ?: "Invalid Altcraft configuration",
875
+ e
649
876
  )
650
877
  }
651
878
  }
652
879
  }
653
880
 
654
- /**
655
- * Maps React Native configuration object to native [AltcraftConfiguration].
656
- */
881
+ /** Maps React Native configuration object to native [AltcraftConfiguration]. */
657
882
  internal object AltcraftRnConfigMapper {
658
883
 
884
+ private const val KEY_API_URL = "apiUrl"
885
+ private const val KEY_R_TOKEN = "rToken"
886
+ private const val KEY_APP_INFO = "appInfo"
887
+ private const val KEY_PROVIDER_PRIORITY_LIST = "providerPriorityList"
888
+ private const val KEY_ENABLE_LOGGING = "enableLogging"
889
+
890
+ private const val KEY_ANDROID_ICON = "android_icon"
891
+ private const val KEY_ANDROID_USING_SERVICE = "android_usingService"
892
+ private const val KEY_ANDROID_SERVICE_MESSAGE = "android_serviceMessage"
893
+ private const val KEY_ANDROID_PUSH_RECEIVER_MODULES = "android_pushReceiverModules"
894
+ private const val KEY_ANDROID_PUSH_CHANNEL_NAME = "android_pushChannelName"
895
+ private const val KEY_ANDROID_PUSH_CHANNEL_DESCRIPTION = "android_pushChannelDescription"
896
+
897
+ private const val KEY_APP_ID = "appID"
898
+ private const val KEY_APP_IID = "appIID"
899
+ private const val KEY_APP_VER = "appVer"
900
+
901
+ private const val MSG_API_URL_REQUIRED = "apiUrl is required for AltcraftConfiguration"
902
+ private const val MSG_API_URL_MUST_BE_STRING = "apiUrl must be a non-null string"
903
+
659
904
  fun buildConfiguration(config: ReadableMap): AltcraftConfiguration {
660
- if (!config.hasKey("apiUrl") || config.isNull("apiUrl")) {
661
- throw IllegalArgumentException("apiUrl is required for AltcraftConfiguration")
905
+ if (!config.hasNonNullKey(KEY_API_URL)) {
906
+ throw IllegalArgumentException(MSG_API_URL_REQUIRED)
662
907
  }
663
908
 
664
- val apiUrl = config.getString("apiUrl")
665
- ?: throw IllegalArgumentException("apiUrl must be a non-null string")
909
+ val apiUrl =
910
+ config.getString(KEY_API_URL)
911
+ ?: throw IllegalArgumentException(MSG_API_URL_MUST_BE_STRING)
666
912
 
667
- val rToken: String? =
668
- if (config.hasKey("rToken") && !config.isNull("rToken")) {
669
- config.getString("rToken")
670
- } else {
671
- null
672
- }
673
-
674
- val appInfo: DataClasses.AppInfo? =
675
- if (config.hasKey("appInfo") && !config.isNull("appInfo")) {
676
- val appInfoMap = config.getMap("appInfo")
677
- if (appInfoMap == null) {
678
- null
679
- } else {
680
- val appID =
681
- if (appInfoMap.hasKey("appID") && !appInfoMap.isNull("appID")) {
682
- appInfoMap.getString("appID") ?: ""
683
- } else ""
684
- val appIID =
685
- if (appInfoMap.hasKey("appIID") && !appInfoMap.isNull("appIID")) {
686
- appInfoMap.getString("appIID") ?: ""
687
- } else ""
688
- val appVer =
689
- if (appInfoMap.hasKey("appVer") && !appInfoMap.isNull("appVer")) {
690
- appInfoMap.getString("appVer") ?: ""
691
- } else ""
913
+ val rToken = config.getStringOrNull(KEY_R_TOKEN)
692
914
 
915
+ val appInfo =
916
+ config.getMapOrNull(KEY_APP_INFO)?.let { appInfoMap ->
917
+ val appID = appInfoMap.getStringOrNull(KEY_APP_ID) ?: ""
918
+ val appIID = appInfoMap.getStringOrNull(KEY_APP_IID) ?: ""
919
+ val appVer = appInfoMap.getStringOrNull(KEY_APP_VER) ?: ""
693
920
  DataClasses.AppInfo(appID = appID, appIID = appIID, appVer = appVer)
694
921
  }
695
- } else {
696
- null
697
- }
698
922
 
699
- val providerPriorityList: List<String>? =
700
- if (config.hasKey("providerPriorityList") && !config.isNull("providerPriorityList")) {
701
- val array = config.getArray("providerPriorityList")
702
- if (array == null) null else readableStringArrayToList(array)
703
- } else null
704
-
705
- val enableLogging: Boolean? =
706
- if (config.hasKey("enableLogging") && !config.isNull("enableLogging")) {
707
- config.getBoolean("enableLogging")
708
- } else null
709
-
710
- val icon: Int? =
711
- if (config.hasKey("android_icon") && !config.isNull("android_icon")) {
712
- config.getInt("android_icon")
713
- } else null
714
-
715
- val usingService: Boolean =
716
- if (config.hasKey("android_usingService") && !config.isNull("android_usingService")) {
717
- config.getBoolean("android_usingService")
718
- } else false
719
-
720
- val serviceMessage: String? =
721
- if (config.hasKey("android_serviceMessage") && !config.isNull("android_serviceMessage")) {
722
- config.getString("android_serviceMessage")
723
- } else null
724
-
725
- val pushReceiverModules: List<String>? =
726
- if (config.hasKey("android_pushReceiverModules") && !config.isNull("android_pushReceiverModules")) {
727
- val array = config.getArray("android_pushReceiverModules")
728
- if (array == null) null else readableStringArrayToList(array)
729
- } else null
730
-
731
- val pushChannelName: String? =
732
- if (config.hasKey("android_pushChannelName") && !config.isNull("android_pushChannelName")) {
733
- config.getString("android_pushChannelName")
734
- } else null
735
-
736
- val pushChannelDescription: String? =
737
- if (config.hasKey("android_pushChannelDescription") && !config.isNull("android_pushChannelDescription")) {
738
- config.getString("android_pushChannelDescription")
739
- } else null
923
+ val providerPriorityList = config.getArrayOrNull(KEY_PROVIDER_PRIORITY_LIST)?.toStringList()
924
+
925
+ val enableLogging = config.getBooleanOrNull(KEY_ENABLE_LOGGING)
926
+
927
+ val icon = config.getIntOrNull(KEY_ANDROID_ICON)
928
+
929
+ val pushReceiverModules =
930
+ config.getArrayOrNull(KEY_ANDROID_PUSH_RECEIVER_MODULES)?.toStringList()
931
+
932
+ val pushChannelName = config.getStringOrNull(KEY_ANDROID_PUSH_CHANNEL_NAME)
933
+
934
+ val pushChannelDescription = config.getStringOrNull(KEY_ANDROID_PUSH_CHANNEL_DESCRIPTION)
740
935
 
741
936
  return AltcraftConfiguration.Builder(
742
- apiUrl = apiUrl,
743
- icon = icon,
744
- rToken = rToken,
745
- usingService = usingService,
746
- serviceMessage = serviceMessage,
747
- appInfo = appInfo,
748
- providerPriorityList = providerPriorityList,
749
- pushReceiverModules = pushReceiverModules,
750
- pushChannelName = pushChannelName,
751
- pushChannelDescription = pushChannelDescription,
752
- enableLogging = enableLogging
753
- ).build()
754
- }
755
-
756
- private fun readableStringArrayToList(array: ReadableArray): List<String> {
757
- val result = ArrayList<String>()
758
- for (i in 0 until array.size()) {
759
- if (!array.isNull(i)) {
760
- val value = array.getString(i)
761
- if (value != null) result.add(value)
762
- }
763
- }
764
- return result
937
+ apiUrl = apiUrl,
938
+ icon = icon,
939
+ rToken = rToken,
940
+ appInfo = appInfo,
941
+ providerPriorityList = providerPriorityList,
942
+ pushReceiverModules = pushReceiverModules,
943
+ pushChannelName = pushChannelName,
944
+ pushChannelDescription = pushChannelDescription,
945
+ enableLogging = enableLogging
946
+ )
947
+ .build()
765
948
  }
766
949
  }