usebecky 0.0.0-stage → 0.2.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 (135) hide show
  1. package/README.md +701 -2
  2. package/dist/analytics/client.d.ts +219 -0
  3. package/dist/analytics/client.js +923 -0
  4. package/dist/analytics/cmp.d.ts +20 -0
  5. package/dist/analytics/cmp.js +166 -0
  6. package/dist/analytics/context.d.ts +29 -0
  7. package/dist/analytics/context.js +97 -0
  8. package/dist/auth/client.d.ts +401 -0
  9. package/dist/auth/client.js +1081 -0
  10. package/dist/auth/webauthn.d.ts +18 -0
  11. package/dist/auth/webauthn.js +138 -0
  12. package/dist/cli/ai.d.ts +54 -0
  13. package/dist/cli/ai.js +202 -0
  14. package/dist/cli/analytics.d.ts +53 -0
  15. package/dist/cli/analytics.js +357 -0
  16. package/dist/cli/config.d.ts +75 -0
  17. package/dist/cli/config.js +718 -0
  18. package/dist/cli/db.d.ts +48 -0
  19. package/dist/cli/db.js +215 -0
  20. package/dist/cli/deploy-api.d.ts +168 -0
  21. package/dist/cli/deploy-api.js +177 -0
  22. package/dist/cli/deploy-ci.d.ts +15 -0
  23. package/dist/cli/deploy-ci.js +54 -0
  24. package/dist/cli/deploy-detect.d.ts +64 -0
  25. package/dist/cli/deploy-detect.js +249 -0
  26. package/dist/cli/deploy-files.d.ts +112 -0
  27. package/dist/cli/deploy-files.js +778 -0
  28. package/dist/cli/deploy.d.ts +10 -0
  29. package/dist/cli/deploy.js +430 -0
  30. package/dist/cli/emails.d.ts +29 -0
  31. package/dist/cli/emails.js +122 -0
  32. package/dist/cli/framework.d.ts +135 -0
  33. package/dist/cli/framework.js +459 -0
  34. package/dist/cli/functions.d.ts +59 -0
  35. package/dist/cli/functions.js +426 -0
  36. package/dist/cli/hosting.d.ts +4 -0
  37. package/dist/cli/hosting.js +532 -0
  38. package/dist/cli/index.d.ts +2 -0
  39. package/dist/cli/index.js +9 -0
  40. package/dist/cli/payments.d.ts +35 -0
  41. package/dist/cli/payments.js +176 -0
  42. package/dist/cli/push.d.ts +36 -0
  43. package/dist/cli/push.js +172 -0
  44. package/dist/cli/run.d.ts +65 -0
  45. package/dist/cli/run.js +850 -0
  46. package/dist/cli/social.d.ts +52 -0
  47. package/dist/cli/social.js +532 -0
  48. package/dist/cli/tokens.d.ts +28 -0
  49. package/dist/cli/tokens.js +114 -0
  50. package/dist/cli/ui.d.ts +38 -0
  51. package/dist/cli/ui.js +140 -0
  52. package/dist/client.d.ts +94 -0
  53. package/dist/client.js +156 -0
  54. package/dist/db/query.d.ts +162 -0
  55. package/dist/db/query.js +336 -0
  56. package/dist/db/types.d.ts +93 -0
  57. package/dist/db/types.js +4 -0
  58. package/dist/forms/client.d.ts +65 -0
  59. package/dist/forms/client.js +106 -0
  60. package/dist/functions/client.d.ts +37 -0
  61. package/dist/functions/client.js +76 -0
  62. package/dist/index.d.ts +17 -0
  63. package/dist/index.js +16 -0
  64. package/dist/lib/dashboard-paths.d.ts +4 -0
  65. package/dist/lib/dashboard-paths.js +8 -0
  66. package/dist/lib/env.d.ts +9 -0
  67. package/dist/lib/env.js +55 -0
  68. package/dist/lib/errors.d.ts +22 -0
  69. package/dist/lib/errors.js +90 -0
  70. package/dist/lib/hosted.d.ts +2 -0
  71. package/dist/lib/hosted.js +7 -0
  72. package/dist/lib/http.d.ts +59 -0
  73. package/dist/lib/http.js +172 -0
  74. package/dist/lib/jwt.d.ts +1 -0
  75. package/dist/lib/jwt.js +31 -0
  76. package/dist/lib/locale.d.ts +12 -0
  77. package/dist/lib/locale.js +51 -0
  78. package/dist/lib/pkce.d.ts +20 -0
  79. package/dist/lib/pkce.js +124 -0
  80. package/dist/lib/storage-adapter.d.ts +15 -0
  81. package/dist/lib/storage-adapter.js +91 -0
  82. package/dist/lib/types.d.ts +339 -0
  83. package/dist/lib/types.js +1 -0
  84. package/dist/newsletter/client.d.ts +140 -0
  85. package/dist/newsletter/client.js +85 -0
  86. package/dist/payments/client.d.ts +352 -0
  87. package/dist/payments/client.js +323 -0
  88. package/dist/push/client.d.ts +110 -0
  89. package/dist/push/client.js +179 -0
  90. package/dist/realtime/client.d.ts +131 -0
  91. package/dist/realtime/client.js +513 -0
  92. package/dist/server/analytics.d.ts +176 -0
  93. package/dist/server/analytics.js +49 -0
  94. package/dist/server/cache.d.ts +74 -0
  95. package/dist/server/cache.js +154 -0
  96. package/dist/server/emails.d.ts +142 -0
  97. package/dist/server/emails.js +123 -0
  98. package/dist/server/events.d.ts +357 -0
  99. package/dist/server/events.js +219 -0
  100. package/dist/server/functions.d.ts +40 -0
  101. package/dist/server/functions.js +1 -0
  102. package/dist/server/http-utils.d.ts +10 -0
  103. package/dist/server/http-utils.js +115 -0
  104. package/dist/server/index.d.ts +195 -0
  105. package/dist/server/index.js +314 -0
  106. package/dist/server/payments.d.ts +218 -0
  107. package/dist/server/payments.js +150 -0
  108. package/dist/server/push.d.ts +85 -0
  109. package/dist/server/push.js +37 -0
  110. package/dist/server/usage.d.ts +43 -0
  111. package/dist/server/usage.js +8 -0
  112. package/dist/storage/client.d.ts +143 -0
  113. package/dist/storage/client.js +224 -0
  114. package/package.json +52 -4
  115. package/skill/usebecky/SKILL.md +339 -0
  116. package/skill/usebecky/references/access-rules.md +307 -0
  117. package/skill/usebecky/references/addons.md +68 -0
  118. package/skill/usebecky/references/analytics.md +166 -0
  119. package/skill/usebecky/references/android.md +434 -0
  120. package/skill/usebecky/references/auth.md +379 -0
  121. package/skill/usebecky/references/cache.md +51 -0
  122. package/skill/usebecky/references/components.md +127 -0
  123. package/skill/usebecky/references/emails.md +105 -0
  124. package/skill/usebecky/references/expo.md +147 -0
  125. package/skill/usebecky/references/functions.md +99 -0
  126. package/skill/usebecky/references/hosting.md +119 -0
  127. package/skill/usebecky/references/http-api.md +233 -0
  128. package/skill/usebecky/references/ios.md +355 -0
  129. package/skill/usebecky/references/payments.md +493 -0
  130. package/skill/usebecky/references/realtime.md +143 -0
  131. package/skill/usebecky/references/scheduled-jobs.md +82 -0
  132. package/skill/usebecky/references/sdk.md +838 -0
  133. package/skill/usebecky/references/storage.md +210 -0
  134. package/skill/usebecky/references/templates.md +191 -0
  135. package/skill/usebecky/references/wordpress.md +87 -0
@@ -0,0 +1,434 @@
1
+ # Android / Kotlin reference
2
+
3
+ Operating manual for writing Android (Jetpack Compose) or JVM Kotlin code with the native SDK `com.usebecky:usebecky-kotlin`. Full API: https://usebecky.com/docs/reference/sdk-kotlin. Beginner guide with complete files: https://usebecky.com/docs/frameworks/android. Do NOT use the npm `usebecky` package (or any npm package), `supabase-kt`, or raw REST calls in Kotlin apps.
4
+
5
+ ## Rules that prevent most bugs
6
+
7
+ 1. Every network call is a `suspend` function that returns data and THROWS `com.usebecky.UseBeckyException` (`code`, `message`, `hint`, `status`, `messageWithHint`). Always `try { } catch (e: UseBeckyException) { }` around calls launched from UI code; an uncaught throw in `rememberCoroutineScope().launch` crashes the app. There is no `{ data, error }` result object. Work that needs the secret key (sending push or emails, admin tasks) runs on a server or in the dashboard.
8
+ 2. ONE client per app. Android needs a `Context` for session storage, so create it in `MainActivity.onCreate` (guarded, idempotent) and expose it as a top-level `val baas`.
9
+ 3. Always pass a persistent `SessionStorage` on Android, or users are signed out on every restart. The default `MemorySessionStorage` is for tests/JVM scripts.
10
+ 4. Publishable key (`ub_pk_...`) only. A secret key (`ub_sk_...`) makes the constructor throw `secret_key_in_app` on Android.
11
+ 5. `AndroidManifest.xml` needs `<uses-permission android:name="android.permission.INTERNET" />` (error code `missing_internet_permission` otherwise).
12
+ 6. Row classes need `@Serializable` + the `org.jetbrains.kotlin.plugin.serialization` Gradle plugin at the SAME version as the project's Kotlin. Map snake_case columns with `@SerialName("created_at")`. Give server-filled columns defaults (`val id: String? = null`) so they are omitted on insert (the client Json has `encodeDefaults = false`, `ignoreUnknownKeys = true`, `explicitNulls = false`).
13
+ 7. For `update`, pass a `Map` (`mapOf("done" to true)`), not a data class: properties equal to their default are not sent.
14
+ 8. Always filter `update`/`delete` (`.eq("id", id)`), then end the chain with a terminal call (`execute()`, `list<T>()`, `single<T>()`, `maybeSingle<T>()`, `count()`). Builders send nothing until a terminal call.
15
+ 9. Always use the `https://` Project URL (Dashboard → Settings → API keys). Android blocks plain `http://` (error code `cleartext_not_permitted`); never add `android:usesCleartextTraffic`.
16
+ 10. Collect realtime in `LaunchedEffect`; the subscription ends when the composable leaves. Turn realtime on for the table (`realtime.tables` in `usebecky/config.json`, `npx usebecky config push`), or the Flow throws `realtime_not_enabled`.
17
+
18
+ ## Install
19
+
20
+ `implementation("com.usebecky:usebecky-kotlin:0.2.0")` in `app/build.gradle.kts` (below); Gradle downloads it from Maven Central (new projects already list `mavenCentral()`). Sync Gradle. `npx usebecky init` in the project folder prints these lines and the `UseBeckyConfig` values, and writes nothing. Never clone or build usebecky itself.
21
+
22
+ ## Gradle
23
+
24
+ ```toml
25
+ # gradle/libs.versions.toml, under [plugins]
26
+ kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
27
+ ```
28
+
29
+ ```kotlin
30
+ // build.gradle.kts (Project): plugins { alias(libs.plugins.kotlin.serialization) apply false }
31
+ // app/build.gradle.kts:
32
+ plugins { alias(libs.plugins.kotlin.serialization) }
33
+ dependencies {
34
+ implementation("com.usebecky:usebecky-kotlin:0.2.0") // api deps: okhttp 4.12, kotlinx-coroutines 1.9, kotlinx-serialization-json 1.7
35
+ implementation("androidx.browser:browser:1.8.0") // Custom Tabs (OAuth, Stripe)
36
+ }
37
+ ```
38
+
39
+ Min SDK 24. The core library has no Android dependency; the helpers below are app code.
40
+
41
+ ## Client + Android helpers (put in Backend.kt)
42
+
43
+ ```kotlin
44
+ package com.example.mynotes
45
+
46
+ import android.content.ActivityNotFoundException
47
+ import android.content.Context
48
+ import android.net.Uri
49
+ import android.widget.Toast
50
+ import androidx.browser.customtabs.CustomTabsIntent
51
+ import com.usebecky.SessionStorage
52
+ import com.usebecky.UseBecky
53
+ import kotlinx.coroutines.Dispatchers
54
+ import kotlinx.coroutines.withContext
55
+
56
+ object UseBeckyConfig {
57
+ const val URL = "https://api.usebecky.com" // Dashboard → Settings → API keys → Project URL
58
+ const val PUBLISHABLE_KEY = "ub_pk_..."
59
+ }
60
+ const val AUTH_REDIRECT = "com.example.mynotes://auth" // your application ID as the scheme; matches the intent filter and an Allowed redirect URL
61
+
62
+ private var client: UseBecky? = null
63
+ val baas: UseBecky get() = client ?: error("Call initBackend(this) in MainActivity.onCreate()")
64
+ fun initBackend(context: Context) {
65
+ if (client != null) return
66
+ client = UseBecky(url = UseBeckyConfig.URL, publishableKey = UseBeckyConfig.PUBLISHABLE_KEY,
67
+ sessionStorage = SharedPrefsSessionStorage(context.applicationContext))
68
+ }
69
+
70
+ class SharedPrefsSessionStorage(context: Context) : SessionStorage {
71
+ private val prefs = context.getSharedPreferences("usebecky", Context.MODE_PRIVATE)
72
+ override suspend fun get(key: String) = withContext(Dispatchers.IO) { prefs.getString(key, null) }
73
+ override suspend fun set(key: String, value: String) { withContext(Dispatchers.IO) { prefs.edit().putString(key, value).commit() } } // commit: refresh tokens rotate
74
+ override suspend fun remove(key: String) { withContext(Dispatchers.IO) { prefs.edit().remove(key).commit() } }
75
+ }
76
+
77
+ fun openInCustomTab(context: Context, url: String) {
78
+ try { CustomTabsIntent.Builder().build().launchUrl(context, Uri.parse(url)) }
79
+ catch (e: ActivityNotFoundException) { Toast.makeText(context, "Install a web browser", Toast.LENGTH_LONG).show() }
80
+ }
81
+ ```
82
+
83
+ Optional per-build keys: `buildFeatures { buildConfig = true }` + `buildConfigField("String", "USEBECKY_PUBLISHABLE_KEY", "\"ub_pk_...\"")`, with a `debug { buildConfigField(...) }` override holding the publishable key of a separate test project.
84
+
85
+ ## Auth
86
+
87
+ ```kotlin
88
+ // inside a @Composable: pick the screen from the session
89
+ val session by baas.auth.session.collectAsState() // Session? ; null = signed out
90
+ val ready by baas.auth.isReady.collectAsState() // false while the stored session loads; show a spinner
91
+ ```
92
+
93
+ ```kotlin
94
+ // suspend calls: run them in a coroutine (rememberCoroutineScope().launch { }, lifecycleScope.launch { }) inside try/catch
95
+ suspend fun authExamples(email: String, password: String, code: String) {
96
+ val now: User? = baas.auth.currentUser // no network; baas.auth.getUser() = fresh from the server
97
+ val result: SignUpResult = baas.auth.signUp(email, password, data = mapOf("name" to "Ada")) // result.session == null → confirm email first
98
+ val session: Session = baas.auth.signIn(email, password) // invalid_credentials (400), email_not_confirmed (403)
99
+ baas.auth.sendMagicLink(email, createUser = true) // emails link + 6-digit code; Unit; succeeds even for unknown emails
100
+ baas.auth.verifyCode(email, code) // Session ; otp_expired. RECOMMENDED mobile flow (email links open the browser, not the app)
101
+ baas.auth.verifyCode(email, code, CodeType.RECOVERY) // password reset by code, then updateUser(password = ...)
102
+ baas.auth.resetPassword(email) // Unit
103
+ // Bot protection: signUp, signIn, sendMagicLink and resetPassword take captchaToken: String? = null (last, named): signIn(email, password, captchaToken = token)
104
+ val updated: User = baas.auth.updateUser(data = mapOf("plan" to "pro")) // also email = ..., password = ...; data keys set to null are removed
105
+ val name: String? = updated.metadata("name") // a text value from user_metadata
106
+ baas.auth.signOut() // never throws; clears the local session
107
+ }
108
+
109
+ // baas.auth.events: SharedFlow<AuthEvent> (SIGNED_IN, SIGNED_OUT, TOKEN_REFRESHED, USER_UPDATED, PASSWORD_RECOVERY, MFA_CHALLENGE_VERIFIED)
110
+ suspend fun logAuthEvents() {
111
+ baas.auth.events.collect { event -> println("auth: $event") }
112
+ }
113
+ ```
114
+
115
+ Refresh is automatic (timer + before each request + one retry on 401 `token_expired`); concurrent refreshes are deduplicated. Never call `refreshSession()` in a loop. `Session.toString()` hides tokens.
116
+
117
+ Bot protection: If you turn on Bot protection for sign-in, your app must show a captcha. Native apps can't do that easily yet; keep sign-in protection off for apps, and protect forms instead.
118
+
119
+ ### Google with Credential Manager (native; recommend this first)
120
+
121
+ No browser, no redirect URL, no deep link: the user picks a Google account in a system sheet.
122
+
123
+ ```kotlin
124
+ // build.gradle.kts (Module :app)
125
+ dependencies {
126
+ implementation("androidx.credentials:credentials:1.5.0")
127
+ implementation("androidx.credentials:credentials-play-services-auth:1.5.0")
128
+ implementation("com.google.android.libraries.identity.googleid:googleid:1.1.1")
129
+ }
130
+ ```
131
+
132
+ ```kotlin
133
+ import android.content.Context
134
+ import androidx.credentials.CredentialManager
135
+ import androidx.credentials.CustomCredential
136
+ import androidx.credentials.GetCredentialRequest
137
+ import com.google.android.libraries.identity.googleid.GetGoogleIdOption
138
+ import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential
139
+ import java.security.MessageDigest
140
+ import java.security.SecureRandom
141
+
142
+ const val GOOGLE_WEB_CLIENT_ID = "1234567890-abc123def456.apps.googleusercontent.com"
143
+
144
+ /** [activityContext]: the Activity, not applicationContext. Throws GetCredentialException or UseBeckyException (see below). */
145
+ suspend fun signInWithGoogle(activityContext: Context) {
146
+ val rawNonce = ByteArray(32).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
147
+ val hashed = MessageDigest.getInstance("SHA-256").digest(rawNonce.toByteArray()).joinToString("") { "%02x".format(it) }
148
+ val option = GetGoogleIdOption.Builder().setServerClientId(GOOGLE_WEB_CLIENT_ID).setFilterByAuthorizedAccounts(false).setNonce(hashed).build()
149
+ val credential = CredentialManager.create(activityContext)
150
+ .getCredential(activityContext, GetCredentialRequest.Builder().addCredentialOption(option).build()).credential
151
+ if (credential is CustomCredential && credential.type == GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) {
152
+ baas.auth.signInWithIdToken("google", GoogleIdTokenCredential.createFrom(credential.data).idToken, rawNonce) // Session
153
+ }
154
+ }
155
+ ```
156
+
157
+ - `GOOGLE_WEB_CLIENT_ID` = the **Web application** client ID saved in Dashboard → Auth → Sign-in methods → Google ("Your own Google app", not "Managed by usebecky"; or paste it in "iOS bundle ID / Android client IDs (for native sign-in)"). Google Cloud also needs an **Android** OAuth client (package name + SHA-1) in the same project.
158
+ - Catch `GetCredentialCancellationException` (user closed: do nothing), `NoCredentialException` (no Google account / Android client missing) and other `GetCredentialException`s: they are NOT `UseBeckyException`.
159
+ - Server errors: `invalid_id_token` (audience mismatch; the message names it), `id_token_expired`, `invalid_nonce`, `provider_not_configured`, `provider_disabled`, `quota_exceeded` (new users only).
160
+
161
+ ### Google / GitHub / Apple in a Custom Tab (deep link, PKCE)
162
+
163
+ Use your app's bundle ID (iOS) / application ID (Android) as the scheme: it is unique to your app, so another app can't register the same scheme and catch the sign-in. Replace `com.example.mynotes` with your own bundle ID / application ID. Never a generic scheme like `myapp`.
164
+
165
+ 1. Dashboard → Auth → Sign-in methods → Google is on by default in a new project ("Managed by usebecky" works here, no keys); if Off → Turn on.
166
+ 2. Dashboard → Settings → General → Your app’s addresses → add `com.example.mynotes://**` → Save changes. Missing → the Custom Tab shows a 400 error page naming the address to add.
167
+ 3. Manifest, on `.MainActivity`: `android:launchMode="singleTask"` and
168
+
169
+ ```xml
170
+ <intent-filter>
171
+ <action android:name="android.intent.action.VIEW" />
172
+ <category android:name="android.intent.category.DEFAULT" />
173
+ <category android:name="android.intent.category.BROWSABLE" />
174
+ <data android:scheme="com.example.mynotes" android:host="auth" />
175
+ <data android:scheme="com.example.mynotes" android:host="checkout" /> <!-- Stripe return links (Payments) -->
176
+ </intent-filter>
177
+ ```
178
+
179
+ 4. Start: `openInCustomTab(context, baas.auth.signInWithUrl("google", AUTH_REDIRECT))` (no network; `"github"`, `"apple"`). PKCE is automatic: the URL carries a code challenge and the SDK remembers the verifier (in memory and in `SessionStorage`, so it survives the app being killed while the browser is open).
180
+ 5. Finish in MainActivity (both entry points):
181
+
182
+ ```kotlin
183
+ class MainActivity : ComponentActivity() {
184
+ override fun onCreate(savedInstanceState: Bundle?) {
185
+ super.onCreate(savedInstanceState)
186
+ initBackend(this)
187
+ if (savedInstanceState == null) handleDeepLink(intent)
188
+ setContent { App() } // your root composable
189
+ }
190
+
191
+ override fun onNewIntent(intent: Intent) { super.onNewIntent(intent); setIntent(intent); handleDeepLink(intent) }
192
+
193
+ private fun handleDeepLink(intent: Intent?) {
194
+ if (intent == null || (intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) return
195
+ val link = intent.data?.toString() ?: return
196
+ if (!baas.auth.isAuthRedirect(link)) return
197
+ intent.data = null
198
+ lifecycleScope.launch {
199
+ try { baas.auth.handleRedirect(link) } catch (e: UseBeckyException) { Toast.makeText(this@MainActivity, e.message, Toast.LENGTH_LONG).show() }
200
+ }
201
+ }
202
+ }
203
+ ```
204
+
205
+ The redirect is `com.example.mynotes://auth?code=<one-time code>`: `handleRedirect` swaps it for the session (`exchangeCodeForSession(authCode)` under the hood, then forgets the verifier); no tokens appear in the URL. `isAuthRedirect` recognises `?code=` and the older `#access_token=...` form, which `handleRedirect` still accepts. Errors arrive as `?error=access_denied&error_code=provider_disabled&error_description=...` (or in the `#fragment`) and are thrown as `UseBeckyException(code = "provider_disabled")`; a used, expired (5 minutes) or mismatched code is `invalid_auth_code`.
206
+
207
+ ### Passkeys, phone codes, guests, SSO
208
+
209
+ - Passkeys: the SDK hands you WebAuthn JSON for Credential Manager (androidx.credentials): `baas.auth.signInWithPasskey { json -> (credentialManager.getCredential(context, GetCredentialRequest(listOf(GetPublicKeyCredentialOption(json)))).credential as PublicKeyCredential).authenticationResponseJson }` and `baas.auth.registerPasskey("Pixel") { json -> (credentialManager.createCredential(context, CreatePublicKeyCredentialRequest(json)) as CreatePublicKeyCredentialResponse).registrationResponseJson }`. Add the app's `android:apk-key-hash:...` in Dashboard → Auth → Sign-in methods → Passkeys → Settings and serve `/.well-known/assetlinks.json` on the passkey domain.
210
+ - Phone: `signInWithPhone("+491701234567")`, then `verifyPhone(phone, code)`; `updatePhone` + `verifyPhoneChange`. Free: only dashboard test numbers.
211
+ - Guests: `signInAnonymously()`; later `linkEmail(email, password)`, `linkIdentityUrl("google", redirectTo)` (Custom Tab + `handleRedirect`), `linkIdToken(...)` or `registerPasskey` keep the same user id.
212
+ - More providers: `"microsoft"`, `"discord"`, `"gitlab"`, `"linkedin"`, `"slack"`, `"x"` with `signInWithUrl`. Company SSO (Business): `signInWithSsoUrl(domain = "acme.com", redirectTo = ...)` then `handleRedirect`.
213
+
214
+ ## Database
215
+
216
+ ```kotlin
217
+ @Serializable
218
+ data class Note(val id: String? = null, @SerialName("user_id") val userId: String? = null, val title: String, val done: Boolean = false, @SerialName("created_at") val createdAt: String? = null)
219
+
220
+ suspend fun notesExamples(id: String) {
221
+ val latest: List<Note> = baas.from("notes").select().order("created_at", ascending = false).limit(50).list<Note>()
222
+ val one: Note = baas.from("notes").select("id, title, author:profiles(name)").eq("id", id).single<Note>() // not_single_row unless exactly 1
223
+ val maybe: Note? = baas.from("notes").select().eq("id", id).maybeSingle<Note>()
224
+ val openCount: Long = baas.from("notes").select().eq("done", false).count()
225
+ val created: Note = baas.from("notes").insert(Note(title = "Buy milk")).single<Note>() // returns the row (adds Prefer: return=representation)
226
+ baas.from("notes").insert(listOf(mapOf("title" to "A"), mapOf("title" to "B", "done" to true)), defaultToNull = false).execute() // rows with different keys: defaultToNull = false, or missing NOT NULL columns fail (missing_value)
227
+ baas.from("notes").update(mapOf("title" to "New")).eq("id", id).execute()
228
+ baas.from("notes").upsert(mapOf("id" to id, "title" to "X"), onConflict = "id").execute()
229
+ baas.from("notes").delete().eq("id", id).execute()
230
+ val points: Int = baas.rpc("add_points", mapOf("amount" to 5)).single<Int>() // .list<T>() for set-returning functions; get = true for GET
231
+ }
232
+ ```
233
+
234
+ Filters: `eq neq gt gte lt lte like ilike("%x%") isNull isNotNull isTrue isFalse isIn(col, list) contains containedBy overlaps textSearch(col, q, config, TextSearchType) not(col, op, value) or("a.eq.1,b.gt.2") match(map) filter(col, op, value)`. Modifiers: `select(cols, count = Count.EXACT)`, `order(col, ascending, nullsFirst, referencedTable)`, `limit(n)`, `range(from, to)`. `execute()` gives `QueryResult(data: JsonElement, count: Long?, status)` + `decode<T>()`.
235
+
236
+ - Owner-only tables (preset "Only the user who created a row can see it" / template `addOwnedTable`): `user_id` defaults to `auth.uid()`; never send it. Other users' rows are invisible (empty list, not an error); anon writes → `permission_denied` (403).
237
+ - `decoding_failed` means the data class doesn't match the JSON: fix names (`@SerialName`), nullability (`String?`), or add defaults.
238
+ - `not_serializable`: the value isn't `@Serializable`/Map/List/primitive.
239
+
240
+ ## Storage
241
+
242
+ ```kotlin
243
+ suspend fun storageExamples(bytes: ByteArray) {
244
+ val uid = baas.auth.currentUser!!.id
245
+ val uploaded: UploadResult = baas.storage.from("photos").upload("$uid/profile.jpg", bytes, contentType = "image/jpeg", upsert = true) // (path, fullPath, id)
246
+ val photo: ByteArray = baas.storage.from("photos").download("$uid/profile.jpg") // object_not_found if missing
247
+ val signed: String = baas.storage.from("photos").createSignedUrl("$uid/profile.jpg", 3600) // private buckets (for Coil etc.)
248
+ val publicLink: String = baas.storage.from("avatars").publicUrl("$uid/a.jpg") // public buckets, no network
249
+ val files: List<FileObject> = baas.storage.from("photos").list(uid) // folders have id == null
250
+ baas.storage.from("photos").remove(listOf("$uid/profile.jpg"))
251
+ }
252
+ ```
253
+
254
+ Photo picker (no permission needed):
255
+
256
+ ```kotlin
257
+ @Composable
258
+ fun ChangePhotoButton() {
259
+ val context = LocalContext.current
260
+ val scope = rememberCoroutineScope()
261
+ val uid = baas.auth.currentUser?.id ?: return
262
+ var message by remember { mutableStateOf<String?>(null) }
263
+ val pick = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
264
+ if (uri != null) scope.launch {
265
+ try {
266
+ val bytes = withContext(Dispatchers.IO) { context.contentResolver.openInputStream(uri)?.use { it.readBytes() } } ?: return@launch
267
+ baas.storage.from("photos").upload("$uid/profile.jpg", bytes, contentType = context.contentResolver.getType(uri), upsert = true)
268
+ } catch (e: UseBeckyException) { message = e.message }
269
+ }
270
+ }
271
+ Button(onClick = { pick.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) }) { Text("Change photo") }
272
+ message?.let { Text(it) }
273
+ }
274
+ ```
275
+
276
+ Bucket rule "Users manage their own folder" requires the first path segment to be the user id. Upload errors: 403 (no rule / wrong folder), 409 `already_exists` (pass `upsert = true`), 413 too large. Decode big photos with `BitmapFactory.Options.inSampleSize`, or let the server resize:
277
+
278
+ ```kotlin
279
+ suspend fun thumbnails() {
280
+ val uid = baas.auth.currentUser!!.id
281
+ val thumb = ImageTransform(width = 200, height = 200, resize = Resize.COVER, quality = 80, format = ImageFormat.WEBP) // Resize.COVER/CONTAIN/FILL; ImageFormat.ORIGIN/WEBP/AVIF/JPEG/PNG
282
+ val publicThumb = baas.storage.from("avatars").publicUrl("$uid/a.jpg", transform = thumb) // /storage/v1/render/image/public/...
283
+ val signedThumb = baas.storage.from("photos").createSignedUrl("$uid/profile.jpg", 3600, transform = thumb) // size baked into the token
284
+ val small: ByteArray = baas.storage.from("photos").download("$uid/profile.jpg", transform = ImageTransform(width = 400))
285
+ }
286
+ ```
287
+
288
+ Sizes 1-2500 px, never enlarged, cached on the server.
289
+
290
+ ## Push notifications (Firebase Cloud Messaging)
291
+
292
+ ```kotlin
293
+ // app/build.gradle.kts: id("com.google.gms.google-services") + implementation(platform("com.google.firebase:firebase-bom:<version>")) + implementation("com.google.firebase:firebase-messaging")
294
+ // google-services.json from Firebase console → Project settings → Your apps goes in app/.
295
+ import com.google.firebase.messaging.FirebaseMessaging
296
+ import com.google.firebase.messaging.FirebaseMessagingService
297
+ import com.usebecky.PushDevice
298
+ import com.usebecky.registerPushToken // extension functions: import them
299
+ import com.usebecky.unregisterPushToken
300
+ import kotlinx.coroutines.CoroutineScope
301
+ import kotlinx.coroutines.Dispatchers
302
+ import kotlinx.coroutines.launch
303
+ import kotlinx.coroutines.tasks.await // needs org.jetbrains.kotlinx:kotlinx-coroutines-play-services
304
+
305
+ class PushService : FirebaseMessagingService() { // <service android:name=".PushService" android:exported="false"> with action com.google.firebase.MESSAGING_EVENT
306
+ override fun onNewToken(token: String) {
307
+ initBackend(applicationContext)
308
+ CoroutineScope(Dispatchers.IO).launch { runCatching { baas.registerPushToken(token) } }
309
+ }
310
+ }
311
+
312
+ // After sign-in (Android 13+: request Manifest.permission.POST_NOTIFICATIONS first):
313
+ suspend fun registerThisPhone(): PushDevice {
314
+ val token = FirebaseMessaging.getInstance().token.await()
315
+ return baas.registerPushToken(token) // or baas.push.register(token, tags = listOf("news")): tags for targeting; null keeps current tags
316
+ }
317
+
318
+ suspend fun stopPush(): Int = baas.unregisterPushToken() // registrations removed; auth.signOut() does this automatically
319
+ ```
320
+
321
+ Sending is server-side only (`baas.push.send` in `usebecky/server`, secret key) or Dashboard → Push notifications. The Firebase service account JSON (Project settings → Service accounts → Generate new private key) goes in Dashboard → Push notifications → Setup. `token.await()` needs `org.jetbrains.kotlinx:kotlinx-coroutines-play-services`. Check it works: Dashboard → Push notifications → Devices lists the phone. Errors: `not_signed_in` (register after sign-in), `invalid_token`.
322
+
323
+ ## Forms and newsletter
324
+
325
+ Contact forms (Dashboard → Forms) and newsletter lists (Dashboard → Newsletter): no table, policy or email code needed. Both use the publishable key and throw `UseBeckyException` like every other call.
326
+
327
+ ```kotlin
328
+ // Contact form: "contact" is the form's key (or its public id "f_..."); value names must match the form's fields
329
+ suspend fun sendContact(name: String, email: String, message: String): String {
330
+ val r = baas.forms.submit(form = "contact", values = mapOf("name" to name, "email" to email, "message" to message), captchaToken = null)
331
+ return r.message // the form's success message: show it ("Thanks! We'll get back to you soon.")
332
+ }
333
+ suspend fun contactForm(): PublicForm = baas.forms.get(form = "contact") // fields (name, label, type, required, options), success message, enabled, captcha
334
+
335
+ // Newsletter sign-up: list = null → the default list; tags ≤ 10
336
+ suspend fun joinNewsletter(email: String, name: String): String {
337
+ val s = baas.newsletter.subscribe(email = email, list = null, name = name, tags = listOf("android"), captchaToken = null)
338
+ // s.status: "pending" (double opt-in: they must click the emailed link) or "subscribed"; s.isPending
339
+ return s.message // show it; the answer is the same whether or not they were already on the list
340
+ }
341
+ ```
342
+
343
+ - Never send `_gotcha` (or any value whose name starts with `_`). HTML forms include a hidden, empty `_gotcha` honeypot; when it is non-empty the server silently drops the message and still answers success.
344
+ - A form with "Allowed websites" set refuses apps (`origin_not_allowed`, 403): apps send no Origin, so clear that list for forms the app posts to.
345
+ - Errors (`e.code`): forms `validation_failed` (400, the message lists the fields), `form_not_found` (404), `form_disabled` (403), `rate_limited` (429), `quota_exceeded` (402), `captcha_required` / `captcha_failed`; newsletter `invalid_email` (400), `list_not_found` (404), `quota_exceeded` (402), `rate_limited` (429).
346
+ - Signed in, `subscribe` also sends the user's access token, so the subscriber is linked to the user (when the email matches).
347
+ - Bot protection for forms / newsletter sign-ups needs a widget token (`captchaToken`). Unless the app shows a Turnstile/hCaptcha web view, leave that protection off for forms the app posts to.
348
+
349
+ ## Functions
350
+
351
+ Server code the app needs (sending an email, calling another service with a secret key) goes into a usebecky Function (written in TypeScript in Dashboard → Functions; see `functions.md`), never into the app. Call it with the signed-in user's token attached automatically:
352
+
353
+ ```kotlin
354
+ @Serializable
355
+ data class Welcome(val sent: Boolean)
356
+
357
+ suspend fun sendWelcome(): Boolean {
358
+ val reply = baas.functions.invoke("send-welcome", body = mapOf("plan" to "pro")) // POST JSON; also method, headers, query, path
359
+ return reply.decode<Welcome>().sent // or reply.text, reply.json(), reply.status
360
+ }
361
+ ```
362
+
363
+ - Throws `UseBeckyException`: `function_error` (500, details in Dashboard → Logs), `function_timeout` (504), `function_busy` (429), `not_signed_in` (401), `secret_key_required` (403, server-only function: never call those from an app), `function_not_found` (404), `quota_exceeded` (402).
364
+ - `body` takes a Map, a List or a `@Serializable` class; raw bytes: `invoke("x", bytes = data, contentType = "image/jpeg")`.
365
+
366
+ ## Realtime
367
+
368
+ ```kotlin
369
+ @Composable
370
+ fun LiveNotes(reload: suspend () -> Unit) {
371
+ var message by remember { mutableStateOf<String?>(null) }
372
+ LaunchedEffect(Unit) {
373
+ try {
374
+ baas.realtime.subscribe("notes", ChangeEvent.ALL, filter = null).collect { change ->
375
+ // change.event INSERT|UPDATE|DELETE; change.decodeNew<Note>() (null on DELETE); change.old = primary key only; change.id
376
+ try { reload() } catch (e: UseBeckyException) { message = e.message }
377
+ }
378
+ } catch (e: UseBeckyException) { message = e.messageWithHint } // realtime_not_enabled, table_not_found, invalid_filter...
379
+ }
380
+ message?.let { Text(it) }
381
+ }
382
+
383
+ @Serializable
384
+ data class Typing(val user: String)
385
+
386
+ suspend fun chatRoom(name: String) {
387
+ val room = baas.realtime.channel("room:42")
388
+ room.send("typing", Typing(user = name)) // or a Map; not echoed back to you
389
+ room.track(mapOf("name" to name)) // presence; room.presence: StateFlow<Map<String, JsonObject>>
390
+ room.messages("typing").collect { b -> println(b.decode<Typing>().user) } // other people's broadcasts; room.leave() when done
391
+ }
392
+ ```
393
+
394
+ One filter per subscription (`col=eq.v`, `neq gt gte lt lte`, `in.(a,b)`). Reconnect, re-subscribe and token updates are automatic. Delivery follows RLS.
395
+
396
+ ## Payments (Stripe in a Custom Tab)
397
+
398
+ ```kotlin
399
+ suspend fun paymentsExamples(context: Context) {
400
+ val products: List<Product> = baas.payments.products() // Price.amount in cents, .formattedAmount ("$9.99", localized), .amountDecimal (Double)
401
+ val url = baas.payments.checkoutUrl("pro_monthly", successUrl = "com.example.mynotes://checkout/done", cancelUrl = "com.example.mynotes://checkout/cancel")
402
+ openInCustomTab(context, url)
403
+ val isPro: Boolean = baas.payments.hasAccess("pro") // re-check when the user returns (webhook may take seconds); false signed out
404
+ val billing: BillingInfo = baas.payments.me() // (customerId, subscriptions, purchases, entitlements, mode)
405
+ val portal: String = baas.payments.portalUrl("com.example.mynotes://account") // manage/cancel; no_customer before the first purchase
406
+ }
407
+ ```
408
+
409
+ `successUrl`/`cancelUrl`/`returnUrl`: deep links back into the app (allowed under Dashboard → Settings → General → Your app’s addresses, e.g. `com.example.mynotes://**`; else `redirect_not_allowed`) or `https://`. Stripe gets the server's `/payments/v1/return` page, which opens the deep link (success adds `?session_id=cs_...`) with a "Return to the app" button fallback. The intent filter needs `<data android:scheme="com.example.mynotes" android:host="checkout" />` next to the `auth` one (`singleTask` closes the Custom Tab), then re-check `hasAccess`. Defaults live in Dashboard → Payments → Stripe connection → Checkout settings. Sign-in required (`not_signed_in`). Mention Google Play's billing policy for digital goods.
410
+
411
+ ## Analytics
412
+
413
+ ```kotlin
414
+ // anywhere (not suspend, never throw):
415
+ baas.analytics.screen("notes") // "$pageview" path "/notes" → Top pages
416
+ baas.analytics.track("note_created", mapOf("length" to 12))
417
+ baas.analytics.identify(mapOf("plan" to "pro"))
418
+ // consent: UseBecky(..., analytics = AnalyticsOptions(enabled = false)) then baas.analytics.enable()
419
+ ```
420
+
421
+ ```kotlin
422
+ class MainActivity : ComponentActivity() {
423
+ // ...
424
+ override fun onStop() { super.onStop(); baas.analytics.flushInBackground() } // or (suspend) baas.analytics.flush(): never throws, returns the number sent (0 offline: events stay queued)
425
+ }
426
+ ```
427
+
428
+ ## Error codes worth handling
429
+
430
+ `network_error` / `timeout` (status 0: offline or wrong URL), `missing_internet_permission`, `cleartext_not_permitted`, `invalid_api_key`, `invalid_credentials`, `email_not_confirmed`, `otp_expired`, `not_signed_in`, `permission_denied`, `table_not_found`, `column_not_found`, `not_single_row`, `decoding_failed`, `object_not_found`, `already_exists`, `realtime_not_enabled`, `provider_disabled`, `invalid_redirect`, `invalid_auth_code`, `invalid_id_token`, `stripe_not_configured`, `price_not_found`, `already_subscribed`, `invalid_url`, `redirect_not_allowed`. Show `e.message` to users; log `e.toString()` (includes code, status and hint).
431
+
432
+ ## Development checklist
433
+
434
+ - Logcat filter `usebecky` shows SDK warnings (lost realtime connection, dropped analytics events).