@altcraft/react-native-sdk 0.0.1

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 (33) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +46 -0
  3. package/Sdk.podspec +48 -0
  4. package/android/build.gradle +78 -0
  5. package/android/gradle.properties +5 -0
  6. package/android/src/main/AndroidManifest.xml +2 -0
  7. package/android/src/main/java/com/altcraft/sdk/SdkModule.kt +1242 -0
  8. package/android/src/main/java/com/altcraft/sdk/SdkPackage.kt +33 -0
  9. package/android/src/main/java/com/altcraft/sdk/interfaces/RnFCMProvider.kt +27 -0
  10. package/android/src/main/java/com/altcraft/sdk/interfaces/RnHMSProvider.kt +32 -0
  11. package/android/src/main/java/com/altcraft/sdk/interfaces/RnJWTProvider.kt +21 -0
  12. package/android/src/main/java/com/altcraft/sdk/interfaces/RnRustoreProvider.kt +53 -0
  13. package/ios/Sdk.h +19 -0
  14. package/ios/Sdk.mm +1112 -0
  15. package/ios/SdkModule.swift +888 -0
  16. package/ios/protocols/RNAPNSProvider.swift +15 -0
  17. package/ios/protocols/RNFCMProvider.swift +24 -0
  18. package/ios/protocols/RNHMSProvider.swift +24 -0
  19. package/ios/protocols/RNJWTProvider.swift +15 -0
  20. package/lib/module/NativeSdk.js +13 -0
  21. package/lib/module/NativeSdk.js.map +1 -0
  22. package/lib/module/index.js +561 -0
  23. package/lib/module/index.js.map +1 -0
  24. package/lib/module/package.json +1 -0
  25. package/lib/typescript/package.json +1 -0
  26. package/lib/typescript/src/NativeSdk.d.ts +114 -0
  27. package/lib/typescript/src/NativeSdk.d.ts.map +1 -0
  28. package/lib/typescript/src/index.d.ts +391 -0
  29. package/lib/typescript/src/index.d.ts.map +1 -0
  30. package/package.json +128 -0
  31. package/react-native.config.js +10 -0
  32. package/src/NativeSdk.ts +171 -0
  33. package/src/index.tsx +670 -0
@@ -0,0 +1,888 @@
1
+ import Foundation
2
+ import Altcraft
3
+ import React
4
+
5
+ /// React Native bridge module for the Altcraft iOS SDK.
6
+ ///
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.
12
+ ///
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.
20
+ @objc(SdkModule)
21
+ @objcMembers
22
+ @available(iOSApplicationExtension, unavailable)
23
+ public final class SdkModule: NSObject {
24
+
25
+ /// Shared singleton instance used by the ObjC++ bridge.
26
+ public static let shared = SdkModule()
27
+
28
+ /// A single lock protecting all mutable state in this module.
29
+ private let lock = NSLock()
30
+
31
+ // MARK: - JWT (stable provider reference)
32
+
33
+ /// Current JWT value used by `jwtProvider`.
34
+ ///
35
+ /// Access must be protected by `lock`.
36
+ private var jwt: String?
37
+
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`.
42
+ private lazy var jwtProvider: RNJWTProvider = RNJWTProvider { [weak self] in
43
+ guard let self else { return nil }
44
+ self.lock.lock(); defer { self.lock.unlock() }
45
+ return self.jwt
46
+ }
47
+
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
58
+ private func installJWTProviderIfNeeded() {
59
+ // double-checked locking pattern (cheap fast-path)
60
+ lock.lock()
61
+ let already = jwtProviderInstalled
62
+ lock.unlock()
63
+ if already { return }
64
+
65
+ AltcraftSDK.shared.setJWTProvider(provider: jwtProvider)
66
+
67
+ lock.lock()
68
+ jwtProviderInstalled = true
69
+ lock.unlock()
70
+ }
71
+
72
+ /// Sets JWT token for requests performed by the Altcraft SDK.
73
+ ///
74
+ /// 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
+ @objc(setJWT:)
80
+ public func setJWT(_ token: String?) {
81
+ installJWTProviderIfNeeded()
82
+ lock.lock()
83
+ jwt = token
84
+ lock.unlock()
85
+ }
86
+
87
+ // MARK: - AppGroup
88
+
89
+ /// Sets the App Group identifier for shared storage (Core Data + UserDefaults/App Group).
90
+ ///
91
+ /// ObjC selector used by `Sdk.mm`: `setAppGroupWithName:`
92
+ ///
93
+ /// Call this before operations that rely on a shared container.
94
+ @objc(setAppGroupWithName:)
95
+ public func setAppGroup(name: String?) {
96
+ AltcraftSDK.shared.setAppGroup(groupName: name)
97
+ }
98
+
99
+ // MARK: - Tokens / Config
100
+
101
+ /// Stored push tokens used by token providers. Access guarded by `lock`.
102
+ private var fcm: String?
103
+ private var hms: String?
104
+ private var apns: String?
105
+
106
+ /// Last built configuration used to initialize the SDK.
107
+ /// Stored for debugging/inspection purposes.
108
+ private var configuration: AltcraftConfiguration?
109
+
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.
114
+ private lazy var fcmProvider: RNFCMProvider = RNFCMProvider(
115
+ get: { [weak self] completion in
116
+ guard let self else { completion(nil); return }
117
+ self.lock.lock(); defer { self.lock.unlock() }
118
+ completion(self.fcm)
119
+ },
120
+ del: { [weak self] completion in
121
+ guard let self else { completion(false); return }
122
+ self.lock.lock(); self.fcm = nil; self.lock.unlock()
123
+ completion(true)
124
+ }
125
+ )
126
+
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.
131
+ private lazy var hmsProvider: RNHMSProvider = RNHMSProvider(
132
+ get: { [weak self] completion in
133
+ guard let self else { completion(nil); return }
134
+ self.lock.lock(); defer { self.lock.unlock() }
135
+ completion(self.hms)
136
+ },
137
+ del: { [weak self] completion in
138
+ guard let self else { completion(false); return }
139
+ self.lock.lock(); self.hms = nil; self.lock.unlock()
140
+ completion(true)
141
+ }
142
+ )
143
+
144
+ /// Stable APNs provider reference created once and reused.
145
+ ///
146
+ /// APNs token is read under lock and returned through completion.
147
+ private lazy var apnsProvider: RNAPNSProvider = RNAPNSProvider { [weak self] completion in
148
+ guard let self else { completion(nil); return }
149
+ self.lock.lock(); defer { self.lock.unlock() }
150
+ completion(self.apns)
151
+ }
152
+
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.
169
+ public func ensureProvidersInstalled() {
170
+ installTokenProvidersIfNeeded()
171
+ }
172
+
173
+ /// Registers token providers (FCM/HMS/APNs) in the SDK exactly once.
174
+ ///
175
+ /// Uses a double-checked locking pattern to avoid repeated work.
176
+ private func installTokenProvidersIfNeeded() {
177
+ lock.lock()
178
+ let already = tokenProvidersInstalled
179
+ lock.unlock()
180
+ if already { return }
181
+
182
+ let push = AltcraftSDK.shared.pushTokenFunction
183
+ push.setFCMTokenProvider(fcmProvider)
184
+ push.setHMSTokenProvider(hmsProvider)
185
+ push.setAPNSTokenProvider(apnsProvider)
186
+
187
+ lock.lock()
188
+ tokenProvidersInstalled = true
189
+ lock.unlock()
190
+ }
191
+
192
+ // MARK: - ✅ RN init (ONLY initialize)
193
+
194
+ /// Initializes Altcraft SDK using configuration received from React Native.
195
+ ///
196
+ /// Contract:
197
+ /// - Resolves with `nil` on success.
198
+ /// - Rejects with:
199
+ /// - `ALTCRAFT_INIT_INVALID_CONFIG` when required fields are missing or configuration build fails.
200
+ /// - `ALTCRAFT_INIT_ERROR` when SDK initialization reports failure.
201
+ ///
202
+ /// Notes:
203
+ /// - Providers are installed before initialization to ensure stable references.
204
+ @objc(initializeWithConfig:resolver:rejecter:)
205
+ public func initialize(
206
+ _ config: NSDictionary,
207
+ resolver resolve: @escaping RCTPromiseResolveBlock,
208
+ rejecter reject: @escaping RCTPromiseRejectBlock
209
+ ) {
210
+ ensureProvidersInstalled()
211
+
212
+ let dict = config as? [String: Any] ?? [:]
213
+
214
+ guard let apiUrl = dict["apiUrl"] as? String, !apiUrl.isEmpty else {
215
+ reject("ALTCRAFT_INIT_INVALID_CONFIG", "apiUrl is required", nil)
216
+ return
217
+ }
218
+
219
+ let rToken = dict["rToken"] as? String
220
+ let enableLogging = dict["enableLogging"] as? Bool
221
+ let providerPriorityList = dict["providerPriorityList"] as? [String]
222
+
223
+ var appInfo: AppInfo? = nil
224
+ if let app = dict["appInfo"] as? [String: Any] {
225
+ let appID = (app["appID"] as? String) ?? ""
226
+ let appIID = (app["appIID"] as? String) ?? ""
227
+ let appVer = (app["appVer"] as? String) ?? ""
228
+ if !appID.isEmpty || !appIID.isEmpty || !appVer.isEmpty {
229
+ appInfo = AppInfo(appID: appID, appIID: appIID, appVer: appVer)
230
+ }
231
+ }
232
+
233
+ guard let built = AltcraftConfiguration.Builder()
234
+ .setApiUrl(apiUrl)
235
+ .setRToken(rToken)
236
+ .setAppInfo(appInfo)
237
+ .setProviderPriorityList(providerPriorityList)
238
+ .setEnableLogging(enableLogging)
239
+ .build()
240
+ else {
241
+ reject("ALTCRAFT_INIT_INVALID_CONFIG", "Invalid Altcraft configuration", nil)
242
+ return
243
+ }
244
+
245
+ lock.lock()
246
+ self.configuration = built
247
+ lock.unlock()
248
+
249
+ AltcraftSDK.shared.initialization(configuration: built) { ok in
250
+ if ok { resolve(nil) }
251
+ else { reject("ALTCRAFT_INIT_ERROR", "Altcraft initialization failed", nil) }
252
+ }
253
+ }
254
+
255
+ // MARK: - ✅ NativeEventEmitter support (no-op)
256
+
257
+ /// Required by `NativeEventEmitter` contract on the JS side.
258
+ ///
259
+ /// iOS bridge uses NotificationCenter forwarding instead, so this is a no-op.
260
+ public func addListener(_ eventName: String) { _ = eventName }
261
+
262
+ /// Required by `NativeEventEmitter` contract on the JS side.
263
+ ///
264
+ /// iOS bridge uses NotificationCenter forwarding instead, so this is a no-op.
265
+ public func removeListeners(_ count: NSNumber) { _ = count }
266
+
267
+ // MARK: - ✅ Events API (called from Sdk.mm)
268
+
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`.
274
+ ///
275
+ /// Notes:
276
+ /// - The actual event source is `SDKEvents.shared`, consistent with the native SDK event bus.
277
+ public func subscribeToEvents() {
278
+ lock.lock()
279
+ let already = eventsSubscribed
280
+ if !already { eventsSubscribed = true }
281
+ lock.unlock()
282
+ if already { return }
283
+
284
+ // Subscribe to native SDK events emitted through SDKEvents.shared.emit(event:)
285
+ SDKEvents.shared.subscribe { [weak self] ev in
286
+ 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
+ )
302
+ }
303
+ }
304
+
305
+ /// Unsubscribes from the SDK event stream.
306
+ ///
307
+ /// After this call, events are no longer forwarded to JS.
308
+ public func unsubscribeFromEvent() {
309
+ lock.lock()
310
+ eventsSubscribed = false
311
+ lock.unlock()
312
+
313
+ SDKEvents.shared.unsubscribe()
314
+ }
315
+
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()
327
+
328
+ let type: String
329
+ if ev is RetryEvent {
330
+ type = "retryError"
331
+ } else if ev is ErrorEvent {
332
+ type = "error"
333
+ } else {
334
+ type = "event"
335
+ }
336
+
337
+ let valueObj: Any
338
+ if let v = ev.value, !v.isEmpty {
339
+ valueObj = sanitizeToJsObject(v)
340
+ } else {
341
+ valueObj = NSNull()
342
+ }
343
+
344
+ return [
345
+ "function": ev.function,
346
+ "code": code,
347
+ "message": message,
348
+ "type": type,
349
+ "value": valueObj
350
+ ]
351
+ }
352
+
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)
393
+
394
+ /// Sets (or clears) the stored FCM token and updates SDK provider registration.
395
+ ///
396
+ /// 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
+ @objc(setFCM:)
402
+ public func setFCM(_ token: String?) {
403
+ ensureProvidersInstalled()
404
+ lock.lock(); fcm = token; lock.unlock()
405
+
406
+ let push = AltcraftSDK.shared.pushTokenFunction
407
+ if token == nil || token?.isEmpty == true {
408
+ push.setFCMTokenProvider(nil)
409
+ } else {
410
+ push.setFCMTokenProvider(fcmProvider)
411
+ }
412
+ }
413
+
414
+ /// Sets (or clears) the stored HMS token and updates SDK provider registration.
415
+ ///
416
+ /// 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
+ @objc(setHMS:)
422
+ public func setHMS(_ token: String?) {
423
+ ensureProvidersInstalled()
424
+ lock.lock(); hms = token; lock.unlock()
425
+
426
+ let push = AltcraftSDK.shared.pushTokenFunction
427
+ if token == nil || token?.isEmpty == true {
428
+ push.setHMSTokenProvider(nil)
429
+ } else {
430
+ push.setHMSTokenProvider(hmsProvider)
431
+ }
432
+ }
433
+
434
+ /// Sets (or clears) the stored APNs token and updates SDK provider registration.
435
+ ///
436
+ /// 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
+ @objc(setAPNS:)
442
+ public func setAPNS(_ token: String?) {
443
+ ensureProvidersInstalled()
444
+ lock.lock(); apns = token; lock.unlock()
445
+
446
+ let push = AltcraftSDK.shared.pushTokenFunction
447
+ if token == nil || token?.isEmpty == true {
448
+ push.setAPNSTokenProvider(nil)
449
+ } else {
450
+ push.setAPNSTokenProvider(apnsProvider)
451
+ }
452
+ }
453
+
454
+ // MARK: - clear
455
+
456
+ /// Clears SDK state (tokens/subscriptions/cache depending on SDK implementation).
457
+ ///
458
+ /// Promise contract:
459
+ /// - Resolves with `nil` after cleanup completes.
460
+ @objc(clearWithResolver:rejecter:)
461
+ public func clear(
462
+ resolver resolve: @escaping RCTPromiseResolveBlock,
463
+ rejecter reject: @escaping RCTPromiseRejectBlock
464
+ ) {
465
+ ensureProvidersInstalled()
466
+ AltcraftSDK.shared.clear {
467
+ resolve(nil)
468
+ }
469
+ }
470
+
471
+ // MARK: - Token API wrappers used by ObjC bridge
472
+
473
+ /// Returns the currently resolved push token from the SDK.
474
+ ///
475
+ /// - Parameter completion: Called with `{ provider, token }` or `nil` if not available.
476
+ @objc(getPushTokenWithCompletion:)
477
+ public func getPushToken(_ completion: @escaping ([String: Any]?) -> Void) {
478
+ ensureProvidersInstalled()
479
+ AltcraftSDK.shared.pushTokenFunction.getPushToken { tokenData in
480
+ guard let tokenData else { completion(nil); return }
481
+ completion([
482
+ "provider": tokenData.provider,
483
+ "token": tokenData.token
484
+ ])
485
+ }
486
+ }
487
+
488
+ /// Deletes device token for a known provider.
489
+ ///
490
+ /// - Parameters:
491
+ /// - provider: Provider name from JS (case-insensitive, expected to match constants).
492
+ /// - completion: `true` if a supported provider was handled, otherwise `false`.
493
+ @objc(deleteDeviceTokenWithProvider:completion:)
494
+ public func deleteDeviceToken(provider: String?, completion: @escaping (Bool) -> Void) {
495
+ ensureProvidersInstalled()
496
+ let p = (provider ?? "").lowercased()
497
+ _ = p // keep for potential normalization usage
498
+
499
+ if provider == Constants.ProviderName.firebase {
500
+ AltcraftSDK.shared.pushTokenFunction.deleteDeviceToken(provider: Constants.ProviderName.firebase) {
501
+ completion(true)
502
+ }
503
+ return
504
+ }
505
+
506
+ if provider == Constants.ProviderName.huawei {
507
+ AltcraftSDK.shared.pushTokenFunction.deleteDeviceToken(provider: Constants.ProviderName.huawei) {
508
+ completion(true)
509
+ }
510
+ return
511
+ }
512
+
513
+ if provider == Constants.ProviderName.apns {
514
+ AltcraftSDK.shared.pushTokenFunction.deleteDeviceToken(provider: Constants.ProviderName.apns) {
515
+ completion(true)
516
+ }
517
+ return
518
+ }
519
+
520
+ completion(false)
521
+ }
522
+
523
+ /// Forces push token update flow in the SDK.
524
+ ///
525
+ /// - Parameter completion: Called when the update flow finishes.
526
+ @objc(forcedTokenUpdateWithCompletion:)
527
+ public func forcedTokenUpdate(_ completion: @escaping () -> Void) {
528
+ ensureProvidersInstalled()
529
+ AltcraftSDK.shared.pushTokenFunction.forcedTokenUpdate {
530
+ completion()
531
+ }
532
+ }
533
+
534
+ /// 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
+ @objc(changePushProviderPriorityListWithList:completion:)
540
+ public func changePushProviderPriorityList(_ list: [String]?, completion: @escaping (Bool) -> Void) {
541
+ ensureProvidersInstalled()
542
+ AltcraftSDK.shared.pushTokenFunction.changePushProviderPriorityList(list ?? [])
543
+ completion(true)
544
+ }
545
+
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`.
549
+ @objc(setPushTokenWithProvider:pushToken:)
550
+ public func setPushToken(provider: String, pushToken: Any?) {
551
+ ensureProvidersInstalled()
552
+ AltcraftSDK.shared.pushTokenFunction.setPushToken(provider: provider, pushToken: pushToken)
553
+ }
554
+
555
+ // MARK: - ✅ Push Subscription (RN bridge)
556
+
557
+ /// Converts an `NSDictionary` into a Swift `[String: Any?]` map.
558
+ ///
559
+ /// Returns `nil` for:
560
+ /// - nil input
561
+ /// - empty dictionaries
562
+ 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
571
+ }
572
+
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
579
+ private func toCats(_ cats: NSArray?) -> [CategoryData]? {
580
+ guard let arr = cats as? [Any], !arr.isEmpty else { return nil }
581
+
582
+ var out: [CategoryData] = []
583
+ out.reserveCapacity(arr.count)
584
+
585
+ 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
+ )
601
+ }
602
+
603
+ return out.isEmpty ? nil : out
604
+ }
605
+
606
+ /// Subscribes device/profile for push notifications.
607
+ ///
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?`
613
+ @objc(pushSubscribe:profileFields:customFields:cats:replace:skipTriggers:)
614
+ public func pushSubscribe(
615
+ _ sync: NSNumber?,
616
+ profileFields: NSDictionary?,
617
+ customFields: NSDictionary?,
618
+ cats: NSArray?,
619
+ replace: NSNumber?,
620
+ skipTriggers: NSNumber?
621
+ ) {
622
+ ensureProvidersInstalled()
623
+
624
+ let s = sync?.boolValue ?? true
625
+ let r: Bool? = (replace != nil) ? replace!.boolValue : nil
626
+ let st: Bool? = (skipTriggers != nil) ? skipTriggers!.boolValue : nil
627
+
628
+ AltcraftSDK.shared.pushSubscriptionFunctions.pushSubscribe(
629
+ sync: s,
630
+ profileFields: toAnyDict(profileFields),
631
+ customFields: toAnyDict(customFields),
632
+ cats: toCats(cats),
633
+ replace: r,
634
+ skipTriggers: st
635
+ )
636
+ }
637
+
638
+ /// Suspends current push subscription (temporarily disables).
639
+ ///
640
+ /// ObjC selector used by `Sdk.mm`: `pushSuspend:profileFields:customFields:cats:replace:skipTriggers:`
641
+ @objc(pushSuspend:profileFields:customFields:cats:replace:skipTriggers:)
642
+ public func pushSuspend(
643
+ _ sync: NSNumber?,
644
+ profileFields: NSDictionary?,
645
+ customFields: NSDictionary?,
646
+ cats: NSArray?,
647
+ replace: NSNumber?,
648
+ skipTriggers: NSNumber?
649
+ ) {
650
+ ensureProvidersInstalled()
651
+
652
+ let s = sync?.boolValue ?? true
653
+ let r: Bool? = (replace != nil) ? replace!.boolValue : nil
654
+ let st: Bool? = (skipTriggers != nil) ? skipTriggers!.boolValue : nil
655
+
656
+ AltcraftSDK.shared.pushSubscriptionFunctions.pushSuspend(
657
+ sync: s,
658
+ profileFields: toAnyDict(profileFields),
659
+ customFields: toAnyDict(customFields),
660
+ cats: toCats(cats),
661
+ replace: r,
662
+ skipTriggers: st
663
+ )
664
+ }
665
+
666
+ /// Unsubscribes (disables) current push subscription.
667
+ ///
668
+ /// ObjC selector used by `Sdk.mm`: `pushUnSubscribe:profileFields:customFields:cats:replace:skipTriggers:`
669
+ @objc(pushUnSubscribe:profileFields:customFields:cats:replace:skipTriggers:)
670
+ public func pushUnSubscribe(
671
+ _ sync: NSNumber?,
672
+ profileFields: NSDictionary?,
673
+ customFields: NSDictionary?,
674
+ cats: NSArray?,
675
+ replace: NSNumber?,
676
+ skipTriggers: NSNumber?
677
+ ) {
678
+ ensureProvidersInstalled()
679
+
680
+ let s = sync?.boolValue ?? true
681
+ let r: Bool? = (replace != nil) ? replace!.boolValue : nil
682
+ let st: Bool? = (skipTriggers != nil) ? skipTriggers!.boolValue : nil
683
+
684
+ AltcraftSDK.shared.pushSubscriptionFunctions.pushUnSubscribe(
685
+ sync: s,
686
+ profileFields: toAnyDict(profileFields),
687
+ customFields: toAnyDict(customFields),
688
+ cats: toCats(cats),
689
+ replace: r,
690
+ skipTriggers: st
691
+ )
692
+ }
693
+
694
+ // MARK: - ✅ MobileEvent (RN bridge)
695
+
696
+ /// Sends a generic mobile event (non-push) to Altcraft via the SDK.
697
+ ///
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:)
704
+ public func mobileEvent(
705
+ _ sid: String,
706
+ eventName: String,
707
+ sendMessageId: String?,
708
+ payload: NSDictionary?,
709
+ matching: NSDictionary?,
710
+ matchingType: String?,
711
+ profileFields: NSDictionary?
712
+ ) {
713
+ ensureProvidersInstalled()
714
+
715
+ let payloadAny = toAnyDict(payload)
716
+ let matchingAny = toAnyDict(matching)
717
+ let profileAny = toAnyDict(profileFields)
718
+
719
+ AltcraftSDK.shared.mobileEventFunctions.mobileEvent(
720
+ sid: sid,
721
+ altcraftClientID: "",
722
+ eventName: eventName,
723
+ sendMessageId: sendMessageId,
724
+ payload: payloadAny,
725
+ matching: matchingAny,
726
+ matchingType: matchingType,
727
+ profileFields: profileAny,
728
+ subscription: nil,
729
+ utm: nil
730
+ )
731
+ }
732
+
733
+ // MARK: - ✅ PushSubscription promise API for RN (ResponseWithHttpCode | null)
734
+
735
+ /// Helper: converts `nil` to `NSNull()` for JS payloads.
736
+ private func nsNull(_ v: Any?) -> Any { v ?? NSNull() }
737
+
738
+ /// Converts an arbitrary `[String: Any?]` map into a `[String: String]` map.
739
+ ///
740
+ /// Used for fields mapping in subscription-related responses.
741
+ private func toStringMap(_ dict: [String: Any?]?) -> [String: String]? {
742
+ guard let dict, !dict.isEmpty else { return nil }
743
+ var out: [String: String] = [:]
744
+ out.reserveCapacity(dict.count)
745
+ for (k, v) in dict {
746
+ guard let v else { continue }
747
+ out[k] = String(describing: v)
748
+ }
749
+ return out.isEmpty ? nil : out
750
+ }
751
+
752
+ /// Maps SDK category model to JS object.
753
+ private func mapCategory(_ c: CategoryData) -> [String: Any] {
754
+ [
755
+ "name": nsNull(c.name),
756
+ "title": nsNull(c.title),
757
+ "steady": nsNull(c.steady),
758
+ "active": nsNull(c.active),
759
+ ]
760
+ }
761
+
762
+ /// Maps SDK subscription model to JS object.
763
+ private func mapSubscription(_ s: SubscriptionData) -> [String: Any] {
764
+ let fieldsString = toStringMap(s.fields)
765
+ let catsArr: [[String: Any]]? = s.cats?.map { mapCategory($0) }
766
+
767
+ return [
768
+ "subscriptionId": nsNull(s.subscriptionId),
769
+ "hashId": nsNull(s.hashId),
770
+ "provider": nsNull(s.provider),
771
+ "status": nsNull(s.status),
772
+ "fields": nsNull(fieldsString),
773
+ "cats": nsNull(catsArr),
774
+ ]
775
+ }
776
+
777
+ /// Maps SDK profile model to JS object.
778
+ private func mapProfile(_ p: ProfileData) -> [String: Any] {
779
+ let subDict: [String: Any]? = p.subscription.map { mapSubscription($0) }
780
+ return [
781
+ "id": nsNull(p.id),
782
+ "status": nsNull(p.status),
783
+ "isTest": nsNull(p.isTest),
784
+ "subscription": nsNull(subDict),
785
+ ]
786
+ }
787
+
788
+ /// Maps SDK response model to JS object.
789
+ private func mapResponse(_ r: Response) -> [String: Any] {
790
+ let profileDict: [String: Any]? = r.profile.map { mapProfile($0) }
791
+ return [
792
+ "error": nsNull(r.error),
793
+ "errorText": nsNull(r.errorText),
794
+ "profile": nsNull(profileDict),
795
+ ]
796
+ }
797
+
798
+ /// Maps SDK response-with-http model to JS object.
799
+ private func mapResponseWithHttp(_ r: ResponseWithHttp) -> [String: Any] {
800
+ let respDict: [String: Any]? = r.response.map { mapResponse($0) }
801
+ return [
802
+ "httpCode": nsNull(r.httpCode),
803
+ "response": nsNull(respDict),
804
+ ]
805
+ }
806
+
807
+ /// 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
+ @objc(unSuspendPushSubscriptionWithResolver:rejecter:)
813
+ public func unSuspendPushSubscription(
814
+ resolver resolve: @escaping RCTPromiseResolveBlock,
815
+ rejecter reject: @escaping RCTPromiseRejectBlock
816
+ ) {
817
+ ensureProvidersInstalled()
818
+
819
+ AltcraftSDK.shared.pushSubscriptionFunctions.unSuspendPushSubscription { result in
820
+ guard let result else { resolve(NSNull()); return }
821
+ resolve(self.mapResponseWithHttp(result))
822
+ }
823
+ }
824
+
825
+ /// 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
+ @objc(getStatusOfLatestSubscriptionWithResolver:rejecter:)
831
+ public func getStatusOfLatestSubscription(
832
+ resolver resolve: @escaping RCTPromiseResolveBlock,
833
+ rejecter reject: @escaping RCTPromiseRejectBlock
834
+ ) {
835
+ ensureProvidersInstalled()
836
+
837
+ AltcraftSDK.shared.pushSubscriptionFunctions.getStatusOfLatestSubscription { result in
838
+ guard let result else { resolve(NSNull()); return }
839
+ resolve(self.mapResponseWithHttp(result))
840
+ }
841
+ }
842
+
843
+ /// 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
+ @objc(getStatusForCurrentSubscriptionWithResolver:rejecter:)
849
+ public func getStatusForCurrentSubscription(
850
+ resolver resolve: @escaping RCTPromiseResolveBlock,
851
+ rejecter reject: @escaping RCTPromiseRejectBlock
852
+ ) {
853
+ ensureProvidersInstalled()
854
+
855
+ AltcraftSDK.shared.pushSubscriptionFunctions.getStatusForCurrentSubscription { result in
856
+ guard let result else { resolve(NSNull()); return }
857
+ resolve(self.mapResponseWithHttp(result))
858
+ }
859
+ }
860
+
861
+ /// 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
+ @objc(getStatusOfLatestSubscriptionForProviderWithProvider:resolver:rejecter:)
867
+ public func getStatusOfLatestSubscriptionForProvider(
868
+ provider: String?,
869
+ resolver resolve: @escaping RCTPromiseResolveBlock,
870
+ rejecter reject: @escaping RCTPromiseRejectBlock
871
+ ) {
872
+ ensureProvidersInstalled()
873
+
874
+ AltcraftSDK.shared.pushSubscriptionFunctions.getStatusOfLatestSubscriptionForProvider(provider: provider) { result in
875
+ guard let result else { resolve(NSNull()); return }
876
+ resolve(self.mapResponseWithHttp(result))
877
+ }
878
+ }
879
+ }
880
+
881
+ // MARK: - Notification name
882
+
883
+ extension Notification.Name {
884
+ /// Notification posted when an SDK event is forwarded to JS.
885
+ ///
886
+ /// Must match ObjC++ constant: `SdkEventsNotificationName = @"AltcraftSdkEventNotification"`.
887
+ static let altcraftSdkEventNotification = Notification.Name("AltcraftSdkEventNotification")
888
+ }