@altcraft/react-native-sdk 0.0.1 → 0.0.2

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.
@@ -1,66 +1,55 @@
1
+ // SdkModule.swift
1
2
  import Foundation
2
3
  import Altcraft
3
4
  import React
4
5
 
5
- /// React Native bridge module for the Altcraft iOS SDK.
6
+ /// React Native bridge module for Altcraft iOS SDK.
6
7
  ///
7
- /// This module acts as the single integration point between JS and the native SDK. It provides:
8
- /// - Stable provider references (JWT / FCM / HMS / APNs) that must outlive individual RN calls.
9
- /// - A single SDK initialization entry point (`initialize(...)`) matching the Android bridge behavior.
10
- /// - A single subscriber model for SDK events, forwarded to JS via NotificationCenter.
11
- /// - Thin wrappers around token APIs, subscription APIs, and mobile event APIs.
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
12
  ///
13
13
  /// Thread-safety:
14
- /// - Internal mutable state is protected by `NSLock`.
15
- /// - Provider closures read token values under the same lock.
16
- ///
17
- /// Notes:
18
- /// - Exceptions are not propagated to JS. Errors are mapped to promise rejections only where required.
19
- /// - Providers are installed once per process lifetime to keep stable references inside the SDK.
14
+ /// - All mutable state is protected by `NSLock`.
15
+ /// - Provider callbacks read token values under the same lock.
20
16
  @objc(SdkModule)
21
17
  @objcMembers
22
18
  @available(iOSApplicationExtension, unavailable)
23
19
  public final class SdkModule: NSObject {
24
20
 
21
+ // MARK: - Singleton & State
22
+
25
23
  /// Shared singleton instance used by the ObjC++ bridge.
26
24
  public static let shared = SdkModule()
27
25
 
28
- /// A single lock protecting all mutable state in this module.
26
+ /// Protects all mutable state in this module.
29
27
  private let lock = NSLock()
30
28
 
31
- // MARK: - JWT (stable provider reference)
29
+ /// Last configuration used to initialize the SDK.
30
+ private var configuration: AltcraftConfiguration?
32
31
 
33
- /// Current JWT value used by `jwtProvider`.
34
- ///
35
- /// Access must be protected by `lock`.
32
+ // MARK: - JWT Provider
33
+
34
+ /// Current JWT value used by `jwtProvider`. Access under `lock`.
36
35
  private var jwt: String?
37
36
 
38
- /// Stable JWT provider reference.
39
- ///
40
- /// The SDK keeps a strong reference to the provider, therefore this object must live
41
- /// for the entire process lifetime. The provider reads `jwt` under `lock`.
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.
42
41
  private lazy var jwtProvider: RNJWTProvider = RNJWTProvider { [weak self] in
43
42
  guard let self else { return nil }
44
43
  self.lock.lock(); defer { self.lock.unlock() }
45
44
  return self.jwt
46
45
  }
47
46
 
48
- /// Indicates whether the JWT provider has been registered in the SDK.
49
- ///
50
- /// Access must be protected by `lock`.
51
- private var jwtProviderInstalled = false
52
-
53
- /// Registers `jwtProvider` in the SDK exactly once.
54
- ///
55
- /// Uses a double-checked locking pattern:
56
- /// - fast path avoids locking when already installed
57
- /// - slow path installs provider and flips the flag under lock
47
+ /// Installs JWT provider into the SDK once.
58
48
  private func installJWTProviderIfNeeded() {
59
- // double-checked locking pattern (cheap fast-path)
60
49
  lock.lock()
61
- let already = jwtProviderInstalled
50
+ let alreadyInstalled = jwtProviderInstalled
62
51
  lock.unlock()
63
- if already { return }
52
+ if alreadyInstalled { return }
64
53
 
65
54
  AltcraftSDK.shared.setJWTProvider(provider: jwtProvider)
66
55
 
@@ -69,13 +58,9 @@ public final class SdkModule: NSObject {
69
58
  lock.unlock()
70
59
  }
71
60
 
72
- /// Sets JWT token for requests performed by the Altcraft SDK.
61
+ /// Sets JWT token used by SDK requests.
73
62
  ///
74
63
  /// ObjC selector used by `Sdk.mm`: `setJWT:`
75
- ///
76
- /// Behavior:
77
- /// - Ensures the stable provider is installed once.
78
- /// - Updates the stored JWT value (provider will start returning the new token).
79
64
  @objc(setJWT:)
80
65
  public func setJWT(_ token: String?) {
81
66
  installJWTProviderIfNeeded()
@@ -84,33 +69,29 @@ public final class SdkModule: NSObject {
84
69
  lock.unlock()
85
70
  }
86
71
 
87
- // MARK: - AppGroup
72
+ // MARK: - App Group
88
73
 
89
- /// Sets the App Group identifier for shared storage (Core Data + UserDefaults/App Group).
74
+ /// Sets the App Group identifier for shared storage.
90
75
  ///
91
76
  /// ObjC selector used by `Sdk.mm`: `setAppGroupWithName:`
92
- ///
93
- /// Call this before operations that rely on a shared container.
94
77
  @objc(setAppGroupWithName:)
95
78
  public func setAppGroup(name: String?) {
96
79
  AltcraftSDK.shared.setAppGroup(groupName: name)
97
80
  }
98
81
 
99
- // MARK: - Tokens / Config
82
+ // MARK: - Push Tokens
100
83
 
101
- /// Stored push tokens used by token providers. Access guarded by `lock`.
84
+ /// Stored push tokens used by token providers. Access under `lock`.
102
85
  private var fcm: String?
103
86
  private var hms: String?
104
87
  private var apns: String?
105
88
 
106
- /// Last built configuration used to initialize the SDK.
107
- /// Stored for debugging/inspection purposes.
108
- private var configuration: AltcraftConfiguration?
89
+ // MARK: - Token Providers
109
90
 
110
- /// Stable FCM provider reference created once and reused.
111
- ///
112
- /// - `get` returns the current token under lock.
113
- /// - `del` clears the token under lock.
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.
114
95
  private lazy var fcmProvider: RNFCMProvider = RNFCMProvider(
115
96
  get: { [weak self] completion in
116
97
  guard let self else { completion(nil); return }
@@ -119,15 +100,14 @@ public final class SdkModule: NSObject {
119
100
  },
120
101
  del: { [weak self] completion in
121
102
  guard let self else { completion(false); return }
122
- self.lock.lock(); self.fcm = nil; self.lock.unlock()
103
+ self.lock.lock()
104
+ self.fcm = nil
105
+ self.lock.unlock()
123
106
  completion(true)
124
107
  }
125
108
  )
126
109
 
127
- /// Stable HMS provider reference created once and reused.
128
- ///
129
- /// - `get` returns the current token under lock.
130
- /// - `del` clears the token under lock.
110
+ /// HMS provider backed by stored `hms` token.
131
111
  private lazy var hmsProvider: RNHMSProvider = RNHMSProvider(
132
112
  get: { [weak self] completion in
133
113
  guard let self else { completion(nil); return }
@@ -136,48 +116,31 @@ public final class SdkModule: NSObject {
136
116
  },
137
117
  del: { [weak self] completion in
138
118
  guard let self else { completion(false); return }
139
- self.lock.lock(); self.hms = nil; self.lock.unlock()
119
+ self.lock.lock()
120
+ self.hms = nil
121
+ self.lock.unlock()
140
122
  completion(true)
141
123
  }
142
124
  )
143
125
 
144
- /// Stable APNs provider reference created once and reused.
145
- ///
146
- /// APNs token is read under lock and returned through completion.
126
+ /// APNs provider backed by stored `apns` token.
147
127
  private lazy var apnsProvider: RNAPNSProvider = RNAPNSProvider { [weak self] completion in
148
128
  guard let self else { completion(nil); return }
149
129
  self.lock.lock(); defer { self.lock.unlock() }
150
130
  completion(self.apns)
151
131
  }
152
132
 
153
- /// Indicates whether token providers have been registered in the SDK.
154
- private var tokenProvidersInstalled = false
155
-
156
- // ---- Events (single subscriber like Android) ----
157
-
158
- /// Indicates whether the module is currently subscribed to SDK events.
159
- ///
160
- /// This is a guard to keep the subscription single (idempotent subscribe/unsubscribe).
161
- private var eventsSubscribed: Bool = false
162
-
163
- // MARK: - Install providers once (App module only)
164
-
165
- /// Ensures all token providers are installed in the SDK.
166
- ///
167
- /// This is called from initialization and from token setters to guarantee the SDK
168
- /// always has stable references.
133
+ /// Ensures token providers are installed in the SDK once.
169
134
  public func ensureProvidersInstalled() {
170
135
  installTokenProvidersIfNeeded()
171
136
  }
172
137
 
173
- /// Registers token providers (FCM/HMS/APNs) in the SDK exactly once.
174
- ///
175
- /// Uses a double-checked locking pattern to avoid repeated work.
138
+ /// Installs token providers using a double-checked locking pattern.
176
139
  private func installTokenProvidersIfNeeded() {
177
140
  lock.lock()
178
- let already = tokenProvidersInstalled
141
+ let alreadyInstalled = tokenProvidersInstalled
179
142
  lock.unlock()
180
- if already { return }
143
+ if alreadyInstalled { return }
181
144
 
182
145
  let push = AltcraftSDK.shared.pushTokenFunction
183
146
  push.setFCMTokenProvider(fcmProvider)
@@ -189,18 +152,18 @@ public final class SdkModule: NSObject {
189
152
  lock.unlock()
190
153
  }
191
154
 
192
- // MARK: - ✅ RN init (ONLY initialize)
155
+ // MARK: - SDK Initialization (RN Promise)
193
156
 
194
157
  /// Initializes Altcraft SDK using configuration received from React Native.
195
158
  ///
196
- /// Contract:
159
+ /// Promise contract:
197
160
  /// - Resolves with `nil` on success.
198
161
  /// - Rejects with:
199
- /// - `ALTCRAFT_INIT_INVALID_CONFIG` when required fields are missing or configuration build fails.
162
+ /// - `ALTCRAFT_INIT_INVALID_CONFIG` when required fields are missing or config cannot be built.
200
163
  /// - `ALTCRAFT_INIT_ERROR` when SDK initialization reports failure.
201
164
  ///
202
165
  /// Notes:
203
- /// - Providers are installed before initialization to ensure stable references.
166
+ /// - Token providers are installed before initialization.
204
167
  @objc(initializeWithConfig:resolver:rejecter:)
205
168
  public func initialize(
206
169
  _ config: NSDictionary,
@@ -209,7 +172,8 @@ public final class SdkModule: NSObject {
209
172
  ) {
210
173
  ensureProvidersInstalled()
211
174
 
212
- let dict = config as? [String: Any] ?? [:]
175
+ // Normalizes numbers/bools, parses JSON strings, and recursively converts nested structures.
176
+ let dict: [String: Any?] = Converter.toAnyDict(config) ?? [:]
213
177
 
214
178
  guard let apiUrl = dict["apiUrl"] as? String, !apiUrl.isEmpty else {
215
179
  reject("ALTCRAFT_INIT_INVALID_CONFIG", "apiUrl is required", nil)
@@ -221,7 +185,14 @@ public final class SdkModule: NSObject {
221
185
  let providerPriorityList = dict["providerPriorityList"] as? [String]
222
186
 
223
187
  var appInfo: AppInfo? = nil
224
- if let app = dict["appInfo"] as? [String: Any] {
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] {
225
196
  let appID = (app["appID"] as? String) ?? ""
226
197
  let appIID = (app["appIID"] as? String) ?? ""
227
198
  let appVer = (app["appVer"] as? String) ?? ""
@@ -252,28 +223,95 @@ public final class SdkModule: NSObject {
252
223
  }
253
224
  }
254
225
 
255
- // MARK: - ✅ NativeEventEmitter support (no-op)
226
+ // MARK: - NativeEventEmitter compatibility
256
227
 
257
- /// Required by `NativeEventEmitter` contract on the JS side.
258
- ///
259
- /// iOS bridge uses NotificationCenter forwarding instead, so this is a no-op.
228
+ /// Required by `NativeEventEmitter` (no-op on iOS).
260
229
  public func addListener(_ eventName: String) { _ = eventName }
261
230
 
262
- /// Required by `NativeEventEmitter` contract on the JS side.
263
- ///
264
- /// iOS bridge uses NotificationCenter forwarding instead, so this is a no-op.
231
+ /// Required by `NativeEventEmitter` (no-op on iOS).
265
232
  public func removeListeners(_ count: NSNumber) { _ = count }
266
233
 
267
- // MARK: - ✅ Events API (called from Sdk.mm)
234
+ // MARK: - RCTEventEmitter
268
235
 
269
- /// Subscribes to native SDK events and forwards them to JS.
270
- ///
271
- /// Single-subscription behavior:
272
- /// - Multiple calls are safe (idempotent).
273
- /// - Events are emitted via NotificationCenter using `.altcraftSdkEventNotification`.
236
+ /// Event emitter used by RN to receive Altcraft SDK events.
274
237
  ///
275
- /// Notes:
276
- /// - The actual event source is `SDKEvents.shared`, consistent with the native SDK event bus.
238
+ /// Emits: `"AltcraftSdkEvent"`.
239
+ @objc(SDKEventEmitter)
240
+ final class SDKEventEmitter: RCTEventEmitter {
241
+
242
+ /// Active emitter instance created by React Native.
243
+ private static weak var _shared: SDKEventEmitter?
244
+
245
+ /// Events buffered before React Native subscribes.
246
+ private static var pending: [(String, Any?)] = []
247
+ private static let pendingLock = NSLock()
248
+
249
+ override init() {
250
+ super.init()
251
+ SDKEventEmitter._shared = self
252
+ SDKEventEmitter.flushPendingIfPossible()
253
+ }
254
+
255
+ override func supportedEvents() -> [String]! {
256
+ ["AltcraftSdkEvent"]
257
+ }
258
+
259
+ @objc override static func requiresMainQueueSetup() -> Bool {
260
+ true
261
+ }
262
+
263
+ /// Emits a single integer code as an Altcraft event payload.
264
+ @objc static func emitAltcraft(code: Int) {
265
+ emit(name: "AltcraftSdkEvent", body: ["code": code])
266
+ }
267
+
268
+ /// Sends an event to JS. If emitter is not ready, buffers it.
269
+ @objc static func emit(name: String, body: Any?) {
270
+ let deliver = {
271
+ if let emitter = _shared {
272
+ emitter.sendEvent(withName: name, body: body)
273
+ } else {
274
+ buffer(name: name, body: body)
275
+ }
276
+ }
277
+
278
+ if Thread.isMainThread {
279
+ deliver()
280
+ } else {
281
+ DispatchQueue.main.async { deliver() }
282
+ }
283
+ }
284
+
285
+ private static func buffer(name: String, body: Any?) {
286
+ pendingLock.lock()
287
+ pending.append((name, body))
288
+ pendingLock.unlock()
289
+ }
290
+
291
+ private static func flushPendingIfPossible() {
292
+ guard Thread.isMainThread else {
293
+ DispatchQueue.main.async { flushPendingIfPossible() }
294
+ return
295
+ }
296
+ guard let emitter = _shared else { return }
297
+
298
+ pendingLock.lock()
299
+ let toSend = pending
300
+ pending.removeAll()
301
+ pendingLock.unlock()
302
+
303
+ for (name, body) in toSend {
304
+ emitter.sendEvent(withName: name, body: body)
305
+ }
306
+ }
307
+ }
308
+
309
+ // MARK: - SDK Events subscription
310
+
311
+ /// Indicates whether this module is currently subscribed to SDK events.
312
+ private var eventsSubscribed: Bool = false
313
+
314
+ /// Subscribes to SDK events and forwards them to JS.
277
315
  public func subscribeToEvents() {
278
316
  lock.lock()
279
317
  let already = eventsSubscribed
@@ -281,123 +319,47 @@ public final class SdkModule: NSObject {
281
319
  lock.unlock()
282
320
  if already { return }
283
321
 
284
- // Subscribe to native SDK events emitted through SDKEvents.shared.emit(event:)
285
- SDKEvents.shared.subscribe { [weak self] ev in
322
+ SDKEvents.shared.subscribe { [weak self] event in
286
323
  guard let self else { return }
287
-
288
- print("[AltcraftSdk] \(ev.eventCode ?? 0)")
289
-
290
- // If unsubscribed meanwhile — ignore
291
- self.lock.lock()
292
- let subscribed = self.eventsSubscribed
293
- self.lock.unlock()
294
- if !subscribed { return }
295
-
296
- let payload = self.mapSdkEventToJs(ev)
297
- NotificationCenter.default.post(
298
- name: .altcraftSdkEventNotification,
299
- object: nil,
300
- userInfo: payload
301
- )
324
+ SDKEventEmitter.emit(name: "AltcraftSdkEvent", body: self.toPayload(event))
302
325
  }
303
326
  }
304
327
 
305
- /// Unsubscribes from the SDK event stream.
306
- ///
307
- /// After this call, events are no longer forwarded to JS.
328
+ /// Unsubscribes from SDK events.
308
329
  public func unsubscribeFromEvent() {
309
330
  lock.lock()
310
331
  eventsSubscribed = false
311
332
  lock.unlock()
312
-
313
333
  SDKEvents.shared.unsubscribe()
314
334
  }
315
335
 
316
- /// Maps a native SDK event into a JS-friendly payload.
317
- ///
318
- /// Output schema (matches Android bridge):
319
- /// - function: String
320
- /// - code: Int | null
321
- /// - message: String
322
- /// - type: "event" | "error" | "retryError"
323
- /// - value: Object | null
324
- private func mapSdkEventToJs(_ ev: Event) -> [String: Any] {
325
- let message = ev.message ?? String(describing: ev)
326
- let code: Any = ev.eventCode.map { $0 } ?? NSNull()
336
+ // MARK: - Event payload mapping
327
337
 
338
+ /// Converts an SDK `Event` into a JS-friendly payload.
339
+ private func toPayload(_ event: Event) -> [String: Any] {
328
340
  let type: String
329
- if ev is RetryEvent {
341
+ if event is RetryEvent {
330
342
  type = "retryError"
331
- } else if ev is ErrorEvent {
343
+ } else if event is ErrorEvent {
332
344
  type = "error"
333
345
  } else {
334
346
  type = "event"
335
347
  }
336
348
 
337
- let valueObj: Any
338
- if let v = ev.value, !v.isEmpty {
339
- valueObj = sanitizeToJsObject(v)
340
- } else {
341
- valueObj = NSNull()
342
- }
343
-
344
349
  return [
345
- "function": ev.function,
346
- "code": code,
347
- "message": message,
350
+ "function": event.function,
351
+ "code": event.eventCode as Any? ?? NSNull(),
352
+ "message": event.message ?? "",
348
353
  "type": type,
349
- "value": valueObj
354
+ "value": Converter.toAny(event.value) ?? NSNull()
350
355
  ]
351
356
  }
352
357
 
353
- /// Converts a Swift dictionary into an `NSDictionary` suitable for React Native.
354
- ///
355
- /// All values are sanitized to supported JS types.
356
- private func sanitizeToJsObject(_ dict: [String: Any]) -> NSDictionary {
357
- let out = NSMutableDictionary(capacity: dict.count)
358
- for (k, v) in dict {
359
- out[k] = sanitizeAnyToJs(v)
360
- }
361
- return out
362
- }
363
-
364
- /// Sanitizes an arbitrary Swift value into a JS-compatible representation.
365
- ///
366
- /// Supported output types:
367
- /// - `NSString` / `NSNumber` / `NSNull`
368
- /// - `NSArray` / `NSDictionary` (recursively sanitized)
369
- ///
370
- /// Unsupported values are stringified via `String(describing:)`.
371
- private func sanitizeAnyToJs(_ v: Any) -> Any {
372
- if v is NSNull { return NSNull() }
373
-
374
- if let s = v as? String { return s }
375
- if let n = v as? NSNumber { return n }
376
- if let b = v as? Bool { return NSNumber(value: b) }
377
- if let i = v as? Int { return NSNumber(value: i) }
378
- if let d = v as? Double { return NSNumber(value: d) }
379
- if let f = v as? Float { return NSNumber(value: Double(f)) }
380
-
381
- if let arr = v as? [Any] {
382
- return arr.map { sanitizeAnyToJs($0) }
383
- }
384
-
385
- if let m = v as? [String: Any] {
386
- return sanitizeToJsObject(m)
387
- }
388
-
389
- return String(describing: v)
390
- }
391
-
392
- // MARK: - Token setters (App module)
358
+ // MARK: - Token setters
393
359
 
394
360
  /// Sets (or clears) the stored FCM token and updates SDK provider registration.
395
361
  ///
396
362
  /// ObjC selector used by `Sdk.mm`: `setFCM:`
397
- ///
398
- /// Behavior:
399
- /// - If `token` is nil/empty: provider is unregistered (SDK won't request FCM token).
400
- /// - Otherwise: provider remains registered and will supply the token.
401
363
  @objc(setFCM:)
402
364
  public func setFCM(_ token: String?) {
403
365
  ensureProvidersInstalled()
@@ -414,10 +376,6 @@ public final class SdkModule: NSObject {
414
376
  /// Sets (or clears) the stored HMS token and updates SDK provider registration.
415
377
  ///
416
378
  /// ObjC selector used by `Sdk.mm`: `setHMS:`
417
- ///
418
- /// Behavior:
419
- /// - If `token` is nil/empty: provider is unregistered.
420
- /// - Otherwise: provider remains registered and will supply the token.
421
379
  @objc(setHMS:)
422
380
  public func setHMS(_ token: String?) {
423
381
  ensureProvidersInstalled()
@@ -434,10 +392,6 @@ public final class SdkModule: NSObject {
434
392
  /// Sets (or clears) the stored APNs token and updates SDK provider registration.
435
393
  ///
436
394
  /// ObjC selector used by `Sdk.mm`: `setAPNS:`
437
- ///
438
- /// Behavior:
439
- /// - If `token` is nil/empty: provider is unregistered.
440
- /// - Otherwise: provider remains registered and will supply the token.
441
395
  @objc(setAPNS:)
442
396
  public func setAPNS(_ token: String?) {
443
397
  ensureProvidersInstalled()
@@ -451,26 +405,22 @@ public final class SdkModule: NSObject {
451
405
  }
452
406
  }
453
407
 
454
- // MARK: - clear
408
+ // MARK: - SDK Clear (RN Promise)
455
409
 
456
410
  /// Clears SDK state (tokens/subscriptions/cache depending on SDK implementation).
457
- ///
458
- /// Promise contract:
459
- /// - Resolves with `nil` after cleanup completes.
460
411
  @objc(clearWithResolver:rejecter:)
461
412
  public func clear(
462
413
  resolver resolve: @escaping RCTPromiseResolveBlock,
463
414
  rejecter reject: @escaping RCTPromiseRejectBlock
464
415
  ) {
416
+ _ = reject
465
417
  ensureProvidersInstalled()
466
- AltcraftSDK.shared.clear {
467
- resolve(nil)
468
- }
418
+ AltcraftSDK.shared.clear { resolve(nil) }
469
419
  }
470
420
 
471
- // MARK: - Token API wrappers used by ObjC bridge
421
+ // MARK: - Token API wrappers
472
422
 
473
- /// Returns the currently resolved push token from the SDK.
423
+ /// Returns the current push token from the SDK.
474
424
  ///
475
425
  /// - Parameter completion: Called with `{ provider, token }` or `nil` if not available.
476
426
  @objc(getPushTokenWithCompletion:)
@@ -485,32 +435,32 @@ public final class SdkModule: NSObject {
485
435
  }
486
436
  }
487
437
 
488
- /// Deletes device token for a known provider.
438
+ /// Deletes device token for a supported provider.
489
439
  ///
490
440
  /// - Parameters:
491
- /// - provider: Provider name from JS (case-insensitive, expected to match constants).
441
+ /// - provider: Provider name from JS (case-insensitive).
492
442
  /// - completion: `true` if a supported provider was handled, otherwise `false`.
493
443
  @objc(deleteDeviceTokenWithProvider:completion:)
494
444
  public func deleteDeviceToken(provider: String?, completion: @escaping (Bool) -> Void) {
495
445
  ensureProvidersInstalled()
446
+
496
447
  let p = (provider ?? "").lowercased()
497
- _ = p // keep for potential normalization usage
498
448
 
499
- if provider == Constants.ProviderName.firebase {
449
+ if p == Constants.ProviderName.firebase.lowercased() {
500
450
  AltcraftSDK.shared.pushTokenFunction.deleteDeviceToken(provider: Constants.ProviderName.firebase) {
501
451
  completion(true)
502
452
  }
503
453
  return
504
454
  }
505
455
 
506
- if provider == Constants.ProviderName.huawei {
456
+ if p == Constants.ProviderName.huawei.lowercased() {
507
457
  AltcraftSDK.shared.pushTokenFunction.deleteDeviceToken(provider: Constants.ProviderName.huawei) {
508
458
  completion(true)
509
459
  }
510
460
  return
511
461
  }
512
462
 
513
- if provider == Constants.ProviderName.apns {
463
+ if p == Constants.ProviderName.apns.lowercased() {
514
464
  AltcraftSDK.shared.pushTokenFunction.deleteDeviceToken(provider: Constants.ProviderName.apns) {
515
465
  completion(true)
516
466
  }
@@ -521,21 +471,13 @@ public final class SdkModule: NSObject {
521
471
  }
522
472
 
523
473
  /// Forces push token update flow in the SDK.
524
- ///
525
- /// - Parameter completion: Called when the update flow finishes.
526
474
  @objc(forcedTokenUpdateWithCompletion:)
527
475
  public func forcedTokenUpdate(_ completion: @escaping () -> Void) {
528
476
  ensureProvidersInstalled()
529
- AltcraftSDK.shared.pushTokenFunction.forcedTokenUpdate {
530
- completion()
531
- }
477
+ AltcraftSDK.shared.pushTokenFunction.forcedTokenUpdate { completion() }
532
478
  }
533
479
 
534
480
  /// Updates push provider priority list.
535
- ///
536
- /// - Parameters:
537
- /// - list: Provider ids ordered by preference.
538
- /// - completion: Returns `true` when the list is applied.
539
481
  @objc(changePushProviderPriorityListWithList:completion:)
540
482
  public func changePushProviderPriorityList(_ list: [String]?, completion: @escaping (Bool) -> Void) {
541
483
  ensureProvidersInstalled()
@@ -543,61 +485,44 @@ public final class SdkModule: NSObject {
543
485
  completion(true)
544
486
  }
545
487
 
546
- /// Sets or clears push token for a specific provider.
547
- ///
548
- /// This is a direct passthrough to the SDK API. The SDK decides how to interpret `pushToken`.
488
+ /// Sets push token for a specific provider.
549
489
  @objc(setPushTokenWithProvider:pushToken:)
550
490
  public func setPushToken(provider: String, pushToken: Any?) {
551
491
  ensureProvidersInstalled()
552
492
  AltcraftSDK.shared.pushTokenFunction.setPushToken(provider: provider, pushToken: pushToken)
553
493
  }
554
494
 
555
- // MARK: - ✅ Push Subscription (RN bridge)
495
+ // MARK: - Push Subscription
556
496
 
557
- /// Converts an `NSDictionary` into a Swift `[String: Any?]` map.
558
- ///
559
- /// Returns `nil` for:
560
- /// - nil input
561
- /// - empty dictionaries
497
+ /// Converts `NSDictionary` into `[String: Any?]` with normalization.
562
498
  private func toAnyDict(_ dict: NSDictionary?) -> [String: Any?]? {
563
- guard let dict = dict as? [String: Any] else { return nil }
564
- if dict.isEmpty { return nil }
565
- var out: [String: Any?] = [:]
566
- out.reserveCapacity(dict.count)
567
- for (k, v) in dict {
568
- out[k] = v
569
- }
570
- return out.isEmpty ? nil : out
499
+ Converter.toAnyDict(dict)
571
500
  }
572
501
 
573
- /// Converts RN categories array into native `[CategoryData]`.
574
- ///
575
- /// Returns `nil` for:
576
- /// - nil input
577
- /// - empty input
578
- /// - when all items are invalid/unparseable
502
+ /// Converts categories into native `[CategoryData]`.
579
503
  private func toCats(_ cats: NSArray?) -> [CategoryData]? {
580
- guard let arr = cats as? [Any], !arr.isEmpty else { return nil }
504
+ guard let arr = cats, arr.count > 0 else { return nil }
581
505
 
582
506
  var out: [CategoryData] = []
583
507
  out.reserveCapacity(arr.count)
584
508
 
585
509
  for item in arr {
586
- guard let m = item as? [String: Any] else { continue }
587
-
588
- let name = m["name"] as? String
589
- let title = m["title"] as? String
590
- let steady = m["steady"] as? Bool
591
- let active = m["active"] as? Bool
592
-
593
- out.append(
594
- CategoryData(
595
- name: name,
596
- title: title,
597
- steady: steady,
598
- active: active
599
- )
600
- )
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
521
+
522
+ if name != nil {
523
+ out.append(CategoryData(name: name, title: title, steady: steady, active: active))
524
+ }
525
+ }
601
526
  }
602
527
 
603
528
  return out.isEmpty ? nil : out
@@ -605,11 +530,8 @@ public final class SdkModule: NSObject {
605
530
 
606
531
  /// Subscribes device/profile for push notifications.
607
532
  ///
608
- /// ObjC selector used by `Sdk.mm`: `pushSubscribe:profileFields:customFields:cats:replace:skipTriggers:`
609
- ///
610
- /// Parameters match the JS spec:
611
- /// - sync: defaults to `true` when nil
612
- /// - replace / skipTriggers: optional flags forwarded as `Bool?`
533
+ /// ObjC selector used by `Sdk.mm`:
534
+ /// `pushSubscribe:profileFields:customFields:cats:replace:skipTriggers:`
613
535
  @objc(pushSubscribe:profileFields:customFields:cats:replace:skipTriggers:)
614
536
  public func pushSubscribe(
615
537
  _ sync: NSNumber?,
@@ -635,9 +557,10 @@ public final class SdkModule: NSObject {
635
557
  )
636
558
  }
637
559
 
638
- /// Suspends current push subscription (temporarily disables).
560
+ /// Suspends current push subscription.
639
561
  ///
640
- /// ObjC selector used by `Sdk.mm`: `pushSuspend:profileFields:customFields:cats:replace:skipTriggers:`
562
+ /// ObjC selector used by `Sdk.mm`:
563
+ /// `pushSuspend:profileFields:customFields:cats:replace:skipTriggers:`
641
564
  @objc(pushSuspend:profileFields:customFields:cats:replace:skipTriggers:)
642
565
  public func pushSuspend(
643
566
  _ sync: NSNumber?,
@@ -665,7 +588,8 @@ public final class SdkModule: NSObject {
665
588
 
666
589
  /// Unsubscribes (disables) current push subscription.
667
590
  ///
668
- /// ObjC selector used by `Sdk.mm`: `pushUnSubscribe:profileFields:customFields:cats:replace:skipTriggers:`
591
+ /// ObjC selector used by `Sdk.mm`:
592
+ /// `pushUnSubscribe:profileFields:customFields:cats:replace:skipTriggers:`
669
593
  @objc(pushUnSubscribe:profileFields:customFields:cats:replace:skipTriggers:)
670
594
  public func pushUnSubscribe(
671
595
  _ sync: NSNumber?,
@@ -691,16 +615,13 @@ public final class SdkModule: NSObject {
691
615
  )
692
616
  }
693
617
 
694
- // MARK: - ✅ MobileEvent (RN bridge)
618
+ // MARK: - Mobile Events
695
619
 
696
- /// Sends a generic mobile event (non-push) to Altcraft via the SDK.
620
+ /// Sends a mobile event to Altcraft via SDK.
697
621
  ///
698
- /// ObjC selector used by `Sdk.mm`: `mobileEvent:eventName:sendMessageId:payload:matching:matchingType:profileFields:`
699
- ///
700
- /// Notes:
701
- /// - `subscription` and `utm` are not bridged from RN yet (passed as nil).
702
- /// - `altcraftClientID` is currently passed as an empty string to match existing native behavior.
703
- @objc(mobileEvent:eventName:sendMessageId:payload:matching:matchingType:profileFields:)
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:)
704
625
  public func mobileEvent(
705
626
  _ sid: String,
706
627
  eventName: String,
@@ -708,36 +629,47 @@ public final class SdkModule: NSObject {
708
629
  payload: NSDictionary?,
709
630
  matching: NSDictionary?,
710
631
  matchingType: String?,
711
- profileFields: NSDictionary?
632
+ profileFields: NSDictionary?,
633
+ utm: NSDictionary?
712
634
  ) {
713
635
  ensureProvidersInstalled()
714
636
 
715
- let payloadAny = toAnyDict(payload)
716
- let matchingAny = toAnyDict(matching)
717
- let profileAny = toAnyDict(profileFields)
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
+ }
718
652
 
719
653
  AltcraftSDK.shared.mobileEventFunctions.mobileEvent(
720
654
  sid: sid,
721
655
  altcraftClientID: "",
722
656
  eventName: eventName,
723
657
  sendMessageId: sendMessageId,
724
- payload: payloadAny,
725
- matching: matchingAny,
658
+ payload: payloadNorm,
659
+ matching: matchingNorm,
726
660
  matchingType: matchingType,
727
- profileFields: profileAny,
661
+ profileFields: profileNorm,
728
662
  subscription: nil,
729
- utm: nil
663
+ utm: utmObj
730
664
  )
731
665
  }
732
666
 
733
- // MARK: - ✅ PushSubscription promise API for RN (ResponseWithHttpCode | null)
667
+ // MARK: - Promise API: PushSubscription status/results
734
668
 
735
- /// Helper: converts `nil` to `NSNull()` for JS payloads.
669
+ /// Converts `nil` to `NSNull()` for JS payloads.
736
670
  private func nsNull(_ v: Any?) -> Any { v ?? NSNull() }
737
671
 
738
- /// Converts an arbitrary `[String: Any?]` map into a `[String: String]` map.
739
- ///
740
- /// Used for fields mapping in subscription-related responses.
672
+ /// Converts `[String: Any?]` to `[String: String]`.
741
673
  private func toStringMap(_ dict: [String: Any?]?) -> [String: String]? {
742
674
  guard let dict, !dict.isEmpty else { return nil }
743
675
  var out: [String: String] = [:]
@@ -749,7 +681,6 @@ public final class SdkModule: NSObject {
749
681
  return out.isEmpty ? nil : out
750
682
  }
751
683
 
752
- /// Maps SDK category model to JS object.
753
684
  private func mapCategory(_ c: CategoryData) -> [String: Any] {
754
685
  [
755
686
  "name": nsNull(c.name),
@@ -759,7 +690,6 @@ public final class SdkModule: NSObject {
759
690
  ]
760
691
  }
761
692
 
762
- /// Maps SDK subscription model to JS object.
763
693
  private func mapSubscription(_ s: SubscriptionData) -> [String: Any] {
764
694
  let fieldsString = toStringMap(s.fields)
765
695
  let catsArr: [[String: Any]]? = s.cats?.map { mapCategory($0) }
@@ -774,7 +704,6 @@ public final class SdkModule: NSObject {
774
704
  ]
775
705
  }
776
706
 
777
- /// Maps SDK profile model to JS object.
778
707
  private func mapProfile(_ p: ProfileData) -> [String: Any] {
779
708
  let subDict: [String: Any]? = p.subscription.map { mapSubscription($0) }
780
709
  return [
@@ -785,7 +714,6 @@ public final class SdkModule: NSObject {
785
714
  ]
786
715
  }
787
716
 
788
- /// Maps SDK response model to JS object.
789
717
  private func mapResponse(_ r: Response) -> [String: Any] {
790
718
  let profileDict: [String: Any]? = r.profile.map { mapProfile($0) }
791
719
  return [
@@ -795,7 +723,6 @@ public final class SdkModule: NSObject {
795
723
  ]
796
724
  }
797
725
 
798
- /// Maps SDK response-with-http model to JS object.
799
726
  private func mapResponseWithHttp(_ r: ResponseWithHttp) -> [String: Any] {
800
727
  let respDict: [String: Any]? = r.response.map { mapResponse($0) }
801
728
  return [
@@ -805,15 +732,12 @@ public final class SdkModule: NSObject {
805
732
  }
806
733
 
807
734
  /// Attempts to un-suspend a push subscription.
808
- ///
809
- /// Promise contract:
810
- /// - Resolves with `null` if SDK returns nil.
811
- /// - Resolves with `{ httpCode, response }` if available.
812
735
  @objc(unSuspendPushSubscriptionWithResolver:rejecter:)
813
736
  public func unSuspendPushSubscription(
814
737
  resolver resolve: @escaping RCTPromiseResolveBlock,
815
738
  rejecter reject: @escaping RCTPromiseRejectBlock
816
739
  ) {
740
+ _ = reject
817
741
  ensureProvidersInstalled()
818
742
 
819
743
  AltcraftSDK.shared.pushSubscriptionFunctions.unSuspendPushSubscription { result in
@@ -823,15 +747,12 @@ public final class SdkModule: NSObject {
823
747
  }
824
748
 
825
749
  /// Returns status of the latest subscription operation.
826
- ///
827
- /// Promise contract:
828
- /// - Resolves with `null` if SDK returns nil.
829
- /// - Resolves with `{ httpCode, response }` if available.
830
750
  @objc(getStatusOfLatestSubscriptionWithResolver:rejecter:)
831
751
  public func getStatusOfLatestSubscription(
832
752
  resolver resolve: @escaping RCTPromiseResolveBlock,
833
753
  rejecter reject: @escaping RCTPromiseRejectBlock
834
754
  ) {
755
+ _ = reject
835
756
  ensureProvidersInstalled()
836
757
 
837
758
  AltcraftSDK.shared.pushSubscriptionFunctions.getStatusOfLatestSubscription { result in
@@ -841,15 +762,12 @@ public final class SdkModule: NSObject {
841
762
  }
842
763
 
843
764
  /// Returns status of the current subscription.
844
- ///
845
- /// Promise contract:
846
- /// - Resolves with `null` if SDK returns nil.
847
- /// - Resolves with `{ httpCode, response }` if available.
848
765
  @objc(getStatusForCurrentSubscriptionWithResolver:rejecter:)
849
766
  public func getStatusForCurrentSubscription(
850
767
  resolver resolve: @escaping RCTPromiseResolveBlock,
851
768
  rejecter reject: @escaping RCTPromiseRejectBlock
852
769
  ) {
770
+ _ = reject
853
771
  ensureProvidersInstalled()
854
772
 
855
773
  AltcraftSDK.shared.pushSubscriptionFunctions.getStatusForCurrentSubscription { result in
@@ -859,16 +777,13 @@ public final class SdkModule: NSObject {
859
777
  }
860
778
 
861
779
  /// Returns status of the latest subscription operation for a specific provider.
862
- ///
863
- /// Promise contract:
864
- /// - Resolves with `null` if SDK returns nil.
865
- /// - Resolves with `{ httpCode, response }` if available.
866
780
  @objc(getStatusOfLatestSubscriptionForProviderWithProvider:resolver:rejecter:)
867
781
  public func getStatusOfLatestSubscriptionForProvider(
868
782
  provider: String?,
869
783
  resolver resolve: @escaping RCTPromiseResolveBlock,
870
784
  rejecter reject: @escaping RCTPromiseRejectBlock
871
785
  ) {
786
+ _ = reject
872
787
  ensureProvidersInstalled()
873
788
 
874
789
  AltcraftSDK.shared.pushSubscriptionFunctions.getStatusOfLatestSubscriptionForProvider(provider: provider) { result in
@@ -876,13 +791,39 @@ public final class SdkModule: NSObject {
876
791
  resolve(self.mapResponseWithHttp(result))
877
792
  }
878
793
  }
879
- }
880
794
 
881
- // MARK: - Notification name
795
+ // MARK: - UserDefaults
882
796
 
883
- extension Notification.Name {
884
- /// Notification posted when an SDK event is forwarded to JS.
797
+ /// Stores a value into UserDefaults.
885
798
  ///
886
- /// Must match ObjC++ constant: `SdkEventsNotificationName = @"AltcraftSdkEventNotification"`.
887
- static let altcraftSdkEventNotification = Notification.Name("AltcraftSdkEventNotification")
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
803
+ @objc(setUserDefaultsValueWithSuiteName:key:value:)
804
+ public func setUserDefaultsValue(
805
+ suiteName: String?,
806
+ key: String,
807
+ value: Any?
808
+ ) {
809
+ let k = key.trimmingCharacters(in: .whitespacesAndNewlines)
810
+ if k.isEmpty { return }
811
+
812
+ let sn = suiteName?.trimmingCharacters(in: .whitespacesAndNewlines)
813
+ let ud: UserDefaults = {
814
+ if let sn, !sn.isEmpty, let g = UserDefaults(suiteName: sn) { return g }
815
+ return .standard
816
+ }()
817
+
818
+ if value == nil || value is NSNull {
819
+ ud.removeObject(forKey: k)
820
+ return
821
+ }
822
+
823
+ if let plist = Converter.toPropertyListValue(value) {
824
+ ud.set(plist, forKey: k)
825
+ } else {
826
+ ud.removeObject(forKey: k)
827
+ }
828
+ }
888
829
  }