@altcraft/react-native-sdk 0.0.4 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +48 -20
  2. package/README.md +21 -120
  3. package/autolink.js +36 -0
  4. package/lib/commonjs/altcraft_sdk.js +297 -0
  5. package/lib/commonjs/altcraft_sdk.js.map +1 -0
  6. package/lib/commonjs/index.js +192 -0
  7. package/lib/commonjs/index.js.map +1 -0
  8. package/lib/commonjs/package.json +1 -0
  9. package/lib/module/altcraft_sdk.js +292 -0
  10. package/lib/module/altcraft_sdk.js.map +1 -0
  11. package/lib/module/index.js +13 -427
  12. package/lib/module/index.js.map +1 -1
  13. package/lib/typescript/commonjs/package.json +1 -0
  14. package/lib/typescript/commonjs/src/altcraft_sdk.d.ts +143 -0
  15. package/lib/typescript/commonjs/src/altcraft_sdk.d.ts.map +1 -0
  16. package/lib/typescript/commonjs/src/index.d.ts +24 -0
  17. package/lib/typescript/commonjs/src/index.d.ts.map +1 -0
  18. package/lib/typescript/module/src/altcraft_sdk.d.ts +143 -0
  19. package/lib/typescript/module/src/altcraft_sdk.d.ts.map +1 -0
  20. package/lib/typescript/module/src/index.d.ts +24 -0
  21. package/lib/typescript/module/src/index.d.ts.map +1 -0
  22. package/package.json +49 -95
  23. package/scripts/postinstall.cjs +195 -0
  24. package/src/altcraft_sdk.ts +337 -0
  25. package/src/index.ts +91 -0
  26. package/Sdk.podspec +0 -48
  27. package/android/build.gradle +0 -77
  28. package/android/gradle.properties +0 -5
  29. package/android/src/main/AndroidManifest.xml +0 -2
  30. package/android/src/main/java/com/altcraft/sdk/SdkEventEmitter.kt +0 -50
  31. package/android/src/main/java/com/altcraft/sdk/SdkModule.kt +0 -949
  32. package/android/src/main/java/com/altcraft/sdk/SdkPackage.kt +0 -41
  33. package/android/src/main/java/com/altcraft/sdk/utilities/Converter.kt +0 -326
  34. package/android/src/main/java/com/altcraft/sdk/utilities/Extension.kt +0 -72
  35. package/ios/Converter.swift +0 -640
  36. package/ios/Sdk.h +0 -20
  37. package/ios/Sdk.mm +0 -979
  38. package/ios/SdkModule.swift +0 -778
  39. package/lib/module/NativeSdk.js +0 -48
  40. package/lib/module/NativeSdk.js.map +0 -1
  41. package/lib/module/Utilities.js +0 -178
  42. package/lib/module/Utilities.js.map +0 -1
  43. package/lib/typescript/src/NativeSdk.d.ts +0 -215
  44. package/lib/typescript/src/NativeSdk.d.ts.map +0 -1
  45. package/lib/typescript/src/Utilities.d.ts +0 -47
  46. package/lib/typescript/src/Utilities.d.ts.map +0 -1
  47. package/lib/typescript/src/index.d.ts +0 -252
  48. package/lib/typescript/src/index.d.ts.map +0 -1
  49. package/react-native.config.js +0 -10
  50. package/src/NativeSdk.ts +0 -313
  51. package/src/Utilities.ts +0 -180
  52. package/src/index.tsx +0 -570
  53. /package/lib/typescript/{package.json → module/package.json} +0 -0
@@ -1,778 +0,0 @@
1
- //
2
- // SdkModule.swift
3
- // AltcraftRnBridge
4
- //
5
- // Created by Andrey Pogodin.
6
- //
7
- // Copyright © 2026 Altcraft. All rights reserved.
8
-
9
-
10
- import Foundation
11
- import Altcraft
12
- import React
13
-
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
-
78
- @objc(SdkModule)
79
- @objcMembers
80
- @available(iOSApplicationExtension, unavailable)
81
- public final class SdkModule: NSObject, @unchecked Sendable {
82
-
83
- // MARK: - Singleton & State
84
-
85
- /// Shared singleton instance used by the React Native bridge.
86
- public static let shared = SdkModule()
87
-
88
- private let lock = NSLock()
89
- private var configuration: AltcraftConfiguration?
90
-
91
- // MARK: - SDK Initialization (RN Promise)
92
-
93
- /// Initializes the Altcraft SDK using a React Native configuration object.
94
- ///
95
- /// The configuration dictionary supports:
96
- /// - Required: `apiUrl` (String)
97
- /// - Optional: `rToken` (String), `enableLogging` (Bool), `providerPriorityList` ([String]),
98
- /// `appInfo` (Map with `appID`, `appIID`, `appVer`)
99
- ///
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.
104
- @objc(initializeWithConfig:resolver:rejecter:)
105
- public func initialize(
106
- _ config: NSDictionary,
107
- resolver resolve: @escaping RCTPromiseResolveBlock,
108
- rejecter reject: @escaping RCTPromiseRejectBlock
109
- ) {
110
- let dict: [String: Any?] = Converter.toAnyDict(config) ?? [:]
111
-
112
- guard let apiUrl = dict[RnConstants.keyApiUrl] as? String, !apiUrl.isEmpty else {
113
- reject(RnConstants.errInitInvalidConfig, RnConstants.msgApiUrlRequired, nil)
114
- return
115
- }
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
-
122
- guard let built = AltcraftConfiguration.Builder()
123
- .setApiUrl(apiUrl)
124
- .setRToken(rToken)
125
- .setAppInfo(appInfo)
126
- .setProviderPriorityList(providerPriorityList)
127
- .setEnableLogging(enableLogging)
128
- .build()
129
- else {
130
- reject(
131
- RnConstants.errInitInvalidConfig,
132
- RnConstants.msgInvalidConfiguration,
133
- nil
134
- )
135
- return
136
- }
137
-
138
- lock.lock()
139
- configuration = built
140
- lock.unlock()
141
-
142
- let resolveBox = UncheckedSendableBox(resolve)
143
- let rejectBox = UncheckedSendableBox(reject)
144
- AltcraftSDK.shared.initialization(configuration: built) { ok in
145
- if ok { resolveBox.value(nil) }
146
- else {
147
- rejectBox.value(
148
- RnConstants.errInitError,
149
- RnConstants.msgInitializationFailed, nil
150
- )
151
- }
152
- }
153
- }
154
-
155
- // MARK: - NativeEventEmitter compatibility
156
-
157
- /// Required by `NativeEventEmitter` on the JS side. No-op on iOS.
158
- ///
159
- /// - Parameter eventName: Event name from JS.
160
- public func addListener(_ eventName: String) { _ = eventName }
161
-
162
- /// Required by `NativeEventEmitter` on the JS side. No-op on iOS.
163
- ///
164
- /// - Parameter count: Number of listeners removed on JS side.
165
- public func removeListeners(_ count: NSNumber) { _ = count }
166
-
167
- // MARK: - RCTEventEmitter
168
-
169
- @objc(SDKEventEmitter)
170
- final class SDKEventEmitter: RCTEventEmitter, @unchecked Sendable {
171
-
172
- nonisolated(unsafe) static var _shared: SDKEventEmitter?
173
- nonisolated(unsafe) static var pending: [(String, Any?)] = []
174
- private static let pendingLock = NSLock()
175
-
176
- /// Creates the event emitter instance and flushes any buffered events.
177
- override init() {
178
- super.init()
179
- SDKEventEmitter._shared = self
180
- SDKEventEmitter.flushPendingIfPossible()
181
- }
182
-
183
- /// Returns the list of supported event names for React Native.
184
- override func supportedEvents() -> [String]! {
185
- [RnConstants.jsEventName]
186
- }
187
-
188
- /// Indicates that this module must be initialized on the main thread.
189
- @objc override static func requiresMainQueueSetup() -> Bool {
190
- true
191
- }
192
-
193
- /// Emits an Altcraft event with an integer code to JS.
194
- ///
195
- /// - Parameter code: Event code.
196
- @objc static func emitAltcraft(code: Int) {
197
- emit(name: RnConstants.jsEventName, body: [RnConstants.keyCode: code])
198
- }
199
-
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.
205
- @objc static func emit(name: String, body: Any?) {
206
- let n = name
207
- let b = body
208
- let deliver: @convention(block) () -> Void = {
209
- if let emitter = _shared {
210
- emitter.sendEvent(withName: n, body: b)
211
- } else {
212
- buffer(name: n, body: b)
213
- }
214
- }
215
-
216
- if Thread.isMainThread { deliver() }
217
- else { DispatchQueue.main.async(execute: deliver) }
218
- }
219
-
220
- /// Buffers an event until the emitter becomes available.
221
- private static func buffer(name: String, body: Any?) {
222
- pendingLock.lock()
223
- pending.append((name, body))
224
- pendingLock.unlock()
225
- }
226
-
227
- /// Flushes buffered events if the emitter is available, always on the main thread.
228
- private static func flushPendingIfPossible() {
229
- guard Thread.isMainThread else {
230
- DispatchQueue.main.async { flushPendingIfPossible() }
231
- return
232
- }
233
- guard let emitter = _shared else { return }
234
-
235
- pendingLock.lock()
236
- let toSend = pending
237
- pending.removeAll()
238
- pendingLock.unlock()
239
-
240
- for (name, body) in toSend {
241
- emitter.sendEvent(withName: name, body: body)
242
- }
243
- }
244
- }
245
-
246
- // MARK: - SDK Events subscription
247
-
248
- private var eventsSubscribed: Bool = false
249
-
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.
253
- public func subscribeToEvents() {
254
- lock.lock()
255
- let already = eventsSubscribed
256
- if !already { eventsSubscribed = true }
257
- lock.unlock()
258
- if already { return }
259
-
260
- SDKEvents.shared.subscribe { [weak self] event in
261
- guard let self else { return }
262
- SDKEventEmitter.emit(
263
- name: RnConstants.jsEventName,
264
- body: toPayload(event)
265
- )
266
- }
267
- }
268
-
269
- /// Unsubscribes from native SDK events.
270
- public func unsubscribeFromEvent() {
271
- lock.lock()
272
- eventsSubscribed = false
273
- lock.unlock()
274
- SDKEvents.shared.unsubscribe()
275
- }
276
-
277
- // MARK: - Event payload mapping
278
-
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`.
283
- private func toPayload(_ event: Event) -> [String: Any] {
284
- let type: String
285
- if event is RetryEvent { type = RnConstants.typeRetryError }
286
- else if event is ErrorEvent { type = RnConstants.typeError }
287
- else { type = RnConstants.typeEvent }
288
-
289
- return [
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()
295
- ]
296
- }
297
-
298
- // MARK: - SDK Clear (RN Promise)
299
-
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).
305
- @objc(clearWithResolver:rejecter:)
306
- public func clear(
307
- resolver resolve: @escaping RCTPromiseResolveBlock,
308
- rejecter reject: @escaping RCTPromiseRejectBlock
309
- ) {
310
- _ = reject
311
- AltcraftSDK.shared.clear { resolve(nil) }
312
- }
313
-
314
- // MARK: - Token API wrappers (ONLY getPushToken / setPushToken)
315
-
316
- /// Returns the current push token data from the native SDK.
317
- ///
318
- /// - Parameter completion: Called with `{ provider, token }` or `nil` if unavailable.
319
- @objc(getPushTokenWithCompletion:)
320
- public func getPushToken(_ completion: @escaping ([String: Any]?) -> Void) {
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
327
- ])
328
- }
329
- }
330
-
331
- /// Sets (or clears) the push token for a given provider.
332
- ///
333
- /// - Parameters:
334
- /// - provider: Provider identifier (e.g., `apns`, `fcm`).
335
- /// - pushToken: Token value. `nil` / `NSNull` clears the token. Non-string values are stringified.
336
- @objc(setPushTokenWithProvider:pushToken:)
337
- public func setPushToken(provider: String, pushToken: Any?) {
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
- }()
343
-
344
- AltcraftSDK.shared.pushTokenFunctions.setPushToken(
345
- provider: provider,
346
- pushToken: (tokenStr ?? "")
347
- )
348
- }
349
-
350
- // MARK: - Push Subscription (void)
351
-
352
- /// Sends a push subscribe request (fire-and-forget).
353
- ///
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.
361
- @objc(pushSubscribe:profileFields:customFields:cats:replace:skipTriggers:)
362
- public func pushSubscribe(
363
- _ sync: NSNumber?,
364
- profileFields: NSDictionary?,
365
- customFields: NSDictionary?,
366
- cats: NSArray?,
367
- replace: NSNumber?,
368
- skipTriggers: NSNumber?
369
- ) {
370
- let s = sync?.boolValue ?? true
371
- let r: Bool? = (replace != nil) ? replace!.boolValue : nil
372
- let st: Bool? = (skipTriggers != nil) ? skipTriggers!.boolValue : nil
373
-
374
- AltcraftSDK.shared.pushSubscriptionFunctions.pushSubscribe(
375
- sync: s,
376
- profileFields: Converter.toAnyDict(profileFields),
377
- customFields: Converter.toAnyDict(customFields),
378
- cats: Converter.toCats(cats),
379
- replace: r,
380
- skipTriggers: st
381
- )
382
- }
383
-
384
- /// Sends a push suspend request (fire-and-forget).
385
- ///
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.
393
- @objc(pushSuspend:profileFields:customFields:cats:replace:skipTriggers:)
394
- public func pushSuspend(
395
- _ sync: NSNumber?,
396
- profileFields: NSDictionary?,
397
- customFields: NSDictionary?,
398
- cats: NSArray?,
399
- replace: NSNumber?,
400
- skipTriggers: NSNumber?
401
- ) {
402
- let s = sync?.boolValue ?? true
403
- let r: Bool? = (replace != nil) ? replace!.boolValue : nil
404
- let st: Bool? = (skipTriggers != nil) ? skipTriggers!.boolValue : nil
405
-
406
- AltcraftSDK.shared.pushSubscriptionFunctions.pushSuspend(
407
- sync: s,
408
- profileFields: Converter.toAnyDict(profileFields),
409
- customFields: Converter.toAnyDict(customFields),
410
- cats: Converter.toCats(cats),
411
- replace: r,
412
- skipTriggers: st
413
- )
414
- }
415
-
416
- /// Sends a push unsubscribe request (fire-and-forget).
417
- ///
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.
425
- @objc(pushUnSubscribe:profileFields:customFields:cats:replace:skipTriggers:)
426
- public func pushUnSubscribe(
427
- _ sync: NSNumber?,
428
- profileFields: NSDictionary?,
429
- customFields: NSDictionary?,
430
- cats: NSArray?,
431
- replace: NSNumber?,
432
- skipTriggers: NSNumber?
433
- ) {
434
- let s = sync?.boolValue ?? true
435
- let r: Bool? = (replace != nil) ? replace!.boolValue : nil
436
- let st: Bool? = (skipTriggers != nil) ? skipTriggers!.boolValue : nil
437
-
438
- AltcraftSDK.shared.pushSubscriptionFunctions.pushUnSubscribe(
439
- sync: s,
440
- profileFields: Converter.toAnyDict(profileFields),
441
- customFields: Converter.toAnyDict(customFields),
442
- cats: Converter.toCats(cats),
443
- replace: r,
444
- skipTriggers: st
445
- )
446
- }
447
-
448
- // MARK: - Mobile Events bridge
449
-
450
- /// Sends a mobile event to the server (fire-and-forget).
451
- ///
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:)
463
- public func mobileEvent(
464
- _ sid: String,
465
- eventName: String,
466
- sendMessageId: String?,
467
- payload: NSDictionary?,
468
- matching: NSDictionary?,
469
- matchingType: String?,
470
- profileFields: NSDictionary?,
471
- subscription: NSDictionary?,
472
- utm: NSDictionary?
473
- ) {
474
- let utmObj = Converter.toUTM(utm)
475
- let subscriptionObj = Converter.toSubscription(subscription)
476
-
477
- AltcraftSDK.shared.mobileEventFunctions.mobileEvent(
478
- sid: sid,
479
- altcraftClientID: "",
480
- eventName: eventName,
481
- sendMessageId: sendMessageId,
482
- payload: Converter.toAnyDict(payload),
483
- matching: Converter.toAnyDict(matching),
484
- matchingType: matchingType,
485
- profileFields: Converter.toAnyDict(profileFields),
486
- subscription: subscriptionObj,
487
- utm: utmObj
488
- )
489
- }
490
-
491
- // MARK: - Promise API: PushSubscription status/results
492
-
493
- private func nsNull(_ v: Any?) -> Any { v ?? NSNull() }
494
-
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).
500
- @objc(unSuspendPushSubscriptionWithResolver:rejecter:)
501
- public func unSuspendPushSubscription(
502
- resolver resolve: @escaping RCTPromiseResolveBlock,
503
- rejecter reject: @escaping RCTPromiseRejectBlock
504
- ) {
505
- let resolveBox = UncheckedSendableBox(resolve)
506
- _ = reject
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))
511
- }
512
- }
513
-
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).
519
- @objc(getStatusOfLatestSubscriptionWithResolver:rejecter:)
520
- public func getStatusOfLatestSubscription(
521
- resolver resolve: @escaping RCTPromiseResolveBlock,
522
- rejecter reject: @escaping RCTPromiseRejectBlock
523
- ) {
524
- let resolveBox = UncheckedSendableBox(resolve)
525
- _ = reject
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))
530
- }
531
- }
532
-
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).
538
- @objc(getStatusForCurrentSubscriptionWithResolver:rejecter:)
539
- public func getStatusForCurrentSubscription(
540
- resolver resolve: @escaping RCTPromiseResolveBlock,
541
- rejecter reject: @escaping RCTPromiseRejectBlock
542
- ) {
543
- let resolveBox = UncheckedSendableBox(resolve)
544
- _ = reject
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))
549
- }
550
- }
551
-
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).
558
- @objc(getStatusOfLatestSubscriptionForProviderWithProvider:resolver:rejecter:)
559
- public func getStatusOfLatestSubscriptionForProvider(
560
- provider: String?,
561
- resolver resolve: @escaping RCTPromiseResolveBlock,
562
- rejecter reject: @escaping RCTPromiseRejectBlock
563
- ) {
564
- _ = reject
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
- }
587
-
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
- ]
643
- }
644
-
645
- // MARK: - UserDefaults
646
-
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
656
- ///
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.
661
- @objc(setUserDefaultsValueWithSuiteName:key:value:)
662
- public func setUserDefaultsValue(
663
- suiteName: String?,
664
- key: String,
665
- value: Any?
666
- ) {
667
- let k = key.trimmingCharacters(in: .whitespacesAndNewlines)
668
- if k.isEmpty { return }
669
-
670
- let sn = suiteName?.trimmingCharacters(in: .whitespacesAndNewlines)
671
- let ud: UserDefaults = {
672
- if let sn, !sn.isEmpty, let g = UserDefaults(suiteName: sn) { return g }
673
- return .standard
674
- }()
675
-
676
- if value == nil || value is NSNull {
677
- ud.removeObject(forKey: k)
678
- return
679
- }
680
-
681
- if let plist = Converter.toPropertyListValue(value) {
682
- ud.set(plist, forKey: k)
683
- } else {
684
- ud.removeObject(forKey: k)
685
- }
686
- }
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
- }