@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,274 @@
1
+ package com.kerdly.sdk.internal.android
2
+
3
+ import android.app.ActivityManager
4
+ import android.content.Context
5
+ import android.content.pm.ApplicationInfo
6
+ import android.content.pm.PackageInfo
7
+ import android.content.pm.PackageManager
8
+ import android.database.Cursor
9
+ import android.hardware.display.DisplayManager
10
+ import android.net.TrafficStats
11
+ import android.net.Uri
12
+ import android.os.Build
13
+ import android.os.LocaleList
14
+ import android.provider.Settings
15
+ import android.util.DisplayMetrics
16
+ import android.view.Display
17
+ import com.kerdly.sdk.internal.AdIdResult
18
+ import com.kerdly.sdk.internal.AdIds
19
+ import com.kerdly.sdk.internal.AppInfo
20
+ import com.kerdly.sdk.internal.ContextJson
21
+ import com.kerdly.sdk.internal.DeviceContext
22
+ import com.kerdly.sdk.internal.InstallInfo
23
+ import com.kerdly.sdk.internal.LocaleFormat
24
+ import com.kerdly.sdk.internal.Logger
25
+ import com.kerdly.sdk.internal.MetaReferrer
26
+ import com.kerdly.sdk.internal.MetaReferrerRow
27
+ import com.kerdly.sdk.internal.Platform
28
+ import com.kerdly.sdk.internal.PlayReferrerResult
29
+ import com.kerdly.sdk.internal.PublicIp
30
+ import com.kerdly.sdk.internal.Scheduler
31
+ import com.kerdly.sdk.internal.TestLab
32
+ import com.google.android.gms.ads.identifier.AdvertisingIdClient
33
+ import java.io.ByteArrayOutputStream
34
+ import java.net.HttpURLConnection
35
+ import java.net.URL
36
+ import java.util.Locale
37
+ import java.util.TimeZone
38
+ import java.util.concurrent.Callable
39
+ import java.util.concurrent.ExecutionException
40
+ import java.util.concurrent.FutureTask
41
+ import java.util.concurrent.TimeUnit
42
+ import java.util.concurrent.atomic.AtomicReference
43
+
44
+ /** [Platform] on Android. Every read is guarded: a failure is a null or empty answer. */
45
+ internal class AndroidPlatform(
46
+ private val context: Context,
47
+ private val scheduler: Scheduler,
48
+ private val log: Logger,
49
+ ) : Platform {
50
+ private val packageName: String = context.packageName
51
+
52
+ /** Read once per launch, on the SDK thread (the first [deviceContext]); it cannot change. */
53
+ private val testLab: Boolean by lazy {
54
+ TestLab.detect { Settings.System.getString(context.contentResolver, TestLab.SETTING) }
55
+ }
56
+
57
+ @Suppress("DEPRECATION")
58
+ private fun packageInfo(): PackageInfo? = try {
59
+ val pm = context.packageManager
60
+ if (Build.VERSION.SDK_INT >= 33) {
61
+ pm.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0))
62
+ } else {
63
+ pm.getPackageInfo(packageName, 0)
64
+ }
65
+ } catch (t: Throwable) {
66
+ null
67
+ }
68
+
69
+ @Suppress("DEPRECATION")
70
+ override fun appInfo(): AppInfo {
71
+ val info = packageInfo()
72
+ val build = info?.let { if (Build.VERSION.SDK_INT >= 28) it.longVersionCode.toString() else it.versionCode.toString() }
73
+ return AppInfo(packageName, info?.versionName, build)
74
+ }
75
+
76
+ @Suppress("DEPRECATION")
77
+ override fun installInfo(): InstallInfo {
78
+ // A failed read or a value ≤ 0 is null, never -1.
79
+ val installedAt = packageInfo()?.firstInstallTime?.takeIf { it > 0 }
80
+ val installer = try {
81
+ val pm = context.packageManager
82
+ if (Build.VERSION.SDK_INT >= 30) {
83
+ pm.getInstallSourceInfo(packageName).installingPackageName
84
+ } else {
85
+ pm.getInstallerPackageName(packageName)
86
+ }
87
+ } catch (t: Throwable) {
88
+ null
89
+ }
90
+ return InstallInfo(installedAt, installer)
91
+ }
92
+
93
+ override fun deviceContext(): DeviceContext {
94
+ val appLocales = context.resources.configuration.locales
95
+ val primary: Locale = if (appLocales.isEmpty) Locale.getDefault() else appLocales.get(0)
96
+ val preferred = LocaleList.getDefault()
97
+ val tags = ArrayList<String>()
98
+ for (i in 0 until preferred.size()) tags.add(preferred.get(i).toLanguageTag())
99
+ if (tags.isEmpty()) tags.add(primary.toLanguageTag())
100
+ val screen = screen()
101
+ return DeviceContext(
102
+ os = Build.VERSION.RELEASE,
103
+ model = Build.MODEL,
104
+ manufacturer = Build.MANUFACTURER,
105
+ locale = LocaleFormat.identifier(primary.toLanguageTag()),
106
+ languages = LocaleFormat.languages(tags),
107
+ tz = TimeZone.getDefault().id,
108
+ screenW = screen?.first,
109
+ screenH = screen?.second,
110
+ scale = screen?.third,
111
+ testLab = testLab,
112
+ )
113
+ }
114
+
115
+ /** The physical display in pixels (DisplayManager works from the application context). */
116
+ @Suppress("DEPRECATION")
117
+ private fun screen(): Triple<Int, Int, Double>? = try {
118
+ val metrics = DisplayMetrics()
119
+ val display = (context.getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager)?.getDisplay(Display.DEFAULT_DISPLAY)
120
+ if (display != null) display.getRealMetrics(metrics) else metrics.setTo(context.resources.displayMetrics)
121
+ ContextJson.screen(metrics.widthPixels, metrics.heightPixels, metrics.density)
122
+ } catch (t: Throwable) {
123
+ null
124
+ }
125
+
126
+ /** Blocking; never on the main thread (AdvertisingIdClient refuses it there). */
127
+ override fun readAdvertisingId(): AdIdResult? = try {
128
+ val info = AdvertisingIdClient.getAdvertisingIdInfo(context)
129
+ AdIds.normalize(info.id, info.isLimitAdTrackingEnabled)
130
+ } catch (t: Throwable) {
131
+ // No Play services, the library excluded by the app, or an IPC failure.
132
+ log.debug { "advertising id unavailable: ${t.javaClass.simpleName}" }
133
+ null
134
+ }
135
+
136
+ override fun readMetaReferrer(metaAppId: String): List<MetaReferrerRow> {
137
+ val rows = ArrayList<MetaReferrerRow>()
138
+ for ((source, authority) in MetaReferrer.PROVIDERS) {
139
+ try {
140
+ val uri = Uri.parse(MetaReferrer.uri(authority, metaAppId))
141
+ context.contentResolver.query(uri, MetaReferrer.COLUMNS, null, null, null)?.use { c ->
142
+ if (c.moveToFirst()) {
143
+ rows.add(
144
+ MetaReferrerRow(
145
+ source = source,
146
+ installReferrer = c.value("install_referrer") as? String,
147
+ isCt = MetaReferrer.isCt(c.value("is_ct")),
148
+ actualTimestamp = MetaReferrer.timestamp(c.value("actual_timestamp")),
149
+ ),
150
+ )
151
+ }
152
+ }
153
+ } catch (t: Throwable) {
154
+ // Not installed, not visible, or the provider refused: no row from this app.
155
+ log.debug { "Meta install referrer ($source): ${t.javaClass.simpleName}" }
156
+ }
157
+ }
158
+ return rows
159
+ }
160
+
161
+ /** Never on the SDK thread: a daemon thread waits for the answer and calls [onResult] once. */
162
+ override fun startPublicIpv6Lookup(echoUrl: String, timeoutMs: Long, onResult: (String?) -> Unit) {
163
+ try {
164
+ Thread({
165
+ val answer = readPublicIpv6(echoUrl, timeoutMs)
166
+ try {
167
+ onResult(answer)
168
+ } catch (t: Throwable) {
169
+ log.warn("public IPv6 result handling failed", t)
170
+ }
171
+ }, "kerdly-sdk-ip6").apply { isDaemon = true }.start()
172
+ } catch (t: Throwable) {
173
+ log.debug { "public IPv6 lookup not started: ${t.javaClass.simpleName}" }
174
+ }
175
+ }
176
+
177
+ /** Blocking, [timeoutMs] in all. The GET runs on a thread of its own so that a slow DNS answer,
178
+ * connect or read cannot outlast the budget (the connection's own timeouts are per phase); at
179
+ * the deadline the connection is torn down. */
180
+ private fun readPublicIpv6(echoUrl: String, timeoutMs: Long): String? {
181
+ val connection = AtomicReference<HttpURLConnection?>()
182
+ val task = FutureTask(Callable { fetchEcho(echoUrl, timeoutMs.toInt(), connection) })
183
+ return try {
184
+ Thread(task, "kerdly-sdk-ip6-get").apply { isDaemon = true }.start()
185
+ task.get(timeoutMs, TimeUnit.MILLISECONDS)
186
+ } catch (t: Throwable) {
187
+ // An IPv4-only network (no AAAA answer, no route), the timeout, a TLS or HTTP failure.
188
+ log.debug { "public IPv6 unavailable: ${((t as? ExecutionException)?.cause ?: t).javaClass.simpleName}" }
189
+ null
190
+ } finally {
191
+ task.cancel(true)
192
+ try {
193
+ connection.get()?.disconnect()
194
+ } catch (_: Throwable) {
195
+ }
196
+ }
197
+ }
198
+
199
+ /** One GET: no redirects, no cache, no cookies of the SDK's own; the answer's `ip`, or null. */
200
+ private fun fetchEcho(echoUrl: String, timeoutMs: Int, connection: AtomicReference<HttpURLConnection?>): String? {
201
+ TrafficStats.setThreadStatsTag(HttpUrlTransport.THREAD_STATS_TAG)
202
+ try {
203
+ val c = URL(echoUrl).openConnection() as HttpURLConnection
204
+ connection.set(c)
205
+ c.connectTimeout = timeoutMs
206
+ c.readTimeout = timeoutMs
207
+ c.instanceFollowRedirects = false
208
+ c.useCaches = false
209
+ c.setRequestProperty("Accept", "application/json")
210
+ if (c.responseCode != 200) return null
211
+ val body = ByteArrayOutputStream()
212
+ c.inputStream.use { input ->
213
+ val buffer = ByteArray(1024)
214
+ while (body.size() < MAX_ECHO_BYTES) {
215
+ val n = input.read(buffer)
216
+ if (n < 0) break
217
+ body.write(buffer, 0, n)
218
+ }
219
+ }
220
+ return PublicIp.parseEcho(String(body.toByteArray(), Charsets.UTF_8))
221
+ } finally {
222
+ connection.get()?.disconnect()
223
+ TrafficStats.clearThreadStatsTag()
224
+ }
225
+ }
226
+
227
+ override fun startPlayReferrer(timeoutMs: Long, onResult: (PlayReferrerResult) -> Unit) {
228
+ PlayReferrerReader(context, scheduler, log).start(timeoutMs, onResult)
229
+ }
230
+
231
+ private fun Cursor.value(column: String): Any? {
232
+ val i = getColumnIndex(column)
233
+ if (i < 0) return null
234
+ return when (getType(i)) {
235
+ Cursor.FIELD_TYPE_INTEGER -> getLong(i)
236
+ Cursor.FIELD_TYPE_FLOAT -> getDouble(i)
237
+ Cursor.FIELD_TYPE_STRING -> getString(i)
238
+ else -> null
239
+ }
240
+ }
241
+
242
+ companion object {
243
+ /** `{"ip": "…"}` is under 64 bytes; anything far larger is not the echo. */
244
+ private const val MAX_ECHO_BYTES = 4 * 1024
245
+
246
+ /** `com.kerdly.sdk.META_APP_ID` from the app's manifest meta-data, or null. The Expo config
247
+ * plugin writes it through a string resource; a hand-written numeric literal arrives as a
248
+ * number, hence `get` + `toString`. */
249
+ fun manifestMetaAppId(context: Context): String? = try {
250
+ @Suppress("DEPRECATION")
251
+ val info = context.packageManager.getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
252
+ info.metaData?.get("com.kerdly.sdk.META_APP_ID")?.toString()?.trim()?.takeIf { it.isNotEmpty() }
253
+ } catch (t: Throwable) {
254
+ null
255
+ }
256
+
257
+ fun isDebuggable(context: Context): Boolean = try {
258
+ (context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0
259
+ } catch (t: Throwable) {
260
+ false
261
+ }
262
+
263
+ /** Whether an activity of this process is visible right now (configure may run late, e.g.
264
+ * from the Expo bridge, after the first activity started). */
265
+ fun isProcessForeground(): Boolean = try {
266
+ val info = ActivityManager.RunningAppProcessInfo()
267
+ ActivityManager.getMyMemoryState(info)
268
+ info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND ||
269
+ info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE
270
+ } catch (t: Throwable) {
271
+ false
272
+ }
273
+ }
274
+ }
@@ -0,0 +1,187 @@
1
+ package com.kerdly.sdk.internal.android
2
+
3
+ import android.app.Activity
4
+ import android.app.Application
5
+ import android.net.TrafficStats
6
+ import android.os.Bundle
7
+ import android.os.Handler
8
+ import android.os.Looper
9
+ import android.os.Process
10
+ import android.util.Log
11
+ import com.kerdly.sdk.KerdlyLogLevel
12
+ import com.kerdly.sdk.internal.Cancellable
13
+ import com.kerdly.sdk.internal.HttpRequest
14
+ import com.kerdly.sdk.internal.HttpResponse
15
+ import com.kerdly.sdk.internal.LogSink
16
+ import com.kerdly.sdk.internal.Logger
17
+ import com.kerdly.sdk.internal.MainDispatcher
18
+ import com.kerdly.sdk.internal.Scheduler
19
+ import com.kerdly.sdk.internal.Transport
20
+ import java.io.ByteArrayOutputStream
21
+ import java.io.IOException
22
+ import java.io.InputStream
23
+ import java.net.HttpURLConnection
24
+ import java.net.URL
25
+ import java.util.concurrent.ScheduledThreadPoolExecutor
26
+ import java.util.concurrent.TimeUnit
27
+
28
+ /** The SDK's single background thread (`kerdly-sdk`, background priority). */
29
+ internal class ExecutorScheduler(private val log: Logger) : Scheduler {
30
+ private val executor = ScheduledThreadPoolExecutor(1) { runnable ->
31
+ Thread({
32
+ try {
33
+ Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)
34
+ } catch (_: Throwable) {
35
+ }
36
+ runnable.run()
37
+ }, "kerdly-sdk").apply { isDaemon = true }
38
+ }.apply { removeOnCancelPolicy = true }
39
+
40
+ override fun execute(task: () -> Unit) {
41
+ try {
42
+ executor.execute(Runnable { run(task) })
43
+ } catch (t: Throwable) {
44
+ log.warn("task rejected", t)
45
+ }
46
+ }
47
+
48
+ override fun schedule(delayMs: Long, task: () -> Unit): Cancellable = try {
49
+ val future = executor.schedule(Runnable { run(task) }, delayMs.coerceAtLeast(0), TimeUnit.MILLISECONDS)
50
+ Cancellable { future.cancel(false) }
51
+ } catch (t: Throwable) {
52
+ log.warn("task rejected", t)
53
+ Cancellable { }
54
+ }
55
+
56
+ private fun run(task: () -> Unit) {
57
+ try {
58
+ task()
59
+ } catch (t: Throwable) {
60
+ log.error("internal error", t)
61
+ }
62
+ }
63
+ }
64
+
65
+ /** `HttpURLConnection`, no redirects (a redirected POST would turn into a GET), bounded reads. */
66
+ internal class HttpUrlTransport : Transport {
67
+ override fun execute(request: HttpRequest): HttpResponse {
68
+ TrafficStats.setThreadStatsTag(THREAD_STATS_TAG)
69
+ var connection: HttpURLConnection? = null
70
+ try {
71
+ val c = URL(request.url).openConnection() as HttpURLConnection
72
+ connection = c
73
+ c.connectTimeout = CONNECT_TIMEOUT_MS
74
+ c.readTimeout = READ_TIMEOUT_MS
75
+ c.instanceFollowRedirects = false
76
+ c.useCaches = false
77
+ c.requestMethod = request.method
78
+ for ((name, value) in request.headers) c.setRequestProperty(name, value)
79
+ val body = request.body
80
+ if (body != null) {
81
+ c.doOutput = true
82
+ c.setFixedLengthStreamingMode(body.size)
83
+ c.outputStream.use { it.write(body) }
84
+ }
85
+ val status = c.responseCode
86
+ val stream: InputStream? = try {
87
+ if (status >= 400) c.errorStream else c.inputStream
88
+ } catch (e: IOException) {
89
+ c.errorStream
90
+ }
91
+ val text = stream?.use { readUtf8(it) } ?: ""
92
+ return HttpResponse(status, text, c.getHeaderField("Retry-After"), c.getHeaderField("ETag"))
93
+ } finally {
94
+ connection?.disconnect()
95
+ TrafficStats.clearThreadStatsTag()
96
+ }
97
+ }
98
+
99
+ private fun readUtf8(input: InputStream): String {
100
+ val out = ByteArrayOutputStream()
101
+ val buffer = ByteArray(8 * 1024)
102
+ while (out.size() < MAX_RESPONSE_BYTES) {
103
+ val n = input.read(buffer)
104
+ if (n < 0) break
105
+ out.write(buffer, 0, n)
106
+ }
107
+ return String(out.toByteArray(), Charsets.UTF_8)
108
+ }
109
+
110
+ companion object {
111
+ private const val CONNECT_TIMEOUT_MS = 10_000
112
+ private const val READ_TIMEOUT_MS = 15_000
113
+ private const val MAX_RESPONSE_BYTES = 1 shl 20
114
+ /** Every socket the SDK opens carries this tag (StrictMode's untagged-socket check). */
115
+ const val THREAD_STATS_TAG = 0xAF5
116
+ }
117
+ }
118
+
119
+ /** Foreground / background from started activities. Configure may run after the first activity
120
+ * started (the Expo bridge configures from JS), so the starting state comes from the process
121
+ * importance, and a stop of an activity started before registration still counts. Rotation
122
+ * (`isChangingConfigurations`) is not a background. */
123
+ internal class LifecycleTracker(
124
+ initialForeground: Boolean,
125
+ private val onForeground: () -> Unit,
126
+ private val onBackground: () -> Unit,
127
+ ) : Application.ActivityLifecycleCallbacks {
128
+ private val started = HashSet<Int>()
129
+ private var foreground = initialForeground
130
+
131
+ override fun onActivityStarted(activity: Activity) {
132
+ started.add(System.identityHashCode(activity))
133
+ if (!foreground) {
134
+ foreground = true
135
+ safely(onForeground)
136
+ }
137
+ }
138
+
139
+ override fun onActivityStopped(activity: Activity) {
140
+ started.remove(System.identityHashCode(activity))
141
+ if (foreground && started.isEmpty() && !isChangingConfigurations(activity)) {
142
+ foreground = false
143
+ safely(onBackground)
144
+ }
145
+ }
146
+
147
+ override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
148
+ override fun onActivityResumed(activity: Activity) {}
149
+ override fun onActivityPaused(activity: Activity) {}
150
+ override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
151
+ override fun onActivityDestroyed(activity: Activity) {}
152
+
153
+ private fun isChangingConfigurations(activity: Activity): Boolean = try {
154
+ activity.isChangingConfigurations
155
+ } catch (_: Throwable) {
156
+ false
157
+ }
158
+
159
+ private fun safely(block: () -> Unit) {
160
+ try {
161
+ block()
162
+ } catch (_: Throwable) {
163
+ }
164
+ }
165
+ }
166
+
167
+ internal object AndroidLogSink : LogSink {
168
+ private const val TAG = "Kerdly"
169
+
170
+ override fun write(level: KerdlyLogLevel, message: String, error: Throwable?) {
171
+ when (level) {
172
+ KerdlyLogLevel.ERROR -> Log.e(TAG, message, error)
173
+ KerdlyLogLevel.WARN -> Log.w(TAG, message, error)
174
+ KerdlyLogLevel.INFO -> Log.i(TAG, message, error)
175
+ KerdlyLogLevel.DEBUG -> Log.d(TAG, message, error)
176
+ KerdlyLogLevel.NONE -> Unit
177
+ }
178
+ }
179
+ }
180
+
181
+ internal object MainThreadDispatcher : MainDispatcher {
182
+ private val handler by lazy { Handler(Looper.getMainLooper()) }
183
+
184
+ override fun post(block: () -> Unit) {
185
+ handler.post(block)
186
+ }
187
+ }
@@ -0,0 +1,97 @@
1
+ package com.kerdly.sdk.internal.android
2
+
3
+ import android.content.Context
4
+ import com.kerdly.sdk.internal.Cancellable
5
+ import com.kerdly.sdk.internal.Logger
6
+ import com.kerdly.sdk.internal.PlayReferrerCodes
7
+ import com.kerdly.sdk.internal.PlayReferrerDetails
8
+ import com.kerdly.sdk.internal.PlayReferrerResult
9
+ import com.kerdly.sdk.internal.Scheduler
10
+ import com.android.installreferrer.api.InstallReferrerClient
11
+ import com.android.installreferrer.api.InstallReferrerStateListener
12
+ import java.util.concurrent.atomic.AtomicBoolean
13
+
14
+ /** One Play Install Referrer read, bounded by a timeout. Exactly one result per attempt, and the
15
+ * connection is always ended — the app's old reader had no timeout and could hang a session. */
16
+ internal class PlayReferrerReader(
17
+ private val context: Context,
18
+ private val scheduler: Scheduler,
19
+ private val log: Logger,
20
+ ) {
21
+ fun start(timeoutMs: Long, onResult: (PlayReferrerResult) -> Unit) {
22
+ Attempt(timeoutMs, onResult).begin()
23
+ }
24
+
25
+ private inner class Attempt(
26
+ private val timeoutMs: Long,
27
+ private val onResult: (PlayReferrerResult) -> Unit,
28
+ ) : InstallReferrerStateListener {
29
+ private val finished = AtomicBoolean(false)
30
+
31
+ @Volatile private var client: InstallReferrerClient? = null
32
+
33
+ @Volatile private var timeout: Cancellable? = null
34
+
35
+ fun begin() {
36
+ try {
37
+ timeout = scheduler.schedule(timeoutMs) {
38
+ finish(PlayReferrerResult.Transient("no answer within $timeoutMs ms"))
39
+ }
40
+ val c = InstallReferrerClient.newBuilder(context).build()
41
+ client = c
42
+ c.startConnection(this)
43
+ } catch (t: Throwable) {
44
+ finish(PlayReferrerResult.Transient("could not connect: ${t.javaClass.simpleName}"))
45
+ }
46
+ }
47
+
48
+ // Play calls back on the main thread; the details read is a binder call, so it runs on
49
+ // the SDK thread instead.
50
+ override fun onInstallReferrerSetupFinished(responseCode: Int) {
51
+ scheduler.execute {
52
+ if (finished.get()) return@execute
53
+ val result = when (PlayReferrerCodes.classify(responseCode)) {
54
+ PlayReferrerCodes.Kind.OK -> read()
55
+ PlayReferrerCodes.Kind.PERMANENT -> PlayReferrerResult.Permanent(responseCode)
56
+ PlayReferrerCodes.Kind.TRANSIENT -> PlayReferrerResult.Transient("response code $responseCode")
57
+ }
58
+ finish(result)
59
+ }
60
+ }
61
+
62
+ override fun onInstallReferrerServiceDisconnected() {
63
+ scheduler.execute { finish(PlayReferrerResult.Transient("service disconnected")) }
64
+ }
65
+
66
+ private fun read(): PlayReferrerResult = try {
67
+ val d = client!!.installReferrer
68
+ PlayReferrerResult.Ok(
69
+ PlayReferrerDetails.of(
70
+ referrer = d.installReferrer,
71
+ clickTs = d.referrerClickTimestampSeconds,
72
+ installBeginTs = d.installBeginTimestampSeconds,
73
+ clickServerTs = d.referrerClickTimestampServerSeconds,
74
+ installBeginServerTs = d.installBeginTimestampServerSeconds,
75
+ installVersion = d.installVersion,
76
+ instant = d.googlePlayInstantParam,
77
+ ),
78
+ )
79
+ } catch (t: Throwable) {
80
+ PlayReferrerResult.Transient("read failed: ${t.javaClass.simpleName}")
81
+ }
82
+
83
+ private fun finish(result: PlayReferrerResult) {
84
+ if (!finished.compareAndSet(false, true)) return
85
+ timeout?.cancel()
86
+ try {
87
+ client?.endConnection()
88
+ } catch (_: Throwable) {
89
+ }
90
+ try {
91
+ onResult(result)
92
+ } catch (t: Throwable) {
93
+ log.warn("install referrer result handling failed", t)
94
+ }
95
+ }
96
+ }
97
+ }
package/app.plugin.js ADDED
@@ -0,0 +1,2 @@
1
+ // Expo resolves `"plugins": ["@kerdly/expo"]` to this file.
2
+ module.exports = require('./plugin/withKerdly').withKerdly;
@@ -0,0 +1,106 @@
1
+ import type { KerdlyAttStatus, KerdlyAttribution, KerdlyAttributionListener, KerdlyConfigureOptions, KerdlyConsent, KerdlyDeepLink, KerdlyEventProperties, KerdlyNetworkSend, KerdlyPurchase, KerdlyPurchaseEvent, KerdlyRegistrationEvent, KerdlyRevenueEvent, KerdlySubscription } from './types';
2
+ /**
3
+ * Starts the native SDK. Call it once, as early as possible (module scope of the root component).
4
+ * Resolves when the native `configure` has run; never rejects.
5
+ */
6
+ /** The Kerdly collector, used when `endpoint` is not given. */
7
+ export declare const DEFAULT_ENDPOINT = "https://app.kerdly.com/api";
8
+ declare function configure(options: KerdlyConfigureOptions): Promise<void>;
9
+ /** Sets (or, with `null`, clears) the app's user id; attached to every later event. */
10
+ declare function setUserId(userId: string | null): void;
11
+ /** Records a custom event. Invalid names drop the event, invalid props are dropped. */
12
+ declare function track(name: string, properties?: KerdlyEventProperties): void;
13
+ /** Records `registration`: the user signed up (`method`: `anonymous`, `apple`, `google`, `email`, …). */
14
+ declare function trackRegistration(event?: KerdlyRegistrationEvent): void;
15
+ /** Records `start_trial`. `value` is what the user paid (0 for a free trial) and needs `currency`. */
16
+ declare function trackStartTrial(event?: KerdlyRevenueEvent): void;
17
+ /** Records `subscribe`: the first paid period started. `value` needs `currency`. */
18
+ declare function trackSubscribe(event?: KerdlyRevenueEvent): void;
19
+ /** Records `purchase`: a one-time purchase. `value` needs `currency`; `quantity` is an integer ≥ 1. */
20
+ declare function trackPurchase(event?: KerdlyPurchaseEvent): void;
21
+ /** Updates consent flags; an omitted flag keeps its current value. */
22
+ declare function setConsent(consent: KerdlyConsent): void;
23
+ /**
24
+ * Hands a deep link to the native SDK (which records `$deeplink`) and returns what it parsed.
25
+ * With `autoDeepLinks` on (the default) Linking URLs are already forwarded: use this only for
26
+ * URLs that do not arrive through React Native's `Linking`.
27
+ */
28
+ declare function handleUrl(url: string): Promise<KerdlyDeepLink | null>;
29
+ /**
30
+ * Sets (or, with `null`, clears) the account token the app's purchases carry. iOS: the StoreKit
31
+ * `appAccountToken` UUID. Android: the Play `obfuscatedAccountId` (a UUID, or Superwall's
32
+ * `$SuperwallAlias:<uuid>` before identify).
33
+ */
34
+ declare function setAppAccountToken(token: string | null): void;
35
+ /** Ids of other SDKs (e.g. `meta_anon_id`, `superwall_alias`) for the collector to join on. */
36
+ declare function setPartnerIds(ids: Record<string, string>): void;
37
+ /**
38
+ * Links a store purchase to this install (`$purchase_link`, once per transaction / token).
39
+ * Accepts the iOS or the Android shape. On iOS, calling it without a purchase sweeps
40
+ * `Transaction.currentEntitlements`; Android needs `purchaseToken`.
41
+ */
42
+ declare function notifyPurchase(purchase?: KerdlyPurchase | null): void;
43
+ /** Records a conversion the app sent to an ad network itself (`$network_send`). */
44
+ declare function recordNetworkSend(send: KerdlyNetworkSend): void;
45
+ /** The cached attribution, or `null` until the collector has decided one. */
46
+ declare function getAttribution(): Promise<KerdlyAttribution | null>;
47
+ /**
48
+ * Calls `listener` with the current attribution at once (when already known) and whenever the
49
+ * native SDK reports a new one, like the native `Kerdly.onAttribution`.
50
+ */
51
+ declare function addAttributionListener(listener: KerdlyAttributionListener): KerdlySubscription;
52
+ /**
53
+ * iOS: shows the App Tracking Transparency prompt (needs `NSUserTrackingUsageDescription`, which
54
+ * the config plugin's `userTrackingPermission` sets) and resolves the resulting status.
55
+ * Android: resolves `not_applicable`.
56
+ */
57
+ declare function requestTrackingAuthorization(): Promise<KerdlyAttStatus>;
58
+ /** Asks the native SDK to send its queue now. Resolves once the request is handed over. */
59
+ declare function flush(): Promise<void>;
60
+ /** The install id (a lowercase UUID), or `null` before the first `configure`. */
61
+ declare function getInstallId(): Promise<string | null>;
62
+ /** One network's answer to a deferred-deep-link request (`debugFetchDeferredLinks`). */
63
+ export interface KerdlyDeferredLinkAnswer {
64
+ network: string;
65
+ /** `link` | `none` | `error` | `skipped_att` | `skipped_consent` | `not_configured`. */
66
+ status: string;
67
+ url?: string;
68
+ clickTime?: string;
69
+ httpStatus?: number;
70
+ detail?: string;
71
+ }
72
+ /**
73
+ * Debug builds only (iOS): asks Meta (ids from the app's Facebook config) and TikTok
74
+ * (`tiktokAppId`) for this device's deferred deep link and resolves each network's raw answer.
75
+ * Sends nothing to Kerdly. Asks only when the `ads` consent is on and tracking is authorized. In a
76
+ * release build it asks nothing and every answer is `error` ("debug builds only"). Android
77
+ * resolves `[]`.
78
+ */
79
+ declare function debugFetchDeferredLinks(options?: {
80
+ tiktokAppId?: string | null;
81
+ storeAppId?: string | null;
82
+ }): Promise<KerdlyDeferredLinkAnswer[]>;
83
+ export declare const Kerdly: {
84
+ configure: typeof configure;
85
+ setUserId: typeof setUserId;
86
+ track: typeof track;
87
+ trackRegistration: typeof trackRegistration;
88
+ trackStartTrial: typeof trackStartTrial;
89
+ trackSubscribe: typeof trackSubscribe;
90
+ trackPurchase: typeof trackPurchase;
91
+ setConsent: typeof setConsent;
92
+ handleUrl: typeof handleUrl;
93
+ setAppAccountToken: typeof setAppAccountToken;
94
+ setPartnerIds: typeof setPartnerIds;
95
+ notifyPurchase: typeof notifyPurchase;
96
+ recordNetworkSend: typeof recordNetworkSend;
97
+ getAttribution: typeof getAttribution;
98
+ addAttributionListener: typeof addAttributionListener;
99
+ requestTrackingAuthorization: typeof requestTrackingAuthorization;
100
+ flush: typeof flush;
101
+ getInstallId: typeof getInstallId;
102
+ debugFetchDeferredLinks: typeof debugFetchDeferredLinks;
103
+ };
104
+ export type KerdlyApi = typeof Kerdly;
105
+ export {};
106
+ //# sourceMappingURL=Kerdly.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Kerdly.d.ts","sourceRoot":"","sources":["../src/Kerdly.ts"],"names":[],"mappings":"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"}