@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,120 @@
1
+ package com.kerdly.sdk.internal
2
+
3
+ import java.net.URI
4
+
5
+ /** The public IPv6 lookup: the echo URL, its answer, and which answers count. */
6
+ internal object PublicIp {
7
+ const val DEFAULT_ECHO_URL = "https://api6.ipify.org?format=json"
8
+
9
+ /** `ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255`: no IPv6 literal is longer. */
10
+ private const val MAX_TEXT = 45
11
+
12
+ /** [raw] when it is an absolute `https` URL with a host, else the default. */
13
+ fun echoUrl(raw: String?): String {
14
+ val s = raw?.trim() ?: return DEFAULT_ECHO_URL
15
+ val uri = try {
16
+ URI(s)
17
+ } catch (e: Exception) {
18
+ return DEFAULT_ECHO_URL
19
+ }
20
+ return if (uri.scheme.equals("https", ignoreCase = true) && !uri.host.isNullOrEmpty()) s else DEFAULT_ECHO_URL
21
+ }
22
+
23
+ /** The `ip` of the echo's `{"ip": "…"}`; null for any other answer. */
24
+ fun parseEcho(body: String?): String? = parseObject(body)?.opt("ip") as? String
25
+
26
+ /** [text] in RFC 5952 form (lowercase, the longest zero run as `::`) when it is a global
27
+ * unicast IPv6 address (2000::/3); null for IPv4, v4-mapped, loopback, link-local, ULA,
28
+ * multicast, a zone id or anything unparsable. The literal is parsed here, never through
29
+ * `InetAddress`, which would resolve a host name. */
30
+ fun globalIpv6(text: String?): String? {
31
+ val groups = parse(text?.trim() ?: return null) ?: return null
32
+ if (groups[0] and 0xE000 != 0x2000) return null
33
+ return format(groups)
34
+ }
35
+
36
+ /** The eight 16-bit groups of an IPv6 literal (`::` and a dotted IPv4 tail allowed), or null. */
37
+ private fun parse(s: String): IntArray? {
38
+ if (s.isEmpty() || s.length > MAX_TEXT) return null
39
+ val gap = s.indexOf("::")
40
+ val groups = IntArray(8)
41
+ if (gap < 0) {
42
+ val all = groups(s.split(':'), ipv4Tail = true) ?: return null
43
+ if (all.size != 8) return null
44
+ all.forEachIndexed { i, g -> groups[i] = g }
45
+ return groups
46
+ }
47
+ if (s.indexOf("::", gap + 1) >= 0) return null
48
+ // An IPv4 tail ends the address, so only the part after `::` may carry one.
49
+ val head = if (gap == 0) emptyList() else groups(s.substring(0, gap).split(':'), ipv4Tail = false) ?: return null
50
+ val tail = if (gap + 2 == s.length) emptyList() else groups(s.substring(gap + 2).split(':'), ipv4Tail = true) ?: return null
51
+ if (head.size + tail.size > 7) return null
52
+ head.forEachIndexed { i, g -> groups[i] = g }
53
+ tail.forEachIndexed { i, g -> groups[8 - tail.size + i] = g }
54
+ return groups
55
+ }
56
+
57
+ private fun groups(pieces: List<String>, ipv4Tail: Boolean): List<Int>? {
58
+ val out = ArrayList<Int>(8)
59
+ for ((i, p) in pieces.withIndex()) {
60
+ if (ipv4Tail && i == pieces.lastIndex && '.' in p) {
61
+ val v4 = ipv4(p) ?: return null
62
+ out.add(v4 ushr 16)
63
+ out.add(v4 and 0xFFFF)
64
+ } else {
65
+ if (p.isEmpty() || p.length > 4 || !p.all { isHex(it) }) return null
66
+ out.add(p.toInt(16))
67
+ }
68
+ }
69
+ return out
70
+ }
71
+
72
+ /** Four decimal octets without leading zeros, as 32 bits. */
73
+ private fun ipv4(s: String): Int? {
74
+ val parts = s.split('.')
75
+ if (parts.size != 4) return null
76
+ var v = 0
77
+ for (p in parts) {
78
+ if (p.isEmpty() || p.length > 3 || !p.all { it in '0'..'9' } || (p.length > 1 && p[0] == '0')) return null
79
+ val n = p.toInt()
80
+ if (n > 255) return null
81
+ v = (v shl 8) or n
82
+ }
83
+ return v
84
+ }
85
+
86
+ private fun isHex(c: Char): Boolean = c in '0'..'9' || c in 'a'..'f' || c in 'A'..'F'
87
+
88
+ /** RFC 5952 §4: the longest run of two or more zero groups (the first of equal runs) is `::`. */
89
+ private fun format(groups: IntArray): String {
90
+ var gapStart = -1
91
+ var gapLen = 1
92
+ var i = 0
93
+ while (i < 8) {
94
+ if (groups[i] != 0) {
95
+ i++
96
+ continue
97
+ }
98
+ var j = i
99
+ while (j < 8 && groups[j] == 0) j++
100
+ if (j - i > gapLen) {
101
+ gapStart = i
102
+ gapLen = j - i
103
+ }
104
+ i = j
105
+ }
106
+ val sb = StringBuilder()
107
+ i = 0
108
+ while (i < 8) {
109
+ if (i == gapStart) {
110
+ sb.append("::")
111
+ i += gapLen
112
+ continue
113
+ }
114
+ if (i > 0 && i != gapStart + gapLen) sb.append(':')
115
+ sb.append(Integer.toHexString(groups[i]))
116
+ i++
117
+ }
118
+ return sb.toString()
119
+ }
120
+ }
@@ -0,0 +1,137 @@
1
+ package com.kerdly.sdk.internal
2
+
3
+ import java.util.Locale
4
+
5
+ /** Play Install Referrer response codes (`InstallReferrerClient.InstallReferrerResponse`) and
6
+ * what each one means for the SDK. */
7
+ internal object PlayReferrerCodes {
8
+ const val SERVICE_DISCONNECTED = -1
9
+ const val OK = 0
10
+ const val SERVICE_UNAVAILABLE = 1
11
+ const val FEATURE_NOT_SUPPORTED = 2
12
+ const val DEVELOPER_ERROR = 3
13
+ const val PERMISSION_ERROR = 4
14
+
15
+ enum class Kind {
16
+ /** Read the details and signal `status: ok`. */
17
+ OK,
18
+
19
+ /** Will never work on this install (e.g. not installed from Play): signal `unavailable` once. */
20
+ PERMANENT,
21
+
22
+ /** Try again at the next foreground or launch, within 90 days of the install. */
23
+ TRANSIENT,
24
+ }
25
+
26
+ fun classify(code: Int): Kind = when (code) {
27
+ OK -> Kind.OK
28
+ FEATURE_NOT_SUPPORTED, DEVELOPER_ERROR, PERMISSION_ERROR -> Kind.PERMANENT
29
+ else -> Kind.TRANSIENT // SERVICE_UNAVAILABLE, SERVICE_DISCONNECTED and anything new
30
+ }
31
+ }
32
+
33
+ /** `ReferrerDetails`, with Play's 0 ("unknown") timestamps turned into null. Seconds. */
34
+ internal class PlayReferrerDetails(
35
+ val referrer: String,
36
+ val clickTs: Long?,
37
+ val installBeginTs: Long?,
38
+ val clickServerTs: Long?,
39
+ val installBeginServerTs: Long?,
40
+ val installVersion: String?,
41
+ val instant: Boolean?,
42
+ ) {
43
+ companion object {
44
+ fun of(
45
+ referrer: String?,
46
+ clickTs: Long,
47
+ installBeginTs: Long,
48
+ clickServerTs: Long,
49
+ installBeginServerTs: Long,
50
+ installVersion: String?,
51
+ instant: Boolean,
52
+ ) = PlayReferrerDetails(
53
+ referrer = referrer ?: "",
54
+ clickTs = clickTs.takeIf { it > 0 },
55
+ installBeginTs = installBeginTs.takeIf { it > 0 },
56
+ clickServerTs = clickServerTs.takeIf { it > 0 },
57
+ installBeginServerTs = installBeginServerTs.takeIf { it > 0 },
58
+ installVersion = installVersion?.takeIf { it.isNotEmpty() },
59
+ instant = instant,
60
+ )
61
+ }
62
+ }
63
+
64
+ internal sealed class PlayReferrerResult {
65
+ class Ok(val details: PlayReferrerDetails) : PlayReferrerResult()
66
+ class Permanent(val code: Int) : PlayReferrerResult()
67
+ class Transient(val reason: String) : PlayReferrerResult()
68
+ }
69
+
70
+ /** One row read from a Meta app's install-referrer content provider. */
71
+ internal class MetaReferrerRow(
72
+ /** `facebook` | `instagram` | `facebook_lite`. */
73
+ val source: String,
74
+ val installReferrer: String?,
75
+ /** 1 click, 0 view. */
76
+ val isCt: Int?,
77
+ /** Seconds. */
78
+ val actualTimestamp: Long?,
79
+ )
80
+
81
+ /** Meta Install Referrer: the providers, and the pick among their rows. */
82
+ internal object MetaReferrer {
83
+ /** `source` → content-provider authority, in the order they are queried. */
84
+ val PROVIDERS: List<Pair<String, String>> = listOf(
85
+ "facebook" to "com.facebook.katana.provider.InstallReferrerProvider",
86
+ "instagram" to "com.instagram.contentprovider.InstallReferrerProvider",
87
+ "facebook_lite" to "com.facebook.lite.provider.InstallReferrerProvider",
88
+ )
89
+
90
+ val COLUMNS: Array<String> = arrayOf("install_referrer", "is_ct", "actual_timestamp")
91
+
92
+ private val APP_ID = Regex("^[0-9]{1,32}$")
93
+
94
+ /** Facebook app ids are numeric; anything else would build a bogus provider path. */
95
+ fun isValidAppId(appId: String): Boolean = APP_ID.matches(appId)
96
+
97
+ fun uri(authority: String, appId: String): String = "content://$authority/$appId"
98
+
99
+ /** The freshest row with a referrer (by `actual_timestamp`; ties keep provider order). */
100
+ fun freshest(rows: List<MetaReferrerRow>): MetaReferrerRow? =
101
+ rows.filter { !it.installReferrer.isNullOrEmpty() }
102
+ .maxWithOrNull(compareBy { it.actualTimestamp ?: Long.MIN_VALUE })
103
+
104
+ /** `is_ct` as the collector takes it: 0 or 1, else null. Providers may answer an int or a string. */
105
+ fun isCt(raw: Any?): Int? {
106
+ val n = when (raw) {
107
+ is Number -> raw.toLong()
108
+ is String -> raw.trim().toLongOrNull()
109
+ else -> null
110
+ }
111
+ return if (n == 0L || n == 1L) n.toInt() else null
112
+ }
113
+
114
+ /** `actual_timestamp` in seconds; non-positive or unreadable is null. */
115
+ fun timestamp(raw: Any?): Long? {
116
+ val n = when (raw) {
117
+ is Number -> raw.toLong()
118
+ is String -> raw.trim().toLongOrNull()
119
+ else -> null
120
+ }
121
+ return n?.takeIf { it > 0 }
122
+ }
123
+ }
124
+
125
+ internal class AdIdResult(val gaid: String?, val lat: Boolean)
126
+
127
+ internal object AdIds {
128
+ /** Limit-ad-tracking on, or a zeroed / missing id (the user deleted it) → no GAID, `lat: true`. */
129
+ fun normalize(id: String?, limitAdTracking: Boolean): AdIdResult {
130
+ val zeroed = id.isNullOrBlank() || id.all { it == '0' || it == '-' }
131
+ return if (limitAdTracking || zeroed) {
132
+ AdIdResult(null, true)
133
+ } else {
134
+ AdIdResult(id!!.trim().lowercase(Locale.ROOT), false)
135
+ }
136
+ }
137
+ }
@@ -0,0 +1,100 @@
1
+ package com.kerdly.sdk.internal
2
+
3
+ import org.json.JSONObject
4
+
5
+ /** `GET /v1/sdk/config`, with defaults for every missing or malformed field.
6
+ * The `skan` block is iOS-only and ignored here. */
7
+ internal class RemoteConfig(
8
+ val version: Int? = null,
9
+ /** Kill switch: false → send nothing, keep collecting reserved events. */
10
+ val enabled: Boolean = true,
11
+ /** Kerdly is off for this app version: record, collect and send nothing. */
12
+ val off: Boolean = false,
13
+ val maxBatch: Int = BatchBody.MAX_EVENTS,
14
+ val queueFlushAt: Int = 20,
15
+ val intervalS: Int = 15,
16
+ val blocked: Set<String> = emptySet(),
17
+ val collectAdvertisingId: Boolean = true,
18
+ val collectInstallReferrer: Boolean = true,
19
+ val collectMetaInstallReferrer: Boolean = true,
20
+ val collectPurchases: Boolean = true,
21
+ val collectPublicIp: Boolean = true,
22
+ /** Where the public IPv6 is looked up; only an `https` URL replaces the default. */
23
+ val ipv6EchoUrl: String = PublicIp.DEFAULT_ECHO_URL,
24
+ /** Deferred deep links; null = off. */
25
+ val ddl: DdlConfig? = null,
26
+ val minSupportedSdk: String? = null,
27
+ val debugDevices: Set<String> = emptySet(),
28
+ ) {
29
+ companion object {
30
+ val DEFAULT = RemoteConfig()
31
+
32
+ fun parse(text: String?): RemoteConfig? = parseObject(text)?.let(::fromJson)
33
+
34
+ fun fromJson(o: JSONObject): RemoteConfig {
35
+ val flush = o.optJSONObject("flush")
36
+ val events = o.optJSONObject("events")
37
+ val collect = o.optJSONObject("collect")
38
+ fun flag(key: String): Boolean = collect?.boolOrNull(key) ?: true
39
+ return RemoteConfig(
40
+ version = o.intOrNull("version"),
41
+ enabled = o.boolOrNull("enabled") ?: true,
42
+ off = o.boolOrNull("off") ?: false,
43
+ maxBatch = (flush?.intOrNull("max_batch") ?: BatchBody.MAX_EVENTS).coerceIn(1, BatchBody.MAX_EVENTS),
44
+ queueFlushAt = (flush?.intOrNull("queue_flush_at") ?: 20).coerceIn(1, 1_000),
45
+ intervalS = (flush?.intOrNull("interval_s") ?: 15).coerceIn(1, 3_600),
46
+ blocked = events?.optJSONArray("block")?.strings()?.toHashSet() ?: emptySet(),
47
+ collectAdvertisingId = flag("advertising_id"),
48
+ collectInstallReferrer = flag("install_referrer"),
49
+ collectMetaInstallReferrer = flag("meta_install_referrer"),
50
+ collectPurchases = flag("purchases"),
51
+ collectPublicIp = flag("public_ip"),
52
+ ipv6EchoUrl = PublicIp.echoUrl(o.stringOrNull("ipv6_echo_url")),
53
+ ddl = DdlConfig.fromJson(o.optJSONObject("ddl")),
54
+ minSupportedSdk = o.stringOrNull("min_supported_sdk"),
55
+ debugDevices = o.optJSONArray("debug_devices")?.strings()?.map { it.lowercase() }?.toHashSet() ?: emptySet(),
56
+ )
57
+ }
58
+ }
59
+ }
60
+
61
+ /** The config as cached on the device: `config.json` = `{etag, fetched_at, config}`. */
62
+ /**
63
+ * The cached config. [appVersion] is the app version it was fetched for: Kerdly resolves the config
64
+ * per version, so after an app update the copy is fetched again. Null in a cache
65
+ * written before the field existed.
66
+ */
67
+ internal class ConfigCache(val etag: String?, val fetchedAt: Long?, val raw: JSONObject?, val appVersion: String? = null) {
68
+ val config: RemoteConfig? = raw?.let(RemoteConfig::fromJson)
69
+
70
+ fun serialize(): String =
71
+ JSONObject().putNullable("etag", etag).putNullable("fetched_at", fetchedAt).putNullable("config", raw)
72
+ .putNullable("app_version", appVersion).toString()
73
+
74
+ companion object {
75
+ val EMPTY = ConfigCache(null, null, null)
76
+
77
+ fun parse(text: String?): ConfigCache {
78
+ val o = parseObject(text) ?: return EMPTY
79
+ val raw = o.optJSONObject("config") ?: return EMPTY
80
+ return ConfigCache(o.stringOrNull("etag"), o.longOrNull("fetched_at"), raw, o.stringOrNull("app_version"))
81
+ }
82
+ }
83
+ }
84
+
85
+ internal object Semver {
86
+ /** Numeric `major.minor.patch` comparison; pre-release and build suffixes are ignored. */
87
+ fun compare(a: String, b: String): Int {
88
+ val pa = parts(a)
89
+ val pb = parts(b)
90
+ for (i in 0 until maxOf(pa.size, pb.size)) {
91
+ val x = pa.getOrElse(i) { 0 }
92
+ val y = pb.getOrElse(i) { 0 }
93
+ if (x != y) return x.compareTo(y)
94
+ }
95
+ return 0
96
+ }
97
+
98
+ private fun parts(v: String): List<Int> =
99
+ v.trim().removePrefix("v").substringBefore('-').substringBefore('+').split('.').map { it.toIntOrNull() ?: 0 }
100
+ }
@@ -0,0 +1,271 @@
1
+ package com.kerdly.sdk.internal
2
+
3
+ import org.json.JSONArray
4
+ import org.json.JSONObject
5
+ import java.io.File
6
+ import java.io.FileOutputStream
7
+ import java.io.IOException
8
+ import java.util.UUID
9
+
10
+ /** The SDK's directory under `base` (`noBackupFilesDir`): `kerdly/`. Builds before 0.1.0 used
11
+ * `afr/`; when only that one exists it is renamed, or used where it is if it cannot be, so an
12
+ * updated app keeps its install id and queued events. */
13
+ internal fun sdkDirectory(base: File): File {
14
+ val dir = File(base, "kerdly")
15
+ val legacy = File(base, "afr")
16
+ if (dir.exists() || !legacy.isDirectory) return dir
17
+ return if (legacy.renameTo(dir)) dir else legacy
18
+ }
19
+
20
+ /** Files in one directory, each replaced atomically (write a temp file, fsync, rename). On
21
+ * Android the directory is `noBackupFilesDir/kerdly/`, which Auto Backup never copies, so a
22
+ * restore cannot bring back an old install id. */
23
+ internal class FileStore(private val dir: File) : Store {
24
+ override fun read(name: String): String? {
25
+ val f = File(dir, name)
26
+ if (!f.exists()) return null
27
+ return f.readText(Charsets.UTF_8) // throws when it exists but cannot be read
28
+ }
29
+
30
+ override fun write(name: String, content: String): Boolean = try {
31
+ if (!dir.isDirectory && !dir.mkdirs() && !dir.isDirectory) throw IOException("cannot create $dir")
32
+ val target = File(dir, name)
33
+ val tmp = File(dir, "$name.tmp")
34
+ FileOutputStream(tmp).use { out ->
35
+ out.write(content.toByteArray(Charsets.UTF_8))
36
+ out.fd.sync()
37
+ }
38
+ if (!tmp.renameTo(target)) {
39
+ target.delete()
40
+ if (!tmp.renameTo(target)) throw IOException("cannot replace $target")
41
+ }
42
+ true
43
+ } catch (e: Exception) {
44
+ false
45
+ }
46
+
47
+ override fun delete(name: String) {
48
+ try {
49
+ File(dir, name).delete()
50
+ } catch (_: Exception) {
51
+ }
52
+ }
53
+ }
54
+
55
+ internal object StoreFiles {
56
+ const val INSTALL_ID = "install_id"
57
+ const val QUEUE = "queue.json"
58
+ const val STATE = "state.json"
59
+ const val CONFIG = "config.json"
60
+ const val PENDING_LINKS = "pending_links.json"
61
+ const val PURCHASES = "purchases.json"
62
+ const val ATTRIBUTION = "attribution.json"
63
+ }
64
+
65
+ /** The install id: a lowercase UUIDv4 in its own file, created on the first
66
+ * `configure` of an install and never changed. No file → a new id and `$install fresh`.
67
+ *
68
+ * `configure` only reads (cheap, on the caller's thread); a new id is written by the launch
69
+ * task before anything is sent, so an id that never reached the disk was never used either. */
70
+ internal object InstallId {
71
+ private val UUID_PATTERN = Regex("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
72
+
73
+ class Result(val id: String, val created: Boolean)
74
+
75
+ fun isValid(id: String): Boolean = UUID_PATTERN.matches(id)
76
+
77
+ fun newId(): String = UUID.randomUUID().toString().lowercase()
78
+
79
+ /** Throws when the id file exists but cannot be read: a new id then would fake an install. */
80
+ @Throws(IOException::class)
81
+ fun load(store: Store, newId: () -> String = ::newId): Result {
82
+ val existing = store.read(StoreFiles.INSTALL_ID)?.trim()?.lowercase()
83
+ if (existing != null && isValid(existing)) return Result(existing, created = false)
84
+ return Result(newId(), created = true)
85
+ }
86
+
87
+ fun persist(store: Store, id: String): Boolean = store.write(StoreFiles.INSTALL_ID, id)
88
+ }
89
+
90
+ /** Everything the SDK remembers about this install besides the queue (`state.json`). */
91
+ internal class SdkState {
92
+ var userId: String? = null
93
+ var analytics: Boolean = true
94
+ var ads: Boolean = true
95
+ var appAccountToken: String? = null
96
+ var partner: Map<String, String> = emptyMap()
97
+ var firstLaunchAt: Long? = null
98
+ var installedAt: Long? = null
99
+ var installEventId: String? = null
100
+ var installAcked: Boolean = false
101
+ var referrerDone: Boolean = false
102
+ var referrerAttempts: Int = 0
103
+ var metaDone: Boolean = false
104
+ var adIdReadAt: Long? = null
105
+ /** sha1 of the last advertising-ids signal sent: a new one goes out only on change. */
106
+ var adIdHash: String? = null
107
+ var lat: Boolean? = null
108
+ /** Deferred deep links: this install's launch enqueued `$install`. */
109
+ var ddlEligible: Boolean = false
110
+ /** TikTok answered, refused, or the SDK gave up after 3 failures in transit. */
111
+ var ddlTiktokDone: Boolean = false
112
+ var ddlTiktokFailures: Int = 0
113
+ /** Play's raw referrer, kept for TikTok's request (it decodes the referrer on its side). */
114
+ var ddlReferrer: String? = null
115
+ /** sha1 of the last context the collector stored (sent in a batch with an accepted event). */
116
+ var contextHash: String? = null
117
+ var retryAttempt: Int = 0
118
+ var retryNextAt: Long = 0
119
+ /** A copy of the queue's counter, so a lost queue file can never make a `seq` repeat. */
120
+ var nextSeq: Long = 1
121
+
122
+ fun serialize(installId: String): String {
123
+ val partnerJson = JSONObject()
124
+ for ((k, v) in partner) partnerJson.put(k, v)
125
+ return JSONObject()
126
+ .put("v", 1)
127
+ .put("install_id", installId)
128
+ .putNullable("user_id", userId)
129
+ .put("consent", JSONObject().put("analytics", analytics).put("ads", ads))
130
+ .putNullable("app_account_token", appAccountToken)
131
+ .put("partner", partnerJson)
132
+ .putNullable("first_launch_at", firstLaunchAt)
133
+ .putNullable("installed_at", installedAt)
134
+ .putNullable("install_event_id", installEventId)
135
+ .put("install_acked", installAcked)
136
+ .put("referrer_done", referrerDone)
137
+ .put("referrer_attempts", referrerAttempts)
138
+ .put("meta_done", metaDone)
139
+ .putNullable("ad_id_read_at", adIdReadAt)
140
+ .putNullable("ad_id_hash", adIdHash)
141
+ .putNullable("lat", lat)
142
+ .put("ddl_eligible", ddlEligible)
143
+ .put("ddl_tiktok_done", ddlTiktokDone)
144
+ .put("ddl_tiktok_failures", ddlTiktokFailures)
145
+ .putNullable("ddl_referrer", ddlReferrer)
146
+ .putNullable("context_hash", contextHash)
147
+ .put("retry_attempt", retryAttempt)
148
+ .put("retry_next_at", retryNextAt)
149
+ .put("next_seq", nextSeq)
150
+ .toString()
151
+ }
152
+
153
+ companion object {
154
+ /** Null when [text] is absent, unreadable, or belongs to another install id. */
155
+ fun parse(text: String?, installId: String): SdkState? {
156
+ val o = parseObject(text) ?: return null
157
+ if (o.stringOrNull("install_id") != installId) return null
158
+ val s = SdkState()
159
+ s.userId = o.stringOrNull("user_id")
160
+ o.optJSONObject("consent")?.let { c ->
161
+ s.analytics = c.boolOrNull("analytics") ?: true
162
+ s.ads = c.boolOrNull("ads") ?: true
163
+ }
164
+ s.appAccountToken = o.stringOrNull("app_account_token")
165
+ o.optJSONObject("partner")?.let { p ->
166
+ val map = LinkedHashMap<String, String>()
167
+ for (k in p.keys()) p.stringOrNull(k)?.let { map[k] = it }
168
+ s.partner = map
169
+ }
170
+ s.firstLaunchAt = o.longOrNull("first_launch_at")
171
+ s.installedAt = o.longOrNull("installed_at")
172
+ s.installEventId = o.stringOrNull("install_event_id")
173
+ s.installAcked = o.boolOrNull("install_acked") ?: false
174
+ s.referrerDone = o.boolOrNull("referrer_done") ?: false
175
+ s.referrerAttempts = o.intOrNull("referrer_attempts") ?: 0
176
+ s.metaDone = o.boolOrNull("meta_done") ?: false
177
+ s.adIdReadAt = o.longOrNull("ad_id_read_at")
178
+ s.adIdHash = o.stringOrNull("ad_id_hash")
179
+ s.lat = o.boolOrNull("lat")
180
+ s.ddlEligible = o.boolOrNull("ddl_eligible") ?: false
181
+ s.ddlTiktokDone = o.boolOrNull("ddl_tiktok_done") ?: false
182
+ s.ddlTiktokFailures = o.intOrNull("ddl_tiktok_failures") ?: 0
183
+ s.ddlReferrer = o.stringOrNull("ddl_referrer")
184
+ s.contextHash = o.stringOrNull("context_hash")
185
+ s.retryAttempt = o.intOrNull("retry_attempt") ?: 0
186
+ s.retryNextAt = o.longOrNull("retry_next_at") ?: 0
187
+ s.nextSeq = o.longOrNull("next_seq") ?: 1
188
+ return s
189
+ }
190
+ }
191
+ }
192
+
193
+ /** Attribution-bearing `$deeplink` events not yet accepted. Each is re-enqueued,
194
+ * same id, on the next launch until the collector answers for it. Bounded: [MAX] entries,
195
+ * [TTL_MS] old at most. */
196
+ internal class PendingLinks {
197
+ class Entry(val addedAt: Long, val event: JSONObject) {
198
+ val id: String? = event.stringOrNull("id")
199
+ }
200
+
201
+ private val entries = ArrayList<Entry>()
202
+
203
+ fun entries(): List<Entry> = entries
204
+
205
+ fun isEmpty(): Boolean = entries.isEmpty()
206
+
207
+ fun maxSeq(): Long = entries.maxOfOrNull { it.event.longOrNull("seq") ?: 0 } ?: 0
208
+
209
+ fun add(eventJson: String, now: Long) {
210
+ val o = parseObject(eventJson) ?: return
211
+ val entry = Entry(now, o)
212
+ if (entry.id == null || entries.any { it.id == entry.id }) return
213
+ entries.add(entry)
214
+ while (entries.size > MAX) entries.removeAt(0)
215
+ }
216
+
217
+ /** True when something was removed. */
218
+ fun remove(ids: Collection<String>): Boolean = entries.removeAll { it.id in ids }
219
+
220
+ /** Drops entries older than [TTL_MS] (or from a clock far in the future); true when any went. */
221
+ fun expire(now: Long): Boolean = entries.removeAll { now - it.addedAt > TTL_MS || it.addedAt - now > TTL_MS }
222
+
223
+ fun serialize(): String {
224
+ val arr = JSONArray()
225
+ for (e in entries) arr.put(JSONObject().put("added_at", e.addedAt).put("event", e.event))
226
+ return JSONObject().put("v", 1).put("links", arr).toString()
227
+ }
228
+
229
+ companion object {
230
+ const val MAX = 20
231
+ const val TTL_MS = 30L * 86_400_000L
232
+
233
+ fun parse(text: String?): PendingLinks {
234
+ val p = PendingLinks()
235
+ val arr = parseObject(text)?.optJSONArray("links") ?: return p
236
+ for (i in 0 until arr.length()) {
237
+ val o = arr.optJSONObject(i) ?: continue
238
+ val event = o.optJSONObject("event") ?: continue
239
+ val entry = Entry(o.longOrNull("added_at") ?: 0, event)
240
+ if (entry.id != null) p.entries.add(entry)
241
+ }
242
+ return p
243
+ }
244
+ }
245
+ }
246
+
247
+ /** sha1 of every purchase token already reported as `$purchase_link`. */
248
+ internal class ReportedPurchases {
249
+ private val hashes = LinkedHashSet<String>()
250
+
251
+ fun contains(hash: String): Boolean = hash in hashes
252
+
253
+ fun add(hash: String) {
254
+ hashes.add(hash)
255
+ while (hashes.size > MAX) hashes.remove(hashes.first())
256
+ }
257
+
258
+ fun serialize(): String = JSONObject().put("v", 1).put("sha1", JSONArray(hashes.toList())).toString()
259
+
260
+ companion object {
261
+ const val MAX = 1_000
262
+
263
+ fun tokenHash(purchaseToken: String): String = sha1Hex(purchaseToken)
264
+
265
+ fun parse(text: String?): ReportedPurchases {
266
+ val r = ReportedPurchases()
267
+ parseObject(text)?.optJSONArray("sha1")?.strings()?.forEach { r.hashes.add(it) }
268
+ return r
269
+ }
270
+ }
271
+ }