@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,206 +1,124 @@
1
- // SdkModule.swift
1
+ //
2
+ // SdkModule.swift
3
+ // AltcraftRnBridge
4
+ //
5
+ // Created by Andrey Pogodin.
6
+ //
7
+ // Copyright © 2026 Altcraft. All rights reserved.
8
+
9
+
2
10
  import Foundation
3
11
  import Altcraft
4
12
  import React
5
13
 
6
- /// React Native bridge module for Altcraft iOS SDK.
7
- ///
8
- /// Responsibilities:
9
- /// - Provide stable token provider references (JWT / FCM / HMS / APNs) that outlive individual RN calls.
10
- /// - Expose a single SDK initialization entry point matching Android bridge behavior.
11
- /// - Forward SDK events to JS via a single `RCTEventEmitter`.
12
- ///
13
- /// Thread-safety:
14
- /// - All mutable state is protected by `NSLock`.
15
- /// - Provider callbacks read token values under the same lock.
14
+ // MARK: - Sendable Box
15
+
16
+ private struct UncheckedSendableBox<T>: @unchecked Sendable {
17
+ let value: T
18
+ init(_ value: T) { self.value = value }
19
+ }
20
+
21
+ // MARK: - Constants
22
+
23
+ private enum RnConstants {
24
+
25
+ // Module / events
26
+ static let jsEventName: String = "AltcraftSdkEvent"
27
+
28
+ // Promise reject codes
29
+ static let errInitInvalidConfig: String = "ALTCRAFT_INIT_INVALID_CONFIG"
30
+ static let errInitError: String = "ALTCRAFT_INIT_ERROR"
31
+
32
+ // Promise reject messages
33
+ static let msgApiUrlRequired: String = "apiUrl is required"
34
+ static let msgInvalidConfiguration: String = "Invalid Altcraft configuration"
35
+ static let msgInitializationFailed: String = "Altcraft initialization failed"
36
+
37
+ // Config keys
38
+ static let keyApiUrl: String = "apiUrl"
39
+ static let keyRToken: String = "rToken"
40
+ static let keyEnableLogging: String = "enableLogging"
41
+ static let keyProviderPriorityList: String = "providerPriorityList"
42
+ static let keyAppInfo: String = "appInfo"
43
+
44
+ // TokenData keys
45
+ static let keyProvider: String = "provider"
46
+ static let keyToken: String = "token"
47
+
48
+ // SDK event payload keys
49
+ static let keyFunction: String = "function"
50
+ static let keyCode: String = "code"
51
+ static let keyMessage: String = "message"
52
+ static let keyType: String = "type"
53
+ static let keyValue: String = "value"
54
+
55
+ // Event types for JS
56
+ static let typeEvent: String = "event"
57
+ static let typeError: String = "error"
58
+ static let typeRetryError: String = "retryError"
59
+
60
+ // ResponseWithHttp mapping keys (outgoing)
61
+ static let keyHttpCode: String = "httpCode"
62
+ static let keyResponse: String = "response"
63
+ static let keyError: String = "error"
64
+ static let keyErrorText: String = "errorText"
65
+ static let keyProfile: String = "profile"
66
+ static let keyId: String = "id"
67
+ static let keyStatus: String = "status"
68
+ static let keyIsTest: String = "isTest"
69
+ static let keySubscription: String = "subscription"
70
+ static let keySubscriptionId: String = "subscriptionId"
71
+ static let keyHashId: String = "hashId"
72
+ static let keyFields: String = "fields"
73
+ static let keyCats: String = "cats"
74
+ }
75
+
76
+ // MARK: - Module
77
+
16
78
  @objc(SdkModule)
17
79
  @objcMembers
18
80
  @available(iOSApplicationExtension, unavailable)
19
- public final class SdkModule: NSObject {
81
+ public final class SdkModule: NSObject, @unchecked Sendable {
20
82
 
21
83
  // MARK: - Singleton & State
22
84
 
23
- /// Shared singleton instance used by the ObjC++ bridge.
85
+ /// Shared singleton instance used by the React Native bridge.
24
86
  public static let shared = SdkModule()
25
87
 
26
- /// Protects all mutable state in this module.
27
88
  private let lock = NSLock()
28
-
29
- /// Last configuration used to initialize the SDK.
30
89
  private var configuration: AltcraftConfiguration?
31
90
 
32
- // MARK: - JWT Provider
33
-
34
- /// Current JWT value used by `jwtProvider`. Access under `lock`.
35
- private var jwt: String?
36
-
37
- /// Indicates whether the JWT provider has been installed in the SDK.
38
- private var jwtProviderInstalled = false
39
-
40
- /// Stable JWT provider reference stored by the SDK for the process lifetime.
41
- private lazy var jwtProvider: RNJWTProvider = RNJWTProvider { [weak self] in
42
- guard let self else { return nil }
43
- self.lock.lock(); defer { self.lock.unlock() }
44
- return self.jwt
45
- }
46
-
47
- /// Installs JWT provider into the SDK once.
48
- private func installJWTProviderIfNeeded() {
49
- lock.lock()
50
- let alreadyInstalled = jwtProviderInstalled
51
- lock.unlock()
52
- if alreadyInstalled { return }
53
-
54
- AltcraftSDK.shared.setJWTProvider(provider: jwtProvider)
55
-
56
- lock.lock()
57
- jwtProviderInstalled = true
58
- lock.unlock()
59
- }
60
-
61
- /// Sets JWT token used by SDK requests.
62
- ///
63
- /// ObjC selector used by `Sdk.mm`: `setJWT:`
64
- @objc(setJWT:)
65
- public func setJWT(_ token: String?) {
66
- installJWTProviderIfNeeded()
67
- lock.lock()
68
- jwt = token
69
- lock.unlock()
70
- }
71
-
72
- // MARK: - App Group
73
-
74
- /// Sets the App Group identifier for shared storage.
75
- ///
76
- /// ObjC selector used by `Sdk.mm`: `setAppGroupWithName:`
77
- @objc(setAppGroupWithName:)
78
- public func setAppGroup(name: String?) {
79
- AltcraftSDK.shared.setAppGroup(groupName: name)
80
- }
81
-
82
- // MARK: - Push Tokens
83
-
84
- /// Stored push tokens used by token providers. Access under `lock`.
85
- private var fcm: String?
86
- private var hms: String?
87
- private var apns: String?
88
-
89
- // MARK: - Token Providers
90
-
91
- /// Indicates whether token providers have been installed in the SDK.
92
- private var tokenProvidersInstalled = false
93
-
94
- /// FCM provider backed by stored `fcm` token.
95
- private lazy var fcmProvider: RNFCMProvider = RNFCMProvider(
96
- get: { [weak self] completion in
97
- guard let self else { completion(nil); return }
98
- self.lock.lock(); defer { self.lock.unlock() }
99
- completion(self.fcm)
100
- },
101
- del: { [weak self] completion in
102
- guard let self else { completion(false); return }
103
- self.lock.lock()
104
- self.fcm = nil
105
- self.lock.unlock()
106
- completion(true)
107
- }
108
- )
109
-
110
- /// HMS provider backed by stored `hms` token.
111
- private lazy var hmsProvider: RNHMSProvider = RNHMSProvider(
112
- get: { [weak self] completion in
113
- guard let self else { completion(nil); return }
114
- self.lock.lock(); defer { self.lock.unlock() }
115
- completion(self.hms)
116
- },
117
- del: { [weak self] completion in
118
- guard let self else { completion(false); return }
119
- self.lock.lock()
120
- self.hms = nil
121
- self.lock.unlock()
122
- completion(true)
123
- }
124
- )
125
-
126
- /// APNs provider backed by stored `apns` token.
127
- private lazy var apnsProvider: RNAPNSProvider = RNAPNSProvider { [weak self] completion in
128
- guard let self else { completion(nil); return }
129
- self.lock.lock(); defer { self.lock.unlock() }
130
- completion(self.apns)
131
- }
132
-
133
- /// Ensures token providers are installed in the SDK once.
134
- public func ensureProvidersInstalled() {
135
- installTokenProvidersIfNeeded()
136
- }
137
-
138
- /// Installs token providers using a double-checked locking pattern.
139
- private func installTokenProvidersIfNeeded() {
140
- lock.lock()
141
- let alreadyInstalled = tokenProvidersInstalled
142
- lock.unlock()
143
- if alreadyInstalled { return }
144
-
145
- let push = AltcraftSDK.shared.pushTokenFunction
146
- push.setFCMTokenProvider(fcmProvider)
147
- push.setHMSTokenProvider(hmsProvider)
148
- push.setAPNSTokenProvider(apnsProvider)
149
-
150
- lock.lock()
151
- tokenProvidersInstalled = true
152
- lock.unlock()
153
- }
154
-
155
91
  // MARK: - SDK Initialization (RN Promise)
156
92
 
157
- /// Initializes Altcraft SDK using configuration received from React Native.
93
+ /// Initializes the Altcraft SDK using a React Native configuration object.
158
94
  ///
159
- /// Promise contract:
160
- /// - Resolves with `nil` on success.
161
- /// - Rejects with:
162
- /// - `ALTCRAFT_INIT_INVALID_CONFIG` when required fields are missing or config cannot be built.
163
- /// - `ALTCRAFT_INIT_ERROR` when SDK initialization reports failure.
95
+ /// The configuration dictionary supports:
96
+ /// - Required: `apiUrl` (String)
97
+ /// - Optional: `rToken` (String), `enableLogging` (Bool), `providerPriorityList` ([String]),
98
+ /// `appInfo` (Map with `appID`, `appIID`, `appVer`)
164
99
  ///
165
- /// Notes:
166
- /// - Token providers are installed before initialization.
100
+ /// - Parameters:
101
+ /// - config: React Native configuration map (`NSDictionary`).
102
+ /// - resolve: Promise resolver called with `nil` on success.
103
+ /// - reject: Promise rejecter called with an error code and message on failure.
167
104
  @objc(initializeWithConfig:resolver:rejecter:)
168
105
  public func initialize(
169
106
  _ config: NSDictionary,
170
107
  resolver resolve: @escaping RCTPromiseResolveBlock,
171
108
  rejecter reject: @escaping RCTPromiseRejectBlock
172
109
  ) {
173
- ensureProvidersInstalled()
174
-
175
- // Normalizes numbers/bools, parses JSON strings, and recursively converts nested structures.
176
110
  let dict: [String: Any?] = Converter.toAnyDict(config) ?? [:]
177
111
 
178
- guard let apiUrl = dict["apiUrl"] as? String, !apiUrl.isEmpty else {
179
- reject("ALTCRAFT_INIT_INVALID_CONFIG", "apiUrl is required", nil)
112
+ guard let apiUrl = dict[RnConstants.keyApiUrl] as? String, !apiUrl.isEmpty else {
113
+ reject(RnConstants.errInitInvalidConfig, RnConstants.msgApiUrlRequired, nil)
180
114
  return
181
115
  }
182
-
183
- let rToken = dict["rToken"] as? String
184
- let enableLogging = dict["enableLogging"] as? Bool
185
- let providerPriorityList = dict["providerPriorityList"] as? [String]
186
-
187
- var appInfo: AppInfo? = nil
188
- if let app = dict["appInfo"] as? [String: Any?] {
189
- let appID = (app["appID"] as? String) ?? ""
190
- let appIID = (app["appIID"] as? String) ?? ""
191
- let appVer = (app["appVer"] as? String) ?? ""
192
- if !appID.isEmpty || !appIID.isEmpty || !appVer.isEmpty {
193
- appInfo = AppInfo(appID: appID, appIID: appIID, appVer: appVer)
194
- }
195
- } else if let app = dict["appInfo"] as? [String: Any] {
196
- let appID = (app["appID"] as? String) ?? ""
197
- let appIID = (app["appIID"] as? String) ?? ""
198
- let appVer = (app["appVer"] as? String) ?? ""
199
- if !appID.isEmpty || !appIID.isEmpty || !appVer.isEmpty {
200
- appInfo = AppInfo(appID: appID, appIID: appIID, appVer: appVer)
201
- }
202
- }
203
-
116
+ let providerPriorityList = dict[RnConstants.keyProviderPriorityList] as? [String]
117
+ let appInfo = Converter.appInfo(from: dict[RnConstants.keyAppInfo] ?? nil)
118
+ let enableLogging = dict[RnConstants.keyEnableLogging] as? Bool
119
+ let rToken = dict[RnConstants.keyRToken] as? String
120
+
121
+
204
122
  guard let built = AltcraftConfiguration.Builder()
205
123
  .setApiUrl(apiUrl)
206
124
  .setRToken(rToken)
@@ -209,85 +127,104 @@ public final class SdkModule: NSObject {
209
127
  .setEnableLogging(enableLogging)
210
128
  .build()
211
129
  else {
212
- reject("ALTCRAFT_INIT_INVALID_CONFIG", "Invalid Altcraft configuration", nil)
130
+ reject(
131
+ RnConstants.errInitInvalidConfig,
132
+ RnConstants.msgInvalidConfiguration,
133
+ nil
134
+ )
213
135
  return
214
136
  }
215
137
 
216
138
  lock.lock()
217
- self.configuration = built
139
+ configuration = built
218
140
  lock.unlock()
219
141
 
142
+ let resolveBox = UncheckedSendableBox(resolve)
143
+ let rejectBox = UncheckedSendableBox(reject)
220
144
  AltcraftSDK.shared.initialization(configuration: built) { ok in
221
- if ok { resolve(nil) }
222
- else { reject("ALTCRAFT_INIT_ERROR", "Altcraft initialization failed", nil) }
145
+ if ok { resolveBox.value(nil) }
146
+ else {
147
+ rejectBox.value(
148
+ RnConstants.errInitError,
149
+ RnConstants.msgInitializationFailed, nil
150
+ )
151
+ }
223
152
  }
224
153
  }
225
154
 
226
155
  // MARK: - NativeEventEmitter compatibility
227
156
 
228
- /// Required by `NativeEventEmitter` (no-op on iOS).
157
+ /// Required by `NativeEventEmitter` on the JS side. No-op on iOS.
158
+ ///
159
+ /// - Parameter eventName: Event name from JS.
229
160
  public func addListener(_ eventName: String) { _ = eventName }
230
161
 
231
- /// Required by `NativeEventEmitter` (no-op on iOS).
162
+ /// Required by `NativeEventEmitter` on the JS side. No-op on iOS.
163
+ ///
164
+ /// - Parameter count: Number of listeners removed on JS side.
232
165
  public func removeListeners(_ count: NSNumber) { _ = count }
233
166
 
234
167
  // MARK: - RCTEventEmitter
235
168
 
236
- /// Event emitter used by RN to receive Altcraft SDK events.
237
- ///
238
- /// Emits: `"AltcraftSdkEvent"`.
239
169
  @objc(SDKEventEmitter)
240
- final class SDKEventEmitter: RCTEventEmitter {
241
-
242
- /// Active emitter instance created by React Native.
243
- private static weak var _shared: SDKEventEmitter?
170
+ final class SDKEventEmitter: RCTEventEmitter, @unchecked Sendable {
244
171
 
245
- /// Events buffered before React Native subscribes.
246
- private static var pending: [(String, Any?)] = []
172
+ nonisolated(unsafe) static var _shared: SDKEventEmitter?
173
+ nonisolated(unsafe) static var pending: [(String, Any?)] = []
247
174
  private static let pendingLock = NSLock()
248
175
 
176
+ /// Creates the event emitter instance and flushes any buffered events.
249
177
  override init() {
250
178
  super.init()
251
179
  SDKEventEmitter._shared = self
252
180
  SDKEventEmitter.flushPendingIfPossible()
253
181
  }
254
182
 
183
+ /// Returns the list of supported event names for React Native.
255
184
  override func supportedEvents() -> [String]! {
256
- ["AltcraftSdkEvent"]
185
+ [RnConstants.jsEventName]
257
186
  }
258
187
 
188
+ /// Indicates that this module must be initialized on the main thread.
259
189
  @objc override static func requiresMainQueueSetup() -> Bool {
260
190
  true
261
191
  }
262
192
 
263
- /// Emits a single integer code as an Altcraft event payload.
193
+ /// Emits an Altcraft event with an integer code to JS.
194
+ ///
195
+ /// - Parameter code: Event code.
264
196
  @objc static func emitAltcraft(code: Int) {
265
- emit(name: "AltcraftSdkEvent", body: ["code": code])
197
+ emit(name: RnConstants.jsEventName, body: [RnConstants.keyCode: code])
266
198
  }
267
199
 
268
- /// Sends an event to JS. If emitter is not ready, buffers it.
200
+ /// Emits an event to JS. If the emitter is not ready, the event is buffered.
201
+ ///
202
+ /// - Parameters:
203
+ /// - name: Event name.
204
+ /// - body: Event payload.
269
205
  @objc static func emit(name: String, body: Any?) {
270
- let deliver = {
206
+ let n = name
207
+ let b = body
208
+ let deliver: @convention(block) () -> Void = {
271
209
  if let emitter = _shared {
272
- emitter.sendEvent(withName: name, body: body)
210
+ emitter.sendEvent(withName: n, body: b)
273
211
  } else {
274
- buffer(name: name, body: body)
212
+ buffer(name: n, body: b)
275
213
  }
276
214
  }
277
215
 
278
- if Thread.isMainThread {
279
- deliver()
280
- } else {
281
- DispatchQueue.main.async { deliver() }
282
- }
216
+ if Thread.isMainThread { deliver() }
217
+ else { DispatchQueue.main.async(execute: deliver) }
283
218
  }
284
219
 
220
+ /// Buffers an event until the emitter becomes available.
285
221
  private static func buffer(name: String, body: Any?) {
286
222
  pendingLock.lock()
287
223
  pending.append((name, body))
288
224
  pendingLock.unlock()
289
225
  }
290
226
 
227
+ /// Flushes buffered events if the emitter is available, always on the main thread.
291
228
  private static func flushPendingIfPossible() {
292
229
  guard Thread.isMainThread else {
293
230
  DispatchQueue.main.async { flushPendingIfPossible() }
@@ -308,10 +245,11 @@ public final class SdkModule: NSObject {
308
245
 
309
246
  // MARK: - SDK Events subscription
310
247
 
311
- /// Indicates whether this module is currently subscribed to SDK events.
312
248
  private var eventsSubscribed: Bool = false
313
249
 
314
- /// Subscribes to SDK events and forwards them to JS.
250
+ /// Subscribes to native SDK events and forwards them to JS via the event emitter.
251
+ ///
252
+ /// Multiple calls are safe; the subscription is activated only once.
315
253
  public func subscribeToEvents() {
316
254
  lock.lock()
317
255
  let already = eventsSubscribed
@@ -321,11 +259,14 @@ public final class SdkModule: NSObject {
321
259
 
322
260
  SDKEvents.shared.subscribe { [weak self] event in
323
261
  guard let self else { return }
324
- SDKEventEmitter.emit(name: "AltcraftSdkEvent", body: self.toPayload(event))
262
+ SDKEventEmitter.emit(
263
+ name: RnConstants.jsEventName,
264
+ body: toPayload(event)
265
+ )
325
266
  }
326
267
  }
327
268
 
328
- /// Unsubscribes from SDK events.
269
+ /// Unsubscribes from native SDK events.
329
270
  public func unsubscribeFromEvent() {
330
271
  lock.lock()
331
272
  eventsSubscribed = false
@@ -335,203 +276,88 @@ public final class SdkModule: NSObject {
335
276
 
336
277
  // MARK: - Event payload mapping
337
278
 
338
- /// Converts an SDK `Event` into a JS-friendly payload.
279
+ /// Maps a native SDK event to a JS-friendly payload dictionary.
280
+ ///
281
+ /// - Parameter event: Native event.
282
+ /// - Returns: Dictionary containing `function`, `code`, `message`, `type`, and `value`.
339
283
  private func toPayload(_ event: Event) -> [String: Any] {
340
284
  let type: String
341
- if event is RetryEvent {
342
- type = "retryError"
343
- } else if event is ErrorEvent {
344
- type = "error"
345
- } else {
346
- type = "event"
347
- }
285
+ if event is RetryEvent { type = RnConstants.typeRetryError }
286
+ else if event is ErrorEvent { type = RnConstants.typeError }
287
+ else { type = RnConstants.typeEvent }
348
288
 
349
289
  return [
350
- "function": event.function,
351
- "code": event.eventCode as Any? ?? NSNull(),
352
- "message": event.message ?? "",
353
- "type": type,
354
- "value": Converter.toAny(event.value) ?? NSNull()
290
+ RnConstants.keyFunction: event.function,
291
+ RnConstants.keyCode: event.eventCode as Any? ?? NSNull(),
292
+ RnConstants.keyMessage: event.message ?? "",
293
+ RnConstants.keyType: type,
294
+ RnConstants.keyValue: Converter.toAny(event.value) ?? NSNull()
355
295
  ]
356
296
  }
357
297
 
358
- // MARK: - Token setters
359
-
360
- /// Sets (or clears) the stored FCM token and updates SDK provider registration.
361
- ///
362
- /// ObjC selector used by `Sdk.mm`: `setFCM:`
363
- @objc(setFCM:)
364
- public func setFCM(_ token: String?) {
365
- ensureProvidersInstalled()
366
- lock.lock(); fcm = token; lock.unlock()
367
-
368
- let push = AltcraftSDK.shared.pushTokenFunction
369
- if token == nil || token?.isEmpty == true {
370
- push.setFCMTokenProvider(nil)
371
- } else {
372
- push.setFCMTokenProvider(fcmProvider)
373
- }
374
- }
375
-
376
- /// Sets (or clears) the stored HMS token and updates SDK provider registration.
377
- ///
378
- /// ObjC selector used by `Sdk.mm`: `setHMS:`
379
- @objc(setHMS:)
380
- public func setHMS(_ token: String?) {
381
- ensureProvidersInstalled()
382
- lock.lock(); hms = token; lock.unlock()
383
-
384
- let push = AltcraftSDK.shared.pushTokenFunction
385
- if token == nil || token?.isEmpty == true {
386
- push.setHMSTokenProvider(nil)
387
- } else {
388
- push.setHMSTokenProvider(hmsProvider)
389
- }
390
- }
391
-
392
- /// Sets (or clears) the stored APNs token and updates SDK provider registration.
393
- ///
394
- /// ObjC selector used by `Sdk.mm`: `setAPNS:`
395
- @objc(setAPNS:)
396
- public func setAPNS(_ token: String?) {
397
- ensureProvidersInstalled()
398
- lock.lock(); apns = token; lock.unlock()
399
-
400
- let push = AltcraftSDK.shared.pushTokenFunction
401
- if token == nil || token?.isEmpty == true {
402
- push.setAPNSTokenProvider(nil)
403
- } else {
404
- push.setAPNSTokenProvider(apnsProvider)
405
- }
406
- }
407
-
408
298
  // MARK: - SDK Clear (RN Promise)
409
299
 
410
- /// Clears SDK state (tokens/subscriptions/cache depending on SDK implementation).
300
+ /// Clears SDK local state and stored data.
301
+ ///
302
+ /// - Parameters:
303
+ /// - resolve: Promise resolver called with `nil` when cleanup finishes.
304
+ /// - reject: Promise rejecter (unused; kept for RN signature compatibility).
411
305
  @objc(clearWithResolver:rejecter:)
412
306
  public func clear(
413
307
  resolver resolve: @escaping RCTPromiseResolveBlock,
414
308
  rejecter reject: @escaping RCTPromiseRejectBlock
415
309
  ) {
416
310
  _ = reject
417
- ensureProvidersInstalled()
418
311
  AltcraftSDK.shared.clear { resolve(nil) }
419
312
  }
420
313
 
421
- // MARK: - Token API wrappers
314
+ // MARK: - Token API wrappers (ONLY getPushToken / setPushToken)
422
315
 
423
- /// Returns the current push token from the SDK.
316
+ /// Returns the current push token data from the native SDK.
424
317
  ///
425
- /// - Parameter completion: Called with `{ provider, token }` or `nil` if not available.
318
+ /// - Parameter completion: Called with `{ provider, token }` or `nil` if unavailable.
426
319
  @objc(getPushTokenWithCompletion:)
427
320
  public func getPushToken(_ completion: @escaping ([String: Any]?) -> Void) {
428
- ensureProvidersInstalled()
429
- AltcraftSDK.shared.pushTokenFunction.getPushToken { tokenData in
430
- guard let tokenData else { completion(nil); return }
431
- completion([
432
- "provider": tokenData.provider,
433
- "token": tokenData.token
321
+ let completionBox = UncheckedSendableBox(completion)
322
+ AltcraftSDK.shared.pushTokenFunctions.getPushToken { tokenData in
323
+ guard let tokenData else { completionBox.value(nil); return }
324
+ completionBox.value([
325
+ RnConstants.keyProvider: tokenData.provider,
326
+ RnConstants.keyToken: tokenData.token
434
327
  ])
435
328
  }
436
329
  }
437
330
 
438
- /// Deletes device token for a supported provider.
331
+ /// Sets (or clears) the push token for a given provider.
439
332
  ///
440
333
  /// - Parameters:
441
- /// - provider: Provider name from JS (case-insensitive).
442
- /// - completion: `true` if a supported provider was handled, otherwise `false`.
443
- @objc(deleteDeviceTokenWithProvider:completion:)
444
- public func deleteDeviceToken(provider: String?, completion: @escaping (Bool) -> Void) {
445
- ensureProvidersInstalled()
446
-
447
- let p = (provider ?? "").lowercased()
448
-
449
- if p == Constants.ProviderName.firebase.lowercased() {
450
- AltcraftSDK.shared.pushTokenFunction.deleteDeviceToken(provider: Constants.ProviderName.firebase) {
451
- completion(true)
452
- }
453
- return
454
- }
455
-
456
- if p == Constants.ProviderName.huawei.lowercased() {
457
- AltcraftSDK.shared.pushTokenFunction.deleteDeviceToken(provider: Constants.ProviderName.huawei) {
458
- completion(true)
459
- }
460
- return
461
- }
462
-
463
- if p == Constants.ProviderName.apns.lowercased() {
464
- AltcraftSDK.shared.pushTokenFunction.deleteDeviceToken(provider: Constants.ProviderName.apns) {
465
- completion(true)
466
- }
467
- return
468
- }
469
-
470
- completion(false)
471
- }
472
-
473
- /// Forces push token update flow in the SDK.
474
- @objc(forcedTokenUpdateWithCompletion:)
475
- public func forcedTokenUpdate(_ completion: @escaping () -> Void) {
476
- ensureProvidersInstalled()
477
- AltcraftSDK.shared.pushTokenFunction.forcedTokenUpdate { completion() }
478
- }
479
-
480
- /// Updates push provider priority list.
481
- @objc(changePushProviderPriorityListWithList:completion:)
482
- public func changePushProviderPriorityList(_ list: [String]?, completion: @escaping (Bool) -> Void) {
483
- ensureProvidersInstalled()
484
- AltcraftSDK.shared.pushTokenFunction.changePushProviderPriorityList(list ?? [])
485
- completion(true)
486
- }
487
-
488
- /// Sets push token for a specific provider.
334
+ /// - provider: Provider identifier (e.g., `apns`, `fcm`).
335
+ /// - pushToken: Token value. `nil` / `NSNull` clears the token. Non-string values are stringified.
489
336
  @objc(setPushTokenWithProvider:pushToken:)
490
337
  public func setPushToken(provider: String, pushToken: Any?) {
491
- ensureProvidersInstalled()
492
- AltcraftSDK.shared.pushTokenFunction.setPushToken(provider: provider, pushToken: pushToken)
493
- }
494
-
495
- // MARK: - Push Subscription
338
+ let tokenStr: String? = {
339
+ if pushToken == nil || pushToken is NSNull { return nil }
340
+ if let s = pushToken as? String { return s }
341
+ return String(describing: pushToken!)
342
+ }()
496
343
 
497
- /// Converts `NSDictionary` into `[String: Any?]` with normalization.
498
- private func toAnyDict(_ dict: NSDictionary?) -> [String: Any?]? {
499
- Converter.toAnyDict(dict)
344
+ AltcraftSDK.shared.pushTokenFunctions.setPushToken(
345
+ provider: provider,
346
+ pushToken: (tokenStr ?? "")
347
+ )
500
348
  }
501
349
 
502
- /// Converts categories into native `[CategoryData]`.
503
- private func toCats(_ cats: NSArray?) -> [CategoryData]? {
504
- guard let arr = cats, arr.count > 0 else { return nil }
505
-
506
- var out: [CategoryData] = []
507
- out.reserveCapacity(arr.count)
508
-
509
- for item in arr {
510
- if let s = item as? String, !s.isEmpty {
511
- out.append(CategoryData(name: s, title: nil, steady: nil, active: true))
512
- continue
513
- }
514
-
515
- if let m = item as? NSDictionary {
516
- let mm = Converter.toAnyDict(m) ?? [:]
517
- let name = mm["name"] as? String
518
- let title = mm["title"] as? String
519
- let steady = mm["steady"] as? Bool
520
- let active = mm["active"] as? Bool
350
+ // MARK: - Push Subscription (void)
521
351
 
522
- if name != nil {
523
- out.append(CategoryData(name: name, title: title, steady: steady, active: active))
524
- }
525
- }
526
- }
527
-
528
- return out.isEmpty ? nil : out
529
- }
530
-
531
- /// Subscribes device/profile for push notifications.
352
+ /// Sends a push subscribe request (fire-and-forget).
532
353
  ///
533
- /// ObjC selector used by `Sdk.mm`:
534
- /// `pushSubscribe:profileFields:customFields:cats:replace:skipTriggers:`
354
+ /// - Parameters:
355
+ /// - sync: Execution mode. Defaults to `true` when `nil`.
356
+ /// - profileFields: Optional profile fields map.
357
+ /// - customFields: Optional custom fields map.
358
+ /// - cats: Optional categories array.
359
+ /// - replace: Optional replace flag.
360
+ /// - skipTriggers: Optional flag to skip trigger execution on the server.
535
361
  @objc(pushSubscribe:profileFields:customFields:cats:replace:skipTriggers:)
536
362
  public func pushSubscribe(
537
363
  _ sync: NSNumber?,
@@ -541,26 +367,29 @@ public final class SdkModule: NSObject {
541
367
  replace: NSNumber?,
542
368
  skipTriggers: NSNumber?
543
369
  ) {
544
- ensureProvidersInstalled()
545
-
546
370
  let s = sync?.boolValue ?? true
547
371
  let r: Bool? = (replace != nil) ? replace!.boolValue : nil
548
372
  let st: Bool? = (skipTriggers != nil) ? skipTriggers!.boolValue : nil
549
373
 
550
374
  AltcraftSDK.shared.pushSubscriptionFunctions.pushSubscribe(
551
375
  sync: s,
552
- profileFields: toAnyDict(profileFields),
553
- customFields: toAnyDict(customFields),
554
- cats: toCats(cats),
376
+ profileFields: Converter.toAnyDict(profileFields),
377
+ customFields: Converter.toAnyDict(customFields),
378
+ cats: Converter.toCats(cats),
555
379
  replace: r,
556
380
  skipTriggers: st
557
381
  )
558
382
  }
559
383
 
560
- /// Suspends current push subscription.
384
+ /// Sends a push suspend request (fire-and-forget).
561
385
  ///
562
- /// ObjC selector used by `Sdk.mm`:
563
- /// `pushSuspend:profileFields:customFields:cats:replace:skipTriggers:`
386
+ /// - Parameters:
387
+ /// - sync: Execution mode. Defaults to `true` when `nil`.
388
+ /// - profileFields: Optional profile fields map.
389
+ /// - customFields: Optional custom fields map.
390
+ /// - cats: Optional categories array.
391
+ /// - replace: Optional replace flag.
392
+ /// - skipTriggers: Optional flag to skip trigger execution on the server.
564
393
  @objc(pushSuspend:profileFields:customFields:cats:replace:skipTriggers:)
565
394
  public func pushSuspend(
566
395
  _ sync: NSNumber?,
@@ -570,26 +399,29 @@ public final class SdkModule: NSObject {
570
399
  replace: NSNumber?,
571
400
  skipTriggers: NSNumber?
572
401
  ) {
573
- ensureProvidersInstalled()
574
-
575
402
  let s = sync?.boolValue ?? true
576
403
  let r: Bool? = (replace != nil) ? replace!.boolValue : nil
577
404
  let st: Bool? = (skipTriggers != nil) ? skipTriggers!.boolValue : nil
578
405
 
579
406
  AltcraftSDK.shared.pushSubscriptionFunctions.pushSuspend(
580
407
  sync: s,
581
- profileFields: toAnyDict(profileFields),
582
- customFields: toAnyDict(customFields),
583
- cats: toCats(cats),
408
+ profileFields: Converter.toAnyDict(profileFields),
409
+ customFields: Converter.toAnyDict(customFields),
410
+ cats: Converter.toCats(cats),
584
411
  replace: r,
585
412
  skipTriggers: st
586
413
  )
587
414
  }
588
415
 
589
- /// Unsubscribes (disables) current push subscription.
416
+ /// Sends a push unsubscribe request (fire-and-forget).
590
417
  ///
591
- /// ObjC selector used by `Sdk.mm`:
592
- /// `pushUnSubscribe:profileFields:customFields:cats:replace:skipTriggers:`
418
+ /// - Parameters:
419
+ /// - sync: Execution mode. Defaults to `true` when `nil`.
420
+ /// - profileFields: Optional profile fields map.
421
+ /// - customFields: Optional custom fields map.
422
+ /// - cats: Optional categories array.
423
+ /// - replace: Optional replace flag.
424
+ /// - skipTriggers: Optional flag to skip trigger execution on the server.
593
425
  @objc(pushUnSubscribe:profileFields:customFields:cats:replace:skipTriggers:)
594
426
  public func pushUnSubscribe(
595
427
  _ sync: NSNumber?,
@@ -599,29 +431,35 @@ public final class SdkModule: NSObject {
599
431
  replace: NSNumber?,
600
432
  skipTriggers: NSNumber?
601
433
  ) {
602
- ensureProvidersInstalled()
603
-
604
434
  let s = sync?.boolValue ?? true
605
435
  let r: Bool? = (replace != nil) ? replace!.boolValue : nil
606
436
  let st: Bool? = (skipTriggers != nil) ? skipTriggers!.boolValue : nil
607
437
 
608
438
  AltcraftSDK.shared.pushSubscriptionFunctions.pushUnSubscribe(
609
439
  sync: s,
610
- profileFields: toAnyDict(profileFields),
611
- customFields: toAnyDict(customFields),
612
- cats: toCats(cats),
440
+ profileFields: Converter.toAnyDict(profileFields),
441
+ customFields: Converter.toAnyDict(customFields),
442
+ cats: Converter.toCats(cats),
613
443
  replace: r,
614
444
  skipTriggers: st
615
445
  )
616
446
  }
617
447
 
618
- // MARK: - Mobile Events
448
+ // MARK: - Mobile Events bridge
619
449
 
620
- /// Sends a mobile event to Altcraft via SDK.
450
+ /// Sends a mobile event to the server (fire-and-forget).
621
451
  ///
622
- /// ObjC selector used by `Sdk.mm`:
623
- /// `mobileEvent:eventName:sendMessageId:payload:matching:matchingType:profileFields:utm:`
624
- @objc(mobileEvent:eventName:sendMessageId:payload:matching:matchingType:profileFields:utm:)
452
+ /// - Parameters:
453
+ /// - sid: Pixel identifier.
454
+ /// - eventName: Event name.
455
+ /// - sendMessageId: Optional message identifier to link the event.
456
+ /// - payload: Optional event payload map.
457
+ /// - matching: Optional matching parameters map.
458
+ /// - matchingType: Optional matching type/mode.
459
+ /// - profileFields: Optional profile fields map.
460
+ /// - subscription: Optional subscription definition (email/sms/push/cc_data).
461
+ /// - utm: Optional UTM tags for attribution.
462
+ @objc(mobileEvent:eventName:sendMessageId:payload:matching:matchingType:profileFields:subscription:utm:)
625
463
  public func mobileEvent(
626
464
  _ sid: String,
627
465
  eventName: String,
@@ -630,153 +468,93 @@ public final class SdkModule: NSObject {
630
468
  matching: NSDictionary?,
631
469
  matchingType: String?,
632
470
  profileFields: NSDictionary?,
471
+ subscription: NSDictionary?,
633
472
  utm: NSDictionary?
634
473
  ) {
635
- ensureProvidersInstalled()
636
-
637
- let payloadNorm = toAnyDict(payload)
638
- let matchingNorm = toAnyDict(matching)
639
- let profileNorm = toAnyDict(profileFields)
640
- let utmNorm = Converter.toAnyDict(utm)
641
-
642
- let utmObj: UTM? = utmNorm.flatMap {
643
- UTM(
644
- campaign: $0["campaign"] as? String,
645
- content: $0["content"] as? String,
646
- keyword: $0["keyword"] as? String,
647
- medium: $0["medium"] as? String,
648
- source: $0["source"] as? String,
649
- temp: $0["temp"] as? String
650
- )
651
- }
474
+ let utmObj = Converter.toUTM(utm)
475
+ let subscriptionObj = Converter.toSubscription(subscription)
652
476
 
653
477
  AltcraftSDK.shared.mobileEventFunctions.mobileEvent(
654
478
  sid: sid,
655
479
  altcraftClientID: "",
656
480
  eventName: eventName,
657
481
  sendMessageId: sendMessageId,
658
- payload: payloadNorm,
659
- matching: matchingNorm,
482
+ payload: Converter.toAnyDict(payload),
483
+ matching: Converter.toAnyDict(matching),
660
484
  matchingType: matchingType,
661
- profileFields: profileNorm,
662
- subscription: nil,
485
+ profileFields: Converter.toAnyDict(profileFields),
486
+ subscription: subscriptionObj,
663
487
  utm: utmObj
664
488
  )
665
489
  }
666
490
 
667
491
  // MARK: - Promise API: PushSubscription status/results
668
492
 
669
- /// Converts `nil` to `NSNull()` for JS payloads.
670
493
  private func nsNull(_ v: Any?) -> Any { v ?? NSNull() }
671
494
 
672
- /// Converts `[String: Any?]` to `[String: String]`.
673
- private func toStringMap(_ dict: [String: Any?]?) -> [String: String]? {
674
- guard let dict, !dict.isEmpty else { return nil }
675
- var out: [String: String] = [:]
676
- out.reserveCapacity(dict.count)
677
- for (k, v) in dict {
678
- guard let v else { continue }
679
- out[k] = String(describing: v)
680
- }
681
- return out.isEmpty ? nil : out
682
- }
683
-
684
- private func mapCategory(_ c: CategoryData) -> [String: Any] {
685
- [
686
- "name": nsNull(c.name),
687
- "title": nsNull(c.title),
688
- "steady": nsNull(c.steady),
689
- "active": nsNull(c.active),
690
- ]
691
- }
692
-
693
- private func mapSubscription(_ s: SubscriptionData) -> [String: Any] {
694
- let fieldsString = toStringMap(s.fields)
695
- let catsArr: [[String: Any]]? = s.cats?.map { mapCategory($0) }
696
-
697
- return [
698
- "subscriptionId": nsNull(s.subscriptionId),
699
- "hashId": nsNull(s.hashId),
700
- "provider": nsNull(s.provider),
701
- "status": nsNull(s.status),
702
- "fields": nsNull(fieldsString),
703
- "cats": nsNull(catsArr),
704
- ]
705
- }
706
-
707
- private func mapProfile(_ p: ProfileData) -> [String: Any] {
708
- let subDict: [String: Any]? = p.subscription.map { mapSubscription($0) }
709
- return [
710
- "id": nsNull(p.id),
711
- "status": nsNull(p.status),
712
- "isTest": nsNull(p.isTest),
713
- "subscription": nsNull(subDict),
714
- ]
715
- }
716
-
717
- private func mapResponse(_ r: Response) -> [String: Any] {
718
- let profileDict: [String: Any]? = r.profile.map { mapProfile($0) }
719
- return [
720
- "error": nsNull(r.error),
721
- "errorText": nsNull(r.errorText),
722
- "profile": nsNull(profileDict),
723
- ]
724
- }
725
-
726
- private func mapResponseWithHttp(_ r: ResponseWithHttp) -> [String: Any] {
727
- let respDict: [String: Any]? = r.response.map { mapResponse($0) }
728
- return [
729
- "httpCode": nsNull(r.httpCode),
730
- "response": nsNull(respDict),
731
- ]
732
- }
733
-
734
- /// Attempts to un-suspend a push subscription.
495
+ /// Unsuspends push subscriptions based on native matching rules.
496
+ ///
497
+ /// - Parameters:
498
+ /// - resolve: Promise resolver called with a mapped `{ httpCode, response }` or `null`.
499
+ /// - reject: Promise rejecter (unused; kept for RN signature compatibility).
735
500
  @objc(unSuspendPushSubscriptionWithResolver:rejecter:)
736
501
  public func unSuspendPushSubscription(
737
502
  resolver resolve: @escaping RCTPromiseResolveBlock,
738
503
  rejecter reject: @escaping RCTPromiseRejectBlock
739
504
  ) {
505
+ let resolveBox = UncheckedSendableBox(resolve)
740
506
  _ = reject
741
- ensureProvidersInstalled()
742
-
743
- AltcraftSDK.shared.pushSubscriptionFunctions.unSuspendPushSubscription { result in
744
- guard let result else { resolve(NSNull()); return }
745
- resolve(self.mapResponseWithHttp(result))
507
+ AltcraftSDK.shared.pushSubscriptionFunctions.unSuspendPushSubscription { [weak self] result in
508
+ guard let self else { resolveBox.value(NSNull()); return }
509
+ guard let result else { resolveBox.value(NSNull()); return }
510
+ resolveBox.value(mapResponseWithHttp(result))
746
511
  }
747
512
  }
748
513
 
749
- /// Returns status of the latest subscription operation.
514
+ /// Returns the status of the latest subscription in profile.
515
+ ///
516
+ /// - Parameters:
517
+ /// - resolve: Promise resolver called with a mapped `{ httpCode, response }` or `null`.
518
+ /// - reject: Promise rejecter (unused; kept for RN signature compatibility).
750
519
  @objc(getStatusOfLatestSubscriptionWithResolver:rejecter:)
751
520
  public func getStatusOfLatestSubscription(
752
521
  resolver resolve: @escaping RCTPromiseResolveBlock,
753
522
  rejecter reject: @escaping RCTPromiseRejectBlock
754
523
  ) {
524
+ let resolveBox = UncheckedSendableBox(resolve)
755
525
  _ = reject
756
- ensureProvidersInstalled()
757
-
758
- AltcraftSDK.shared.pushSubscriptionFunctions.getStatusOfLatestSubscription { result in
759
- guard let result else { resolve(NSNull()); return }
760
- resolve(self.mapResponseWithHttp(result))
526
+ AltcraftSDK.shared.pushSubscriptionFunctions.getStatusOfLatestSubscription { [weak self] result in
527
+ guard let self else { resolveBox.value(NSNull()); return }
528
+ guard let result else { resolveBox.value(NSNull()); return }
529
+ resolveBox.value(mapResponseWithHttp(result))
761
530
  }
762
531
  }
763
532
 
764
- /// Returns status of the current subscription.
533
+ /// Returns the status for current subscription (by current provider/token context).
534
+ ///
535
+ /// - Parameters:
536
+ /// - resolve: Promise resolver called with a mapped `{ httpCode, response }` or `null`.
537
+ /// - reject: Promise rejecter (unused; kept for RN signature compatibility).
765
538
  @objc(getStatusForCurrentSubscriptionWithResolver:rejecter:)
766
539
  public func getStatusForCurrentSubscription(
767
540
  resolver resolve: @escaping RCTPromiseResolveBlock,
768
541
  rejecter reject: @escaping RCTPromiseRejectBlock
769
542
  ) {
543
+ let resolveBox = UncheckedSendableBox(resolve)
770
544
  _ = reject
771
- ensureProvidersInstalled()
772
-
773
- AltcraftSDK.shared.pushSubscriptionFunctions.getStatusForCurrentSubscription { result in
774
- guard let result else { resolve(NSNull()); return }
775
- resolve(self.mapResponseWithHttp(result))
545
+ AltcraftSDK.shared.pushSubscriptionFunctions.getStatusForCurrentSubscription { [weak self] result in
546
+ guard let self else { resolveBox.value(NSNull()); return }
547
+ guard let result else { resolveBox.value(NSNull()); return }
548
+ resolveBox.value(mapResponseWithHttp(result))
776
549
  }
777
550
  }
778
551
 
779
- /// Returns status of the latest subscription operation for a specific provider.
552
+ /// Returns the status of the latest subscription for the given provider.
553
+ ///
554
+ /// - Parameters:
555
+ /// - provider: Optional provider identifier.
556
+ /// - resolve: Promise resolver called with a mapped `{ httpCode, response }` or `null`.
557
+ /// - reject: Promise rejecter (unused; kept for RN signature compatibility).
780
558
  @objc(getStatusOfLatestSubscriptionForProviderWithProvider:resolver:rejecter:)
781
559
  public func getStatusOfLatestSubscriptionForProvider(
782
560
  provider: String?,
@@ -784,22 +562,102 @@ public final class SdkModule: NSObject {
784
562
  rejecter reject: @escaping RCTPromiseRejectBlock
785
563
  ) {
786
564
  _ = reject
787
- ensureProvidersInstalled()
565
+ let resolveBox = UncheckedSendableBox(resolve)
566
+ AltcraftSDK.shared.pushSubscriptionFunctions
567
+ .getStatusOfLatestSubscriptionForProvider(
568
+ provider: provider
569
+ ) { [weak self] result in
570
+ guard let self else { resolveBox.value(NSNull()); return }
571
+ guard let result else { resolveBox.value(NSNull()); return }
572
+ resolveBox.value(mapResponseWithHttp(result))
573
+ }
574
+ }
575
+
576
+ /// Maps a native `ResponseWithHttp` into a JS-friendly dictionary.
577
+ ///
578
+ /// - Parameter r: Response with HTTP object.
579
+ /// - Returns: Dictionary with HTTP code and response payload.
580
+ private func mapResponseWithHttp(_ r: ResponseWithHttp) -> [String: Any] {
581
+ let respDict: [String: Any]? = r.response.map { mapResponse($0) }
582
+ return [
583
+ RnConstants.keyHttpCode: nsNull(r.httpCode),
584
+ RnConstants.keyResponse: nsNull(respDict)
585
+ ]
586
+ }
788
587
 
789
- AltcraftSDK.shared.pushSubscriptionFunctions.getStatusOfLatestSubscriptionForProvider(provider: provider) { result in
790
- guard let result else { resolve(NSNull()); return }
791
- resolve(self.mapResponseWithHttp(result))
792
- }
588
+ /// Maps a native `Response` into a JS-friendly dictionary.
589
+ ///
590
+ /// - Parameter r: Response object.
591
+ /// - Returns: Dictionary with response fields.
592
+ private func mapResponse(_ r: Response) -> [String: Any] {
593
+ let profileDict: [String: Any]? = r.profile.map { mapProfile($0) }
594
+ return [
595
+ RnConstants.keyError: nsNull(r.error),
596
+ RnConstants.keyErrorText: nsNull(r.errorText),
597
+ RnConstants.keyProfile: nsNull(profileDict)
598
+ ]
599
+ }
600
+
601
+ /// Maps a native `ProfileData` into a JS-friendly dictionary.
602
+ ///
603
+ /// - Parameter p: Profile data.
604
+ /// - Returns: Dictionary with profile fields.
605
+ private func mapProfile(_ p: ProfileData) -> [String: Any] {
606
+ let subDict: [String: Any]? = p.subscription.map { mapSubscription($0) }
607
+ return [
608
+ RnConstants.keyId: nsNull(p.id),
609
+ RnConstants.keyStatus: nsNull(p.status),
610
+ RnConstants.keyIsTest: nsNull(p.isTest),
611
+ RnConstants.keySubscription: nsNull(subDict)
612
+ ]
613
+ }
614
+
615
+ /// Maps a native `SubscriptionData` into a JS-friendly dictionary.
616
+ ///
617
+ /// - Parameter s: Subscription data.
618
+ /// - Returns: Dictionary with subscription fields.
619
+ private func mapSubscription(_ s: SubscriptionData) -> [String: Any] {
620
+ let fieldsString = Converter.toStringMap(s.fields)
621
+ let catsArr: [[String: Any]]? = s.cats?.map { mapCategory($0) }
622
+ return [
623
+ RnConstants.keySubscriptionId: nsNull(s.subscriptionId),
624
+ RnConstants.keyHashId: nsNull(s.hashId),
625
+ RnConstants.keyProvider: nsNull(s.provider),
626
+ RnConstants.keyStatus: nsNull(s.status),
627
+ RnConstants.keyFields: nsNull(fieldsString),
628
+ RnConstants.keyCats: nsNull(catsArr)
629
+ ]
630
+ }
631
+
632
+ /// Maps a native `CategoryData` into a JS-friendly dictionary.
633
+ ///
634
+ /// - Parameter c: Category data.
635
+ /// - Returns: Dictionary with category fields.
636
+ private func mapCategory(_ c: CategoryData) -> [String: Any] {
637
+ [
638
+ "name": nsNull(c.name),
639
+ "title": nsNull(c.title),
640
+ "steady": nsNull(c.steady),
641
+ "active": nsNull(c.active)
642
+ ]
793
643
  }
794
644
 
795
645
  // MARK: - UserDefaults
796
646
 
797
- /// Stores a value into UserDefaults.
647
+ /// Stores a key-value pair in persistent storage.
648
+ ///
649
+ /// Platform behavior:
650
+ /// - iOS: Uses `UserDefaults` (optionally scoped by `suiteName` / App Group).
651
+ ///
652
+ /// Supported value types:
653
+ /// - Property list compatible values (Bool, Number, String, Data, Date, Arrays/Dictionaries of those)
654
+ /// - Complex values may be converted to a property list representation by `Converter`
655
+ /// - `nil`/`NSNull` removes the stored value
798
656
  ///
799
- /// - suiteName != nil: uses UserDefaults(suiteName:) (App Group)
800
- /// - suiteName == nil: uses UserDefaults.standard
801
- /// - nil/NSNull: removes the key
802
- /// - values are normalized and stored as property list types when possible
657
+ /// - Parameters:
658
+ /// - suiteName: Optional suite name (App Group) for scoped `UserDefaults`.
659
+ /// - key: Storage key (trimmed; empty keys are ignored).
660
+ /// - value: Value to store or `nil`/`NSNull` to remove.
803
661
  @objc(setUserDefaultsValueWithSuiteName:key:value:)
804
662
  public func setUserDefaultsValue(
805
663
  suiteName: String?,
@@ -826,4 +684,95 @@ public final class SdkModule: NSObject {
826
684
  ud.removeObject(forKey: k)
827
685
  }
828
686
  }
829
- }
687
+
688
+ // MARK: - Profile API
689
+
690
+ /// Updates profile fields on the server.
691
+ ///
692
+ /// - Parameters:
693
+ /// - profileFields: Optional profile fields map (primitives only).
694
+ /// - skipTriggers: Optional flag to skip trigger execution on the server.
695
+ @objc(updateProfileFields:skipTriggers:)
696
+ public func updateProfileFields(
697
+ _ profileFields: NSDictionary?,
698
+ skipTriggers: NSNumber?
699
+ ) {
700
+ let st: Bool? = (skipTriggers != nil) ? skipTriggers!.boolValue : nil
701
+ AltcraftSDK.shared.profileFunctions.updateProfileFields(
702
+ profileFields: Converter.toAnyDict(profileFields),
703
+ skipTriggers: st
704
+ )
705
+ }
706
+
707
+ // MARK: - Token management API
708
+
709
+ /// Forces a push token refresh (delete + re-register).
710
+ ///
711
+ /// - Parameters:
712
+ /// - resolve: Promise resolver called when the flow completes.
713
+ /// - reject: Promise rejecter (unused; kept for RN signature compatibility).
714
+ @objc(forcedTokenUpdateWithResolver:rejecter:)
715
+ public func forcedTokenUpdate(
716
+ resolver resolve: @escaping RCTPromiseResolveBlock,
717
+ rejecter reject: @escaping RCTPromiseRejectBlock
718
+ ) {
719
+ let resolveBox = UncheckedSendableBox(resolve)
720
+ _ = reject
721
+ AltcraftSDK.shared.pushTokenFunctions.forcedTokenUpdate {
722
+ resolveBox.value(nil)
723
+ }
724
+ }
725
+
726
+ /// Deletes the device token for a given provider.
727
+ ///
728
+ /// - Parameters:
729
+ /// - provider: Provider identifier (e.g. `ios-firebase`, `ios-huawei`).
730
+ /// - resolve: Promise resolver called when the delete call completes.
731
+ /// - reject: Promise rejecter (unused; kept for RN signature compatibility).
732
+ @objc(deleteDeviceTokenWithProvider:resolver:rejecter:)
733
+ public func deleteDeviceToken(
734
+ provider: String,
735
+ resolver resolve: @escaping RCTPromiseResolveBlock,
736
+ rejecter reject: @escaping RCTPromiseRejectBlock
737
+ ) {
738
+ let resolveBox = UncheckedSendableBox(resolve)
739
+ _ = reject
740
+ AltcraftSDK.shared.pushTokenFunctions.deleteDeviceToken(
741
+ provider: provider
742
+ ) {
743
+ resolveBox.value(nil)
744
+ }
745
+ }
746
+
747
+ /// Changes the push provider priority list at runtime.
748
+ ///
749
+ /// - Parameter priorityList: Ordered list of provider identifiers.
750
+ @objc(changePushProviderPriorityList:)
751
+ public func changePushProviderPriorityList(_ priorityList: NSArray) {
752
+ let list = priorityList.compactMap { $0 as? String }
753
+ AltcraftSDK.shared.pushTokenFunctions.changePushProviderPriorityList(list)
754
+ }
755
+
756
+ // MARK: - PushReceiver helpers
757
+
758
+ /// Checks whether a push payload belongs to Altcraft.
759
+ ///
760
+ /// - Parameter message: Push payload dictionary.
761
+ /// - Returns: `true` if the message contains the Altcraft marker key.
762
+ @objc(isAltcraftPush:)
763
+ public func isAltcraftPush(_ message: NSDictionary?) -> Bool {
764
+ guard let message else { return false }
765
+ return message["_ac_push"] != nil
766
+ }
767
+
768
+ // MARK: - App Group
769
+
770
+ /// Sets the App Group name for shared UserDefaults and Core Data.
771
+ /// Must be called before SDK initialization.
772
+ ///
773
+ /// - Parameter groupName: App Group identifier or `nil` to clear.
774
+ @objc(setAppGroup:)
775
+ public func setAppGroup(_ groupName: String?) {
776
+ AltcraftSDK.shared.setAppGroup(groupName: groupName)
777
+ }
778
+ }