@kerdly/expo 0.0.0-stage → 0.1.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 (113) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +235 -2
  3. package/android/build.gradle +61 -0
  4. package/android/src/main/AndroidManifest.xml +19 -0
  5. package/android/src/main/java/com/kerdly/expo/KerdlySdkModule.kt +326 -0
  6. package/android/vendor/kerdly-sdk/.kerdly-sync.json +8 -0
  7. package/android/vendor/kerdly-sdk/consumer-rules.pro +15 -0
  8. package/android/vendor/kerdly-sdk/kerdly-sdk.properties +2 -0
  9. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/Kerdly.kt +343 -0
  10. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/KerdlyTypes.kt +89 -0
  11. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Attribution.kt +39 -0
  12. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Batch.kt +159 -0
  13. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Core.kt +991 -0
  14. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeepLinks.kt +114 -0
  15. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeferredLinks.kt +110 -0
  16. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeviceContext.kt +137 -0
  17. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/EventQueue.kt +135 -0
  18. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Events.kt +314 -0
  19. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Json.kt +116 -0
  20. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Logger.kt +49 -0
  21. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Options.kt +47 -0
  22. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Ports.kt +83 -0
  23. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/PublicIp.kt +120 -0
  24. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Referrers.kt +137 -0
  25. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/RemoteConfig.kt +100 -0
  26. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Storage.kt +271 -0
  27. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidPlatform.kt +274 -0
  28. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidRuntime.kt +187 -0
  29. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/PlayReferrerReader.kt +97 -0
  30. package/app.plugin.js +2 -0
  31. package/build/Kerdly.d.ts +106 -0
  32. package/build/Kerdly.d.ts.map +1 -0
  33. package/build/Kerdly.js +494 -0
  34. package/build/Kerdly.js.map +1 -0
  35. package/build/index.d.ts +4 -0
  36. package/build/index.d.ts.map +1 -0
  37. package/build/index.js +2 -0
  38. package/build/index.js.map +1 -0
  39. package/build/log.d.ts +13 -0
  40. package/build/log.d.ts.map +1 -0
  41. package/build/log.js +45 -0
  42. package/build/log.js.map +1 -0
  43. package/build/native.d.ts +74 -0
  44. package/build/native.d.ts.map +1 -0
  45. package/build/native.js +56 -0
  46. package/build/native.js.map +1 -0
  47. package/build/normalize.d.ts +8 -0
  48. package/build/normalize.d.ts.map +1 -0
  49. package/build/normalize.js +86 -0
  50. package/build/normalize.js.map +1 -0
  51. package/build/types.d.ts +134 -0
  52. package/build/types.d.ts.map +1 -0
  53. package/build/types.js +3 -0
  54. package/build/types.js.map +1 -0
  55. package/build/validation.d.ts +70 -0
  56. package/build/validation.d.ts.map +1 -0
  57. package/build/validation.js +349 -0
  58. package/build/validation.js.map +1 -0
  59. package/build/version.d.ts +4 -0
  60. package/build/version.d.ts.map +1 -0
  61. package/build/version.js +5 -0
  62. package/build/version.js.map +1 -0
  63. package/expo-module.config.json +9 -0
  64. package/ios/KerdlySDK/.kerdly-sync.json +7 -0
  65. package/ios/KerdlySDK/Core/Dependencies.swift +163 -0
  66. package/ios/KerdlySDK/Core/KerdlyCore+API.swift +117 -0
  67. package/ios/KerdlySDK/Core/KerdlyCore+Collectors.swift +410 -0
  68. package/ios/KerdlySDK/Core/KerdlyCore+DeferredLinks.swift +220 -0
  69. package/ios/KerdlySDK/Core/KerdlyCore+Delivery.swift +424 -0
  70. package/ios/KerdlySDK/Core/KerdlyCore.swift +557 -0
  71. package/ios/KerdlySDK/Core/Support.swift +95 -0
  72. package/ios/KerdlySDK/Logic/Backoff.swift +22 -0
  73. package/ios/KerdlySDK/Logic/Batch.swift +180 -0
  74. package/ios/KerdlySDK/Logic/Context.swift +85 -0
  75. package/ios/KerdlySDK/Logic/DeepLinks.swift +93 -0
  76. package/ios/KerdlySDK/Logic/DeferredLinks.swift +236 -0
  77. package/ios/KerdlySDK/Logic/Environment.swift +39 -0
  78. package/ios/KerdlySDK/Logic/EventQueue.swift +85 -0
  79. package/ios/KerdlySDK/Logic/EventValidator.swift +84 -0
  80. package/ios/KerdlySDK/Logic/Events.swift +102 -0
  81. package/ios/KerdlySDK/Logic/IPv6Address.swift +26 -0
  82. package/ios/KerdlySDK/Logic/InstallIdentity.swift +106 -0
  83. package/ios/KerdlySDK/Logic/JSONValue.swift +198 -0
  84. package/ios/KerdlySDK/Logic/Purchases.swift +84 -0
  85. package/ios/KerdlySDK/Logic/RemoteConfig.swift +185 -0
  86. package/ios/KerdlySDK/Logic/Skan.swift +343 -0
  87. package/ios/KerdlySDK/Logic/StandardEvents.swift +126 -0
  88. package/ios/KerdlySDK/Platform/AdSignals.swift +19 -0
  89. package/ios/KerdlySDK/Platform/DeferredLinkBundle.swift +25 -0
  90. package/ios/KerdlySDK/Platform/DeviceInfo.swift +82 -0
  91. package/ios/KerdlySDK/Platform/Lifecycle.swift +74 -0
  92. package/ios/KerdlySDK/Platform/PublicIp.swift +33 -0
  93. package/ios/KerdlySDK/Platform/SkanWriter.swift +70 -0
  94. package/ios/KerdlySDK/Platform/StoreKitAdapter.swift +185 -0
  95. package/ios/KerdlySDK/Platform/SystemStores.swift +200 -0
  96. package/ios/KerdlySDK/Platform/Tracking.swift +124 -0
  97. package/ios/KerdlySDK/Public/Kerdly.swift +202 -0
  98. package/ios/KerdlySDK/Public/KerdlyTypes.swift +130 -0
  99. package/ios/KerdlySDK/Resources/PrivacyInfo.xcprivacy +96 -0
  100. package/ios/KerdlySDK/Storage/PersistedState.swift +175 -0
  101. package/ios/KerdlySDK/Storage/StateStore.swift +36 -0
  102. package/ios/KerdlySdk.podspec +45 -0
  103. package/ios/KerdlySdkModule.swift +332 -0
  104. package/package.json +96 -4
  105. package/plugin/withKerdly.js +163 -0
  106. package/src/Kerdly.ts +524 -0
  107. package/src/index.ts +23 -0
  108. package/src/log.ts +49 -0
  109. package/src/native.ts +150 -0
  110. package/src/normalize.ts +82 -0
  111. package/src/types.ts +182 -0
  112. package/src/validation.ts +343 -0
  113. package/src/version.ts +5 -0
@@ -0,0 +1,15 @@
1
+ # Applied to the host app's R8/ProGuard run.
2
+ #
3
+ # The public API stays intact for wrappers that reach it by name (the Expo bridge, Java callers,
4
+ # reflection-based bridges). Everything under com.kerdly.sdk.internal may be shrunk and obfuscated.
5
+ -keep class com.kerdly.sdk.Kerdly { public *; }
6
+ -keep class com.kerdly.sdk.KerdlyOptions { *; }
7
+ -keep class com.kerdly.sdk.KerdlyDeepLink { *; }
8
+ -keep class com.kerdly.sdk.KerdlyPurchase { *; }
9
+ -keep class com.kerdly.sdk.KerdlyNetworkSend { *; }
10
+ -keep class com.kerdly.sdk.KerdlyAttribution { *; }
11
+ -keep enum com.kerdly.sdk.KerdlyEnvironment { *; }
12
+ -keep enum com.kerdly.sdk.KerdlyLogLevel { *; }
13
+
14
+ # Install Referrer and the advertising-id client are called directly (no reflection) and ship
15
+ # their own consumer rules.
@@ -0,0 +1,2 @@
1
+ # Written by scripts/sync-native.mjs from android/gradle.properties
2
+ KERDLY_VERSION=0.1.0
@@ -0,0 +1,343 @@
1
+ package com.kerdly.sdk
2
+
3
+ import android.app.Application
4
+ import android.content.Context
5
+ import android.os.StrictMode
6
+ import com.kerdly.sdk.internal.Clock
7
+ import com.kerdly.sdk.internal.Core
8
+ import com.kerdly.sdk.internal.CoreConfig
9
+ import com.kerdly.sdk.internal.DeepLinkSources
10
+ import com.kerdly.sdk.internal.DeepLinks
11
+ import com.kerdly.sdk.internal.FileStore
12
+ import com.kerdly.sdk.internal.InstallId
13
+ import com.kerdly.sdk.internal.Launch
14
+ import com.kerdly.sdk.internal.Logger
15
+ import com.kerdly.sdk.internal.OptionRules
16
+ import com.kerdly.sdk.internal.Scheduler
17
+ import com.kerdly.sdk.internal.StandardEvents
18
+ import com.kerdly.sdk.internal.android.AndroidLogSink
19
+ import com.kerdly.sdk.internal.android.AndroidPlatform
20
+ import com.kerdly.sdk.internal.android.ExecutorScheduler
21
+ import com.kerdly.sdk.internal.android.HttpUrlTransport
22
+ import com.kerdly.sdk.internal.android.LifecycleTracker
23
+ import com.kerdly.sdk.internal.android.MainThreadDispatcher
24
+ import com.kerdly.sdk.internal.sdkDirectory
25
+
26
+ /** The Kerdly SDK (protocol v1). Call [configure] once, in `Application.onCreate`.
27
+ *
28
+ * Every method is safe from any thread, returns at once and never throws: work runs on the
29
+ * SDK's own background thread. Calls made before [configure] are held (up to 100) and run right
30
+ * after it. */
31
+ object Kerdly {
32
+ private const val MAX_BUFFERED_CALLS = 100
33
+
34
+ private val lock = Any()
35
+ private val log = Logger(KerdlyLogLevel.WARN, AndroidLogSink)
36
+ private val deepLinkSources = DeepLinkSources()
37
+ private val buffered = ArrayList<(Core) -> Unit>()
38
+
39
+ @Volatile private var core: Core? = null
40
+
41
+ @Volatile private var scheduler: Scheduler? = null
42
+
43
+ @Volatile private var currentInstallId: String? = null
44
+
45
+ /** Loads or creates the install id and enqueues `$install` (first launch) and `$open`; the
46
+ * rest happens on the SDK thread. Cheap on the calling thread. A second call is ignored. */
47
+ @JvmStatic
48
+ fun configure(context: Context, options: KerdlyOptions) {
49
+ try {
50
+ synchronized(lock) { configureLocked(context, options) }
51
+ } catch (t: Throwable) {
52
+ log.error("configure failed; the SDK is off for this launch", t)
53
+ }
54
+ }
55
+
56
+ private fun configureLocked(context: Context, options: KerdlyOptions) {
57
+ if (core != null) {
58
+ log.info("configure: already configured; this call is ignored")
59
+ return
60
+ }
61
+ log.level = options.logLevel
62
+ val endpoint = OptionRules.endpoint(options.endpoint)
63
+ if (endpoint == null) {
64
+ log.error("configure: endpoint must be an http(s) base URL; the SDK is off")
65
+ return
66
+ }
67
+ val key = options.key.trim()
68
+ when (OptionRules.checkKey(key)) {
69
+ OptionRules.KeyCheck.INVALID -> {
70
+ log.error("configure: the key is empty or malformed; the SDK is off")
71
+ return
72
+ }
73
+ OptionRules.KeyCheck.SECRET -> {
74
+ log.error("configure: that is a server key (sk_…); apps take their public pk_ key. The SDK is off")
75
+ return
76
+ }
77
+ OptionRules.KeyCheck.NOT_PUBLIC -> log.warn("configure: app keys start with pk_live_ or pk_test_")
78
+ OptionRules.KeyCheck.OK -> Unit
79
+ }
80
+ val appContext = context.applicationContext ?: context
81
+ // Without an explicit metaAppId, the manifest's `com.kerdly.sdk.META_APP_ID` meta-data
82
+ // (what the Expo config plugin writes) turns the Meta Install Referrer read on.
83
+ val (metaAppId, metaAppIdValid) = OptionRules.metaAppId(options.metaAppId ?: AndroidPlatform.manifestMetaAppId(appContext))
84
+ if (!metaAppIdValid) log.warn("configure: metaAppId must be the numeric Facebook app id; the Meta Install Referrer is off")
85
+
86
+ val now = System.currentTimeMillis()
87
+ val (store, identity) = withDiskAccess {
88
+ // All SDK state lives in noBackupFilesDir/kerdly/: Auto Backup never copies it. Only the
89
+ // id is read here; a new one is written by the launch task.
90
+ val s = FileStore(sdkDirectory(appContext.noBackupFilesDir))
91
+ s to InstallId.load(s)
92
+ }
93
+
94
+ val sdkScheduler = ExecutorScheduler(log)
95
+ val engine = Core(
96
+ cfg = CoreConfig(
97
+ key = key,
98
+ endpoint = endpoint,
99
+ environment = OptionRules.environment(options.environment, AndroidPlatform.isDebuggable(appContext)),
100
+ collectAdvertisingId = options.collectAdvertisingId,
101
+ metaAppId = metaAppId,
102
+ wrapper = OptionRules.wrapper(options.wrapper),
103
+ ),
104
+ platform = AndroidPlatform(appContext, sdkScheduler, log),
105
+ transport = HttpUrlTransport(),
106
+ store = store,
107
+ scheduler = sdkScheduler,
108
+ clock = Clock { System.currentTimeMillis() },
109
+ log = log,
110
+ main = MainThreadDispatcher,
111
+ )
112
+ val foreground = AndroidPlatform.isProcessForeground()
113
+ val replay = ArrayList(buffered)
114
+ buffered.clear()
115
+ // The launch task is the first task on the SDK thread; every later call queues behind it.
116
+ sdkScheduler.execute { engine.start(Launch(identity.id, identity.created, now, foreground), replay) }
117
+ currentInstallId = identity.id
118
+ scheduler = sdkScheduler
119
+ core = engine
120
+
121
+ val application = appContext as? Application
122
+ if (application != null) {
123
+ application.registerActivityLifecycleCallbacks(
124
+ LifecycleTracker(
125
+ initialForeground = foreground,
126
+ onForeground = {
127
+ val ts = System.currentTimeMillis()
128
+ sdkScheduler.execute { engine.onForeground(ts) }
129
+ },
130
+ onBackground = {
131
+ deepLinkSources.onBackground()
132
+ val ts = System.currentTimeMillis()
133
+ sdkScheduler.execute { engine.onBackground(ts) }
134
+ },
135
+ ),
136
+ )
137
+ } else {
138
+ log.warn("configure: no Application context; foreground and background are not tracked")
139
+ }
140
+ log.info("configured; install ${identity.id}${if (identity.created) " (new)" else ""}")
141
+ }
142
+
143
+ /** This install's id (lowercase UUIDv4); null before [configure]. */
144
+ @JvmStatic
145
+ val installId: String?
146
+ get() = currentInstallId
147
+
148
+ /** Sets (or, with null, clears) the user id stamped on later events; `$identify` on change. */
149
+ @JvmStatic
150
+ fun setUserId(userId: String?) = call("setUserId") { ts ->
151
+ submit { it.setUserId(userId, ts) }
152
+ }
153
+
154
+ /** A custom event: name and keys `[a-z][a-z0-9_]{0,39}`, ≤ 25 props of string, number or
155
+ * boolean. Invalid props are dropped; an invalid name drops the event. A standard event's name
156
+ * (`registration`, `start_trial`, `subscribe`, `purchase`) gets its typed checks too; prefer
157
+ * the typed methods below. */
158
+ @JvmStatic
159
+ @JvmOverloads
160
+ fun track(name: String, properties: Map<String, Any?> = emptyMap()) = call("track") { ts ->
161
+ val props = LinkedHashMap(properties)
162
+ submit { it.track(name, props, ts) }
163
+ }
164
+
165
+ // Standard events: ordinary events with typed props. Each argument is
166
+ // optional; `properties` adds custom props under the `track` rules and never replaces an
167
+ // argument. `product_id` and `transaction_id` are cut at 128 characters; `value` is the price
168
+ // paid in `currency` (0 for a free trial), dropped unless it is a finite number ≥ 0 with a
169
+ // three-letter ISO 4217 currency (upper-cased by the SDK).
170
+
171
+ /** `registration`: [method] is how the user signed up (`anonymous`, `apple`, `google`,
172
+ * `email`, …; ≤ 64 characters). */
173
+ @JvmStatic
174
+ @JvmOverloads
175
+ fun trackRegistration(method: String? = null, properties: Map<String, Any?> = emptyMap()) = call("trackRegistration") { ts ->
176
+ val args = StandardEvents.registration(method)
177
+ val props = copyOf(properties)
178
+ submit { it.trackStandard(StandardEvents.REGISTRATION, args, props, ts) }
179
+ }
180
+
181
+ /** `start_trial`: a trial began (`value` 0 for a free trial). */
182
+ @JvmStatic
183
+ @JvmOverloads
184
+ fun trackStartTrial(
185
+ productId: String? = null,
186
+ value: Double? = null,
187
+ currency: String? = null,
188
+ transactionId: String? = null,
189
+ properties: Map<String, Any?> = emptyMap(),
190
+ ) = call("trackStartTrial") { ts ->
191
+ val args = StandardEvents.money(productId, value, currency, transactionId)
192
+ val props = copyOf(properties)
193
+ submit { it.trackStandard(StandardEvents.START_TRIAL, args, props, ts) }
194
+ }
195
+
196
+ /** `subscribe`: a paid subscription began. */
197
+ @JvmStatic
198
+ @JvmOverloads
199
+ fun trackSubscribe(
200
+ productId: String? = null,
201
+ value: Double? = null,
202
+ currency: String? = null,
203
+ transactionId: String? = null,
204
+ properties: Map<String, Any?> = emptyMap(),
205
+ ) = call("trackSubscribe") { ts ->
206
+ val args = StandardEvents.money(productId, value, currency, transactionId)
207
+ val props = copyOf(properties)
208
+ submit { it.trackStandard(StandardEvents.SUBSCRIBE, args, props, ts) }
209
+ }
210
+
211
+ /** `purchase`: a one-time purchase; [quantity] is an integer ≥ 1. */
212
+ @JvmStatic
213
+ @JvmOverloads
214
+ fun trackPurchase(
215
+ productId: String? = null,
216
+ value: Double? = null,
217
+ currency: String? = null,
218
+ quantity: Int? = null,
219
+ transactionId: String? = null,
220
+ properties: Map<String, Any?> = emptyMap(),
221
+ ) = call("trackPurchase") { ts ->
222
+ val args = StandardEvents.money(productId, value, currency, transactionId, quantity)
223
+ val props = copyOf(properties)
224
+ submit { it.trackStandard(StandardEvents.PURCHASE, args, props, ts) }
225
+ }
226
+
227
+ /** Null leaves a flag unchanged. `analytics = false` keeps only the SDK's attribution events;
228
+ * `ads = false` stops advertising-id reads. `$consent` on change. */
229
+ @JvmStatic
230
+ @JvmOverloads
231
+ fun setConsent(analytics: Boolean? = null, ads: Boolean? = null) = call("setConsent") { ts ->
232
+ submit { it.setConsent(analytics, ads, ts) }
233
+ }
234
+
235
+ /** Records a URL the app was opened with (`$deeplink`) and returns its parsed params; null
236
+ * for a blank string. Call it from every URL entry point (onCreate / onNewIntent).
237
+ * `source` is `"initial"` for the URL that launched the app and `"runtime"` for one that
238
+ * arrived while it ran; a caller that knows (the Expo bridge) passes it, otherwise the SDK
239
+ * infers it (the first URL before the app first went to the background is `initial`). */
240
+ @JvmStatic
241
+ @JvmOverloads
242
+ fun handleUrl(url: String, source: String? = null): KerdlyDeepLink? = try {
243
+ val link = DeepLinks.parse(url)
244
+ if (link != null) {
245
+ val source = deepLinkSources.next(source)
246
+ val ts = System.currentTimeMillis()
247
+ submit { it.handleUrl(link, source, ts) }
248
+ }
249
+ link
250
+ } catch (t: Throwable) {
251
+ log.error("handleUrl failed", t)
252
+ null
253
+ }
254
+
255
+ /** The account token purchases carry: a UUID, or Superwall's `$SuperwallAlias:<uuid>`
256
+ * obfuscated account id before identify. `$ids` on change. */
257
+ @JvmStatic
258
+ fun setAppAccountToken(token: String?) = call("setAppAccountToken") { ts ->
259
+ submit { it.setAppAccountToken(token, ts) }
260
+ }
261
+
262
+ /** Ids other SDKs own (e.g. `meta_anon_id`, `superwall_alias`), merged into the stored set;
263
+ * an empty value removes its key. `$ids` on change. */
264
+ @JvmStatic
265
+ fun setPartnerIds(ids: Map<String, String>) = call("setPartnerIds") { ts ->
266
+ val copy = LinkedHashMap(ids)
267
+ submit { it.setPartnerIds(copy, ts) }
268
+ }
269
+
270
+ /** A Play purchase the paywall completed: `$purchase_link`, once per purchase token. */
271
+ @JvmStatic
272
+ fun notifyPurchase(purchase: KerdlyPurchase) = call("notifyPurchase") { ts ->
273
+ val copy = purchase.copy(products = purchase.products.toList())
274
+ submit { it.notifyPurchase(copy, ts) }
275
+ }
276
+
277
+ /** An event the app just sent to an ad network through that network's SDK (`$network_send`). */
278
+ @JvmStatic
279
+ fun recordNetworkSend(send: KerdlyNetworkSend) = call("recordNetworkSend") { ts ->
280
+ submit { it.recordNetworkSend(send, ts) }
281
+ }
282
+
283
+ /** The cached attribution; null until the collector decides one. */
284
+ @JvmStatic
285
+ val attribution: KerdlyAttribution?
286
+ get() = core?.attribution
287
+
288
+ /** Called on the main thread with the attribution now (if known) and whenever it changes. */
289
+ @JvmStatic
290
+ fun onAttribution(listener: (KerdlyAttribution) -> Unit) = call("onAttribution") { _ ->
291
+ submit { it.addAttributionListener(listener) }
292
+ }
293
+
294
+ /** Sends what is queued now (subject to back-off). */
295
+ @JvmStatic
296
+ fun flush() = call("flush") { _ ->
297
+ submit { it.flush() }
298
+ }
299
+
300
+ private inline fun call(what: String, block: (Long) -> Unit) {
301
+ try {
302
+ block(System.currentTimeMillis())
303
+ } catch (t: Throwable) {
304
+ log.error("$what failed", t)
305
+ }
306
+ }
307
+
308
+ /** A copy taken on the caller's thread; a Java caller's null map is empty, so the typed
309
+ * arguments still go out. */
310
+ private fun copyOf(properties: Map<String, Any?>?): Map<String, Any?> =
311
+ if (properties == null) emptyMap() else LinkedHashMap(properties)
312
+
313
+ private fun submit(op: (Core) -> Unit) {
314
+ val c = core
315
+ val s = scheduler
316
+ if (c != null && s != null) {
317
+ s.execute { op(c) }
318
+ return
319
+ }
320
+ synchronized(lock) {
321
+ val c2 = core
322
+ val s2 = scheduler
323
+ if (c2 != null && s2 != null) {
324
+ s2.execute { op(c2) }
325
+ } else if (buffered.size < MAX_BUFFERED_CALLS) {
326
+ buffered.add(op)
327
+ } else {
328
+ log.warn("called before configure: call dropped (over $MAX_BUFFERED_CALLS waiting)")
329
+ }
330
+ }
331
+ }
332
+
333
+ /** The id file is tiny; reading it here keeps [installId] valid as soon as configure returns.
334
+ * Lifted out of the app's StrictMode disk policy for that one read. */
335
+ private inline fun <T> withDiskAccess(block: () -> T): T {
336
+ val policy = StrictMode.allowThreadDiskWrites()
337
+ try {
338
+ return block()
339
+ } finally {
340
+ StrictMode.setThreadPolicy(policy)
341
+ }
342
+ }
343
+ }
@@ -0,0 +1,89 @@
1
+ package com.kerdly.sdk
2
+
3
+ /** `app.environment` of every batch. [AUTO]: `development` when the app is
4
+ * debuggable (`ApplicationInfo.FLAG_DEBUGGABLE`), else `production`. */
5
+ enum class KerdlyEnvironment { AUTO, PRODUCTION, SANDBOX, DEVELOPMENT }
6
+
7
+ /** Logcat verbosity. Messages are prefixed `[Kerdly]`; keys and full advertising
8
+ * ids are never logged. */
9
+ enum class KerdlyLogLevel { NONE, ERROR, WARN, INFO, DEBUG }
10
+
11
+ /** Options for [Kerdly.configure]. */
12
+ data class KerdlyOptions @JvmOverloads constructor(
13
+ /** The app's public key, `pk_live_…` / `pk_test_…`. */
14
+ val key: String,
15
+ /** Base URL; `/v1/sdk/batch` etc. are appended. Default: [DEFAULT_ENDPOINT]. */
16
+ val endpoint: String = DEFAULT_ENDPOINT,
17
+ val environment: KerdlyEnvironment = KerdlyEnvironment.AUTO,
18
+ /** Read the Google advertising id (never when limit-ad-tracking is on or `ads` consent is off). */
19
+ val collectAdvertisingId: Boolean = true,
20
+ /** Facebook app id; enables the Meta Install Referrer read (once per install). */
21
+ val metaAppId: String? = null,
22
+ val logLevel: KerdlyLogLevel = KerdlyLogLevel.WARN,
23
+ /** Set by wrappers such as the Expo bridge, e.g. `expo/0.1.0`. */
24
+ val wrapper: String? = null,
25
+ ) {
26
+ override fun toString(): String =
27
+ "KerdlyOptions(key=${key.take(8)}…, endpoint=$endpoint, environment=$environment, " +
28
+ "collectAdvertisingId=$collectAdvertisingId, metaAppId=$metaAppId, logLevel=$logLevel, wrapper=$wrapper)"
29
+
30
+ companion object {
31
+ /** The Kerdly collector. */
32
+ const val DEFAULT_ENDPOINT: String = "https://app.kerdly.com/api"
33
+ }
34
+ }
35
+
36
+ /** What [Kerdly.handleUrl] parsed from a URL's query string. */
37
+ data class KerdlyDeepLink(
38
+ val url: String,
39
+ val cpp: String?,
40
+ val ppid: String?,
41
+ /** The click id of the Kerdly link that opened the app (`kerdly_c`). */
42
+ val clickId: String?,
43
+ /** The web visit that link continues (`kerdly_v`). */
44
+ val visitId: String?,
45
+ val campaignIds: String?,
46
+ )
47
+
48
+ /** A Google Play purchase as the paywall reports it (`$purchase_link`). */
49
+ data class KerdlyPurchase @JvmOverloads constructor(
50
+ val purchaseToken: String,
51
+ val orderId: String? = null,
52
+ val products: List<String> = emptyList(),
53
+ /** Milliseconds since the epoch. */
54
+ val purchaseTime: Long? = null,
55
+ val obfuscatedAccountId: String? = null,
56
+ val obfuscatedProfileId: String? = null,
57
+ )
58
+
59
+ /** An event the app itself sent to an ad network (`$network_send`). */
60
+ data class KerdlyNetworkSend @JvmOverloads constructor(
61
+ val network: String,
62
+ val event: String,
63
+ val eventId: String? = null,
64
+ val value: Double? = null,
65
+ val currency: String? = null,
66
+ val flag: String? = null,
67
+ )
68
+
69
+ /** The install's attribution as the collector decided it. [raw] is the whole
70
+ * JSON object. */
71
+ data class KerdlyAttribution(
72
+ val state: String,
73
+ val network: String,
74
+ val status: String,
75
+ val method: String,
76
+ val campaignId: String?,
77
+ val campaign: String?,
78
+ val adsetId: String?,
79
+ val adset: String?,
80
+ val adId: String?,
81
+ val ad: String?,
82
+ val keywordId: String?,
83
+ val keyword: String?,
84
+ val linkId: String?,
85
+ val cppId: String?,
86
+ /** Milliseconds since the epoch. */
87
+ val decidedAt: Long?,
88
+ val raw: String,
89
+ )
@@ -0,0 +1,39 @@
1
+ package com.kerdly.sdk.internal
2
+
3
+ import com.kerdly.sdk.KerdlyAttribution
4
+ import org.json.JSONObject
5
+
6
+ /** The public attribution object from a batch response or the attribution poll. */
7
+ internal object AttributionParser {
8
+ /** Null unless the object carries at least `state` and `network`. */
9
+ fun fromJson(o: JSONObject?): KerdlyAttribution? {
10
+ if (o == null) return null
11
+ val state = o.stringOrNull("state") ?: return null
12
+ val network = o.stringOrNull("network") ?: return null
13
+ return KerdlyAttribution(
14
+ state = state,
15
+ network = network,
16
+ status = o.stringOrNull("status") ?: "",
17
+ method = o.stringOrNull("method") ?: "",
18
+ campaignId = o.stringOrNull("campaign_id"),
19
+ campaign = o.stringOrNull("campaign"),
20
+ adsetId = o.stringOrNull("adset_id"),
21
+ adset = o.stringOrNull("adset"),
22
+ adId = o.stringOrNull("ad_id"),
23
+ ad = o.stringOrNull("ad"),
24
+ keywordId = o.stringOrNull("keyword_id"),
25
+ keyword = o.stringOrNull("keyword"),
26
+ linkId = o.stringOrNull("link_id"),
27
+ cppId = o.stringOrNull("cpp_id"),
28
+ decidedAt = o.longOrNull("decided_at"),
29
+ raw = o.toString(),
30
+ )
31
+ }
32
+
33
+ /** `GET /v1/sdk/attribution`: `{"attribution": {…} | null, …}`, or the bare object. */
34
+ fun fromPollBody(body: String): KerdlyAttribution? {
35
+ val o = parseObject(body) ?: return null
36
+ if (o.has("attribution")) return fromJson(o.optJSONObject("attribution"))
37
+ return fromJson(o)
38
+ }
39
+ }
@@ -0,0 +1,159 @@
1
+ package com.kerdly.sdk.internal
2
+
3
+ import org.json.JSONObject
4
+ import kotlin.random.Random
5
+
6
+ /** `POST /v1/sdk/batch` bodies. */
7
+ internal object BatchBody {
8
+ const val MAX_EVENTS = 50
9
+ const val MAX_BODY_BYTES = 256 * 1024
10
+ private const val EVENTS_OVERHEAD = 16 // ,"events":[ … ]
11
+
12
+ class Envelope(
13
+ val sdkName: String,
14
+ val sdkVersion: String,
15
+ val wrapper: String?,
16
+ val bundle: String,
17
+ val appVersion: String?,
18
+ val appBuild: String?,
19
+ val environment: String,
20
+ val installId: String,
21
+ )
22
+
23
+ /** The batch object without `events` (closed with `}`). */
24
+ fun envelope(e: Envelope, sentAt: Long, context: JSONObject?): String {
25
+ val sdk = JSONObject().put("name", e.sdkName).put("version", e.sdkVersion)
26
+ if (e.wrapper != null) sdk.put("wrapper", e.wrapper)
27
+ val app = JSONObject()
28
+ .put("bundle", e.bundle)
29
+ .putNullable("version", e.appVersion)
30
+ .putNullable("build", e.appBuild)
31
+ .put("environment", e.environment)
32
+ val o = JSONObject()
33
+ .put("sdk", sdk)
34
+ .put("app", app)
35
+ .put("install_id", e.installId)
36
+ .put("sent_at", sentAt)
37
+ if (context != null) o.put("context", context)
38
+ return o.toString()
39
+ }
40
+
41
+ /** Budget left for the events once [envelope] is in the body. */
42
+ fun eventBudget(envelope: String): Int = MAX_BODY_BYTES - utf8Length(envelope) - EVENTS_OVERHEAD
43
+
44
+ /** The head of the queue that fits: at most [maxCount] events and [maxBytes] of event JSON. */
45
+ fun select(events: List<QueuedEvent>, maxCount: Int, maxBytes: Int): List<QueuedEvent> {
46
+ val out = ArrayList<QueuedEvent>()
47
+ var total = 0
48
+ for (e in events) {
49
+ if (out.size >= maxCount) break
50
+ val add = e.bytes + if (out.isEmpty()) 0 else 1
51
+ if (total + add > maxBytes) break
52
+ out.add(e)
53
+ total += add
54
+ }
55
+ return out
56
+ }
57
+
58
+ fun join(envelope: String, events: List<QueuedEvent>): String {
59
+ val sb = StringBuilder(envelope.length + events.sumOf { it.json.length + 1 } + EVENTS_OVERHEAD)
60
+ sb.append(envelope, 0, envelope.length - 1)
61
+ sb.append(",\"events\":[")
62
+ events.forEachIndexed { i, e ->
63
+ if (i > 0) sb.append(',')
64
+ sb.append(e.json)
65
+ }
66
+ sb.append("]}")
67
+ return sb.toString()
68
+ }
69
+ }
70
+
71
+ internal class Rejection(val id: String?, val reason: String)
72
+
73
+ /** A 200 batch response. */
74
+ internal class BatchAck(
75
+ val accepted: List<String>,
76
+ val rejected: List<Rejection>,
77
+ val configEtag: String?,
78
+ val attribution: JSONObject?,
79
+ val needs: List<String>,
80
+ )
81
+
82
+ internal sealed class SendOutcome {
83
+ /** 2xx with a readable body: remove what it accepted and rejected. */
84
+ class Acked(val ack: BatchAck) : SendOutcome()
85
+
86
+ /** Drop the batch. [stop]: 401/403 — send nothing more until the next launch. */
87
+ class Drop(val status: Int, val code: String?, val stop: Boolean) : SendOutcome()
88
+
89
+ /** 413: halve the batch and retry; a single event that is still too large is dropped. */
90
+ object Split : SendOutcome()
91
+
92
+ /** 408, 429, 5xx, a network error ([status] null) or an unreadable answer: back off. */
93
+ class Retry(val status: Int?, val retryAfterMs: Long?) : SendOutcome()
94
+ }
95
+
96
+ internal object BatchResponses {
97
+ /** Retry-After is capped at a day; a bigger value is a broken server, not a plan. */
98
+ const val MAX_RETRY_AFTER_S = 86_400L
99
+
100
+ fun classify(status: Int, body: String, retryAfter: String?): SendOutcome = when {
101
+ status in 200..299 -> parseAck(body)?.let { SendOutcome.Acked(it) } ?: SendOutcome.Retry(status, null)
102
+ status == 401 || status == 403 -> SendOutcome.Drop(status, errorCode(body), stop = true)
103
+ status == 408 || status == 429 -> SendOutcome.Retry(status, parseRetryAfter(retryAfter))
104
+ status == 413 -> SendOutcome.Split
105
+ // 400 malformed, and any other 4xx: resending the same bytes cannot succeed.
106
+ status in 400..499 -> SendOutcome.Drop(status, errorCode(body), stop = false)
107
+ status >= 500 -> SendOutcome.Retry(status, parseRetryAfter(retryAfter))
108
+ else -> SendOutcome.Retry(status, null) // 1xx / 3xx: redirects are not followed for POSTs
109
+ }
110
+
111
+ fun parseAck(body: String): BatchAck? {
112
+ val o = parseObject(body) ?: return null
113
+ val accepted = o.optJSONArray("accepted")?.strings() ?: emptyList()
114
+ val rejected = ArrayList<Rejection>()
115
+ val rej = o.optJSONArray("rejected")
116
+ if (rej != null) {
117
+ for (i in 0 until rej.length()) {
118
+ val r = rej.optJSONObject(i) ?: continue
119
+ rejected.add(Rejection(r.stringOrNull("id"), r.stringOrNull("reason") ?: "unknown"))
120
+ }
121
+ }
122
+ return BatchAck(
123
+ accepted = accepted,
124
+ rejected = rejected,
125
+ configEtag = o.stringOrNull("config_etag"),
126
+ attribution = o.optJSONObject("attribution"),
127
+ needs = o.optJSONArray("needs")?.strings() ?: emptyList(),
128
+ )
129
+ }
130
+
131
+ /** `{"error": …, "code": …}` → code. */
132
+ fun errorCode(body: String): String? = parseObject(body)?.stringOrNull("code")
133
+
134
+ /** `Retry-After` in seconds → ms. HTTP-date values are not used by the collector. */
135
+ fun parseRetryAfter(value: String?): Long? {
136
+ val s = value?.trim()?.toLongOrNull() ?: return null
137
+ if (s < 0) return null
138
+ return minOf(s, MAX_RETRY_AFTER_S) * 1000
139
+ }
140
+ }
141
+
142
+ /** Exponential back-off with full jitter from 1 s to 5 min. */
143
+ internal object Backoff {
144
+ const val BASE_MS = 1_000L
145
+ const val MAX_MS = 300_000L
146
+
147
+ /** The cap for retry number [attempt] (1-based): 1 s, 2 s, 4 s … 5 min. */
148
+ fun capMs(attempt: Int): Long {
149
+ val shift = (attempt - 1).coerceIn(0, 20)
150
+ return minOf(MAX_MS, BASE_MS shl shift)
151
+ }
152
+
153
+ /** A uniform delay in [1 s, cap]. */
154
+ fun delayMs(attempt: Int, random: Random): Long {
155
+ val cap = capMs(attempt)
156
+ if (cap <= BASE_MS) return BASE_MS
157
+ return BASE_MS + (random.nextDouble() * (cap - BASE_MS)).toLong()
158
+ }
159
+ }