@kerdly/expo 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 (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 +111 -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 +239 -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 +95 -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 +92 -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 +183 -0
  112. package/src/validation.ts +343 -0
  113. package/src/version.ts +5 -0
@@ -0,0 +1,314 @@
1
+ package com.kerdly.sdk.internal
2
+
3
+ import com.kerdly.sdk.KerdlyDeepLink
4
+ import com.kerdly.sdk.KerdlyNetworkSend
5
+ import com.kerdly.sdk.KerdlyPurchase
6
+ import org.json.JSONArray
7
+ import org.json.JSONObject
8
+ import java.util.Locale
9
+ import kotlin.math.abs
10
+
11
+ /** Reserved event names. */
12
+ internal object EventNames {
13
+ const val INSTALL = "\$install"
14
+ const val OPEN = "\$open"
15
+ const val SIGNAL = "\$signal"
16
+ const val DEEPLINK = "\$deeplink"
17
+ const val IDENTIFY = "\$identify"
18
+ const val CONSENT = "\$consent"
19
+ const val IDS = "\$ids"
20
+ const val PURCHASE_LINK = "\$purchase_link"
21
+ const val SKAN = "\$skan"
22
+ const val NETWORK_SEND = "\$network_send"
23
+
24
+ /** What is still recorded with `analytics == false`. */
25
+ val ANALYTICS_OFF_ALLOWED = setOf(INSTALL, OPEN, SIGNAL, CONSENT, IDENTIFY, IDS, PURCHASE_LINK, SKAN)
26
+
27
+ fun isReserved(name: String): Boolean = name.startsWith("$")
28
+ }
29
+
30
+ internal class SanitizedProps(val json: JSONObject, val dropped: List<String>)
31
+
32
+ /** Custom events: names and keys `[a-z][a-z0-9_]{0,39}`, at most 25 props,
33
+ * values strings (cut at 256 chars), finite numbers or booleans. A bad name drops the event;
34
+ * a bad key or value drops only that prop. */
35
+ internal object CustomEvents {
36
+ private val NAME = Regex("^[a-z][a-z0-9_]{0,39}$")
37
+ const val MAX_PROPS = 25
38
+ const val MAX_STRING = 256
39
+
40
+ fun isValidName(name: String): Boolean = NAME.matches(name)
41
+
42
+ fun sanitize(props: Map<String, Any?>): SanitizedProps {
43
+ val json = JSONObject()
44
+ val dropped = ArrayList<String>()
45
+ append(json, props, dropped)
46
+ return SanitizedProps(json, dropped)
47
+ }
48
+
49
+ /** Adds [props] to [json] under the custom rules, skipping [skip]; what is already in
50
+ * [json] counts toward the 25. */
51
+ fun append(json: JSONObject, props: Map<String, Any?>, dropped: MutableList<String>, skip: Set<String> = emptySet()) {
52
+ var count = json.length()
53
+ for ((key, raw) in props) {
54
+ if (key in skip) continue
55
+ if (!NAME.matches(key)) {
56
+ dropped += "$key (invalid key)"
57
+ continue
58
+ }
59
+ val value = normalize(raw)
60
+ if (value == null) {
61
+ dropped += "$key (unsupported value)"
62
+ continue
63
+ }
64
+ if (count >= MAX_PROPS) {
65
+ dropped += "$key (over $MAX_PROPS props)"
66
+ continue
67
+ }
68
+ json.put(key, value)
69
+ count++
70
+ }
71
+ }
72
+
73
+ /** A JSON-safe value, or null when the type is not allowed (null, NaN and ∞ included). */
74
+ fun normalize(value: Any?): Any? = when (value) {
75
+ null -> null
76
+ is String -> truncate(value, MAX_STRING)
77
+ is Boolean -> value
78
+ is Int -> value.toLong()
79
+ is Long -> value
80
+ is Short -> value.toLong()
81
+ is Byte -> value.toLong()
82
+ is Double -> value.takeIf { it.isFinite() }
83
+ // Float → its shortest decimal form, so 0.1f is 0.1 rather than 0.10000000149011612.
84
+ is Float -> value.takeIf { it.isFinite() }?.toString()?.toDouble()
85
+ is Number -> value.toDouble().takeIf { it.isFinite() }
86
+ else -> null
87
+ }
88
+
89
+ /** Cuts at [max] UTF-16 units without splitting a surrogate pair. */
90
+ fun truncate(s: String, max: Int): String {
91
+ if (s.length <= max) return s
92
+ var end = max
93
+ if (Character.isHighSurrogate(s[end - 1])) end--
94
+ return s.substring(0, end)
95
+ }
96
+ }
97
+
98
+ /** Standard events: ordinary names whose typed props are checked the same way
99
+ * whether they come from the typed methods or from `track`. Other props follow the custom
100
+ * rules; the typed ones count toward the 25. A bad typed prop drops only that prop. */
101
+ internal object StandardEvents {
102
+ const val REGISTRATION = "registration"
103
+ const val START_TRIAL = "start_trial"
104
+ const val SUBSCRIBE = "subscribe"
105
+ const val PURCHASE = "purchase"
106
+
107
+ const val MAX_ID = 128
108
+ const val MAX_METHOD = 64
109
+ private val CURRENCY = Regex("^[A-Z]{3}$")
110
+ /** 2^53: beyond it a double no longer holds every integer. */
111
+ private const val MAX_EXACT_DOUBLE = 9_007_199_254_740_992.0
112
+
113
+ private val MONEY = listOf("product_id", "value", "currency", "transaction_id")
114
+
115
+ /** Each standard event's typed keys. */
116
+ val TYPED_KEYS: Map<String, List<String>> = mapOf(
117
+ REGISTRATION to listOf("method"),
118
+ START_TRIAL to MONEY,
119
+ SUBSCRIBE to MONEY,
120
+ PURCHASE to listOf("product_id", "value", "currency", "quantity", "transaction_id"),
121
+ )
122
+
123
+ /** The typed methods' arguments, as props. */
124
+ fun registration(method: String?): Map<String, Any?> = linkedMapOf("method" to method)
125
+
126
+ fun money(productId: String?, value: Double?, currency: String?, transactionId: String?, quantity: Int? = null): Map<String, Any?> {
127
+ val m = linkedMapOf<String, Any?>("product_id" to productId, "value" to value, "currency" to currency)
128
+ if (quantity != null) m["quantity"] = quantity
129
+ m["transaction_id"] = transactionId
130
+ return m
131
+ }
132
+
133
+ /** A typed method's props: its non-null [args] first, then [properties]. A key an argument
134
+ * set is never taken from [properties]; those keys come back as the second value. */
135
+ fun merge(args: Map<String, Any?>, properties: Map<String, Any?>): Pair<Map<String, Any?>, List<String>> {
136
+ val merged = LinkedHashMap<String, Any?>()
137
+ for ((k, v) in args) if (v != null) merged[k] = v
138
+ val ignored = ArrayList<String>()
139
+ for ((k, v) in properties) {
140
+ if (k in merged) ignored += k else merged[k] = v
141
+ }
142
+ return merged to ignored
143
+ }
144
+
145
+ /** Props of an event named [name]: the typed checks for a standard name, then the custom
146
+ * rules for the rest (only the custom rules for any other name). */
147
+ fun sanitize(name: String, props: Map<String, Any?>): SanitizedProps {
148
+ val typedKeys = TYPED_KEYS[name] ?: return CustomEvents.sanitize(props)
149
+ val json = JSONObject()
150
+ val dropped = ArrayList<String>()
151
+ for (key in typedKeys) {
152
+ if (!props.containsKey(key)) continue
153
+ val value = typed(key, props[key])
154
+ if (value == null) dropped += "$key (${problem(key)})" else json.put(key, value)
155
+ }
156
+ // A value without a currency means nothing to a network.
157
+ if (json.has("value") && !json.has("currency")) {
158
+ json.remove("value")
159
+ dropped += "value (no valid currency)"
160
+ }
161
+ CustomEvents.append(json, props, dropped, skip = typedKeys.toSet())
162
+ return SanitizedProps(json, dropped)
163
+ }
164
+
165
+ private fun typed(key: String, raw: Any?): Any? = when (key) {
166
+ "product_id", "transaction_id" -> (raw as? String)?.let { CustomEvents.truncate(it, MAX_ID) }
167
+ "method" -> (raw as? String)?.let { CustomEvents.truncate(it, MAX_METHOD) }
168
+ "currency" -> (raw as? String)?.trim()?.uppercase(Locale.ROOT)?.takeIf { CURRENCY.matches(it) }
169
+ "value" -> number(raw)?.takeIf { it.toDouble() >= 0 }
170
+ "quantity" -> wholeNumber(raw)?.takeIf { it >= 1 }
171
+ else -> null
172
+ }
173
+
174
+ /** A finite number, as [CustomEvents.normalize] writes it; null for anything else. */
175
+ private fun number(raw: Any?): Number? = if (raw is Number) CustomEvents.normalize(raw) as? Number else null
176
+
177
+ /** An integral number (2 and 2.0, not 2.5) as a Long; null otherwise. */
178
+ private fun wholeNumber(raw: Any?): Long? = when (val n = number(raw)) {
179
+ is Long -> n
180
+ is Double -> n.takeIf { it % 1.0 == 0.0 && abs(it) <= MAX_EXACT_DOUBLE }?.toLong()
181
+ else -> null
182
+ }
183
+
184
+ private fun problem(key: String): String = when (key) {
185
+ "product_id", "transaction_id", "method" -> "not a string"
186
+ "currency" -> "not a three-letter ISO 4217 code"
187
+ "value" -> "not a finite number ≥ 0"
188
+ "quantity" -> "not an integer ≥ 1"
189
+ else -> "invalid"
190
+ }
191
+ }
192
+
193
+ /** Props of the SDK's own events. */
194
+ internal object ReservedProps {
195
+ const val MAX_PRODUCTS = 20
196
+
197
+ /** [device] is [ContextJson.device], taken at enqueue. */
198
+ fun install(installedAt: Long?, firstLaunchAt: Long, installer: String?, initialUrl: String?, device: JSONObject): JSONObject =
199
+ JSONObject()
200
+ .put("install_state", "fresh")
201
+ .putNullable("installed_at", installedAt)
202
+ .putNullable("installed_at_source", if (installedAt != null) "package_manager" else null)
203
+ .put("first_launch_at", firstLaunchAt)
204
+ .putNullable("installer", installer)
205
+ .putNullable("initial_url", initialUrl)
206
+ .put("device", device)
207
+
208
+ fun open(reason: String): JSONObject = JSONObject().put("reason", reason)
209
+
210
+ fun deeplink(link: KerdlyDeepLink, source: String): JSONObject =
211
+ JSONObject()
212
+ .put("url", CustomEvents.truncate(link.url, DeepLinks.MAX_URL_CHARS))
213
+ .put("source", source)
214
+ .putNullable("cpp", link.cpp)
215
+ .putNullable("ppid", link.ppid)
216
+ .putNullable(DeepLinks.CLICK_ID, link.clickId)
217
+ .putNullable(DeepLinks.VISIT_ID, link.visitId)
218
+ .putNullable("campaign_ids", link.campaignIds)
219
+
220
+ fun identify(userId: String?, previousUserId: String?): JSONObject =
221
+ JSONObject().putNullable("user_id", userId).putNullable("previous_user_id", previousUserId)
222
+
223
+ fun consent(analytics: Boolean, ads: Boolean): JSONObject =
224
+ JSONObject().put("att", "not_applicable").put("analytics", analytics).put("ads", ads)
225
+
226
+ fun ids(appAccountToken: String?, partner: Map<String, String>): JSONObject {
227
+ val p = JSONObject()
228
+ for ((k, v) in partner) p.put(k, v)
229
+ return JSONObject().putNullable("app_account_token", appAccountToken).put("partner", p)
230
+ }
231
+
232
+ fun purchaseLink(purchase: KerdlyPurchase): JSONObject =
233
+ JSONObject()
234
+ .put("store", "play_store")
235
+ .put("purchase_token", purchase.purchaseToken)
236
+ .putNullable("order_id", purchase.orderId)
237
+ .put("products", JSONArray(purchase.products.filter { it.isNotEmpty() }.take(MAX_PRODUCTS)))
238
+ .putNullable("purchase_time", purchase.purchaseTime?.takeIf { it > 0 })
239
+ .putNullable("obfuscated_account_id", purchase.obfuscatedAccountId)
240
+ .putNullable("obfuscated_profile_id", purchase.obfuscatedProfileId)
241
+ .put("source", "notify")
242
+
243
+ fun networkSend(send: KerdlyNetworkSend): JSONObject =
244
+ JSONObject()
245
+ .put("network", send.network)
246
+ .put("event", send.event)
247
+ .putNullable("event_id", send.eventId)
248
+ .putNullable("value", send.value?.takeIf { it.isFinite() })
249
+ .putNullable("currency", send.currency)
250
+ .putNullable("flag", send.flag)
251
+ }
252
+
253
+ /** `$signal` props (Android kinds). */
254
+ internal object Signals {
255
+ fun installReferrerOk(d: PlayReferrerDetails): JSONObject =
256
+ JSONObject()
257
+ .put("kind", "install_referrer")
258
+ .put("status", "ok")
259
+ .put("response_code", JSONObject.NULL)
260
+ .put("referrer", d.referrer)
261
+ .putNullable("click_ts", d.clickTs)
262
+ .putNullable("install_begin_ts", d.installBeginTs)
263
+ .putNullable("click_server_ts", d.clickServerTs)
264
+ .putNullable("install_begin_server_ts", d.installBeginServerTs)
265
+ .putNullable("install_version", d.installVersion)
266
+ .putNullable("instant", d.instant)
267
+
268
+ fun installReferrerUnavailable(responseCode: Int): JSONObject =
269
+ JSONObject()
270
+ .put("kind", "install_referrer")
271
+ .put("status", "unavailable")
272
+ .put("response_code", responseCode)
273
+ .put("referrer", "")
274
+ .put("click_ts", JSONObject.NULL)
275
+ .put("install_begin_ts", JSONObject.NULL)
276
+ .put("click_server_ts", JSONObject.NULL)
277
+ .put("install_begin_server_ts", JSONObject.NULL)
278
+ .put("install_version", JSONObject.NULL)
279
+ .put("instant", JSONObject.NULL)
280
+
281
+ fun advertisingIds(gaid: String?, lat: Boolean): JSONObject =
282
+ JSONObject().put("kind", "advertising_ids").putNullable("gaid", gaid).put("lat", lat)
283
+
284
+ /** [ipv6] is already [PublicIp.globalIpv6]'s canonical text. */
285
+ fun publicIp(ipv6: String): JSONObject = JSONObject().put("kind", "public_ip").put("ipv6", ipv6)
286
+
287
+ /** One network's deferred-deep-link answer, with the params [DeepLinks] reads from it. */
288
+ fun deferredLink(answer: DdlAnswer, attempt: Int): JSONObject {
289
+ val parsed = answer.url?.let(DeepLinks::parse)
290
+ return JSONObject()
291
+ .put("kind", "deferred_link")
292
+ .put("network", answer.network)
293
+ .put("status", answer.status)
294
+ .putNullable("url", answer.url?.take(DeepLinks.MAX_URL_CHARS))
295
+ .put("click_ts", JSONObject.NULL)
296
+ .putNullable("cpp", parsed?.cpp)
297
+ .putNullable("ppid", parsed?.ppid)
298
+ .putNullable(DeepLinks.CLICK_ID, parsed?.clickId)
299
+ .putNullable(DeepLinks.VISIT_ID, parsed?.visitId)
300
+ .putNullable("campaign_ids", parsed?.campaignIds)
301
+ .putNullable("http_status", answer.httpStatus)
302
+ .putNullable("detail", answer.detail?.take(300))
303
+ .put("attempt", attempt)
304
+ .put("att", "not_applicable")
305
+ }
306
+
307
+ fun metaInstallReferrer(row: MetaReferrerRow): JSONObject =
308
+ JSONObject()
309
+ .put("kind", "meta_install_referrer")
310
+ .put("source", row.source)
311
+ .put("install_referrer", row.installReferrer ?: "")
312
+ .putNullable("is_ct", row.isCt)
313
+ .putNullable("actual_timestamp", row.actualTimestamp)
314
+ }
@@ -0,0 +1,116 @@
1
+ package com.kerdly.sdk.internal
2
+
3
+ import org.json.JSONArray
4
+ import org.json.JSONObject
5
+ import java.security.MessageDigest
6
+
7
+ // Helpers over org.json that behave the same on Android's implementation and the reference
8
+ // one used by the JVM tests (they differ on NULL handling in optString and friends).
9
+
10
+ /** `put` that writes JSON null for a Kotlin null (Android's `put(key, null)` removes the key). */
11
+ internal fun JSONObject.putNullable(key: String, value: Any?): JSONObject = put(key, value ?: JSONObject.NULL)
12
+
13
+ internal fun JSONObject.stringOrNull(key: String): String? {
14
+ if (!has(key) || isNull(key)) return null
15
+ return when (val v = opt(key)) {
16
+ is String -> v
17
+ is Number, is Boolean -> v.toString()
18
+ else -> null
19
+ }
20
+ }
21
+
22
+ internal fun JSONObject.longOrNull(key: String): Long? {
23
+ if (!has(key) || isNull(key)) return null
24
+ return when (val v = opt(key)) {
25
+ is Number -> {
26
+ val d = v.toDouble()
27
+ if (d.isFinite()) v.toLong() else null
28
+ }
29
+ is String -> v.trim().toLongOrNull()
30
+ else -> null
31
+ }
32
+ }
33
+
34
+ internal fun JSONObject.intOrNull(key: String): Int? =
35
+ longOrNull(key)?.takeIf { it in Int.MIN_VALUE..Int.MAX_VALUE }?.toInt()
36
+
37
+ internal fun JSONObject.boolOrNull(key: String): Boolean? {
38
+ if (!has(key) || isNull(key)) return null
39
+ return opt(key) as? Boolean
40
+ }
41
+
42
+ internal fun JSONArray.strings(): List<String> {
43
+ val out = ArrayList<String>(length())
44
+ for (i in 0 until length()) {
45
+ if (isNull(i)) continue
46
+ val v = opt(i)
47
+ if (v is String) out.add(v)
48
+ }
49
+ return out
50
+ }
51
+
52
+ /** Parses a JSON object; null for blank, malformed or non-object text. */
53
+ internal fun parseObject(text: String?): JSONObject? {
54
+ if (text.isNullOrBlank()) return null
55
+ return try {
56
+ JSONObject(text)
57
+ } catch (e: Exception) {
58
+ null
59
+ }
60
+ }
61
+
62
+ /** Structural JSON equality: key order is ignored and 5 equals 5.0 (Android's org.json has no
63
+ * `similar`). */
64
+ internal fun jsonEquals(a: Any?, b: Any?): Boolean {
65
+ val x = if (a == null) JSONObject.NULL else a
66
+ val y = if (b == null) JSONObject.NULL else b
67
+ return when {
68
+ x is JSONObject && y is JSONObject -> {
69
+ if (x.length() != y.length()) return false
70
+ val keys = x.keys()
71
+ while (keys.hasNext()) {
72
+ val k = keys.next()
73
+ if (!y.has(k) || !jsonEquals(x.opt(k), y.opt(k))) return false
74
+ }
75
+ true
76
+ }
77
+ x is JSONArray && y is JSONArray -> {
78
+ if (x.length() != y.length()) return false
79
+ (0 until x.length()).all { jsonEquals(x.opt(it), y.opt(it)) }
80
+ }
81
+ x is Number && y is Number -> x.toDouble() == y.toDouble()
82
+ else -> x == y
83
+ }
84
+ }
85
+
86
+ internal fun utf8Length(s: String): Int {
87
+ var n = 0
88
+ var i = 0
89
+ while (i < s.length) {
90
+ val c = s[i]
91
+ when {
92
+ c.code < 0x80 -> n += 1
93
+ c.code < 0x800 -> n += 2
94
+ Character.isHighSurrogate(c) && i + 1 < s.length && Character.isLowSurrogate(s[i + 1]) -> {
95
+ n += 4
96
+ i++
97
+ }
98
+ else -> n += 3
99
+ }
100
+ i++
101
+ }
102
+ return n
103
+ }
104
+
105
+ private val HEX = "0123456789abcdef".toCharArray()
106
+
107
+ internal fun sha1Hex(s: String): String {
108
+ val digest = MessageDigest.getInstance("SHA-1").digest(s.toByteArray(Charsets.UTF_8))
109
+ val out = CharArray(digest.size * 2)
110
+ for (i in digest.indices) {
111
+ val b = digest[i].toInt() and 0xff
112
+ out[i * 2] = HEX[b ushr 4]
113
+ out[i * 2 + 1] = HEX[b and 0x0f]
114
+ }
115
+ return String(out)
116
+ }
@@ -0,0 +1,49 @@
1
+ package com.kerdly.sdk.internal
2
+
3
+ import com.kerdly.sdk.KerdlyLogLevel
4
+ import com.kerdly.sdk.BuildConfig
5
+
6
+ internal object SdkInfo {
7
+ const val NAME = "kerdly-android"
8
+ val VERSION: String = BuildConfig.KERDLY_VERSION
9
+
10
+ /** `X-Kerdly-Sdk`: `kerdly-android/0.1.0`, plus ` expo/0.1.0` under a wrapper. */
11
+ fun header(wrapper: String?): String = if (wrapper == null) "$NAME/$VERSION" else "$NAME/$VERSION $wrapper"
12
+ }
13
+
14
+ internal fun interface LogSink {
15
+ fun write(level: KerdlyLogLevel, message: String, error: Throwable?)
16
+ }
17
+
18
+ /** Level-filtered logging with the `[Kerdly]` prefix. Never pass it keys or full
19
+ * advertising ids; see [maskId]. */
20
+ internal class Logger(@Volatile var level: KerdlyLogLevel, private val sink: LogSink) {
21
+ /** Set when the remote config lists this install in `debug_devices`: log everything. */
22
+ @Volatile var verbose: Boolean = false
23
+
24
+ fun enabled(at: KerdlyLogLevel): Boolean =
25
+ at != KerdlyLogLevel.NONE && (verbose || at.ordinal <= level.ordinal)
26
+
27
+ fun error(message: String, error: Throwable? = null) = write(KerdlyLogLevel.ERROR, message, error)
28
+ fun warn(message: String, error: Throwable? = null) = write(KerdlyLogLevel.WARN, message, error)
29
+ fun info(message: String) = write(KerdlyLogLevel.INFO, message, null)
30
+ fun debug(message: () -> String) {
31
+ if (enabled(KerdlyLogLevel.DEBUG)) write(KerdlyLogLevel.DEBUG, message(), null)
32
+ }
33
+
34
+ private fun write(at: KerdlyLogLevel, message: String, error: Throwable?) {
35
+ if (!enabled(at)) return
36
+ try {
37
+ sink.write(at, "[Kerdly] $message", error)
38
+ } catch (_: Throwable) {
39
+ // Logging must never break the host app.
40
+ }
41
+ }
42
+ }
43
+
44
+ /** First four characters only: enough to tell ids apart in a log, useless to anyone else. */
45
+ internal fun maskId(id: String?): String = when {
46
+ id == null -> "null"
47
+ id.length <= 4 -> "…"
48
+ else -> id.take(4) + "…"
49
+ }
@@ -0,0 +1,47 @@
1
+ package com.kerdly.sdk.internal
2
+
3
+ import com.kerdly.sdk.KerdlyEnvironment
4
+ import java.util.Locale
5
+
6
+ /** Validation of [com.kerdly.sdk.KerdlyOptions]: a bad option turns the SDK off with a log line, never
7
+ * an exception. */
8
+ internal object OptionRules {
9
+ enum class KeyCheck { OK, NOT_PUBLIC, SECRET, INVALID }
10
+
11
+ /** Base URL without trailing slashes; null unless it is an http(s) URL with no query. */
12
+ fun endpoint(raw: String): String? {
13
+ val e = raw.trim().trimEnd('/')
14
+ val lower = e.lowercase(Locale.ROOT)
15
+ val scheme = when {
16
+ lower.startsWith("https://") -> 8
17
+ lower.startsWith("http://") -> 7
18
+ else -> return null
19
+ }
20
+ if (e.length <= scheme || e.any { it.isWhitespace() || it == '?' || it == '#' }) return null
21
+ return e
22
+ }
23
+
24
+ fun checkKey(key: String): KeyCheck = when {
25
+ key.isEmpty() || key.any { it.isWhitespace() || it.isISOControl() } -> KeyCheck.INVALID
26
+ key.startsWith("sk_") -> KeyCheck.SECRET // a server key must never ship in an app
27
+ key.startsWith("pk_") -> KeyCheck.OK
28
+ else -> KeyCheck.NOT_PUBLIC
29
+ }
30
+
31
+ fun wrapper(raw: String?): String? = raw?.trim()?.takeIf { it.isNotEmpty() }?.take(64)
32
+
33
+ /** (id, valid): id null when absent or invalid; valid false when set but not a numeric
34
+ * Facebook app id. */
35
+ fun metaAppId(raw: String?): Pair<String?, Boolean> {
36
+ val id = raw?.trim()?.takeIf { it.isNotEmpty() } ?: return null to true
37
+ return if (MetaReferrer.isValidAppId(id)) id to true else null to false
38
+ }
39
+
40
+ /** Android: AUTO is `development` for a debuggable app, else `production`. */
41
+ fun environment(env: KerdlyEnvironment, debuggable: Boolean): String = when (env) {
42
+ KerdlyEnvironment.AUTO -> if (debuggable) "development" else "production"
43
+ KerdlyEnvironment.PRODUCTION -> "production"
44
+ KerdlyEnvironment.SANDBOX -> "sandbox"
45
+ KerdlyEnvironment.DEVELOPMENT -> "development"
46
+ }
47
+ }
@@ -0,0 +1,83 @@
1
+ package com.kerdly.sdk.internal
2
+
3
+ import java.io.IOException
4
+
5
+ // The engine (Core) talks to the device only through these ports, so every rule in it runs in
6
+ // plain JVM tests with fakes. The Android implementations live in `internal.android`.
7
+
8
+ internal fun interface Clock {
9
+ fun now(): Long
10
+ }
11
+
12
+ internal fun interface Cancellable {
13
+ fun cancel()
14
+ }
15
+
16
+ /** One serial background thread: every Core method runs on it, in submission order. */
17
+ internal interface Scheduler {
18
+ fun execute(task: () -> Unit)
19
+ fun schedule(delayMs: Long, task: () -> Unit): Cancellable
20
+ }
21
+
22
+ /** Small named files under `noBackupFilesDir/kerdly/`. */
23
+ internal interface Store {
24
+ /** The file's text, or null when the file does not exist. Throws when it exists but cannot be read. */
25
+ @Throws(IOException::class)
26
+ fun read(name: String): String?
27
+
28
+ /** Replaces the file atomically. False when it could not be written. */
29
+ fun write(name: String, content: String): Boolean
30
+
31
+ fun delete(name: String)
32
+ }
33
+
34
+ internal class HttpRequest(
35
+ val method: String,
36
+ val url: String,
37
+ val headers: Map<String, String>,
38
+ val body: ByteArray?,
39
+ )
40
+
41
+ internal class HttpResponse(
42
+ val status: Int,
43
+ val body: String,
44
+ val retryAfter: String? = null,
45
+ val etag: String? = null,
46
+ )
47
+
48
+ internal interface Transport {
49
+ /** Blocking. Throws [IOException] on a network failure; any HTTP status is a response. */
50
+ @Throws(IOException::class)
51
+ fun execute(request: HttpRequest): HttpResponse
52
+ }
53
+
54
+ /** Runs listener callbacks for the app (the main thread on Android). */
55
+ internal fun interface MainDispatcher {
56
+ fun post(block: () -> Unit)
57
+ }
58
+
59
+ internal class AppInfo(val bundle: String, val version: String?, val build: String?)
60
+
61
+ internal class InstallInfo(
62
+ /** `PackageInfo.firstInstallTime`, or null when the read failed or returned ≤ 0. */
63
+ val installedAt: Long?,
64
+ /** The installing package, e.g. `com.android.vending`. */
65
+ val installer: String?,
66
+ )
67
+
68
+ /** Device facts that read the platform. Collectors block (Core calls them on its own thread),
69
+ * except [startPlayReferrer] and [startPublicIpv6Lookup], which answer through their callback
70
+ * exactly once. */
71
+ internal interface Platform {
72
+ fun appInfo(): AppInfo
73
+ fun installInfo(): InstallInfo
74
+ fun deviceContext(): DeviceContext
75
+ /** Null when the advertising id is unavailable (no Play services, an error). */
76
+ fun readAdvertisingId(): AdIdResult?
77
+ /** One row per Meta app that answered; empty when none did. */
78
+ fun readMetaReferrer(metaAppId: String): List<MetaReferrerRow>
79
+ /** One GET of [echoUrl] off the calling thread, [timeoutMs] in all: the answer's `ip` as sent,
80
+ * or null on any failure (an IPv4-only network, the timeout, an error, another answer). */
81
+ fun startPublicIpv6Lookup(echoUrl: String, timeoutMs: Long, onResult: (String?) -> Unit)
82
+ fun startPlayReferrer(timeoutMs: Long, onResult: (PlayReferrerResult) -> Unit)
83
+ }