@cavlyn/react-native-sdk 0.0.0-stage → 0.1.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 (51) hide show
  1. package/CavlynReactNative.podspec +22 -0
  2. package/LICENSE +202 -0
  3. package/README.md +164 -2
  4. package/android/build.gradle +47 -0
  5. package/android/src/main/AndroidManifest.xml +3 -0
  6. package/android/src/main/kotlin/com/cavlyn/reactnative/CavlynReactNativeModule.kt +384 -0
  7. package/android/src/main/kotlin/com/cavlyn/reactnative/CavlynReactNativePackage.kt +14 -0
  8. package/dist/client.d.ts +95 -0
  9. package/dist/client.d.ts.map +1 -0
  10. package/dist/client.js +395 -0
  11. package/dist/client.js.map +1 -0
  12. package/dist/hooks.d.ts +24 -0
  13. package/dist/hooks.d.ts.map +1 -0
  14. package/dist/hooks.js +78 -0
  15. package/dist/hooks.js.map +1 -0
  16. package/dist/http.d.ts +30 -0
  17. package/dist/http.d.ts.map +1 -0
  18. package/dist/http.js +126 -0
  19. package/dist/http.js.map +1 -0
  20. package/dist/index.d.ts +8 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +26 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/nativeBridge.d.ts +46 -0
  25. package/dist/nativeBridge.d.ts.map +1 -0
  26. package/dist/nativeBridge.js +99 -0
  27. package/dist/nativeBridge.js.map +1 -0
  28. package/dist/parser.d.ts +38 -0
  29. package/dist/parser.d.ts.map +1 -0
  30. package/dist/parser.js +198 -0
  31. package/dist/parser.js.map +1 -0
  32. package/dist/storage.d.ts +27 -0
  33. package/dist/storage.d.ts.map +1 -0
  34. package/dist/storage.js +72 -0
  35. package/dist/storage.js.map +1 -0
  36. package/dist/types.d.ts +182 -0
  37. package/dist/types.d.ts.map +1 -0
  38. package/dist/types.js +3 -0
  39. package/dist/types.js.map +1 -0
  40. package/ios/CavlynReactNative.m +40 -0
  41. package/ios/CavlynReactNative.swift +455 -0
  42. package/package.json +65 -4
  43. package/react-native.config.js +14 -0
  44. package/src/client.ts +479 -0
  45. package/src/hooks.ts +117 -0
  46. package/src/http.ts +158 -0
  47. package/src/index.ts +38 -0
  48. package/src/nativeBridge.ts +109 -0
  49. package/src/parser.ts +202 -0
  50. package/src/storage.ts +76 -0
  51. package/src/types.ts +214 -0
@@ -0,0 +1,455 @@
1
+ import Foundation
2
+ import React
3
+ import UIKit
4
+
5
+ #if canImport(AdServices)
6
+ import AdServices
7
+ #endif
8
+
9
+ @objc(CavlynReactNative)
10
+ public final class CavlynReactNative: RCTEventEmitter {
11
+ private static let eventNameLinkReceived = "CavlynLinkReceived"
12
+ private static let initialUriKey = "com.cavlyn.sdk.initial_uri"
13
+ private static let currentUriKey = "com.cavlyn.sdk.current_uri"
14
+ private static let installationIdKey = "com.cavlyn.sdk.installation_id"
15
+ private static let linkIdKeys: Set<String> = ["linkId", "link_id"]
16
+ private static let clickIdKeys: Set<String> = ["clickId", "click_id"]
17
+
18
+ private static weak var activeInstance: CavlynReactNative?
19
+ private static var pendingUrl: URL?
20
+ private static let staticLock = NSLock()
21
+
22
+ private let lock = NSLock()
23
+ private let queue = DispatchQueue(label: "com.cavlyn.rn.dispatcher", qos: .utility)
24
+ private let defaults = UserDefaults.standard
25
+ private let isoFormatter = ISO8601DateFormatter()
26
+
27
+ private var apiKey: String?
28
+ private var apiBaseUrl: String = "https://api.cavlyn.com"
29
+ private var isInitialized = false
30
+ private var hasListeners = false
31
+
32
+ public override init() {
33
+ super.init()
34
+ Self.staticLock.lock()
35
+ Self.activeInstance = self
36
+ Self.staticLock.unlock()
37
+ }
38
+
39
+ @objc
40
+ public override static func requiresMainQueueSetup() -> Bool {
41
+ return false
42
+ }
43
+
44
+ public override func supportedEvents() -> [String]! {
45
+ return [Self.eventNameLinkReceived]
46
+ }
47
+
48
+ public override func startObserving() {
49
+ lock.lock()
50
+ hasListeners = true
51
+ lock.unlock()
52
+ }
53
+
54
+ public override func stopObserving() {
55
+ lock.lock()
56
+ hasListeners = false
57
+ lock.unlock()
58
+ }
59
+
60
+ // MARK: - AppDelegate Helpers
61
+
62
+ /// Forward iOS Universal Links from `AppDelegate.application(_:continue:restorationHandler:)`.
63
+ @objc
64
+ @discardableResult
65
+ public static func application(
66
+ _ application: UIApplication,
67
+ continue userActivity: NSUserActivity,
68
+ restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void
69
+ ) -> Bool {
70
+ guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
71
+ let url = userActivity.webpageURL else {
72
+ return false
73
+ }
74
+ return handleIncomingUrlFromAppDelegate(url)
75
+ }
76
+
77
+ /// Forward custom URL schemes from `AppDelegate.application(_:open:options:)`.
78
+ @objc
79
+ @discardableResult
80
+ public static func application(
81
+ _ app: UIApplication,
82
+ open url: URL,
83
+ options: [UIApplication.OpenURLOptionsKey: Any] = [:]
84
+ ) -> Bool {
85
+ return handleIncomingUrlFromAppDelegate(url)
86
+ }
87
+
88
+ private static func handleIncomingUrlFromAppDelegate(_ url: URL) -> Bool {
89
+ staticLock.lock()
90
+ let instance = activeInstance
91
+ if instance == nil || !(instance?.isReady() ?? false) {
92
+ pendingUrl = url
93
+ staticLock.unlock()
94
+ return parse(url: url) != nil
95
+ }
96
+ staticLock.unlock()
97
+ return instance?.processUrl(url) != nil
98
+ }
99
+
100
+ private func isReady() -> Bool {
101
+ lock.lock()
102
+ defer { lock.unlock() }
103
+ return isInitialized
104
+ }
105
+
106
+ // MARK: - React Native Bridged Methods
107
+
108
+ @objc(initialize:apiBaseUrl:resolver:rejecter:)
109
+ public func initialize(
110
+ _ apiKey: String,
111
+ apiBaseUrl: String,
112
+ resolver resolve: @escaping RCTPromiseResolveBlock,
113
+ rejecter reject: @escaping RCTPromiseRejectBlock
114
+ ) {
115
+ let trimmedKey = apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
116
+ guard !trimmedKey.isEmpty else {
117
+ reject("INVALID_ARGS", "Cavlyn: apiKey is required", nil)
118
+ return
119
+ }
120
+
121
+ lock.lock()
122
+ if !isInitialized {
123
+ self.apiKey = trimmedKey
124
+ let trimmedUrl = apiBaseUrl.trimmingCharacters(in: .whitespacesAndNewlines)
125
+ self.apiBaseUrl = (trimmedUrl.isEmpty ? "https://api.cavlyn.com" : trimmedUrl)
126
+ .replacingOccurrences(of: "/+$", with: "", options: .regularExpression)
127
+ self.isInitialized = true
128
+ }
129
+ lock.unlock()
130
+
131
+ Self.staticLock.lock()
132
+ let buffered = Self.pendingUrl
133
+ Self.pendingUrl = nil
134
+ Self.staticLock.unlock()
135
+
136
+ if let url = buffered {
137
+ _ = processUrl(url)
138
+ }
139
+
140
+ resolve(nil)
141
+ }
142
+
143
+ @objc(handleUrl:resolver:rejecter:)
144
+ public func handleUrl(
145
+ _ urlString: String,
146
+ resolver resolve: @escaping RCTPromiseResolveBlock,
147
+ rejecter reject: @escaping RCTPromiseRejectBlock
148
+ ) {
149
+ guard isReady() else {
150
+ reject("NOT_INITIALIZED", "Call Cavlyn.initialize before using the SDK", nil)
151
+ return
152
+ }
153
+ guard let url = URL(string: urlString) else {
154
+ resolve(nil)
155
+ return
156
+ }
157
+ resolve(processUrl(url))
158
+ }
159
+
160
+ @objc(initialLink:rejecter:)
161
+ public func initialLink(
162
+ _ resolve: @escaping RCTPromiseResolveBlock,
163
+ rejecter reject: @escaping RCTPromiseRejectBlock
164
+ ) {
165
+ guard isReady() else {
166
+ reject("NOT_INITIALIZED", "Call Cavlyn.initialize before using the SDK", nil)
167
+ return
168
+ }
169
+ resolve(readStoredLink(forKey: Self.initialUriKey))
170
+ }
171
+
172
+ @objc(currentLink:rejecter:)
173
+ public func currentLink(
174
+ _ resolve: @escaping RCTPromiseResolveBlock,
175
+ rejecter reject: @escaping RCTPromiseRejectBlock
176
+ ) {
177
+ guard isReady() else {
178
+ reject("NOT_INITIALIZED", "Call Cavlyn.initialize before using the SDK", nil)
179
+ return
180
+ }
181
+ resolve(readStoredLink(forKey: Self.currentUriKey))
182
+ }
183
+
184
+ @objc(trackEvent:properties:resolver:rejecter:)
185
+ public func trackEvent(
186
+ _ name: String,
187
+ properties: NSDictionary,
188
+ resolver resolve: @escaping RCTPromiseResolveBlock,
189
+ rejecter reject: @escaping RCTPromiseRejectBlock
190
+ ) {
191
+ guard isReady() else {
192
+ reject("NOT_INITIALIZED", "Call Cavlyn.initialize before using the SDK", nil)
193
+ return
194
+ }
195
+ let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
196
+ guard !trimmed.isEmpty else {
197
+ reject("INVALID_ARGS", "Event name must not be blank", nil)
198
+ return
199
+ }
200
+
201
+ if let context = readStoredLink(forKey: Self.currentUriKey) ?? readStoredLink(forKey: Self.initialUriKey) {
202
+ let metadata = properties as? [String: Any] ?? [:]
203
+ dispatchEvent(
204
+ type: "CONVERSION",
205
+ eventName: trimmed,
206
+ link: context,
207
+ extraFields: [:],
208
+ metadata: metadata,
209
+ idempotencyKey: UUID().uuidString.lowercased()
210
+ )
211
+ }
212
+ resolve(nil)
213
+ }
214
+
215
+ @objc(trackCommerceEvent:resolver:rejecter:)
216
+ public func trackCommerceEvent(
217
+ _ payload: NSDictionary,
218
+ resolver resolve: @escaping RCTPromiseResolveBlock,
219
+ rejecter reject: @escaping RCTPromiseRejectBlock
220
+ ) {
221
+ guard isReady() else {
222
+ reject("NOT_INITIALIZED", "Call Cavlyn.initialize before using the SDK", nil)
223
+ return
224
+ }
225
+ guard let rawType = payload["type"] as? String, !rawType.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
226
+ reject("INVALID_ARGS", "Commerce event type is required", nil)
227
+ return
228
+ }
229
+
230
+ if let context = readStoredLink(forKey: Self.currentUriKey) ?? readStoredLink(forKey: Self.initialUriKey) {
231
+ var extra: [String: Any] = [:]
232
+ for key in ["storeId", "productId", "variantId", "orderId", "currency", "value", "quantity"] {
233
+ if let val = payload[key] {
234
+ extra[key] = val
235
+ }
236
+ }
237
+ let eventName = (payload["eventName"] as? String) ?? rawType.lowercased()
238
+ let metadata = payload["metadata"] as? [String: Any] ?? [:]
239
+ dispatchEvent(
240
+ type: rawType,
241
+ eventName: eventName,
242
+ link: context,
243
+ extraFields: extra,
244
+ metadata: metadata,
245
+ idempotencyKey: UUID().uuidString.lowercased()
246
+ )
247
+ }
248
+ resolve(nil)
249
+ }
250
+
251
+ @objc(getAdServicesToken:rejecter:)
252
+ public func getAdServicesToken(
253
+ _ resolve: @escaping RCTPromiseResolveBlock,
254
+ rejecter reject: @escaping RCTPromiseRejectBlock
255
+ ) {
256
+ #if canImport(AdServices)
257
+ if #available(iOS 14.3, *) {
258
+ do {
259
+ let token = try AAAttribution.attributionToken()
260
+ resolve(token)
261
+ return
262
+ } catch {
263
+ resolve(nil)
264
+ return
265
+ }
266
+ }
267
+ #endif
268
+ resolve(nil)
269
+ }
270
+
271
+ @objc(recordAdServicesToken:resolver:rejecter:)
272
+ public func recordAdServicesToken(
273
+ _ token: String,
274
+ resolver resolve: @escaping RCTPromiseResolveBlock,
275
+ rejecter reject: @escaping RCTPromiseRejectBlock
276
+ ) {
277
+ guard isReady() else {
278
+ reject("NOT_INITIALIZED", "Call Cavlyn.initialize before using the SDK", nil)
279
+ return
280
+ }
281
+ let trimmed = token.trimmingCharacters(in: .whitespacesAndNewlines)
282
+ if !trimmed.isEmpty,
283
+ let context = readStoredLink(forKey: Self.currentUriKey) ?? readStoredLink(forKey: Self.initialUriKey) {
284
+ dispatchEvent(
285
+ type: "CONVERSION",
286
+ eventName: "apple_search_ads_token",
287
+ link: context,
288
+ extraFields: [:],
289
+ metadata: ["adServicesToken": trimmed],
290
+ idempotencyKey: UUID().uuidString.lowercased()
291
+ )
292
+ }
293
+ resolve(nil)
294
+ }
295
+
296
+ @objc(getInstallationId:rejecter:)
297
+ public func getInstallationId(
298
+ _ resolve: @escaping RCTPromiseResolveBlock,
299
+ rejecter reject: @escaping RCTPromiseRejectBlock
300
+ ) {
301
+ resolve(getOrCreateInstallationId())
302
+ }
303
+
304
+ // MARK: - Internal Processing & Networking
305
+
306
+ private func processUrl(_ url: URL) -> [String: Any]? {
307
+ guard let link = Self.parse(url: url) else {
308
+ return nil
309
+ }
310
+
311
+ let installId = getOrCreateInstallationId()
312
+ lock.lock()
313
+ let isFirstLink = defaults.string(forKey: Self.initialUriKey) == nil
314
+ if isFirstLink {
315
+ defaults.set(url.absoluteString, forKey: Self.initialUriKey)
316
+ }
317
+ defaults.set(url.absoluteString, forKey: Self.currentUriKey)
318
+ let shouldEmit = hasListeners
319
+ lock.unlock()
320
+
321
+ if isFirstLink, let linkId = link["linkId"] as? String {
322
+ dispatchEvent(
323
+ type: "INSTALL",
324
+ eventName: nil,
325
+ link: link,
326
+ extraFields: [:],
327
+ metadata: [:],
328
+ idempotencyKey: "install:\(installId):\(linkId)"
329
+ )
330
+ }
331
+
332
+ dispatchEvent(
333
+ type: "APP_OPEN",
334
+ eventName: "app_open",
335
+ link: link,
336
+ extraFields: [:],
337
+ metadata: [:],
338
+ idempotencyKey: UUID().uuidString.lowercased()
339
+ )
340
+
341
+ if shouldEmit {
342
+ sendEvent(withName: Self.eventNameLinkReceived, body: link)
343
+ }
344
+
345
+ return link
346
+ }
347
+
348
+ private static func parse(url: URL) -> [String: Any]? {
349
+ guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true),
350
+ let queryItems = components.queryItems else {
351
+ return nil
352
+ }
353
+
354
+ var params: [String: String] = [:]
355
+ var linkIdUUID: UUID?
356
+ var clickIdUUID: UUID?
357
+
358
+ for item in queryItems {
359
+ let key = item.name
360
+ let value = item.value ?? ""
361
+ if linkIdKeys.contains(key) {
362
+ if linkIdUUID == nil { linkIdUUID = UUID(uuidString: value) }
363
+ } else if clickIdKeys.contains(key) {
364
+ if clickIdUUID == nil { clickIdUUID = UUID(uuidString: value) }
365
+ } else {
366
+ params[key] = value
367
+ }
368
+ }
369
+
370
+ guard let validLinkId = linkIdUUID else {
371
+ return nil
372
+ }
373
+
374
+ var result: [String: Any] = [
375
+ "uri": url.absoluteString,
376
+ "linkId": validLinkId.uuidString.lowercased(),
377
+ "parameters": params
378
+ ]
379
+ if let validClickId = clickIdUUID {
380
+ result["clickId"] = validClickId.uuidString.lowercased()
381
+ }
382
+ return result
383
+ }
384
+
385
+ private func readStoredLink(forKey key: String) -> [String: Any]? {
386
+ guard let uriString = defaults.string(forKey: key),
387
+ let url = URL(string: uriString) else {
388
+ return nil
389
+ }
390
+ return Self.parse(url: url)
391
+ }
392
+
393
+ private func getOrCreateInstallationId() -> String {
394
+ if let existing = defaults.string(forKey: Self.installationIdKey), !existing.isEmpty {
395
+ return existing
396
+ }
397
+ let fresh = UUID().uuidString.lowercased()
398
+ defaults.set(fresh, forKey: Self.installationIdKey)
399
+ return fresh
400
+ }
401
+
402
+ private func dispatchEvent(
403
+ type: String,
404
+ eventName: String?,
405
+ link: [String: Any],
406
+ extraFields: [String: Any],
407
+ metadata: [String: Any],
408
+ idempotencyKey: String
409
+ ) {
410
+ lock.lock()
411
+ let key = apiKey
412
+ let baseUrl = apiBaseUrl
413
+ lock.unlock()
414
+
415
+ guard let apiKey = key,
416
+ let linkId = link["linkId"] as? String,
417
+ let endpoint = URL(string: "\(baseUrl)/api/v1/events") else {
418
+ return
419
+ }
420
+
421
+ var body: [String: Any] = [
422
+ "linkId": linkId,
423
+ "type": type,
424
+ "installId": getOrCreateInstallationId(),
425
+ "platform": "IOS",
426
+ "occurredAt": isoFormatter.string(from: Date()),
427
+ "metadata": metadata
428
+ ]
429
+ if let clickId = link["clickId"] as? String {
430
+ body["clickId"] = clickId
431
+ }
432
+ if let eventName = eventName, type != "INSTALL" {
433
+ body["eventName"] = eventName
434
+ }
435
+ for (field, value) in extraFields {
436
+ body[field] = value
437
+ }
438
+
439
+ queue.async {
440
+ var request = URLRequest(url: endpoint)
441
+ request.httpMethod = "POST"
442
+ request.timeoutInterval = 10
443
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
444
+ request.setValue(apiKey, forHTTPHeaderField: "X-API-Key")
445
+ request.setValue(idempotencyKey, forHTTPHeaderField: "Idempotency-Key")
446
+ guard let jsonData = try? JSONSerialization.data(withJSONObject: body, options: []) else {
447
+ return
448
+ }
449
+ request.httpBody = jsonData
450
+ URLSession.shared.dataTask(with: request) { _, _, _ in
451
+ // Non-fatal to host application runtime
452
+ }.resume()
453
+ }
454
+ }
455
+ }
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "@cavlyn/react-native-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "React Native SDK for Cavlyn dynamic links, Universal Links / App Links routing, deferred link resolution, and install/conversion/commerce attribution.",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "react-native": "src/index.ts",
8
+ "files": [
9
+ "dist",
10
+ "src",
11
+ "ios",
12
+ "android",
13
+ "CavlynReactNative.podspec",
14
+ "react-native.config.js",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsc -p tsconfig.json",
20
+ "clean": "rm -rf dist",
21
+ "test": "node --test tests/*.test.js",
22
+ "prepublishOnly": "npm run clean && npm run build && npm test"
23
+ },
24
+ "keywords": [
25
+ "react-native",
26
+ "expo",
27
+ "cavlyn",
28
+ "dynamic-links",
29
+ "deep-linking",
30
+ "universal-links",
31
+ "app-links",
32
+ "attribution",
33
+ "deferred-deep-linking"
34
+ ],
35
+ "author": "Cavlyn System <dev@cavlyn.com>",
36
+ "license": "Apache-2.0",
37
+ "homepage": "https://github.com/casontek/smart-attribution-system/tree/main/sdk/react-native#readme",
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/casontek/smart-attribution-system.git",
41
+ "directory": "sdk/react-native"
42
+ },
43
+ "bugs": {
44
+ "url": "https://github.com/casontek/smart-attribution-system/issues"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ },
49
+ "peerDependencies": {
50
+ "react": ">=18.0.0",
51
+ "react-native": ">=0.72.0"
52
+ },
53
+ "peerDependenciesMeta": {
54
+ "react": {
55
+ "optional": true
56
+ },
57
+ "react-native": {
58
+ "optional": true
59
+ }
60
+ },
61
+ "devDependencies": {
62
+ "typescript": "^5.7.0"
63
+ },
64
+ "engines": {
65
+ "node": ">=18.0.0"
66
+ }
67
+ }
@@ -0,0 +1,14 @@
1
+ module.exports = {
2
+ dependency: {
3
+ platforms: {
4
+ ios: {
5
+ podspecPath: './CavlynReactNative.podspec',
6
+ },
7
+ android: {
8
+ sourceDir: './android',
9
+ packageImportPath: 'import com.cavlyn.reactnative.CavlynReactNativePackage;',
10
+ packageInstance: 'new CavlynReactNativePackage()',
11
+ },
12
+ },
13
+ },
14
+ };