create-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 (157) hide show
  1. package/README.md +80 -2
  2. package/dist/create.js +842 -0
  3. package/dist/extension-skill/usebecky-extension/SKILL.md +181 -0
  4. package/dist/extension-skill/usebecky-extension/references/accounts.md +125 -0
  5. package/dist/extension-skill/usebecky-extension/references/dev-server.md +102 -0
  6. package/dist/extension-skill/usebecky-extension/references/manifest.md +104 -0
  7. package/dist/extension-skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
  8. package/dist/extension-skill/usebecky-extension/references/partner-api.md +87 -0
  9. package/dist/extension-skill/usebecky-extension/references/submit-and-pricing.md +31 -0
  10. package/dist/extension-skill/usebecky-extension/references/ui.md +172 -0
  11. package/dist/extension-skill/usebecky-extension/references/webhooks.md +97 -0
  12. package/dist/index.js +10 -0
  13. package/dist/keys.js +72 -0
  14. package/dist/platform.js +104 -0
  15. package/dist/pm.js +69 -0
  16. package/dist/prompts.js +242 -0
  17. package/dist/scaffold.js +108 -0
  18. package/dist/setup.js +130 -0
  19. package/dist/shared/ai.js +203 -0
  20. package/dist/shared/extension-skill.js +107 -0
  21. package/dist/shared/framework.js +460 -0
  22. package/dist/shared/hosted.js +8 -0
  23. package/dist/shared/ui.js +141 -0
  24. package/dist/skill/usebecky/SKILL.md +339 -0
  25. package/dist/skill/usebecky/references/access-rules.md +307 -0
  26. package/dist/skill/usebecky/references/addons.md +68 -0
  27. package/dist/skill/usebecky/references/analytics.md +166 -0
  28. package/dist/skill/usebecky/references/android.md +434 -0
  29. package/dist/skill/usebecky/references/auth.md +379 -0
  30. package/dist/skill/usebecky/references/cache.md +51 -0
  31. package/dist/skill/usebecky/references/components.md +127 -0
  32. package/dist/skill/usebecky/references/emails.md +105 -0
  33. package/dist/skill/usebecky/references/expo.md +147 -0
  34. package/dist/skill/usebecky/references/functions.md +99 -0
  35. package/dist/skill/usebecky/references/hosting.md +119 -0
  36. package/dist/skill/usebecky/references/http-api.md +233 -0
  37. package/dist/skill/usebecky/references/ios.md +355 -0
  38. package/dist/skill/usebecky/references/payments.md +493 -0
  39. package/dist/skill/usebecky/references/realtime.md +143 -0
  40. package/dist/skill/usebecky/references/scheduled-jobs.md +82 -0
  41. package/dist/skill/usebecky/references/sdk.md +838 -0
  42. package/dist/skill/usebecky/references/storage.md +210 -0
  43. package/dist/skill/usebecky/references/templates.md +191 -0
  44. package/dist/skill/usebecky/references/wordpress.md +87 -0
  45. package/dist/templates.js +74 -0
  46. package/package.json +37 -4
  47. package/templates/expo/App.tsx +48 -0
  48. package/templates/expo/README.md +59 -0
  49. package/templates/expo/_env.example +4 -0
  50. package/templates/expo/_gitignore +12 -0
  51. package/templates/expo/app.json +25 -0
  52. package/templates/expo/assets/icon.png +0 -0
  53. package/templates/expo/brand.ts +7 -0
  54. package/templates/expo/components/Avatar.tsx +75 -0
  55. package/templates/expo/components/ui.tsx +57 -0
  56. package/templates/expo/index.ts +4 -0
  57. package/templates/expo/lib/theme.ts +43 -0
  58. package/templates/expo/lib/usebecky.ts +15 -0
  59. package/templates/expo/package.json +29 -0
  60. package/templates/expo/screens/Home.tsx +187 -0
  61. package/templates/expo/screens/SignIn.tsx +112 -0
  62. package/templates/expo/tsconfig.json +6 -0
  63. package/templates/expo/usebecky.template.json +36 -0
  64. package/templates/extension/README.md +128 -0
  65. package/templates/extension/_env.example +21 -0
  66. package/templates/extension/_gitignore +11 -0
  67. package/templates/extension/logo.svg +1 -0
  68. package/templates/extension/package.json +25 -0
  69. package/templates/extension/src/accounts.ts +90 -0
  70. package/templates/extension/src/app.ts +178 -0
  71. package/templates/extension/src/pages.ts +108 -0
  72. package/templates/extension/src/replay-guard.ts +17 -0
  73. package/templates/extension/src/server.ts +57 -0
  74. package/templates/extension/src/settings.ts +69 -0
  75. package/templates/extension/src/ui.ts +70 -0
  76. package/templates/extension/test/app.test.ts +222 -0
  77. package/templates/extension/tsconfig.json +16 -0
  78. package/templates/extension/usebecky-extension.json +36 -0
  79. package/templates/extension/usebecky.template.json +22 -0
  80. package/templates/landing/README.md +43 -0
  81. package/templates/landing/_env.example +4 -0
  82. package/templates/landing/_gitignore +9 -0
  83. package/templates/landing/index.html +16 -0
  84. package/templates/landing/package.json +28 -0
  85. package/templates/landing/public/icon.svg +1 -0
  86. package/templates/landing/src/App.tsx +97 -0
  87. package/templates/landing/src/components/Contact.tsx +43 -0
  88. package/templates/landing/src/components/Counter.tsx +34 -0
  89. package/templates/landing/src/components/Feedback.tsx +36 -0
  90. package/templates/landing/src/components/Logo.tsx +11 -0
  91. package/templates/landing/src/components/Receipt.tsx +128 -0
  92. package/templates/landing/src/components/Setup.tsx +20 -0
  93. package/templates/landing/src/components/fields.tsx +63 -0
  94. package/templates/landing/src/content.ts +22 -0
  95. package/templates/landing/src/index.css +119 -0
  96. package/templates/landing/src/lib/usebecky.ts +11 -0
  97. package/templates/landing/src/lib/waitlist.ts +46 -0
  98. package/templates/landing/src/main.tsx +12 -0
  99. package/templates/landing/src/vite-env.d.ts +6 -0
  100. package/templates/landing/tsconfig.json +19 -0
  101. package/templates/landing/usebecky.template.json +20 -0
  102. package/templates/landing/vite.config.ts +10 -0
  103. package/templates/notes/README.md +68 -0
  104. package/templates/notes/_env.example +4 -0
  105. package/templates/notes/_gitignore +9 -0
  106. package/templates/notes/index.html +15 -0
  107. package/templates/notes/package.json +28 -0
  108. package/templates/notes/public/icon.svg +1 -0
  109. package/templates/notes/src/App.tsx +35 -0
  110. package/templates/notes/src/brand.ts +7 -0
  111. package/templates/notes/src/components/Composer.tsx +113 -0
  112. package/templates/notes/src/components/NoteEntry.tsx +151 -0
  113. package/templates/notes/src/components/Notes.tsx +163 -0
  114. package/templates/notes/src/components/Setup.tsx +44 -0
  115. package/templates/notes/src/components/SignIn.tsx +112 -0
  116. package/templates/notes/src/components/icons.tsx +54 -0
  117. package/templates/notes/src/index.css +105 -0
  118. package/templates/notes/src/lib/notes.ts +68 -0
  119. package/templates/notes/src/lib/usebecky.ts +9 -0
  120. package/templates/notes/src/main.tsx +22 -0
  121. package/templates/notes/src/vite-env.d.ts +6 -0
  122. package/templates/notes/tsconfig.json +19 -0
  123. package/templates/notes/usebecky.template.json +34 -0
  124. package/templates/notes/vite.config.ts +10 -0
  125. package/templates/saas/README.md +69 -0
  126. package/templates/saas/_env.example +10 -0
  127. package/templates/saas/_gitignore +11 -0
  128. package/templates/saas/app/(app)/account/ManageBilling.tsx +26 -0
  129. package/templates/saas/app/(app)/account/page.tsx +71 -0
  130. package/templates/saas/app/(app)/dashboard/Projects.tsx +227 -0
  131. package/templates/saas/app/(app)/dashboard/page.tsx +21 -0
  132. package/templates/saas/app/(app)/layout.tsx +29 -0
  133. package/templates/saas/app/(app)/premium/page.tsx +62 -0
  134. package/templates/saas/app/auth/callback/page.tsx +33 -0
  135. package/templates/saas/app/globals.css +143 -0
  136. package/templates/saas/app/icon.svg +1 -0
  137. package/templates/saas/app/layout.tsx +20 -0
  138. package/templates/saas/app/page.tsx +87 -0
  139. package/templates/saas/app/pricing/Plans.tsx +133 -0
  140. package/templates/saas/app/pricing/TestCardHint.tsx +18 -0
  141. package/templates/saas/app/pricing/page.tsx +21 -0
  142. package/templates/saas/app/setup/page.tsx +34 -0
  143. package/templates/saas/app/sign-in/SignInForm.tsx +195 -0
  144. package/templates/saas/app/sign-in/page.tsx +21 -0
  145. package/templates/saas/brand.ts +10 -0
  146. package/templates/saas/components/AppNav.tsx +45 -0
  147. package/templates/saas/components/Logo.tsx +22 -0
  148. package/templates/saas/components/SiteHeader.tsx +50 -0
  149. package/templates/saas/components/Status.tsx +15 -0
  150. package/templates/saas/lib/session.ts +26 -0
  151. package/templates/saas/lib/usebecky.ts +11 -0
  152. package/templates/saas/next-env.d.ts +5 -0
  153. package/templates/saas/next.config.ts +5 -0
  154. package/templates/saas/package.json +26 -0
  155. package/templates/saas/postcss.config.mjs +3 -0
  156. package/templates/saas/tsconfig.json +21 -0
  157. package/templates/saas/usebecky.template.json +31 -0
@@ -0,0 +1,838 @@
1
+ # usebecky SDK reference
2
+
3
+ Package `usebecky` (zero dependencies; browsers, Node 22.18+, Next.js, Vite, Expo / React Native, Deno, Bun). Two entry points:
4
+
5
+ - `import { createClient } from 'usebecky'` for browser, mobile and edge code. Apps create the client once in `src/lib/usebecky.ts` (`npx usebecky init` writes it) and import it: `import { baas } from './lib/usebecky'`.
6
+ - `import { baas, createServerClient } from 'usebecky/server'` for Node server code (uses `node:crypto`; secret key, never in browser or app code).
7
+
8
+ Samples that start with `// inside an async function:` or `// inside your component:` are fragments for that spot; every other sample is a whole file (its first line may name it).
9
+
10
+ ## Contents
11
+
12
+ 1. Results and errors
13
+ 2. `createClient` and the client object
14
+ 3. Auth (`baas.auth`)
15
+ 4. Database (`baas.from`, `baas.rpc`)
16
+ 5. Storage (`baas.storage`)
17
+ 6. Realtime (`baas.realtime`)
18
+ 7. Payments (`baas.payments`)
19
+ 8. Server (`usebecky/server`)
20
+ 9. Events / webhooks (`baas.events`)
21
+ 10. Data types with example values
22
+ 11. Exports
23
+ 12. Forms (`baas.forms`)
24
+ 13. Newsletter (`baas.newsletter`)
25
+ 14. Push notifications (`baas.push`)
26
+ 15. Scheduled jobs and database webhooks (dashboard; your server verifies the calls); Functions (`baas.functions.invoke`)
27
+ 16. Recipes (React sign-in and live notes, Next.js pages and routes, paywall SQL, avatar upload, webhooks)
28
+
29
+ ## 1. Results and errors
30
+
31
+ ```ts
32
+ import type { UseBeckyError } from 'usebecky'
33
+
34
+ // Both are exported as types from 'usebecky'.
35
+ type Result<T> = { data: T; error: null } | { data: null; error: UseBeckyError }
36
+ type QueryResult<T> =
37
+ | { data: T; error: null; count: number | null; status: number }
38
+ | { data: null; error: UseBeckyError; count: null; status: number }
39
+ ```
40
+
41
+ Calls never throw for API errors or network failures. Exceptions: `createClient()` and `createServerClient()` throw when the URL or key is missing or the URL does not start with `http(s)://`; `realtime.subscribe()` throws a `TypeError` without a callback; `events.verify()` throws on a bad signature.
42
+
43
+ ```ts
44
+ // inside an async function:
45
+ import { isUseBeckyError } from 'usebecky'
46
+
47
+ const { error } = await baas.from('notes').select()
48
+ if (error) {
49
+ error.code // string, stable snake_case: 'invalid_credentials', 'permission_denied', 'network_error', ...
50
+ error.message // string, plain English, safe to show
51
+ error.hint // string | undefined: what to do next
52
+ error.status // number: HTTP status; 0 = never reached the server
53
+ error.toJSON() // { code, message, status, hint? }
54
+ }
55
+ isUseBeckyError(error) // type guard: true for a UseBeckyError (class exported from 'usebecky' and 'usebecky/server')
56
+ ```
57
+
58
+ Example errors:
59
+
60
+ ```json
61
+ { "code": "table_not_found", "message": "The table \"note\" does not exist in your database.", "hint": "Did you mean \"notes\"? Table names are case-sensitive.", "status": 404 }
62
+ { "code": "network_error", "message": "Could not reach the usebecky API at https://api.example.com (ECONNREFUSED).", "hint": "Check your internet connection and that your usebecky URL is correct (Dashboard → Settings → API keys).", "status": 0 }
63
+ { "code": "not_single_row", "message": "Expected exactly one row, but the request matched 0.", "hint": "Check your filters, or use .maybeSingle() if no row is OK. Rows hidden by RLS policies also count as missing.", "status": 406 }
64
+ ```
65
+
66
+ An expired access token (`token_expired` / `invalid_token`) is refreshed and the request retried once automatically.
67
+
68
+ ## 2. `createClient(url?, publishableKey?, options?)`
69
+
70
+ ```ts
71
+ import type { ClientOptions, UseBeckyClient } from 'usebecky'
72
+
73
+ // The signature of createClient:
74
+ type CreateClient = <DB = any>(url?: string, publishableKey?: string, options?: ClientOptions) => UseBeckyClient<DB>
75
+ ```
76
+
77
+ - With no arguments it reads `NEXT_PUBLIC_USEBECKY_URL` / `EXPO_PUBLIC_USEBECKY_URL` / `USEBECKY_URL` (and the matching `_PUBLISHABLE_KEY`) from `process.env`. It cannot read `import.meta.env` (Vite), `$env` (SvelteKit) or Nuxt runtime config: pass those values explicitly.
78
+ - Throws `usebecky: createClient() is missing your project URL...` when nothing is found.
79
+ - Warns in the console when given a secret key (`ub_sk_`) in a browser, or a key that does not start with `ub_`.
80
+
81
+ ```ts
82
+ import type { AnalyticsOptions, RealtimeOptions } from 'usebecky'
83
+
84
+ // The shapes of ClientOptions and StorageAdapter (both exported as types from 'usebecky'):
85
+ interface ClientOptions {
86
+ storage?: StorageAdapter // default: localStorage in browsers, memory elsewhere. Pass AsyncStorage in React Native.
87
+ autoRefresh?: boolean // default true: refresh the access token before it expires (deduplicated across tabs)
88
+ detectSessionInUrl?: boolean // default true: finish OAuth / magic-link / recovery redirects (?code= with PKCE, or #access_token=...)
89
+ cookie?: boolean // default true (browsers only): mirror the access token to the "ub-access-token" cookie
90
+ storageKey?: string // default `ub-<ref>-auth`
91
+ fetch?: (input: string, init?: RequestInit) => Promise<Response>
92
+ headers?: Record<string, string> // extra headers on every request
93
+ realtime?: RealtimeOptions // e.g. { WebSocket } for runtimes without a global WebSocket
94
+ analytics?: boolean | AnalyticsOptions // false turns baas.analytics off (enable() later, e.g. after consent)
95
+ locale?: string // email language ('de', 'pt-BR'): sent as Accept-Language on every request. Default: none (the browser sends its own)
96
+ }
97
+ interface StorageAdapter {
98
+ getItem(key: string): string | null | Promise<string | null>
99
+ setItem(key: string, value: string): void | Promise<void>
100
+ removeItem(key: string): void | Promise<void>
101
+ }
102
+ ```
103
+
104
+ `UseBeckyClient<DB>` members: `url`, `key`, `auth`, `storage`, `realtime`, `payments`, `analytics`, `forms`, `newsletter`, `push`, `from(table)`, `rpc(fn, args?, options?)`, `locale` (string | null), `setLocale(locale | null)` (email language for every later request; `null` = the browser's).
105
+
106
+ ## 3. Auth: `baas.auth`
107
+
108
+ | Method | Returns (`data`) | Notes |
109
+ |---|---|---|
110
+ | `signUp({ email, password, data?, redirectTo?, captchaToken?, locale? })` | `{ user, session: Session \| null }` | `data` becomes `user.user_metadata`. `session` is null when the project requires email confirmation (email sent). Fires `SIGNED_IN` when a session is returned. `captchaToken`: when bot protection is on (`captcha_required` otherwise). `locale`: the email's language (all email calls; `emails.md`). |
111
+ | `signIn({ email, password, captchaToken? })` | `{ user, session, mfaRequired? }` | `mfaRequired: true` → ask for the authenticator code and call `mfa.verify()`. |
112
+ | `signInWith(provider, { redirectTo?, skipBrowserRedirect? })` | `{ provider, url }` | `provider`: `'google' \| 'github' \| 'apple'`. In a browser it navigates to `url` (unless `skipBrowserRedirect`). `redirectTo` defaults to the current page. |
113
+ | `sendMagicLink(email, { redirectTo?, createUser?, captchaToken?, locale? })` | `{}` | Emails a link and a 6-digit code. Without `createUser: true`, unknown emails silently get nothing. |
114
+ | `verifyCode(email, code, type?)` | `{ user, session }` | `type`: `'magiclink'` (default) \| `'signup'` \| `'recovery'` \| `'invite'` \| `'email_change'`. `'recovery'` fires `PASSWORD_RECOVERY`. |
115
+ | `resetPassword(email, { redirectTo?, captchaToken?, locale? })` | `{}` | Same result whether or not the email exists. Can still fail: `rate_limited` (5 emails per address per 5 min), invalid email. |
116
+ | `resend(email, type?, { locale? })` | `{}` | `type`: `'signup'` (default) \| `'magiclink'`. |
117
+ | `updateUser({ email?, password?, data?, locale? })` | `{ user }` | `data` is merged into `user_metadata`. New email needs confirmation (`locale` = its language). New password signs out other devices. Fires `USER_UPDATED`. `data: { locale: 'de' }` saves the user's email language for every later email. |
118
+ | `signOut({ everywhere? })` | `data: null` | Result is `{ data: null, error }`. Fires `SIGNED_OUT`. `everywhere: true` revokes all sessions. |
119
+ | `getSession()` | `{ session: Session \| null }` | Synchronous, from memory. `error` is set if a redirect sign-in failed. |
120
+ | `getUser()` | `{ user: User \| null }` | Fresh from the server. `null` when signed out (no error). |
121
+ | `onAuthStateChange((event, session) => void)` | unsubscribe function | Called once with `INITIAL_SESSION` after the stored session loads, then on every change. |
122
+ | `refreshSession()` | `{ session }` | Normally automatic. |
123
+ | `getAccessToken()` | `Promise<string \| null>` (not a Result) | Refreshes first when about to expire. |
124
+ | `setSessionFromUrl(url)` | `{ session }` | Finish a redirect yourself (Expo deep links). Browsers do it automatically. |
125
+ | `setSessionTokens({ access_token, refresh_token })` | `{ session }` | Use tokens obtained elsewhere. |
126
+ | `settings()` | `AuthSettings` | Which sign-in methods are on, for building a login screen. |
127
+ | `ready` | `Promise<void>` | Resolves when the stored session (and any session in the URL) is loaded. |
128
+ | `mfa.enroll({ friendlyName? })` | `{ id, type: 'totp', secret, uri }` | Show `uri` (otpauth://) as a QR code, then `mfa.verify(id, code)`. |
129
+ | `mfa.verify(factorId, code)` | `{ user, session }` | Session upgrades to `aal2`. Fires `MFA_CHALLENGE_VERIFIED`. |
130
+ | `mfa.unenroll(factorId)` | `{ id }` | |
131
+ | `mfa.listFactors()` | `{ all: Factor[], totp: Factor[] }` | `totp` = verified TOTP factors. |
132
+ | `mfa.getAssuranceLevel()` | `{ currentLevel, nextLevel }` (sync, not a Result) | `'aal1' \| 'aal2' \| null`. `nextLevel === 'aal2' && currentLevel === 'aal1'` → ask for a code. |
133
+ | `dispose()` | void | Stop timers (tests, scripts). |
134
+
135
+ Auth events (`AuthChangeEvent`): `INITIAL_SESSION`, `SIGNED_IN`, `SIGNED_OUT`, `TOKEN_REFRESHED`, `USER_UPDATED`, `PASSWORD_RECOVERY`, `MFA_CHALLENGE_VERIFIED`.
136
+
137
+ `AuthSettings` example:
138
+
139
+ ```json
140
+ { "signup_enabled": true, "email_password": true, "magic_link": true, "providers": { "google": true, "github": false, "apple": false }, "mfa_totp": true, "site_url": "http://localhost:3000" }
141
+ ```
142
+
143
+ ## 4. Database
144
+
145
+ ### Entry points
146
+
147
+ ```ts
148
+ import type { QueryBuilder, TableQuery } from 'usebecky'
149
+ import { baas } from './lib/usebecky'
150
+
151
+ const notes: TableQuery = baas.from('notes') // from(table: string)
152
+ const topTags: QueryBuilder = baas.rpc('top_tags', { max: 5 }, { get: true }) // rpc(fn, args?: Record<string, unknown>, options?: { head?: boolean; get?: boolean; count?: 'exact' | 'planned' | 'estimated' })
153
+ // Nothing is sent until you await a builder: const { data, error } = await topTags
154
+ ```
155
+
156
+ `TableQuery` methods (each returns a chainable, awaitable `QueryBuilder`):
157
+
158
+ | Method | Default result `data` |
159
+ |---|---|
160
+ | `select(columns = '*', { count?, head? })` | `Row[]`. `head: true` returns no rows (`data: null`), only `count`. |
161
+ | `insert(row \| rows, { count?, defaultToNull? })` | `null`; chain `.select()` to get the inserted rows. `defaultToNull: false` uses column defaults for missing keys in bulk inserts. |
162
+ | `upsert(row \| rows, { onConflict?, ignoreDuplicates?, count?, defaultToNull? })` | `null`; chain `.select()`. `onConflict: 'col'` or `'a,b'` must name a unique constraint (default: primary key). `ignoreDuplicates: true` = insert or do nothing. |
163
+ | `update(values, { count? })` | `null`; chain `.select()`. A filter is required. |
164
+ | `delete({ count? })` | `null`; chain `.select()`. A filter is required. |
165
+
166
+ Without a filter, `update()` and `delete()` fail with `filter_required` (only the secret key may change every row).
167
+
168
+ ### Filters (all return the builder)
169
+
170
+ | Method | Meaning |
171
+ |---|---|
172
+ | `eq(col, v)` `neq` `gt` `gte` `lt` `lte` | comparisons |
173
+ | `like(col, pattern)` `ilike(col, pattern)` | `%` (or `*`) wildcard; `ilike` is case-insensitive |
174
+ | `is(col, null \| true \| false)` | `IS NULL` / `IS TRUE` / `IS FALSE` |
175
+ | `in(col, values[])` | one of |
176
+ | `contains(col, value)` `containedBy(col, value)` `overlaps(col, value)` | arrays, jsonb, ranges |
177
+ | `textSearch(col, query, { config?, type?: 'plain' \| 'phrase' \| 'websearch' })` | full-text search |
178
+ | `not(col, operator, value)` | e.g. `.not('status', 'eq', 'done')`, `.not('id', 'in', [1, 2])` |
179
+ | `or('a.eq.1,b.gt.2', { referencedTable? })` | any of (PostgREST syntax) |
180
+ | `match({ col: value, ... })` | several `eq` |
181
+ | `filter(col, operator, value)` | any PostgREST operator, e.g. `.filter('tags', 'cs', '{a,b}')` |
182
+
183
+ Filter on an embedded table with a dotted column: `.eq('comments.approved', true)`.
184
+
185
+ ### Modifiers
186
+
187
+ | Method | Effect |
188
+ |---|---|
189
+ | `select(columns?, { count? })` | after a write: return the changed rows |
190
+ | `order(col, { ascending?, nullsFirst?, referencedTable? })` | call again for a tiebreaker |
191
+ | `limit(n, { referencedTable? })` | |
192
+ | `range(from, to, { referencedTable? })` | inclusive, 0-based: `range(0, 9)` = first 10 |
193
+ | `single()` | one object; error `not_single_row` (406) unless exactly one row |
194
+ | `maybeSingle()` | one object or `null`; error if more than one |
195
+ | `abortSignal(signal)` | cancel; error code `aborted` |
196
+ | `returns<T>()` | override the result type |
197
+
198
+ Reads return at most 1000 rows per request; paginate with `range()`.
199
+
200
+ ### Select syntax
201
+
202
+ ```ts
203
+ // inside an async function:
204
+ await baas.from('notes').select('id, title') // columns
205
+ await baas.from('notes').select('*, comments(*)') // embed through a foreign key (either direction, nesting allowed)
206
+ await baas.from('notes').select('id, author:profiles(display_name)') // alias an embed
207
+ await baas.from('notes').select('title, comments(count)') // embedded count
208
+ await baas.from('products').select('meta->>color, price::text') // JSON path, cast
209
+ ```
210
+
211
+ Embedding needs a foreign key between two tables in `public`. `auth.users` cannot be embedded: to show author names, reference `public.profiles (id)` (which itself references `auth.users`) and embed `profiles`.
212
+
213
+ ### Example
214
+
215
+ ```ts
216
+ // inside an async function:
217
+ const { data, error, count, status } = await baas
218
+ .from('notes')
219
+ .select('id, title, created_at, author:profiles(display_name)', { count: 'exact' })
220
+ .eq('archived', false)
221
+ .order('created_at', { ascending: false })
222
+ .range(0, 1)
223
+ ```
224
+
225
+ ```json
226
+ {
227
+ "data": [
228
+ { "id": "6f1c2a1e-8a43-4c6e-9d55-0b6b1c9e7a10", "title": "Groceries", "created_at": "2026-11-12T09:30:11.214Z", "author": { "display_name": "ada" } },
229
+ { "id": "b2d8f0c4-1e7a-4c39-8f0e-2a4d7e9c5b31", "title": "Ideas", "created_at": "2026-11-11T17:02:45.880Z", "author": { "display_name": "ada" } }
230
+ ],
231
+ "error": null,
232
+ "count": 14,
233
+ "status": 200
234
+ }
235
+ ```
236
+
237
+ Statuses: select 200 (`range()` sends offset/limit, so still 200), insert 201, update/delete 200 with `.select()` or 204 without. An update or delete that matches no rows (wrong filter, or no RLS policy for it) is not an error: chain `.select()` and check `data.length`.
238
+
239
+ ### RPC
240
+
241
+ ```ts
242
+ // inside an async function:
243
+ const { data, error } = await baas.rpc('top_tags', { max: 5 }) // POST /rest/v1/rpc/top_tags
244
+ await baas.rpc('search_notes', { q: 'milk' }, { get: true }) // GET (stable/immutable functions only)
245
+ ```
246
+
247
+ Arguments are passed by name. Functions run with the caller's role, so RLS applies unless the function is `security definer`.
248
+
249
+ ### Vector search (AI search)
250
+
251
+ Dashboard → Database → Postgres extensions → Vector search → **Add AI search** creates `documents` (`id`, `user_id`, `content`, `metadata` jsonb, `embedding vector(N)`, `created_at`; HNSW cosine index), access rules (default: anyone can search, only the secret key writes) and `match_documents(query_embedding, match_count = 5, match_threshold = 0)` → `{ id, content, metadata, similarity }[]`, best first (security invoker: RLS applies). Embeddings come from the customer's AI provider and are made on the server (the AI key is a secret): never in browser or app code. Pass vectors as plain JSON arrays of numbers. The question and the stored rows must use the same embedding model.
252
+
253
+ ```ts
254
+ // inside an Express route handler:
255
+ const embedding = [0.01, -0.02, 0.03] // from your AI provider's embeddings API, made on this server
256
+ await baas.db.admin.from('documents').insert({ content: 'Open Monday to Friday, 9 to 5.', embedding })
257
+ const { data, error } = await baas.db.as(req).rpc('match_documents', { query_embedding: embedding, match_count: 5 })
258
+ if (error) return res.status(400).json(error)
259
+ res.json(data)
260
+ ```
261
+
262
+ ### TypeScript
263
+
264
+ ```ts
265
+ // lib/usebecky.ts (Next.js) with generated types; the same in any framework's client file
266
+ import { createClient } from 'usebecky'
267
+ import type { Database, Tables } from '../usebecky.types' // written to the project folder by `npx usebecky types`
268
+
269
+ export const baas = createClient<Database>(process.env.NEXT_PUBLIC_USEBECKY_URL!, process.env.NEXT_PUBLIC_USEBECKY_PUBLISHABLE_KEY!)
270
+ export type Note = Tables<'notes'>
271
+
272
+ export async function noteTitles() {
273
+ const { data } = await baas.from('notes').select('id, title') // data: { id: string; title: string }[] | null
274
+ return data ?? []
275
+ }
276
+ ```
277
+
278
+ Without generated types every value is `any`.
279
+
280
+ ## 5. Storage: `baas.storage`
281
+
282
+ `baas.storage.from(bucketId)` returns a `BucketApi`:
283
+
284
+ | Method | Returns (`data`) |
285
+ |---|---|
286
+ | `upload(path, file, { upsert?, contentType?, cacheControl? })` | `{ path, fullPath, id }` e.g. `{ "path": "0b6f.../avatar.png", "fullPath": "avatars/0b6f.../avatar.png", "id": "c41e..." }` |
287
+ | `update(path, file, { contentType?, cacheControl? })` | same; replaces (upsert) |
288
+ | `download(path, { transform? })` | `Blob` (with `transform`: the resized image, same read access) |
289
+ | `info(path)` | `ObjectInfo` |
290
+ | `exists(path)` | `boolean` (false for missing or unreadable) |
291
+ | `getPublicUrl(path, { download?, transform? })` | `{ publicUrl }` (sync, no request, public buckets only; returns `{ data }` without `error`) |
292
+ | `createSignedUrl(path, expiresIn, { download?, transform? })` | `{ signedUrl, path }`; `expiresIn` in seconds, max 31536000 |
293
+ | `createSignedUrls(paths, expiresIn, { transform? })` | `[{ path, signedUrl \| null, error \| null }]` |
294
+ | `createSignedUploadUrl(path)` | `{ signedUrl, token, path }`; anyone can `PUT` one file to `signedUrl` |
295
+ | `list(prefix = '', { limit?, offset?, search?, sortBy?: { column: 'name' \| 'created_at' \| 'updated_at', order?: 'asc' \| 'desc' } })` | `FileObject[]` (folders have `id: null`) |
296
+ | `remove(path \| paths)` | `ObjectInfo[]` deleted |
297
+ | `move(from, to)` | `{ message }` |
298
+ | `copy(from, to)` | `{ message, path }` |
299
+
300
+ `file` may be a `File`, `Blob`, `ArrayBuffer`, typed array / `Buffer`, `ReadableStream`, `FormData` or `string`. Content type defaults to the file's type, then the extension, then `text/plain;charset=UTF-8` for strings or `application/octet-stream`. `upload` without `upsert: true` fails with `already_exists` (409) when the path is taken. `download: true | 'name.pdf'` adds a download disposition.
301
+
302
+ Image transformations: `transform: { width?, height?, resize?: 'cover' | 'contain' | 'fill', quality?: 20-100 (80), format?: 'origin' | 'webp' | 'avif' | 'jpeg' | 'png' }` resizes on the fly (1-2500 px, never enlarged, cached per size). `getPublicUrl(path, { transform: { width: 400, format: 'webp' } })` → `.../storage/v1/render/image/public/<bucket>/<path>?apikey=...&width=400&format=webp`; `createSignedUrl` bakes the options into the token (`/render/image/sign/...`). See storage.md for limits.
303
+
304
+ Bucket management (secret key only, so call it via `baas.admin.storage` on the server):
305
+
306
+ ```ts
307
+ // scripts/buckets.ts: server only (secret key)
308
+ import { baas } from 'usebecky/server'
309
+
310
+ const storage = baas.admin.storage
311
+ await storage.listBuckets() // data: Bucket[]
312
+ await storage.getBucket('avatars') // data: Bucket
313
+ await storage.createBucket('avatars', { public: true, fileSizeLimit: 5_000_000, allowedMimeTypes: ['image/*'] }) // data: Bucket; fileSizeLimit in bytes
314
+ await storage.updateBucket('avatars', { public: false, fileSizeLimit: null, allowedMimeTypes: null }) // data: Bucket; null = no limit
315
+ await storage.emptyBucket('avatars') // data: {}
316
+ await storage.deleteBucket('avatars') // data: {}; the bucket must be empty
317
+ ```
318
+
319
+ `list('0b6f...')` example:
320
+
321
+ ```json
322
+ [
323
+ { "name": "photos", "id": null, "metadata": null, "created_at": null, "updated_at": null },
324
+ { "name": "avatar.png", "id": "c41e5d2a-7f0b-4b8e-9a7d-3e2f1c0b9a88", "metadata": { "size": 48213, "mimetype": "image/png", "etag": "\"9b2c...\"", "cacheControl": "max-age=3600" }, "created_at": "2026-11-12T10:01:02.000Z", "updated_at": "2026-11-12T10:01:02.000Z" }
325
+ ]
326
+ ```
327
+
328
+ ## 6. Realtime: `baas.realtime`
329
+
330
+ ```ts
331
+ import type { SubscribeOptions } from 'usebecky'
332
+ import { baas } from './lib/usebecky'
333
+
334
+ const options: SubscribeOptions = {
335
+ event: 'INSERT', // 'INSERT' | 'UPDATE' | 'DELETE' | '*' (default '*')
336
+ filter: 'room_id=eq.42', // 'col=eq.42' | neq | gt | gte | lt | lte | 'col=in.(a,b)'
337
+ onSubscribed: () => console.log('listening'),
338
+ onError: (error) => console.warn(error.code, error.message), // without it, errors are logged as console warnings
339
+ }
340
+ const stop = baas.realtime.subscribe('messages', options, (change) => {
341
+ change.event // 'INSERT' | 'UPDATE' | 'DELETE'
342
+ change.table // 'messages'
343
+ change.new // the row as the subscriber may see it; null for DELETE
344
+ change.old // primary key only for UPDATE and DELETE; null for INSERT
345
+ change.commit_timestamp // ISO timestamp
346
+ })
347
+ const stopAll = baas.realtime.subscribe('messages', (change) => console.log(change)) // options are optional
348
+ stop() // subscribe() returns the unsubscribe function
349
+
350
+ const room = baas.realtime.channel('room:42') // RealtimeChannel; same instance for the same name
351
+ baas.realtime.status // 'idle' | 'connecting' | 'open' | 'reconnecting'
352
+ baas.realtime.disconnect() // drop every subscription and channel
353
+ ```
354
+
355
+ `RealtimeChannel`: `on(event | '*', (payload, event) => void): () => void`, `send(event, payload?)`, `track(state)`, `untrack()`, `onPresence((state) => void): () => void`, `onError((error) => void): () => void`, `presence()`, `leave()`, `name`, `presenceKey` (your key once joined), `joined`.
356
+
357
+ `RealtimeOptions`: `{ WebSocket?, heartbeatIntervalMs? (25000), heartbeatTimeoutMs? (10000), reconnectDelaysMs?, idleTimeoutMs? (1000) }`.
358
+
359
+ Details and change examples: `realtime.md`.
360
+
361
+ ## 7. Payments: `baas.payments`
362
+
363
+ | Method | Returns (`data`) | Notes |
364
+ |---|---|---|
365
+ | `products()` | `Product[]` | Public catalog, works signed out. |
366
+ | `checkout(priceKey, { successUrl?, cancelUrl?, quantity?, promotionCodes?, redirect? })` | `{ url, id }` | Signed in only. Browsers navigate to `url` unless `redirect: false`. In browsers, success/cancel default to the current page (after the dashboard's Checkout settings, if set); outside a browser pass `successUrl` or set a dashboard default (else `missing_success_url`). |
367
+ | `portal({ returnUrl?, redirect? })` | `{ url }` | Signed in only. `returnUrl` defaults to the current page in browsers. |
368
+ | `me()` | `BillingInfo` | Signed out → empty lists, no error. |
369
+ | `hasAccess(feature)` | `boolean` | Signed out → `false`, no request. |
370
+ | `checkAccess(feature)` | `{ access, source: 'subscription' \| 'purchase' \| 'gift' \| null }` | Like `hasAccess`, plus where the access comes from. |
371
+ | `createPayment(priceKey, { quantity?, coupon? })` | `PaymentSetup` | Embedded payment form (Stripe Payment Element) instead of the Checkout page (`payments.md`). |
372
+ | `waitForAccess(feature, { timeoutMs?, intervalMs? })` | `boolean` | After paying: polls `hasAccess` until true (default 20 s). |
373
+ | `stripeConfig()` / `mode()` | `{ publishable_key, stripe_account, connected, currency_default, mode }` / `'test' \| 'live' \| null` | `'test'`: Stripe test cards, nothing is charged. |
374
+ | `download(productKey)` | `{ url, expiresIn }` | Signed link to a purchased file; `not_purchased` (403) otherwise. |
375
+
376
+ Details: `payments.md`.
377
+
378
+ ## 8. Server: `usebecky/server`
379
+
380
+ ```ts
381
+ // Server only: both clients hold the secret key.
382
+ import { baas } from 'usebecky/server' // lazy singleton: created on first property access
383
+ import { createServerClient } from 'usebecky/server'
384
+ import type { Database } from './usebecky.types'
385
+
386
+ // Every option is optional:
387
+ export const server = createServerClient<Database>({
388
+ url: process.env.USEBECKY_URL, // default env USEBECKY_URL (then NEXT_PUBLIC_USEBECKY_URL)
389
+ secretKey: process.env.USEBECKY_SECRET_KEY, // default env USEBECKY_SECRET_KEY
390
+ publishableKey: process.env.USEBECKY_PUBLISHABLE_KEY, // default env USEBECKY_PUBLISHABLE_KEY (then NEXT_PUBLIC_...); used by as() when there is no user
391
+ webhookSecret: process.env.USEBECKY_WEBHOOK_SECRET, // default env USEBECKY_WEBHOOK_SECRET
392
+ userCacheTtlMs: 30_000, // default 30000
393
+ fetch, // default: the global fetch
394
+ })
395
+ ```
396
+
397
+ Throws `usebecky/server: missing USEBECKY_URL and USEBECKY_SECRET_KEY...` when they are not set (the singleton throws on first use, never at import; `baas.events` works with only the webhook secret).
398
+
399
+ | Member | Description |
400
+ |---|---|
401
+ | `url` | Project URL. |
402
+ | `auth.getUser(input)` | `Promise<User \| null>`. `input`: Express/Node `req`, Fetch `Request`/`NextRequest`, Next.js `cookies()`/`headers()` result (or the promise), a raw token, or `'Bearer <token>'`. Reads `Authorization: Bearer` first, then the `ub-access-token` cookie. Verified with usebecky; cached ~30s per token. Not a Result. |
403
+ | `auth.middleware()` | Express/Connect: sets `req.user` to `User \| null`, never blocks. |
404
+ | `auth.requireUser()` | Express/Connect: responds `401 {"error":{"code":"not_signed_in","message":"You need to be signed in.","hint":"..."}}` unless signed in; sets `req.user`. |
405
+ | `auth.admin.listUsers({ page?, perPage?, q? })` | `{ users, total, page, perPage }` (newest first; `q` searches email) |
406
+ | `auth.admin.createUser({ email, password?, emailConfirm?, userMetadata?, appMetadata? })` | `User` |
407
+ | `auth.admin.getUserById(id)` | `User` |
408
+ | `auth.admin.updateUser(id, { email?, password?, emailConfirm?, ban?: 'none' \| '24h' \| 'forever' \| '<n>h', appMetadata?, userMetadata? })` | `User` |
409
+ | `auth.admin.deleteUser(id)` | `{ id }` (409 `user_has_data` when your tables still reference the user) |
410
+ | `auth.admin.inviteUser(email, { redirectTo?, data?, locale? })` | `User` (invite email sent; `locale` = its language) |
411
+ | `auth.admin.signOutUser(id)` | `{ ok: true }` |
412
+ | `auth.admin.createSession(id)` | `Session` (access + refresh token, aal1): sign a user in from your server without password, code or captcha (automated tests); activity log `session_created`. Browser client: `auth.setSessionTokens(session)` |
413
+ | `as(input)` | `UserScopedClient`: `from`, `rpc`, `storage`, `payments` as that user (RLS applies). `input`: same as `getUser`, or a `User` returned by `getUser`/`middleware` (`req.user`). No token: runs as `anon` when a publishable key is configured (`publishableKey`, `USEBECKY_PUBLISHABLE_KEY` or `NEXT_PUBLIC_USEBECKY_PUBLISHABLE_KEY`); otherwise database and storage calls return `not_signed_in` (payments `me()`/`hasAccess()` return empty/false). |
414
+ | `admin` | `ScopedClient`: `from`, `rpc`, `storage` as `service_role` (bypasses RLS). |
415
+ | `db.as(input)`, `db.admin` | aliases |
416
+ | `payments.hasAccess(userOrId, feature)` | `Promise<boolean>`; `false` on any error; never throws |
417
+ | `payments.checkAccess(userOrId, feature)`, `listSubscriptions(user, { status? })`, `cancelSubscription(id, { atPeriodEnd? })`, `resumeSubscription(id)` | `{ access, source }` with errors as errors; subscriptions (`payments.md`) |
418
+ | `payments.test.subscribe(userOrId, price, { card?: 'visa' \| 'declined', trial? })` | Test mode only: a paid Stripe test subscription without a browser (`ServerSubscription`) |
419
+ | `usage.get()` | `{ plan, period, quotas: [{ key, label, used, limit, percent, status: 'ok' \| 'warning' \| 'exceeded', scope }], upgrade_url }`: usage against the plan. Events `quota.warning` (80%) / `quota.exceeded` (100%) say it too |
420
+ | `analytics.overview / report(dimension) / timeseries(options)` | Visitor analytics reports, `filters: { hostname }` for one site (`analytics.md`) |
421
+ | `payments.gift(userOrEmail, product, options?)`, `updateGift(id, changes)`, `revokeGift(id)`, `listGifts(options?)` | Give a user a product for free (`payments.md`) |
422
+ | `push.send({ userIds?, tag?, title, body, url?, data? })`, `push.getMessage(id)`, `push.registerDevice(...)` | Push notifications (section 14) |
423
+ | `emails.send({ to, subject?, text?, html?, heading?, buttonText?, buttonUrl?, replyTo?, template?, data?, locale?, attachments?, sendAt?, tags?, idempotencyKey? })` | `{ id, status? }`; your own emails (`emails.md`) |
424
+ | `emails.batch(emails, { idempotencyKey? })`, `emails.get(id)`, `emails.cancel(id)` | up to 100 at once `{ results: [{ id, status?, error }] }`; status + events; stop a scheduled email (`emails.md`) |
425
+ | `newsletter.add(email, options?)`, `unsubscribe(email, options?)`, `list(options?)` | Newsletter subscribers (section 13) |
426
+ | `events` | see section 9 |
427
+
428
+ `baas.as(req).payments.checkout(...)` and `.portal(...)` return the URL (no redirect on the server). Express gets `req.user` typed as `User` through a global `Express.User` augmentation.
429
+
430
+ ```ts
431
+ // server.ts (Express)
432
+ import express from 'express'
433
+ import { baas } from 'usebecky/server'
434
+
435
+ const app = express()
436
+ app.post('/api/usebecky-events', baas.events.handler()) // before express.json()
437
+ app.use(express.json())
438
+ app.use(baas.auth.middleware())
439
+ app.get('/api/notes', baas.auth.requireUser(), async (req, res) => {
440
+ const { data, error } = await baas.as(req).from('notes').select('id, title')
441
+ if (error) return res.status(error.status || 500).json({ error })
442
+ res.json(data)
443
+ })
444
+ app.listen(3000)
445
+ ```
446
+
447
+ ## 9. Events (webhooks from usebecky): `baas.events`
448
+
449
+ ```ts
450
+ // Server only (needs USEBECKY_WEBHOOK_SECRET, or pass the secret)
451
+ import { baas, signEvent, verifyEvent, SIGNATURE_HEADER } from 'usebecky/server'
452
+
453
+ const off = baas.events.on('subscription.*', async (event) => console.log(event.type)) // type: an EventType, '*' for all, or 'group.*'; returns an unsubscribe function
454
+ const expressHandler = baas.events.handler() // Express / Connect / node:http handler; reads the raw body itself
455
+ const fetchHandler = baas.events.fetchHandler() // (request: Request) => Promise<Response> for Next.js, Remix, Hono, Bun, Deno
456
+
457
+ // Verify by hand: each throws a UseBeckyError (invalid_signature, stale_signature, ...) on a bad signature
458
+ const rawBody = '{"id":"evt_1","type":"test.ping","created_at":"2026-11-12T09:00:00.000Z","project":"k3x9q2m7p4ab","data":{}}'
459
+ const header = signEvent(rawBody, 'whsec_test') // build a signature header (tests); optional 3rd argument: unix timestamp
460
+ const event = baas.events.verify(rawBody, header, 'whsec_test', { toleranceSeconds: 300 }) // secret defaults to USEBECKY_WEBHOOK_SECRET
461
+ await baas.events.dispatch(event) // run the handlers for an already verified event
462
+ verifyEvent(rawBody, header, 'whsec_test') // standalone export, same check
463
+ SIGNATURE_HEADER // 'usebecky-signature'
464
+ ```
465
+
466
+ ```ts
467
+ interface UseBeckyEvent<T = any> { id: string /* evt_... */; type: string; created_at: string; project: string; data: T }
468
+ ```
469
+
470
+ Responses: 200 `{"received":true}`; a bad signature returns 400 with `missing_signature`, `invalid_signature`, `stale_signature` (older than 300 s) or `invalid_payload`; a missing secret returns 500 `missing_webhook_secret`; a throwing handler returns 500 `handler_error` and usebecky retries after 10s, 1m, 5m, 30m, 2h. Deliveries can repeat: deduplicate by `event.id`.
471
+
472
+ Event types and `data`:
473
+
474
+ | Type | `data` |
475
+ |---|---|
476
+ | `user.created`, `user.updated` | `{ user: User }` |
477
+ | `user.deleted` | `{ user: { id, ... } }` |
478
+ | `user.signed_in` | `{ user: User, method: 'password' \| ... }` |
479
+ | `subscription.created`, `subscription.updated`, `subscription.canceled` | `{ user_id, subscription: Subscription, previous_status: string \| null }` |
480
+ | `subscription.trial_will_end` | `{ user_id, subscription, previous_status: null, trial_end }` |
481
+ | `purchase.completed` | `{ user_id, purchase: Purchase }` |
482
+ | `purchase.refunded` | `{ user_id, purchase, amount_refunded }` |
483
+ | `payment.failed` | `{ user_id, subscription: Subscription \| null, invoice: { id, amount_due, currency, attempt_count, next_payment_attempt, hosted_invoice_url } }` |
484
+ | `payment.disputed` / `payment.dispute_closed` / `payment.fraud_warning` | Disputes and fraud warnings on sales: `PaymentDisputedData`, `PaymentDisputeClosedData` (`outcome`), `PaymentFraudWarningData` (`refunded`) |
485
+ | `storage.object.created` | `{ id, bucket_id, name, owner, metadata, overwritten }`; copies send `{ id, bucket_id, name, metadata, copied_from }` |
486
+ | `storage.object.deleted` | `{ id, bucket_id, name, owner? }` |
487
+ | `test.ping` | `{ message: 'Hello from usebecky! Your endpoint works.' }` |
488
+ | `job.failed` | `{ job: { id, name, type: 'function' \| 'http' }, run: { id, trigger, status, error, output, http_status, attempts, started_at, finished_at, ... } }` (section 15) |
489
+ | `email.sent`, `email.delivered`, `email.delayed`, `email.bounced`, `email.complained`, `email.suppressed`, `email.failed` | `{ email: { id, to (masked), template_id, kind, subject, status, reason, error, tags, locale, created_at }, user_id }` (`emails.md`) |
490
+
491
+ ## 10. Data types with example values
492
+
493
+ ```jsonc
494
+ // User
495
+ {
496
+ "id": "0b6f3c2e-5d1a-4f7e-8c9b-2a1d3e4f5a6b",
497
+ "email": "ada@example.com",
498
+ "email_confirmed_at": "2026-11-10T08:00:00.000Z",
499
+ "phone": null,
500
+ "created_at": "2026-11-10T08:00:00.000Z",
501
+ "updated_at": "2026-11-12T09:15:00.000Z",
502
+ "last_sign_in_at": "2026-11-12T09:15:00.000Z",
503
+ "app_metadata": { "provider": "google", "providers": ["google"] },
504
+ "user_metadata": { "name": "Ada Lovelace", "avatar_url": "https://lh3.googleusercontent.com/a/x" },
505
+ "identities": [{ "provider": "google", "provider_id": "1098765432", "email": "ada@example.com", "created_at": "2026-11-10T08:00:00.000Z" }],
506
+ "factors": [],
507
+ "banned_until": null,
508
+ "is_anonymous": false
509
+ }
510
+
511
+ // Session
512
+ {
513
+ "access_token": "eyJhbGciOiJIUzI1NiIs...",
514
+ "token_type": "bearer",
515
+ "expires_in": 3600,
516
+ "expires_at": 1794560100,
517
+ "refresh_token": "v1.Qm9vb...",
518
+ "user": { "id": "0b6f3c2e-...", "email": "ada@example.com" }
519
+ }
520
+ // + "mfa_required": true when the user has a verified authenticator and must still enter a code.
521
+ // Access token claims: sub, role ('authenticated'), email, aal ('aal1' | 'aal2'), session_id, app_metadata, user_metadata, is_anonymous, iat, exp.
522
+
523
+ // Factor
524
+ { "id": "5e2d...", "type": "totp", "status": "verified", "friendly_name": "iPhone", "created_at": "2026-11-12T09:20:00.000Z" }
525
+
526
+ // Product (payments.products())
527
+ {
528
+ "id": "7a1b...", "key": "pro", "name": "Pro", "description": "Everything in Free, plus premium content.",
529
+ "type": "subscription", "features": ["pro"], "active": true, "image_url": null,
530
+ "prices": [
531
+ { "id": "91c2...", "key": "pro_monthly", "product_key": "pro", "amount": 900, "currency": "usd", "interval": "month", "trial_days": 14, "active": true },
532
+ { "id": "a3d4...", "key": "pro_yearly", "product_key": "pro", "amount": 9000, "currency": "usd", "interval": "year", "trial_days": 14, "active": true }
533
+ ],
534
+ "has_download": false, "download": null
535
+ }
536
+
537
+ // BillingInfo (payments.me())
538
+ {
539
+ "customer_id": "cus_Q8x...",
540
+ "subscriptions": [{ "id": "4f5e...", "status": "trialing", "price_key": "pro_monthly", "product_key": "pro", "current_period_end": "2026-11-26T09:00:00.000Z", "trial_end": "2026-11-26T09:00:00.000Z", "cancel_at_period_end": false, "created_at": "2026-11-12T09:00:00.000Z" }],
541
+ "purchases": [{ "id": "8b9c...", "product_key": "ebook", "price_key": "ebook_once", "amount": 1900, "currency": "usd", "status": "paid", "created_at": "2026-11-01T12:00:00.000Z" }],
542
+ "entitlements": ["pro", "ebook"]
543
+ }
544
+
545
+ // Bucket
546
+ { "id": "avatars", "name": "avatars", "public": true, "file_size_limit": null, "allowed_mime_types": null, "created_at": "...", "updated_at": "..." }
547
+
548
+ // ObjectInfo (info(), remove())
549
+ { "id": "c41e...", "bucket_id": "avatars", "name": "0b6f.../avatar.png", "owner": "0b6f...", "metadata": { "size": 48213, "mimetype": "image/png", "etag": "\"9b2c...\"", "cacheControl": "max-age=3600" }, "created_at": "...", "updated_at": "..." }
550
+ ```
551
+
552
+ Amounts are in minor units (cents): `900` = $9.00. Subscription `status`: `trialing | active | past_due | canceled | incomplete | unpaid` (the database can also hold `incomplete_expired` and `paused`; only `active`, `trialing` and `past_due` within the grace period grant access). Purchase `status`: `paid | refunded`.
553
+
554
+ ## 11. Exports
555
+
556
+ Main exports (newer modules may add more; check `node_modules/usebecky/dist/index.d.ts`).
557
+
558
+ From `usebecky`: `createClient`, `UseBeckyClient`, `UseBeckyError`, `isUseBeckyError`, `memoryStorage`, `AuthClient`, `QueryBuilder`, `TableQuery`, `StorageClient`, `BucketApi`, `RealtimeClient`, `RealtimeChannel`, `PaymentsClient`, `AnalyticsClient`, `FormsClient`, `NewsletterClient`, `PushClient`, `vapidKeyToBytes`; types `ClientOptions`, `AnalyticsOptions`, `PaymentSetup`, `StripeConfig`, `FormInput`, `FormSubmitResult`, `PublicForm`, `NewsletterSubscribeOptions`, `NewsletterSubscribeResult`, `TransformOptions`, `PushPlatform`, `PushRegisterOptions`, `PushDevice`, `PushConfig`, `StorageAdapter`, `AuthListener`, `QueryResult`, `CountOption`, `UploadOptions`, `FileBody`, `RealtimeOptions`, `SubscribeOptions`, `RealtimeStatus`, `GenericSchema`, `GenericTable`, `GenericFunction`, `SelectResult`, `Result`, `User`, `Session`, `Identity`, `Factor`, `AuthChangeEvent`, `AuthSettings`, `CaptchaInfo`, `OAuthProvider`, `Product`, `Price`, `Subscription`, `SubscriptionSource`, `AccessSource`, `AccessInfo`, `Purchase`, `BillingInfo`, `PaymentsMode`, `Bucket`, `FileObject`, `ObjectInfo`, `Change`, `ChangeEvent`, `PresenceState`.
559
+
560
+ From `usebecky/server`: `baas`, `createServerClient`, `Events`, `verifyEvent`, `signEvent`, `SIGNATURE_HEADER`, `extractToken`, `parseCookies`, `ACCESS_TOKEN_COOKIE` (`'ub-access-token'`), `UseBeckyError`, `isUseBeckyError`, `resetServerClient` (tests: re-read env vars); types `ServerClient`, `ServerClientOptions`, `RequestLike`, `ScopedClient`, `UserScopedClient`, `AdminUsersApi`, `ServerAuth`, `ServerPayments`, `Gift`, `GiftOptions`, `ServerEmails`, `SendEmailOptions`, `SentEmail`, `EmailAttachment`, `EmailTag`, `EmailStatus`, `EmailDetails`, `EmailEvent`, `BatchEmailResult`, `EmailEventData`, `EmailFailedData`, `ServerNewsletter`, `ServerPush`, `PushSendOptions`, `PushMessage`, `UseBeckyEvent`, `EventType`, `EventHandler`, `EventDataMap`, `QueryResult`, `Result`, `User`, `Session`, `Product`, `Price`, `Subscription`, `Purchase`, `BillingInfo`, `Bucket`, `FileObject`.
561
+
562
+ ## 12. Forms: `baas.forms`
563
+
564
+ Contact forms (and similar) made in Dashboard → Forms. Submissions go to the dashboard inbox, email the form's notification addresses and emit the `form.submitted` webhook. No table, policy or server code needed.
565
+
566
+ | Method | Returns (`data`) | Notes |
567
+ |---|---|---|
568
+ | `submit(formIdOrKey, values, { captchaToken? })` | `{ ok: true, message }` | `formIdOrKey`: the form's key (`'contact'`) or public id (`'f_k3x9m2p7q1zt'`). `values`: object, `FormData` or a `<form>` element; names must match the form's fields (unknown names are kept as "extra"). `message` is the form's success message: show it. |
569
+ | `get(formIdOrKey)` | `{ id, key, name, fields, success_message, enabled, submit_url, captcha }` | Public definition, e.g. to render the fields. `captcha` (`{ provider, site_key }` or null): show that widget and pass its token to `submit`. |
570
+
571
+ ```tsx
572
+ // src/Contact.tsx
573
+ import { useState, type FormEvent } from 'react'
574
+ import { baas } from './lib/usebecky'
575
+
576
+ export function Contact() {
577
+ const [status, setStatus] = useState('')
578
+ async function onSubmit(e: FormEvent<HTMLFormElement>) {
579
+ e.preventDefault()
580
+ const { data, error } = await baas.forms.submit('contact', e.currentTarget) // inputs named name, email, message
581
+ if (error) return setStatus(error.message) // validation_failed (400), rate_limited (429), origin_not_allowed / form_disabled (403), form_not_found (404)
582
+ setStatus(data.message)
583
+ }
584
+ return (
585
+ <form onSubmit={onSubmit}>
586
+ <input name="name" placeholder="Name" required />
587
+ <input name="email" type="email" placeholder="Email" required />
588
+ <textarea name="message" placeholder="Message" required />
589
+ <button type="submit">Send</button>
590
+ {status && <p>{status}</p>}
591
+ </form>
592
+ )
593
+ }
594
+ ```
595
+
596
+ - No JavaScript at all: a plain `<form action="<api url>/forms/v1/f/<formId>" method="POST">` works on any site and shows a hosted thank-you page (or redirects to the form's allowed `success_redirect_url`). Copy the snippet from Dashboard → Forms → the form → Embed. Keep its hidden `_gotcha` input (spam trap).
597
+ - Swift / Kotlin apps: `baas.forms.submit(form:values:captchaToken:)` / `baas.forms.submit(form = ..., values = ...)` (`ios.md`, `android.md`). Other stacks: `POST /forms/v1/f/<key or formId>` with `apikey: ub_pk_...` and a JSON body → `{ "ok": true, "message": "..." }`; without a key only the `f_...` id works (`http-api.md`). Apps never send `_gotcha`. A form with "Allowed websites" set refuses apps (`origin_not_allowed`): clear the list for forms an app posts to.
598
+ - Text only (files → `files_not_supported`). Limits: 5,000 characters per value, 20 KB per submission, 5 per minute and 50 per day per visitor and form.
599
+
600
+ ## 13. Newsletter: `baas.newsletter`
601
+
602
+ Email sign-ups for lists made in Dashboard → Newsletter (tabs Subscribers, Campaigns, Settings). Double opt-in (confirmation email), one-click unsubscribe, the postal address footer and sending campaigns are handled by usebecky: no table, policy or email code needed. Campaigns are written and sent in the dashboard.
603
+
604
+ | Method | Returns (`data`) | Notes |
605
+ |---|---|---|
606
+ | `subscribe(email, { list?, name?, tags?, captchaToken? })` | `{ status: 'pending' \| 'subscribed', message }` | Browser/app, publishable key. `pending` = double opt-in list (they must click the emailed link). Same answer whether or not they were already on the list. `list` = list key, default list when omitted. `tags` ≤ 10. Show `message`. |
607
+ | server `add(email, { list?, name?, tags?, consent?, consentSource?, confirmedAt? })` | `{ subscriber, created, confirmationSent }` | `usebecky/server`, secret key. `consent: 'send_confirmation'` (default) emails a link; `'already_agreed'` subscribes now (only when they asked, e.g. ticked a box) — pass `consentSource` (where) and `confirmedAt` (when) so `subscriber.consent.proof` is `complete`. Idempotent; someone who unsubscribed → `previously_unsubscribed` (409), never re-added. CSV imports (and their legal rules) are a dashboard feature. |
608
+ | server `unsubscribe(email, { list? })` | `{ found, changed, subscriber }` | Stops all campaigns to that address on the list. |
609
+ | server `list({ list?, status?, tag?, search?, limit?, cursor? })` | `{ subscribers, nextCursor, total, list }` | Newest first; pass `nextCursor` as `cursor`. |
610
+
611
+ ```tsx
612
+ // src/Newsletter.tsx
613
+ import { useState, type FormEvent } from 'react'
614
+ import { baas } from './lib/usebecky'
615
+
616
+ export function Newsletter() {
617
+ const [status, setStatus] = useState('')
618
+ async function onSubmit(e: FormEvent<HTMLFormElement>) {
619
+ e.preventDefault()
620
+ const email = new FormData(e.currentTarget).get('email') as string
621
+ const { data, error } = await baas.newsletter.subscribe(email, { tags: ['footer'] })
622
+ if (error) return setStatus(error.message) // invalid_email (400), list_not_found (404), quota_exceeded (402), rate_limited (429)
623
+ setStatus(data.message) // "Thanks! Check your inbox and click the link to confirm your subscription."
624
+ }
625
+ return (
626
+ <form onSubmit={onSubmit}>
627
+ <input name="email" type="email" placeholder="you@example.com" required />
628
+ <button type="submit">Subscribe</button>
629
+ {status && <p>{status}</p>}
630
+ </form>
631
+ )
632
+ }
633
+ ```
634
+
635
+ - Ready-made UI: `<NewsletterSignup list="newsletter" tags={['footer']} />` from `@usebecky/ui`.
636
+ - Swift / Kotlin apps: `baas.newsletter.subscribe(email:list:name:tags:captchaToken:)` / `baas.newsletter.subscribe(email = ..., ...)` (`ios.md`, `android.md`). Other stacks: `POST /newsletter/v1/subscribe` with `apikey: ub_pk_...` (`http-api.md`).
637
+ - No JavaScript: `<form action="<api url>/newsletter/v1/subscribe?apikey=<publishable key>" method="POST">` with `email` (and optional `name`, `list`, `tags`) inputs plus a hidden `_gotcha` spam-trap input shows a hosted "Check your inbox" page. Copy it from Dashboard → Newsletter → Subscribers → Add a signup form.
638
+ - Webhooks: `newsletter.subscribed` and `newsletter.unsubscribed` (`event.data = { list, subscriber, reason?, campaign_id? }`).
639
+ - Before the first campaign the developer must set a postal address (Newsletter → Settings), else `postal_address_required`. Only `subscribed` people get campaigns; people who left are never emailed, imported or re-added.
640
+
641
+ ## 14. Push notifications: `baas.push`
642
+
643
+ Notifications to iOS (APNs), Android (FCM) and browsers (Web Push). Credentials (Apple `.p8` key, Firebase service-account JSON) are added by the developer in Dashboard → Push notifications → Setup; Web Push keys are generated per project. Devices belong to users: register after sign-in. Sending is server-side (secret key) or from the dashboard. No table or policy needed (devices live in the `push` schema, not readable through the REST API).
644
+
645
+ | Method | Returns (`data`) | Notes |
646
+ |---|---|---|
647
+ | `register({ platform: 'ios' \| 'android' \| 'web', token, appId?, locale?, tags? })` | `PushDevice` `{ id, user_id, platform, token_preview, app_id, locale, tags, created_at, last_seen_at, created }` | Signed-in user required (`not_signed_in` 401). Upsert: call on every app start and on token refresh. iOS token = hex text; web token = the `PushSubscription`. `tags` (≤ 10) left out keeps the current ones. |
648
+ | `unregister(token?)` | `{ removed }` | No argument: the token registered last on this device. `auth.signOut()` calls it automatically. |
649
+ | `subscribeWebPush(serviceWorkerRegistration, { tags?, locale? })` | `PushDevice` | Websites: asks permission (call from a click), subscribes with the project's VAPID key, registers. Errors: `push_not_supported`, `permission_denied`, `push_subscribe_failed`. Needs https or localhost. |
650
+ | `unsubscribeWebPush(serviceWorkerRegistration)` | `{ removed }` | |
651
+ | `getConfig()` | `{ web: { vapid_public_key }, platforms: { ios, android, web } }` | Which platforms are set up. |
652
+ | server `push.send({ userIds?, tag?, title, body, url?, data? })` | `PushMessage` `{ id, status: 'queued', devices, sent, failed, stats: { ios, android, web }, ... }` | `usebecky/server`, secret key, `202`. Neither `userIds` nor `tag` → every device. `title` ≤ 200, `body` ≤ 2000, `url` = https link or deep link (`com.example.mynotes://orders/42`), `data` ≤ 2 KB (values arrive as strings; reserved keys `aps`, `from`, `notification`, `message_type`, `collapse_key`, `url`, `title`, `body`, `google.*`, `gcm.*`). `quota_exceeded` (402) per matching device count. |
653
+ | server `push.getMessage(id)` | `PushMessage` with `status` `'sending' \| 'sent' \| 'failed'` and per-platform `{ sent, failed, pending }` | Delivery runs in the background (retries, invalid tokens removed). |
654
+ | server `push.registerDevice({ userId, platform, token, ... })` | `{ id, created }` | Register a token for a user from the server. |
655
+
656
+ ```js
657
+ // public/sw.js: the service worker shows Web Push notifications. The payload is { title, body, url, data }.
658
+ self.addEventListener('push', (event) => {
659
+ const n = event.data ? event.data.json() : {}
660
+ event.waitUntil(self.registration.showNotification(n.title ?? 'New notification', { body: n.body, data: { url: n.url ?? '/' } }))
661
+ })
662
+ self.addEventListener('notificationclick', (event) => {
663
+ event.notification.close()
664
+ event.waitUntil(self.clients.openWindow(event.notification.data.url))
665
+ })
666
+ ```
667
+
668
+ ```ts
669
+ // inside an async function:
670
+ // Browser, from a click, after sign-in
671
+ const registration = await navigator.serviceWorker.register('/sw.js')
672
+ const { error } = await baas.push.subscribeWebPush(registration, { tags: ['news'] })
673
+ if (error) alert(error.message) // push_not_supported, permission_denied, push_subscribe_failed
674
+ ```
675
+
676
+ ```ts
677
+ // Server only (secret key), e.g. after an order ships
678
+ import { baas } from 'usebecky/server'
679
+
680
+ export async function notifyShipped(order: { id: number; user_id: string }) {
681
+ const { data, error } = await baas.push.send({ userIds: [order.user_id], title: 'Your order shipped', body: 'It arrives Tuesday.', url: `com.example.mynotes://orders/${order.id}`, data: { orderId: String(order.id) } })
682
+ if (error) console.error(error.code, error.message) // quota_exceeded (402), ...
683
+ return data // PushMessage: { id, status: 'queued', devices, ... }
684
+ }
685
+ ```
686
+
687
+ - Native apps: Swift `try await baas.registerForPush(deviceToken:)` in `didRegisterForRemoteNotificationsWithDeviceToken`; Kotlin `baas.registerPushToken(token)` in `FirebaseMessagingService.onNewToken` (see ios.md / android.md references). The tapped notification's link arrives as `url` (iOS `userInfo["url"]`, Android `data["url"]`).
688
+ - React Native / Expo: register the native token from `Notifications.getDevicePushTokenAsync()` with `baas.push.register({ platform: Platform.OS, token: data })` (not the Expo push token).
689
+ - Plan limit `push_notifications_per_month`: Free 100, Pro 10,000, Business 200,000, the team's total across its projects (one per device delivered; dashboard test sends are free).
690
+
691
+ ## 15. Scheduled jobs and database webhooks (dashboard features, no SDK calls)
692
+
693
+ Run a database function or call your server on a schedule (cron), and POST row changes to your server: set up in the dashboard or with the platform API. Your server verifies the signed calls with `verifyEvent(rawBody, signatureHeader, secret)` from `usebecky/server`. Everything (schedules, SQL example, verification, platform API, plan limits): `scheduled-jobs.md`.
694
+
695
+ ### Functions: `baas.functions`
696
+
697
+ Your own code running on usebecky (no server needed; writing, deploying, triggers: `functions.md`).
698
+
699
+ ```ts
700
+ // inside an async function:
701
+ // Browser/app client: publishable key + the signed-in user's token (ctx.user in the function).
702
+ const { data, error } = await baas.functions.invoke('send-welcome', { body: { plan: 'pro' } }) // → parsed JSON, or text
703
+ // Options: method ('POST' default), headers, query ({ page: 2 }), path ('/orders/42'), responseType ('text' | 'blob'), signal
704
+ if (error) console.error(error.code) // function_error, function_timeout, function_busy (429), not_signed_in, secret_key_required, function_not_found
705
+ console.log(data)
706
+ ```
707
+
708
+ From `usebecky/server`: `baas.functions.invoke(...)` uses the secret key ("servers only" functions), `baas.as(req).functions.invoke(...)` calls as that user. Types for writing one: `FunctionHandler`, `FunctionContext`, `FunctionUser` from `usebecky/server`.
709
+
710
+ ## 16. Recipes
711
+
712
+ Whole files, ready to copy. The browser client is the `baas` export of `src/lib/usebecky.ts`; server files import `baas` from `usebecky/server`.
713
+
714
+ ```tsx
715
+ // src/GoogleSignIn.tsx: current user + Google sign-in. Enable Google in Dashboard → Auth → Sign-in methods first,
716
+ // or the redirect shows provider_disabled. Redirect URLs must be allowed (default: http://localhost:*).
717
+ import { useEffect, useState } from 'react'
718
+ import type { User } from 'usebecky'
719
+ import { baas } from './lib/usebecky'
720
+
721
+ export function useUser() {
722
+ const [user, setUser] = useState<User | null>(baas.auth.getSession().data.session?.user ?? null)
723
+ useEffect(() => baas.auth.onAuthStateChange((_event, session) => setUser(session?.user ?? null)), [])
724
+ return user
725
+ }
726
+
727
+ export function GoogleSignIn() {
728
+ const user = useUser()
729
+ if (user) return <p>Signed in as {user.email}</p>
730
+ return <button onClick={() => baas.auth.signInWith('google', { redirectTo: `${location.origin}/notes` })}>Continue with Google</button>
731
+ }
732
+ ```
733
+
734
+ ```tsx
735
+ // src/Notes.tsx: own notes, live. Needs the policies above and realtime enabled for "notes".
736
+ import { useEffect, useState } from 'react'
737
+ import { baas } from './lib/usebecky'
738
+
739
+ type Note = { id: string; title: string }
740
+
741
+ export function Notes() {
742
+ const [notes, setNotes] = useState<Note[]>([])
743
+ const [error, setError] = useState<string | null>(null)
744
+ useEffect(() => {
745
+ const load = async () => {
746
+ const { data, error } = await baas.from('notes').select('id, title').order('created_at', { ascending: false })
747
+ if (error) return setError(error.message)
748
+ setNotes(data)
749
+ }
750
+ load()
751
+ return baas.realtime.subscribe('notes', () => load()) // subscribe() returns the unsubscribe function
752
+ }, [])
753
+ if (error) return <p role="alert">{error}</p>
754
+ return <ul>{notes.map((note) => <li key={note.id}>{note.title}</li>)}</ul>
755
+ }
756
+ ```
757
+
758
+ ```tsx
759
+ // app/notes/page.tsx (Next.js server component): await cookies() before passing it
760
+ import { cookies } from 'next/headers'
761
+ import { redirect } from 'next/navigation'
762
+ import { baas } from 'usebecky/server'
763
+
764
+ type Note = { id: string; title: string }
765
+
766
+ export default async function NotesPage() {
767
+ const jar = await cookies()
768
+ if (!(await baas.auth.getUser(jar))) redirect('/login')
769
+ const { data } = await baas.as(jar).from('notes').select('id, title')
770
+ const notes: Note[] = data ?? []
771
+ return <ul>{notes.map((note) => <li key={note.id}>{note.title}</li>)}</ul>
772
+ }
773
+ ```
774
+
775
+ ```ts
776
+ // app/api/notes/route.ts (Next.js route handler)
777
+ import { baas } from 'usebecky/server'
778
+
779
+ export async function POST(request: Request) {
780
+ const user = await baas.auth.getUser(request)
781
+ if (!user) return Response.json({ error: { code: 'not_signed_in', message: 'Sign in first.' } }, { status: 401 })
782
+ const { title } = await request.json()
783
+ const { data, error } = await baas.as(request).from('notes').insert({ title }).select().single()
784
+ if (error) return Response.json({ error }, { status: error.status || 500 })
785
+ return Response.json(data, { status: 201 })
786
+ }
787
+ ```
788
+
789
+ ```sql
790
+ -- Paywall rows in SQL; the UI only mirrors it with payments.hasAccess('pro').
791
+ create policy "Free lessons, or Pro" on public.lessons for select to anon, authenticated using (not premium or billing.has_access('pro'));
792
+ ```
793
+
794
+ ```ts
795
+ // inside an async function:
796
+ // Avatar upload: public bucket "avatars" + the "user_folder" policy preset. The first folder must be the user's id.
797
+ const user = baas.auth.getSession().data.session?.user
798
+ const file = document.querySelector<HTMLInputElement>('#avatar')?.files?.[0]
799
+ if (user && file) {
800
+ const { error } = await baas.storage.from('avatars').upload(`${user.id}/avatar.png`, file, { upsert: true, contentType: file.type })
801
+ if (error) alert(error.message)
802
+ }
803
+ ```
804
+
805
+ ```ts
806
+ // app/api/usebecky-events/route.ts: webhooks from usebecky (Next.js; server only, needs USEBECKY_WEBHOOK_SECRET)
807
+ import { baas } from 'usebecky/server'
808
+
809
+ baas.events.on('subscription.created', async (event) => {
810
+ console.log(event.data.user_id, event.data.subscription.product_key)
811
+ })
812
+ export const POST = baas.events.fetchHandler()
813
+ // Express: mount BEFORE express.json(): app.post('/api/usebecky-events', baas.events.handler())
814
+ ```
815
+
816
+ ## CLI (`npx usebecky`)
817
+
818
+ | Command | Does |
819
+ |---|---|
820
+ | `init` | Pick or create a project and connect the app in this folder. JavaScript: detect the framework, write `.env.local`/`.env`, git-ignore it, create the client file. iOS (Xcode project, `Package.swift`) / Android (Gradle): print the Swift/Kotlin client code with the Project URL and publishable key; writes nothing and never shows the secret key. A folder with none of these: explains and stops |
821
+ | `create` | Make a new app from a starter, connected to a project (same as `npm create usebecky@latest`) |
822
+ | `functions` | `new <name> [--template <id>]` writes `usebecky/functions/<name>.ts`; `deploy [name...]` bundles with the app's esbuild and deploys (a new version each time); `list`; `logs [name] [--errors]`; `secrets set NAME=value ...`, `secrets list`, `secrets unset NAME` (`functions.md`) |
823
+ | `login` / `logout` | Dashboard account: `login` opens the browser to sign in (any account: Google, GitHub, password, passkey, two-factor); `--no-browser` only prints the link, `--email` asks for email and password in the terminal. Token in `~/.usebecky/config.json`; CI: `USEBECKY_ACCESS_TOKEN` |
824
+ | `projects` | List projects |
825
+ | `types` | Write `usebecky.types.ts` (`--out <file>`) |
826
+ | `open` | Open the dashboard for the linked project |
827
+ | `status` | Show the linked project; check the API and key |
828
+ | `analytics` | Put the visitor analytics tag in a website's `<head>` (`--key`, `--dry-run`) |
829
+ | `db new <name>` / `db push` / `db pull` / `db diff` | Schema migrations as SQL files in `usebecky/migrations/<version>_<name>.sql`: `new` creates a file; `push` applies the files the project doesn't have yet, oldest first, all in one transaction (`--dry-run` checks only; refuses while the database has dashboard changes that aren't in a migration: run `db pull` first, or `--force`); `pull` saves dashboard changes as a migration and writes every recorded migration the folder lacks; `diff` prints the unsaved dashboard changes as SQL. Migrations run as the project owner (like the SQL editor; no `begin`/`commit` inside, `create extension vector` is allowed) |
830
+ | `config pull` / `config push` | The project's settings in `usebecky/config.json`: `auth` (site_url, redirect_urls, signup_enabled, email_password, magic_link, mfa, providers.<name>), `captcha`, `emails` (from_name, from_email, reply_to, default_locale, locales, templates.<signup\|magiclink\|recovery\|invite\|email_change\|welcome\|order_…>.<locale> {subject, heading, body, button_text, footer}, welcome `enabled`), `storage.buckets.<id>` (public, file_size_limit, allowed_mime_types, presets), `realtime.tables`, `analytics` (enabled, goals, allowed_hosts, switches), `payments.products.<key>` (name, type, features, download, prices.<key> {amount in cents, currency, interval, trial_days}). `pull` writes it (never secrets; `--force` replaces a changed file); `push` applies only what the file names, nothing is deleted (`--dry-run` lists the changes). Secrets as `"${NAME}"`: from the environment, else `.env.local` / `.env` |
831
+ | `push [--dry-run] [-y]` / `push --github` | One release: `db push`, `config push`, `functions deploy`, `deploy --prod`, only what the folder has (migrations, config.json, functions, hosting.json), in that order; stops at the first error. `--github` writes `.github/workflows/usebecky-push.yml` (main: `push -y`, pull requests: `--dry-run`) and prints the token scopes it needs |
832
+ | `tokens list\|create <name> --scope db,config [--expires <days>]\|delete <name>` | Project tokens for CI: `USEBECKY_ACCESS_TOKEN=ubpt_…` instead of `login`. Scopes `db`, `config`, `functions`, `deploy`, `admin` (admin: owners/admins make it). Shown once; one project only |
833
+ | `payments connect [test\|live]` | Connect Stripe: opens Stripe's sign-in (the user must approve there; it can't be skipped) and waits until connected; default live when the server takes live payments (one sign-in also connects test) |
834
+ | `payments mode [live\|test]` / `payments products` | Show or switch the payments mode (live: owners/admins, the live Stripe account connected first); list products and prices |
835
+ | `emails domains list\|add\|check\|remove <domain>` | Send emails from your own domain (paid plans): `add` prints the DNS records; `add <domain> --dns cloudflare` writes them at Cloudflare with `CLOUDFLARE_API_TOKEN` from the environment ("Edit zone DNS" token) and checks them |
836
+ | `ai` (alias `skill`) | Install this skill into `.claude/skills/usebecky/` and an `AGENTS.md` section whose rules fit the app (JavaScript, Swift or Kotlin); `--force` overwrites edited files. Works without a `package.json` (Xcode / Android Studio projects): `npx usebecky@latest ai` |
837
+
838
+ Flags: `--api-url <url>` (env `USEBECKY_API_URL`), `--project <ref>`, `--yes`.