@altcraft/react-native-sdk 0.0.5 → 1.0.0

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