Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
109 commits
Select commit Hold shift + click to select a range
c5b7d77
fix(sdk): requests made before the device has a did are neither lost …
Xyzcancer Nov 13, 2026
b4b0a50
feat(sdk): the SDK's log has levels and a handler for the app: Rees46…
Xyzcancer Nov 13, 2026
d432939
test(sdk): a harness for the core: an injectable clock and dispatcher…
Xyzcancer Nov 13, 2026
435b3a0
build: check fails on a new `!!` in the SDK's Kotlin sources; the vie…
Xyzcancer Nov 13, 2026
647ae03
fix(sdk): the log carries no exception text, URLs or server messages:…
Xyzcancer Nov 13, 2026
b1a057c
fix(sdk): a shop's log level applies to its instance's lines: instanc…
Xyzcancer Nov 13, 2026
253eb6b
refactor(sdk): the core's main dispatcher is looked up on first use, …
Xyzcancer Nov 13, 2026
af2e4d7
build: the `!!` check counts code only, not comments, strings or char…
Xyzcancer Nov 13, 2026
154a3a7
fix(sdk): log codes follow the spec's table at its levels: a 4xx /ini…
Xyzcancer Nov 13, 2026
2b2bb55
fix(sdk): a new device's first requests carry its did: the requests t…
Xyzcancer Nov 13, 2026
397b98f
build: minSdk 23 (Android 6.0) for the SDK and the demo app, as decis…
Xyzcancer Nov 13, 2026
27dd53e
build: OkHttp 5.3 for the new core's client, with mockwebserver3 for …
Xyzcancer Nov 13, 2026
45a33f6
refactor(core): the core's internal seams (clock, dispatchers, connec…
Xyzcancer Nov 13, 2026
5410800
feat(core): SdkError, the failure type of the new API (notInitialized…
Xyzcancer Nov 13, 2026
7eddb72
feat(core): Rees46Config.coreV2 (off by default, one core per process…
Xyzcancer Nov 13, 2026
cc542a8
test(core): the new client against mockwebserver3: the classification…
Xyzcancer Nov 13, 2026
4832115
fix(sdk): an app callback that throws is logged as callback_failed (t…
Xyzcancer Nov 13, 2026
92e214e
docs(core): Rees46Config.coreV2 says how the new core's answers diffe…
Xyzcancer Nov 13, 2026
ae472b3
fix(sdk): a shop's log level registers on Android 6: the levels live …
Xyzcancer Nov 13, 2026
f73b99b
build: lint 8.9 over AGP 8.5, whose lint cannot read the kotlin-stdli…
Xyzcancer Nov 13, 2026
dcd1333
build: OkHttp 4.12 instead of 5 for the new core's client, so an app …
Xyzcancer Nov 13, 2026
8484f1e
fix(sdk): log codes follow the extended table: a push that is not the…
Xyzcancer Nov 13, 2026
ba071e3
feat(core): storage for the new core: a device-level store (personali…
Xyzcancer Nov 13, 2026
c4c5c35
feat(core): deleteUserCredentials(), a suspend function and a Java fo…
Xyzcancer Nov 13, 2026
e808a91
test(core): upgrades from the layouts installs have on disk (the 2.4x…
Xyzcancer Nov 13, 2026
9491ffa
fix(sdk): the User-Agent is upper-cased without the device's locale, …
Xyzcancer Nov 13, 2026
6972771
fix(sdk): deleteUserCredentials() after review: the restart begins be…
Xyzcancer Nov 13, 2026
008dbbe
fix(sdk): a push token never goes out without a did: it waits with th…
Xyzcancer Nov 13, 2026
ff18eea
fix(sdk): log lines after review: an exception reaches the log as its…
Xyzcancer Nov 13, 2026
46aa31c
feat(core): initialization and the instance (stage 3). Both cores: SD…
Xyzcancer Nov 13, 2026
dd0f80e
test(core): every row of the init answer table, the pauses and Retry-…
Xyzcancer Nov 13, 2026
138ade4
test(sdk): the storage tests wait for the legacy path's requests to b…
Xyzcancer Nov 13, 2026
a98821d
fix(core): onStateChange calls a new listener at once with the curren…
Xyzcancer Nov 13, 2026
844d5f3
fix(sdk): the forms of PreferencesDataSource.initialize, PreferencesR…
Xyzcancer Nov 13, 2026
79b3ec1
fix(core): the new core's /init carries no segment, as core/init.md l…
Xyzcancer Nov 13, 2026
c30a97d
fix(core): a Retry-After pause is kept between 1 s and 5 min, for /in…
Xyzcancer Nov 13, 2026
f97677c
fix(core): stage 3 after review. deleteUserCredentials() runs to its …
Xyzcancer Nov 13, 2026
a22f835
feat(core): the session of the new core (stage 4, core/session.md, de…
Xyzcancer Nov 13, 2026
04032b1
test(core): the session: a new device has no sid until /init brings t…
Xyzcancer Nov 13, 2026
0a75f20
fix(core): a request that finds the session's window ended while the …
Xyzcancer Nov 13, 2026
1c62168
feat(core): the event queue of the new core (stage 5, core/queue.md, …
Xyzcancer Nov 13, 2026
1f09eb8
test(core): the event queue over its files and a real /init: every ro…
Xyzcancer Nov 13, 2026
0e3cd3a
fix(sdk): initialize of the preferences data source and repository an…
Xyzcancer Nov 13, 2026
2a31c40
fix(core): tracking on the new core refuses an empty custom event and…
Xyzcancer Nov 13, 2026
10042e9
fix(core): the guard that keeps OkHttp from repeating a 408 or a 503 …
Xyzcancer Nov 13, 2026
b13da8c
fix(core): the event queue after review. An event read before the cus…
Xyzcancer Nov 13, 2026
546609b
fix(core): the session and /init after review. An /init answer withou…
Xyzcancer Nov 13, 2026
b1026ab
refactor(core): what nothing used goes: the ReadyGate interface, Core…
Xyzcancer Nov 13, 2026
a67ff08
test(core): the session listener and the Java form of flush() are hea…
Xyzcancer Nov 13, 2026
f86fb9a
fix(core): the new core sends an event's numbers as JSON numbers, as …
Xyzcancer Nov 13, 2026
9c0aa8c
feat(core): push on the new core (stage 6, core/push.md, decision 000…
Xyzcancer Nov 13, 2026
359dbd3
feat(core): an API for the Flutter and React Native bridges (stage 7)…
Xyzcancer Nov 13, 2026
9922bea
fix(core): an ordinary pause between /init repeats ends when the netw…
Xyzcancer Nov 13, 2026
7d55cbe
fix(core): a 402, 403 or 404 to an event less than ten minutes after …
Xyzcancer Nov 13, 2026
cf700f6
fix(core): on the new core the popups v3 and stories v3 clients, whic…
Xyzcancer Nov 13, 2026
09df57c
docs(core): the tracking methods say that on the new core an event's …
Xyzcancer Nov 13, 2026
1bef78d
fix(push): a notification the SDK draws is reported only on the new c…
Xyzcancer Nov 13, 2026
5d7d51f
fix(push): a push asks no /init. Its events need only the stored did,…
Xyzcancer Nov 13, 2026
81b3f42
fix(core): flush() ends however the pass it waits for ends, and a req…
Xyzcancer Nov 13, 2026
34997a0
fix(push): setPushToken around release() answers notInitialized, a cl…
Xyzcancer Nov 13, 2026
bb2d968
fix(bridge): the checks of the tracking managers reach a bridge as in…
Xyzcancer Nov 13, 2026
c9ff3d2
fix(core): an /init answer without a seance wakes the queue that wait…
Xyzcancer Nov 13, 2026
21b5de6
fix(push): a push event counts as sent once the queue accepted it, so…
Xyzcancer Nov 13, 2026
a516bb0
test(push): what must not go is checked once the work it would come f…
Xyzcancer Nov 13, 2026
3a73ee1
fix(core): the event queue sends in two lanes, push events and tracki…
Xyzcancer Nov 13, 2026
d03c106
fix(push): the push callbacks and the bridges' onPushEvent hear an ev…
Xyzcancer Nov 13, 2026
9245e12
fix(push): a claim of the token's week is free after five minutes, a …
Xyzcancer Nov 13, 2026
c08a43c
fix(core): an instance that is not ready holds the queue's two lanes …
Xyzcancer Nov 13, 2026
98596fa
test(core): a live run of both cores against the demo shop, and the n…
Xyzcancer Nov 14, 2026
f21141d
fix(push): the app never gets the instance brought up for a push, a p…
Xyzcancer Nov 14, 2026
a64cde9
fix(push): on the legacy core a push for a shop without a did makes i…
Xyzcancer Nov 14, 2026
d6be25c
fix(push): a token send begun before deleteUserCredentials records no…
Xyzcancer Nov 14, 2026
1c26ad5
fix(push): the new core decides no_did from every source of a did, so…
Xyzcancer Nov 14, 2026
4d90465
fix(core): the queue's two lanes each have their own pause and count …
Xyzcancer Nov 14, 2026
1d51eb8
perf(core): the queue's head scan keeps an index of the events it kno…
Xyzcancer Nov 14, 2026
f31e32c
refactor(core): what only tests used goes: CoreInit.awaitUsable(timeo…
Xyzcancer Nov 14, 2026
9568b3c
docs(core): Rees46Config.coreV2 and deleteUserCredentials say which r…
Xyzcancer Nov 14, 2026
fa70ee3
test(legacy): the legacy /init repeats a failure without an answer or…
Xyzcancer Nov 16, 2026
1b219e6
test(legacy): the legacy core answers the old callbacks as 2.49.0 did…
Xyzcancer Nov 16, 2026
ac6ef6a
test(core): the new core sends its User-Agent and never a cookie, a t…
Xyzcancer Nov 16, 2026
c6b3c51
test(core): on the new core every tracking method refuses an empty id…
Xyzcancer Nov 16, 2026
78fcf6f
test(core): the advertising id goes with /init only with sendAdvertis…
Xyzcancer Nov 16, 2026
695a43b
fix(core): an object the deprecated initialize moves to another shop …
Xyzcancer Nov 16, 2026
302b3f4
test(push): the token a provider gives at the start goes once with th…
Xyzcancer Nov 16, 2026
3055c0f
test(push): on the legacy core a tap in the old form sends track/clic…
Xyzcancer Nov 16, 2026
d141a32
test(push): a notification of a push the SDK did not see is reported …
Xyzcancer Nov 16, 2026
10ef88e
test(core): the system's network callback is registered once for the …
Xyzcancer Nov 16, 2026
1415017
test(push): the hub forgets the oldest message past a thousand and th…
Xyzcancer Nov 16, 2026
aeb8c03
test(push): a token sent under the keys of older releases keeps its w…
Xyzcancer Nov 16, 2026
e0eda65
test(core): a saved init answer or a queue file the disk refuses is s…
Xyzcancer Nov 16, 2026
f953663
fix(core): OkHttp never sends a request again by itself: a POST whose…
Xyzcancer Nov 16, 2026
c41de34
fix(core): flush of a refused shop ends without an error: its queue w…
Xyzcancer Nov 16, 2026
1fb4480
fix(core): the listeners of the events a shop's refusal cleared from …
Xyzcancer Nov 16, 2026
1f4d0cd
fix(core): a push's delivery and its notification shown or dismissed …
Xyzcancer Nov 16, 2026
58c67e7
fix(core): an event the disk refused is not sent from the background …
Xyzcancer Nov 16, 2026
df5ec72
fix(core): deleteUserCredentials racing release no longer leaves the …
Xyzcancer Nov 16, 2026
b65c7b0
fix(logs): the log speaks the contract: device_id_kept is a reason of…
Xyzcancer Nov 16, 2026
4d04922
fix(push): needReInitialization forgets the push token's week with th…
Xyzcancer Nov 16, 2026
8621ff9
fix(push): a push the app's first call overtakes goes to the app's in…
Xyzcancer Nov 16, 2026
b8fdf2d
fix(push): a tap sets its source before it is handed to a queue, so a…
Xyzcancer Nov 16, 2026
16695af
fix(push): on the legacy core a cold push for a shop without a did se…
Xyzcancer Nov 16, 2026
c79f26f
fix(push): SDK.instance while only the instance a push brought up liv…
Xyzcancer Nov 16, 2026
1ec1810
fix(push): on the legacy core a request the push's instance holds for…
Xyzcancer Nov 16, 2026
852983b
docs(core): the popups v3 client follows the app's CookieHandler too,…
Xyzcancer Nov 16, 2026
d2f36a9
test(push): the fixes of the push's bring-up and the token's week tha…
Xyzcancer Nov 16, 2026
9da1c82
test(core): the queue's and /init's paths no test ran: a shop check t…
Xyzcancer Nov 16, 2026
c4f9df6
test(core): two shops kept apart, a refused shop's customer deleted, …
Xyzcancer Nov 16, 2026
3ade067
test(core): the tests of an /init repeated as retrying wait for init_…
Xyzcancer Nov 16, 2026
8bd2df7
fix(core): OkHttp moves on to a host's next address again when it can…
Xyzcancer Nov 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions demo-app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ android {

defaultConfig {
applicationId "com.personalization.demo"
// Compose requires 21. The SDK keeps minSdk 19 — it takes Compose as compileOnly.
minSdkVersion 21
// The SDK's minimum.
minSdkVersion 23
targetSdkVersion 34
versionCode 1
versionName "1.0"
multiDexEnabled true

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
testInstrumentationRunner "com.personalization.demo.DemoTestRunner"

// Add shop ID to BuildConfig
buildConfigField "String", "SHOP_ID", "\"${shopId}\""
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.personalization.demo

import android.app.Application
import android.os.Bundle
import androidx.test.runner.AndroidJUnitRunner

/**
* The demo's test runner: [AndroidJUnitRunner] with one switch, for tests that need a process the demo
* has not touched.
*
* [DemoApplication] initializes the demo shop in `onCreate`, and the first initialization of a process
* decides its core (`Rees46Config.coreV2`). With the argument `cleanProcess=true` the application's
* `onCreate` is not called, so the test makes the process's first initialization itself:
* `-Pandroid.testInstrumentationRunnerArguments.cleanProcess=true`, or `-e cleanProcess true` with
* `am instrument`. Without it the runner behaves as [AndroidJUnitRunner].
*/
class DemoTestRunner : AndroidJUnitRunner() {

// Called before callApplicationOnCreate: the system passes the arguments first.
override fun onCreate(arguments: Bundle?) {
cleanProcess = arguments?.getString(ARG_CLEAN_PROCESS) == "true"
super.onCreate(arguments)
}

override fun callApplicationOnCreate(app: Application) {
if (cleanProcess) return
super.callApplicationOnCreate(app)
}

companion object {
const val ARG_CLEAN_PROCESS = "cleanProcess"

/** True when the application's `onCreate` was not called in this process. */
@Volatile
var cleanProcess: Boolean = false
private set
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ class MultiInstanceE2ETest {

@Test
fun bothShops_resolveToDistinctInstances() {
val a = Rees46.getInstance(shopA)
val b = Rees46.getInstance(shopB) // materializes the lazily-registered shop B
val a = Rees46.instance(shopA)
val b = Rees46.instance(shopB) // materializes the lazily-registered shop B
assertNotNull(a)
assertNotNull(b)
assertNotSame("Each shop must have its own SDK instance", a, b)
Expand All @@ -84,19 +84,19 @@ class MultiInstanceE2ETest {

@Test
fun defaultGetInstance_isAmbiguousWithTwoShopsLive() {
Rees46.getInstance(shopB) // make both live
assertThrowsOf<AmbiguousShopException> { Rees46.getInstance() }
Rees46.instance(shopB) // make both live
assertThrowsOf<AmbiguousShopException> { Rees46.instance() }
}

@Test
fun getInstance_forUnknownShop_throwsUnknownShopId() {
assertThrowsOf<UnknownShopIdException> { Rees46.getInstance("nope-not-a-shop") }
assertThrowsOf<UnknownShopIdException> { Rees46.instance("nope-not-a-shop") }
}

@Test
fun handlePush_routesToTheNamedShopOnly() {
val a = Rees46.getInstance(shopA)
val b = Rees46.getInstance(shopB)
val a = Rees46.instance(shopA)
val b = Rees46.instance(shopB)
val toA = mutableListOf<NotificationData>()
val toB = mutableListOf<NotificationData>()
a.setOnMessageListener { toA.add(it) }
Expand All @@ -113,8 +113,8 @@ class MultiInstanceE2ETest {

@Test
fun handlePush_withUnknownShop_isDropped() {
val a = Rees46.getInstance(shopA)
val b = Rees46.getInstance(shopB)
val a = Rees46.instance(shopA)
val b = Rees46.instance(shopB)
val toA = mutableListOf<NotificationData>()
val toB = mutableListOf<NotificationData>()
a.setOnMessageListener { toA.add(it) }
Expand All @@ -130,7 +130,7 @@ class MultiInstanceE2ETest {

@Test
fun handlePush_clicked_tracksTheClickOnTheNamedShop() {
Rees46.getInstance(shopB) // ensure B is live and its session is ready
Rees46.instance(shopB) // ensure B is live and its session is ready
HttpLogStore.clear()

// CLICKED goes through notificationClicked, whose extractor reads NOTIFICATION_TYPE/
Expand Down Expand Up @@ -161,7 +161,7 @@ class MultiInstanceE2ETest {
// used by no other test, so on a fresh process it is genuinely pending here.
val lazyShop = "mi-materialize-on-push"
val context = InstrumentationRegistry.getInstrumentation().targetContext
Rees46.registerShops(
Rees46.register(
context = context,
configs = listOf(Rees46Config(shopId = lazyShop, autoSendPushToken = false)),
eagerInit = false
Expand Down Expand Up @@ -196,8 +196,8 @@ class MultiInstanceE2ETest {

/** Both shops live, then poll until the server has assigned each a did/sid (async /init). */
private fun awaitSessions(timeoutMs: Long = 10_000): Sessions {
val a = Rees46.getInstance(shopA)
val b = Rees46.getInstance(shopB)
val a = Rees46.instance(shopA)
val b = Rees46.instance(shopB)
val deadline = System.currentTimeMillis() + timeoutMs
var s = read(a, b)
while (System.currentTimeMillis() < deadline &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class DemoApplication : MultiDexApplication() {
// Official initialization (per docs): initialize the shop once in Application.onCreate through
// the Rees46 entry point so it is registered and ready in every process start — including the
// cold process FCM starts just to deliver a push. Reach it anywhere with
// Rees46.getInstance(shopId).
// Rees46.instance(shopId).
try {
sdk = Rees46.initialize(
context = applicationContext,
Expand All @@ -55,7 +55,7 @@ class DemoApplication : MultiDexApplication() {
// Second shop for the Multi-instance tab: registered but not initialized here. It comes
// to life lazily the first time that tab resolves it (getInstance / a StoriesWidget with
// its shopId) — demonstrating per-shop lazy materialization alongside the eager default.
Rees46.registerShops(
Rees46.register(
context = applicationContext,
configs = listOf(Rees46Config(shopId = BuildConfig.SHOP_ID_2)),
eagerInit = false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ class MainActivity : AppCompatActivity() {
// The shop is initialized once in DemoApplication.onCreate (Application) so it is ready in
// every process — including the cold process FCM/HMS starts to deliver a push. Reach that same
// registered instance by its shopId (do NOT create a new SDK()).
sdk = Rees46.getInstance(BuildConfig.SHOP_ID)
sdk = Rees46.instance(BuildConfig.SHOP_ID)
// Show the registered push provider(s) + token (FCM and/or HMS) in the header.
observePushTokens()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ fun MultiInstancePane(

// Re-reading the sessions after B's async /init lands: bumping this recomposes the cards.
var refreshToken by remember { mutableStateOf(0) }
val shopA = remember(refreshToken) { runCatching { Rees46.getInstance(shopIdA) }.getOrNull() }
val shopA = remember(refreshToken) { runCatching { Rees46.instance(shopIdA) }.getOrNull() }
// Resolving B by its id materializes the lazy registration — this is where shop B is born.
val shopB = remember(refreshToken) { runCatching { Rees46.getInstance(shopIdB) }.getOrNull() }
val shopB = remember(refreshToken) { runCatching { Rees46.instance(shopIdB) }.getOrNull() }

// The global Rees46.setOnMessageListener (DemoApplication) already posts a notification for every
// shop. This extra, screen-scoped subscriber shows the (deprecated) per-instance
Expand Down Expand Up @@ -115,10 +115,10 @@ fun MultiInstancePane(

// Fail-fast contracts, exercised live.
Text(text = stringResource(R.string.mi_contracts_title), fontWeight = FontWeight.Bold)
Button(onClick = { log(runContract { Rees46.getInstance() }) }) {
Button(onClick = { log(runContract { Rees46.instance() }) }) {
Text(text = stringResource(R.string.mi_btn_ambiguous))
}
Button(onClick = { log(runContract { Rees46.getInstance("nope") }) }) {
Button(onClick = { log(runContract { Rees46.instance("nope") }) }) {
Text(text = stringResource(R.string.mi_btn_unknown))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ class GameActivity : AppCompatActivity() {
)

/** `null` — the shop did not initialize. */
private fun shopSdk(): SDK? = runCatching { Rees46.getInstance(BuildConfig.SHOP_ID) }.getOrNull()
private fun shopSdk(): SDK? = runCatching { Rees46.instance(BuildConfig.SHOP_ID) }.getOrNull()

/** Opens the game of the game link [link] over the screen of [context]. */
fun start(context: Context, link: String) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class ShopActivity : AppCompatActivity() {
statusBar.onSystemBars { top, _ -> statusBar.updateLayoutParams { height = top } }
shop = DemoShop(
context = this,
sdk = Rees46.getInstance(BuildConfig.SHOP_ID),
sdk = Rees46.instance(BuildConfig.SHOP_ID),
shopId = BuildConfig.SHOP_ID,
storiesCode = getString(R.string.shop_stories_code),
container = container
Expand Down
132 changes: 129 additions & 3 deletions personalization-sdk/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ android {
}
}
defaultConfig {
minSdkVersion 19
// Android 6.0: what current Firebase Messaging and media3 need (decision 0003).
minSdkVersion 23
targetSdkVersion 34
buildConfigField "String", "VERSION_NAME", "\"" + version + "\""
multiDexEnabled true
Expand Down Expand Up @@ -111,6 +112,11 @@ dependencies {
// through lifecycle-process; declared because the SDK now relies on it directly.
implementation 'androidx.startup:startup-runtime:1.1.1'
implementation 'com.google.code.gson:gson:2.11.0'
// The new core's HTTP client (Rees46Config.coreV2): one connection pool for the process. 4.12, not 5:
// OkHttp 5 brings kotlin-stdlib 2.2, which asks apps for a Kotlin compiler of 2.1 or later, and adds an
// androidx.startup initializer to their manifest. 4.12 brings neither: its kotlin-stdlib is older than
// the SDK's own.
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
implementation 'org.jetbrains.kotlin:kotlin-stdlib'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4'

Expand All @@ -128,8 +134,7 @@ dependencies {
// compileOnly mirrors the Huawei setup above: Compose stays off every consumer's classpath and
// out of the published POM, so a View-based app pulls none of it. A host that wants the wrapper
// already has Compose and declares it as `implementation` itself. compileOnly artifacts take no
// part in manifest merging either, which keeps the SDK's minSdk 19 intact even though Compose
// itself requires 21.
// part in manifest merging either.
compileOnly platform('androidx.compose:compose-bom:2024.06.00')
compileOnly 'androidx.compose.ui:ui'
compileOnly 'androidx.compose.foundation:foundation'
Expand All @@ -150,8 +155,10 @@ dependencies {

testImplementation 'junit:junit:4.13.2'
testImplementation 'io.mockk:mockk:1.13.11'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4'
testImplementation 'androidx.test:core:1.6.1'
testImplementation 'org.robolectric:robolectric:4.12.1'
testImplementation 'com.squareup.okhttp3:mockwebserver:4.12.0'
// compileOnly dependencies are absent from the unit test classpath, and the Compose compiler
// plugin refuses to compile the test variant without the runtime it can see. These mirror the
// compileOnly declarations above and stay confined to tests, so the published POM is unaffected.
Expand Down Expand Up @@ -254,3 +261,122 @@ tasks.register('publishToMavenCentral') {
println "Publishing to Maven Central only"
}
}

// No new `!!` in the SDK: a force unwrap on a path the app reaches crashes the app instead of failing one call.
// force-unwrap-baseline.txt lists the views that still have them and how many; it may only shrink, and it must
// stay exact, so a removed `!!` or file shows up as a stale line to delete. Plain text scan that skips
// comments, strings and characters (`"https://…"`, `"Hi!!"`), so it needs no compiler and runs in `check`.
tasks.register('checkForceUnwraps') {
group = 'verification'
description = 'Fails when the `!!` in the Kotlin sources differ from force-unwrap-baseline.txt.'
def sourceRoot = file('src/main/kotlin')
def baseline = file('force-unwrap-baseline.txt')
def sources = fileTree(sourceRoot) { include '**/*.kt' }
inputs.files(sources)
inputs.file(baseline)
outputs.upToDateWhen { false }
doLast {
def allowed = [:]
baseline.eachLine { line ->
def entry = line.trim()
if (entry && !entry.startsWith('#')) {
def parts = entry.split(/\s+/)
allowed[parts[0]] = parts[1] as int
}
}
def counts = [:]
sources.each { File source ->
def path = sourceRoot.toPath().relativize(source.toPath()).toString().replace(File.separator, '/')
counts[path] = ForceUnwraps.count(source.getText('UTF-8'))
}
def problems = []
counts.each { path, count ->
if (!allowed.containsKey(path)) {
if (count > 0) problems << "${path}: ${count} `!!` in a file the baseline does not list; new code handles the null instead"
} else {
int limit = allowed[path] as int
if (count > limit) problems << "${path}: ${count} `!!`, ${limit} allowed"
if (count < limit) {
def fix = count == 0 ? 'remove its line' : "lower its count to ${count}"
problems << "${path}: ${count} `!!`, the baseline still allows ${limit}: ${fix} in force-unwrap-baseline.txt"
}
}
}
allowed.keySet().findAll { !counts.containsKey(it) }.each { path ->
problems << "${path}: no such file any more: remove its line from force-unwrap-baseline.txt"
}
if (!problems.isEmpty()) {
throw new GradleException("Force unwraps (`!!`) in the SDK do not match the baseline:\n" + problems.join('\n'))
}
}
}

/** Counts `!!` in Kotlin code, skipping comments, string and character literals but not string templates. */
class ForceUnwraps {
static int count(String text) {
int count = 0
int i = 0
int n = text.length()
// Frames: [kind, brace depth]. The bottom one is the file's code; a code frame above it is a
// string template (`${…}`), closed by its own `}`.
def frames = new ArrayDeque<List>()
frames.push(['code', 0])
while (i < n) {
def frame = frames.peek()
char c = text.charAt(i)
switch (frame[0]) {
case 'code':
if (text.startsWith('//', i)) {
int end = text.indexOf('\n', i)
i = end < 0 ? n : end
} else if (text.startsWith('/*', i)) {
int depth = 1
i += 2
while (i < n && depth > 0) {
if (text.startsWith('/*', i)) { depth++; i += 2 }
else if (text.startsWith('*/', i)) { depth--; i += 2 }
else i++
}
} else if (text.startsWith('"""', i)) {
frames.push(['raw', 0]); i += 3
} else if (c == '"' as char) {
frames.push(['string', 0]); i++
} else if (c == '\'' as char) {
int from = (i + 1 < n && text.charAt(i + 1) == '\\' as char) ? i + 3 : i + 2
int close = text.indexOf("'", Math.min(from, n))
i = close < 0 ? n : close + 1
} else if (text.startsWith('!!', i)) {
count++; i += 2
} else if (c == '{' as char) {
frame[1]++; i++
} else if (c == '}' as char) {
if (frame[1] == 0 && frames.size() > 1) frames.pop() else frame[1]--
i++
} else {
i++
}
break
case 'string':
if (c == '\\' as char) i += 2
else if (c == '"' as char || c == '\n' as char) { frames.pop(); i++ }
else if (text.startsWith('${', i)) { frames.push(['code', 0]); i += 2 }
else i++
break
case 'raw':
if (text.startsWith('"""', i)) {
i += 3
while (i < n && text.charAt(i) == '"' as char) i++
frames.pop()
} else if (text.startsWith('${', i)) {
frames.push(['code', 0]); i += 2
} else {
i++
}
break
}
}
return count
}
}

tasks.named('check') { dependsOn 'checkForceUnwraps' }
15 changes: 15 additions & 0 deletions personalization-sdk/force-unwrap-baseline.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Kotlin sources that may still have `!!`, and exactly how many. The list may only shrink:
# a force unwrap on a path the app reaches crashes the app instead of failing one call.
# Removing a `!!` means lowering its count here (or removing the line at 0) in the same change.
# Checked by `./gradlew checkForceUnwraps`, which `check` runs; comments and strings are not counted.
com/personalization/inAppNotification/view/component/dialog/alert/AlertDialog.kt 1
com/personalization/inAppNotification/view/component/dialog/bottom/BottomDialog.kt 1
com/personalization/inAppNotification/view/component/dialog/fullScreen/FullScreenDialog.kt 1
com/personalization/inAppNotification/view/component/dialog/top/TopDialog.kt 1
com/personalization/stories/Player.kt 1
com/personalization/stories/viewAdapters/StoriesAdapter.kt 5
com/personalization/stories/views/StoriesView.kt 5
com/personalization/stories/views/StoryDialog.kt 1
com/personalization/stories/views/StoryView.kt 5
com/personalization/stories/views/storyItem/StoryItemView.kt 3
com/personalization/ui/components/PersonalizationProductsGrid.kt 1
Loading
Loading