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.
- package/README.md +80 -2
- package/dist/create.js +842 -0
- package/dist/extension-skill/usebecky-extension/SKILL.md +181 -0
- package/dist/extension-skill/usebecky-extension/references/accounts.md +125 -0
- package/dist/extension-skill/usebecky-extension/references/dev-server.md +102 -0
- package/dist/extension-skill/usebecky-extension/references/manifest.md +104 -0
- package/dist/extension-skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
- package/dist/extension-skill/usebecky-extension/references/partner-api.md +87 -0
- package/dist/extension-skill/usebecky-extension/references/submit-and-pricing.md +31 -0
- package/dist/extension-skill/usebecky-extension/references/ui.md +172 -0
- package/dist/extension-skill/usebecky-extension/references/webhooks.md +97 -0
- package/dist/index.js +10 -0
- package/dist/keys.js +72 -0
- package/dist/platform.js +104 -0
- package/dist/pm.js +69 -0
- package/dist/prompts.js +242 -0
- package/dist/scaffold.js +108 -0
- package/dist/setup.js +130 -0
- package/dist/shared/ai.js +203 -0
- package/dist/shared/extension-skill.js +107 -0
- package/dist/shared/framework.js +460 -0
- package/dist/shared/hosted.js +8 -0
- package/dist/shared/ui.js +141 -0
- package/dist/skill/usebecky/SKILL.md +339 -0
- package/dist/skill/usebecky/references/access-rules.md +307 -0
- package/dist/skill/usebecky/references/addons.md +68 -0
- package/dist/skill/usebecky/references/analytics.md +166 -0
- package/dist/skill/usebecky/references/android.md +434 -0
- package/dist/skill/usebecky/references/auth.md +379 -0
- package/dist/skill/usebecky/references/cache.md +51 -0
- package/dist/skill/usebecky/references/components.md +127 -0
- package/dist/skill/usebecky/references/emails.md +105 -0
- package/dist/skill/usebecky/references/expo.md +147 -0
- package/dist/skill/usebecky/references/functions.md +99 -0
- package/dist/skill/usebecky/references/hosting.md +119 -0
- package/dist/skill/usebecky/references/http-api.md +233 -0
- package/dist/skill/usebecky/references/ios.md +355 -0
- package/dist/skill/usebecky/references/payments.md +493 -0
- package/dist/skill/usebecky/references/realtime.md +143 -0
- package/dist/skill/usebecky/references/scheduled-jobs.md +82 -0
- package/dist/skill/usebecky/references/sdk.md +838 -0
- package/dist/skill/usebecky/references/storage.md +210 -0
- package/dist/skill/usebecky/references/templates.md +191 -0
- package/dist/skill/usebecky/references/wordpress.md +87 -0
- package/dist/templates.js +74 -0
- package/package.json +37 -4
- package/templates/expo/App.tsx +48 -0
- package/templates/expo/README.md +59 -0
- package/templates/expo/_env.example +4 -0
- package/templates/expo/_gitignore +12 -0
- package/templates/expo/app.json +25 -0
- package/templates/expo/assets/icon.png +0 -0
- package/templates/expo/brand.ts +7 -0
- package/templates/expo/components/Avatar.tsx +75 -0
- package/templates/expo/components/ui.tsx +57 -0
- package/templates/expo/index.ts +4 -0
- package/templates/expo/lib/theme.ts +43 -0
- package/templates/expo/lib/usebecky.ts +15 -0
- package/templates/expo/package.json +29 -0
- package/templates/expo/screens/Home.tsx +187 -0
- package/templates/expo/screens/SignIn.tsx +112 -0
- package/templates/expo/tsconfig.json +6 -0
- package/templates/expo/usebecky.template.json +36 -0
- package/templates/extension/README.md +128 -0
- package/templates/extension/_env.example +21 -0
- package/templates/extension/_gitignore +11 -0
- package/templates/extension/logo.svg +1 -0
- package/templates/extension/package.json +25 -0
- package/templates/extension/src/accounts.ts +90 -0
- package/templates/extension/src/app.ts +178 -0
- package/templates/extension/src/pages.ts +108 -0
- package/templates/extension/src/replay-guard.ts +17 -0
- package/templates/extension/src/server.ts +57 -0
- package/templates/extension/src/settings.ts +69 -0
- package/templates/extension/src/ui.ts +70 -0
- package/templates/extension/test/app.test.ts +222 -0
- package/templates/extension/tsconfig.json +16 -0
- package/templates/extension/usebecky-extension.json +36 -0
- package/templates/extension/usebecky.template.json +22 -0
- package/templates/landing/README.md +43 -0
- package/templates/landing/_env.example +4 -0
- package/templates/landing/_gitignore +9 -0
- package/templates/landing/index.html +16 -0
- package/templates/landing/package.json +28 -0
- package/templates/landing/public/icon.svg +1 -0
- package/templates/landing/src/App.tsx +97 -0
- package/templates/landing/src/components/Contact.tsx +43 -0
- package/templates/landing/src/components/Counter.tsx +34 -0
- package/templates/landing/src/components/Feedback.tsx +36 -0
- package/templates/landing/src/components/Logo.tsx +11 -0
- package/templates/landing/src/components/Receipt.tsx +128 -0
- package/templates/landing/src/components/Setup.tsx +20 -0
- package/templates/landing/src/components/fields.tsx +63 -0
- package/templates/landing/src/content.ts +22 -0
- package/templates/landing/src/index.css +119 -0
- package/templates/landing/src/lib/usebecky.ts +11 -0
- package/templates/landing/src/lib/waitlist.ts +46 -0
- package/templates/landing/src/main.tsx +12 -0
- package/templates/landing/src/vite-env.d.ts +6 -0
- package/templates/landing/tsconfig.json +19 -0
- package/templates/landing/usebecky.template.json +20 -0
- package/templates/landing/vite.config.ts +10 -0
- package/templates/notes/README.md +68 -0
- package/templates/notes/_env.example +4 -0
- package/templates/notes/_gitignore +9 -0
- package/templates/notes/index.html +15 -0
- package/templates/notes/package.json +28 -0
- package/templates/notes/public/icon.svg +1 -0
- package/templates/notes/src/App.tsx +35 -0
- package/templates/notes/src/brand.ts +7 -0
- package/templates/notes/src/components/Composer.tsx +113 -0
- package/templates/notes/src/components/NoteEntry.tsx +151 -0
- package/templates/notes/src/components/Notes.tsx +163 -0
- package/templates/notes/src/components/Setup.tsx +44 -0
- package/templates/notes/src/components/SignIn.tsx +112 -0
- package/templates/notes/src/components/icons.tsx +54 -0
- package/templates/notes/src/index.css +105 -0
- package/templates/notes/src/lib/notes.ts +68 -0
- package/templates/notes/src/lib/usebecky.ts +9 -0
- package/templates/notes/src/main.tsx +22 -0
- package/templates/notes/src/vite-env.d.ts +6 -0
- package/templates/notes/tsconfig.json +19 -0
- package/templates/notes/usebecky.template.json +34 -0
- package/templates/notes/vite.config.ts +10 -0
- package/templates/saas/README.md +69 -0
- package/templates/saas/_env.example +10 -0
- package/templates/saas/_gitignore +11 -0
- package/templates/saas/app/(app)/account/ManageBilling.tsx +26 -0
- package/templates/saas/app/(app)/account/page.tsx +71 -0
- package/templates/saas/app/(app)/dashboard/Projects.tsx +227 -0
- package/templates/saas/app/(app)/dashboard/page.tsx +21 -0
- package/templates/saas/app/(app)/layout.tsx +29 -0
- package/templates/saas/app/(app)/premium/page.tsx +62 -0
- package/templates/saas/app/auth/callback/page.tsx +33 -0
- package/templates/saas/app/globals.css +143 -0
- package/templates/saas/app/icon.svg +1 -0
- package/templates/saas/app/layout.tsx +20 -0
- package/templates/saas/app/page.tsx +87 -0
- package/templates/saas/app/pricing/Plans.tsx +133 -0
- package/templates/saas/app/pricing/TestCardHint.tsx +18 -0
- package/templates/saas/app/pricing/page.tsx +21 -0
- package/templates/saas/app/setup/page.tsx +34 -0
- package/templates/saas/app/sign-in/SignInForm.tsx +195 -0
- package/templates/saas/app/sign-in/page.tsx +21 -0
- package/templates/saas/brand.ts +10 -0
- package/templates/saas/components/AppNav.tsx +45 -0
- package/templates/saas/components/Logo.tsx +22 -0
- package/templates/saas/components/SiteHeader.tsx +50 -0
- package/templates/saas/components/Status.tsx +15 -0
- package/templates/saas/lib/session.ts +26 -0
- package/templates/saas/lib/usebecky.ts +11 -0
- package/templates/saas/next-env.d.ts +5 -0
- package/templates/saas/next.config.ts +5 -0
- package/templates/saas/package.json +26 -0
- package/templates/saas/postcss.config.mjs +3 -0
- package/templates/saas/tsconfig.json +21 -0
- package/templates/saas/usebecky.template.json +31 -0
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
# HTTP API (non-JS stacks, curl, debugging)
|
|
2
|
+
|
|
3
|
+
Use this when the app is not JavaScript, Swift or Kotlin (Python, Go, Ruby, PHP, ...) or to debug with curl. The JS, Swift (`ios.md`) and Kotlin (`android.md`) SDKs wrap exactly these endpoints; prefer them in those languages.
|
|
4
|
+
|
|
5
|
+
## Basics
|
|
6
|
+
|
|
7
|
+
- Base URL: the project URL (`USEBECKY_URL`, `https://api.usebecky.com`, or the project's custom domain like `https://api.myapp.com` once it is live: Pro/Business, Dashboard → Settings → Custom domain; same paths and keys, the usebecky URL keeps working). JSON in, JSON out. CORS is open for the data-plane endpoints below.
|
|
8
|
+
- Every request sends the project key: header `apikey: <key>` (or `?apikey=` for WebSockets and links).
|
|
9
|
+
- Publishable key `ub_pk_...` → role `anon` (safe in clients).
|
|
10
|
+
- Secret key `ub_sk_...` → role `service_role` (bypasses RLS, unlocks admin endpoints). Server only.
|
|
11
|
+
- Acting as a user: add `Authorization: Bearer <access_token>` (from sign-in). The user's role (`authenticated`) overrides the key's role, so secret key + user token still applies RLS.
|
|
12
|
+
- Errors, every endpoint: `{"error": {"code": "snake_case", "message": "Plain English.", "hint": "What to do (optional)."}}` with an HTTP status.
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
export UB_URL="$USEBECKY_URL" UB_KEY="$USEBECKY_PUBLISHABLE_KEY"
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Auth `/auth/v1`
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
# Sign up → {"user": {...}, "session": {...} | null}
|
|
22
|
+
curl -s "$UB_URL/auth/v1/signup" -H "apikey: $UB_KEY" -H 'content-type: application/json' \
|
|
23
|
+
-d '{"email":"ada@example.com","password":"correct-horse","data":{"name":"Ada"}}'
|
|
24
|
+
|
|
25
|
+
# Sign in → Session {"access_token","token_type":"bearer","expires_in":3600,"expires_at":<unix>,"refresh_token","user"}
|
|
26
|
+
curl -s "$UB_URL/auth/v1/token?grant_type=password" -H "apikey: $UB_KEY" -H 'content-type: application/json' \
|
|
27
|
+
-d '{"email":"ada@example.com","password":"correct-horse"}'
|
|
28
|
+
export UB_TOKEN="<access_token from the response>"
|
|
29
|
+
|
|
30
|
+
# Refresh (refresh tokens are single use: always store the new one)
|
|
31
|
+
curl -s "$UB_URL/auth/v1/token?grant_type=refresh_token" -H "apikey: $UB_KEY" -H 'content-type: application/json' -d '{"refresh_token":"<refresh_token>"}'
|
|
32
|
+
|
|
33
|
+
# Current user, update user, sign out
|
|
34
|
+
curl -s "$UB_URL/auth/v1/user" -H "apikey: $UB_KEY" -H "Authorization: Bearer $UB_TOKEN"
|
|
35
|
+
curl -s -X PUT "$UB_URL/auth/v1/user" -H "apikey: $UB_KEY" -H "Authorization: Bearer $UB_TOKEN" -H 'content-type: application/json' -d '{"data":{"name":"Ada L."}}'
|
|
36
|
+
curl -s -X POST "$UB_URL/auth/v1/logout?scope=local" -H "apikey: $UB_KEY" -H "Authorization: Bearer $UB_TOKEN" # 204; scope=global|others
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
| Method & path | Body | Response |
|
|
40
|
+
|---|---|---|
|
|
41
|
+
| `GET /settings` | | `{signup_enabled, email_password, magic_link, providers:{google,github,apple}, mfa_totp, site_url, captcha: {provider, site_key, features} \| null}` |
|
|
42
|
+
| `POST /magiclink` | `{email, redirect_to?, create_user?}` | `{}` (email with link + 6-digit code) |
|
|
43
|
+
| `POST /verify` | `{email, token: "<6-digit code>", type: "magiclink"\|"signup"\|"recovery"\|"invite"\|"email_change"}` | Session |
|
|
44
|
+
| `POST /recover` | `{email, redirect_to?}` | `{}` |
|
|
45
|
+
| `POST /resend` | `{email, type: "signup"\|"magiclink"}` | `{}` |
|
|
46
|
+
| `GET /authorize?provider=google&redirect_to=<url>&apikey=<key>&code_challenge=<challenge>&code_challenge_method=S256` | browser navigation | PKCE (use it in apps): 302 to the provider; back to `redirect_to?code=<one-time code>` (no tokens in the URL; errors: `?error=access_denied&error_code=...&error_description=...`). Bad challenge → 400 `invalid_code_challenge` / `invalid_code_challenge_method`. Without `code_challenge` (older flow): back to `redirect_to#access_token=...&refresh_token=...&expires_in=...&expires_at=...&token_type=bearer` (errors in the `#fragment`) |
|
|
47
|
+
| `POST /token?grant_type=pkce` | `{auth_code, code_verifier}` | Session, like `grant_type=password`. Code verifier = 32 random bytes, base64url without padding (43 chars); challenge = base64url-no-padding(SHA-256(verifier)). Codes work once, within 5 minutes: 400 `auth_code_required`, `invalid_code_verifier`, `invalid_auth_code` |
|
|
48
|
+
| `POST /factors` | `{factor_type: "totp", friendly_name?}` | `{id, type, totp: {secret, uri}}` |
|
|
49
|
+
| `POST /factors/:id/verify` | `{code}` | Session with `aal2` |
|
|
50
|
+
| `DELETE /factors/:id` | | `{id}` |
|
|
51
|
+
| `GET /admin/users?page=1&per_page=50&q=` (secret key) | | `{users, total, page, per_page}` |
|
|
52
|
+
| `POST /admin/users` (secret) | `{email, password?, email_confirm?, user_metadata?, app_metadata?}` | 201 User |
|
|
53
|
+
| `GET` / `PUT` / `DELETE /admin/users/:id` (secret) | PUT: `{email?, password?, email_confirm?, user_metadata?, app_metadata?, ban_duration?: "none"\|"24h"\|"forever"\|"<n>h"}` | User / `{id}` |
|
|
54
|
+
| `POST /admin/invite` (secret) | `{email, redirect_to?, data?}` | User |
|
|
55
|
+
| `POST /admin/users/:id/logout` (secret) | | `{ok}` |
|
|
56
|
+
|
|
57
|
+
Verifying a user on your own non-JS server: call `GET /auth/v1/user` with the user's token and your key, and cache the result briefly. 401 means signed out or expired.
|
|
58
|
+
|
|
59
|
+
## Database REST `/rest/v1` (PostgREST-compatible subset, `public` schema)
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
H=(-H "apikey: $UB_KEY" -H "Authorization: Bearer $UB_TOKEN")
|
|
63
|
+
|
|
64
|
+
# Read with columns, filter, order, pagination and total count
|
|
65
|
+
curl -s "$UB_URL/rest/v1/notes?select=id,title,author:profiles(display_name)&archived=eq.false&order=created_at.desc&limit=20&offset=0" \
|
|
66
|
+
"${H[@]}" -H 'Prefer: count=exact' -D - # Content-Range: 0-19/57
|
|
67
|
+
|
|
68
|
+
# Insert and return the row
|
|
69
|
+
curl -s -X POST "$UB_URL/rest/v1/notes" "${H[@]}" -H 'content-type: application/json' -H 'Prefer: return=representation' -d '{"title":"Buy milk"}'
|
|
70
|
+
|
|
71
|
+
# Single object instead of an array (406 not_single_row unless exactly one)
|
|
72
|
+
curl -s "$UB_URL/rest/v1/notes?id=eq.6f1c2a1e-8a43-4c6e-9d55-0b6b1c9e7a10" "${H[@]}" -H 'Accept: application/vnd.pgrst.object+json'
|
|
73
|
+
|
|
74
|
+
# Update / delete (a filter is required unless you use the secret key)
|
|
75
|
+
curl -s -X PATCH "$UB_URL/rest/v1/notes?id=eq.6f1c2a1e-..." "${H[@]}" -H 'content-type: application/json' -d '{"title":"Buy oat milk"}'
|
|
76
|
+
curl -s -X DELETE "$UB_URL/rest/v1/notes?id=eq.6f1c2a1e-..." "${H[@]}"
|
|
77
|
+
|
|
78
|
+
# Upsert
|
|
79
|
+
curl -s -X POST "$UB_URL/rest/v1/profiles?on_conflict=id" "${H[@]}" -H 'content-type: application/json' \
|
|
80
|
+
-H 'Prefer: resolution=merge-duplicates,return=representation' -d '{"id":"0b6f...","display_name":"Ada"}'
|
|
81
|
+
|
|
82
|
+
# Call a function (named arguments)
|
|
83
|
+
curl -s -X POST "$UB_URL/rest/v1/rpc/complete_all_todos" "${H[@]}" -H 'content-type: application/json' -d '{}'
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
- `select`: `id,title`, `*`, embeds `comments(*)`, aliases `author:profiles(name)`, `!inner`, counts `comments(count)`, casts `col::text`, JSON `meta->>color`.
|
|
87
|
+
- Filters: `col=eq.v`, `neq`, `gt`, `gte`, `lt`, `lte`, `like.*milk*`, `ilike`, `is.null|true|false`, `in.(a,b,"c d")`, `cs.{a,b}`, `cd`, `ov`, `fts(english).word` (`plfts`, `phfts`, `wfts`), negation `not.eq.v`, `or=(a.eq.1,b.gt.2)`, `and=(...)`, embedded `comments.approved=eq.true`.
|
|
88
|
+
- `order=created_at.desc.nullslast,id.asc`; `limit`, `offset`, or header `Range: 0-9` (206).
|
|
89
|
+
- `Prefer`: `return=minimal|representation`, `count=exact|planned|estimated`, `resolution=merge-duplicates|ignore-duplicates`, `missing=default`.
|
|
90
|
+
- Status: GET 200 (206 with Range), POST 201, PATCH/DELETE 200 with representation or 204. At most 1000 rows per read; 30 s statement timeout; GET is read-only.
|
|
91
|
+
- `GET /rest/v1/` describes tables and functions. `GET /rest/v1/rpc/<fn>?arg=1` for stable functions.
|
|
92
|
+
|
|
93
|
+
## Storage `/storage/v1`
|
|
94
|
+
|
|
95
|
+
```sh
|
|
96
|
+
# Upload (raw body; x-upsert: true to overwrite) → {"key":"avatars/<path>","id":"<uuid>"}
|
|
97
|
+
curl -s -X POST "$UB_URL/storage/v1/object/avatars/0b6f.../avatar.png" "${H[@]}" -H 'content-type: image/png' --data-binary @avatar.png
|
|
98
|
+
# Download (supports Range)
|
|
99
|
+
curl -s "$UB_URL/storage/v1/object/avatars/0b6f.../avatar.png" "${H[@]}" -o avatar.png
|
|
100
|
+
# Public bucket link (no auth headers)
|
|
101
|
+
curl -s "$UB_URL/storage/v1/object/public/avatars/0b6f.../avatar.png?apikey=$UB_KEY" -o avatar.png
|
|
102
|
+
# Signed link → {"signedURL":"/storage/v1/object/sign/<bucket>/<path>?token=...","url":"<absolute>"}
|
|
103
|
+
curl -s -X POST "$UB_URL/storage/v1/object/sign/documents/0b6f.../report.pdf" "${H[@]}" -H 'content-type: application/json' -d '{"expiresIn":3600}'
|
|
104
|
+
# List a folder
|
|
105
|
+
curl -s -X POST "$UB_URL/storage/v1/object/list/avatars" "${H[@]}" -H 'content-type: application/json' -d '{"prefix":"0b6f...","limit":100,"offset":0}'
|
|
106
|
+
# Delete
|
|
107
|
+
curl -s -X DELETE "$UB_URL/storage/v1/object/avatars" "${H[@]}" -H 'content-type: application/json' -d '{"prefixes":["0b6f.../avatar.png"]}'
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
| Method & path | Notes |
|
|
111
|
+
|---|---|
|
|
112
|
+
| `PUT /object/:bucket/<path>` | upsert |
|
|
113
|
+
| `HEAD /object/:bucket/<path>` | metadata headers |
|
|
114
|
+
| `GET /object/info/:bucket/<path>` | `{id, bucket_id, name, owner, metadata, created_at, updated_at}` |
|
|
115
|
+
| `POST /object/move`, `POST /object/copy` | `{bucketId, sourceKey, destinationKey}` |
|
|
116
|
+
| `POST /object/upload/sign/:bucket/<path>` | `{url, signedURL, token, path}`; then `PUT` the file to `url` without auth |
|
|
117
|
+
| `GET` / `POST /bucket`, `GET` / `PUT` / `DELETE /bucket/:id`, `POST /bucket/:id/empty` | secret key; create body `{id, public?, file_size_limit?, allowed_mime_types?}` |
|
|
118
|
+
|
|
119
|
+
## Payments `/payments/v1`
|
|
120
|
+
|
|
121
|
+
| Method & path | Auth | Body | Response |
|
|
122
|
+
|---|---|---|---|
|
|
123
|
+
| `GET /products` | key | | `[Product]` |
|
|
124
|
+
| `POST /checkout` | user | `{price, success_url?, cancel_url?, quantity?, promotion_codes?}` | `{url, id, livemode}` |
|
|
125
|
+
| `POST /portal` | user | `{return_url?}` | `{url}` |
|
|
126
|
+
| `GET /me` | user | | `{mode, customer_id, subscriptions, purchases, entitlements}` |
|
|
127
|
+
| `GET /access/:feature` | user, or secret key + `?user_id=<uuid>` | | `{access: boolean, source: "subscription"\|"purchase"\|"gift"\|null}` |
|
|
128
|
+
| `GET /downloads/:product_key` | user | | `{url, expires_in}` |
|
|
129
|
+
|
|
130
|
+
## Forms `/forms/v1` and newsletter `/newsletter/v1`
|
|
131
|
+
|
|
132
|
+
For apps and servers in any language (Swift and Kotlin have `baas.forms` / `baas.newsletter`: `ios.md`, `android.md`). Send the publishable key in the `apikey` header and a JSON body. Errors use the usual `{"error": {...}}` shape.
|
|
133
|
+
|
|
134
|
+
```sh
|
|
135
|
+
# Contact form (made in Dashboard → Forms). With the key, address it by key ("contact") or public id ("f_k3x9m2p7q1zt").
|
|
136
|
+
# Body = the field values (names as in the form) + "captcha_token" only when bot protection covers forms.
|
|
137
|
+
curl -s -X POST "$UB_URL/forms/v1/f/contact" -H "apikey: $UB_KEY" -H 'content-type: application/json' \
|
|
138
|
+
-d '{"name":"Ada","email":"ada@example.com","message":"Hi!"}'
|
|
139
|
+
# → 200 {"ok": true, "message": "Thanks! We'll get back to you soon."} (show "message")
|
|
140
|
+
|
|
141
|
+
# The form's fields, e.g. to build the screen → {id, key, name, fields:[{name,label,type,required,options?}], success_message, enabled, submit_url, captcha: {provider, site_key} | null}
|
|
142
|
+
curl -s "$UB_URL/forms/v1/f/contact" -H "apikey: $UB_KEY"
|
|
143
|
+
|
|
144
|
+
# Newsletter sign-up (lists in Dashboard → Newsletter). "list" = list key (default list when left out), tags ≤ 10.
|
|
145
|
+
# Add "Authorization: Bearer <access_token>" when the user is signed in, to link the subscriber to them.
|
|
146
|
+
curl -s -X POST "$UB_URL/newsletter/v1/subscribe" -H "apikey: $UB_KEY" -H 'content-type: application/json' \
|
|
147
|
+
-d '{"email":"ada@example.com","list":"weekly","name":"Ada","tags":["app"]}'
|
|
148
|
+
# → 200 {"status": "pending" | "subscribed", "message": "Thanks! Check your inbox and click the link to confirm your subscription."}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
- `_gotcha` honeypot: plain HTML forms include a hidden, empty `<input name="_gotcha">`. When it is non-empty the server silently drops the message (forms) or stores nothing (newsletter) and still answers success. Apps and servers must not send it (or must leave it empty). Every name starting with `_` is reserved (`_t`, `_page`, `_redirect`).
|
|
152
|
+
- Without a key, a form only accepts its public id (`/forms/v1/f/f_k3x9m2p7q1zt`); a form key without a key → 404 `form_not_found`.
|
|
153
|
+
- Form errors: 400 `validation_failed` (message lists the fields; `details.fields`), 404 `form_not_found`, 403 `form_disabled`, 403 `origin_not_allowed` (the form has "Allowed websites": apps and servers send no Origin, so clear the list), 429 `rate_limited` (5 per minute, 50 per day per visitor and form), 402 `quota_exceeded`, 400 `captcha_required` / `captcha_failed`, 413 `submission_too_large` (over 20 KB), 400 `files_not_supported`. Values: text, numbers, booleans or lists of those, 5,000 characters each.
|
|
154
|
+
- Newsletter errors: 400 `invalid_email`, 404 `list_not_found`, 402 `quota_exceeded`, 429 `rate_limited`, 400 `captcha_required` / `captcha_failed`, 401 `missing_api_key` / `invalid_api_key`. The answer is the same whether or not the address was already on the list.
|
|
155
|
+
- Server-side adding/removing subscribers (secret key): `POST /newsletter/v1/subscribers`, `POST /newsletter/v1/subscribers/unsubscribe` (`sdk.md` section 13). Your own transactional emails: `POST /email/v1/send` (`emails.md`). Scheduled jobs and database webhooks: `scheduled-jobs.md`.
|
|
156
|
+
|
|
157
|
+
## Functions `/functions/v1`
|
|
158
|
+
|
|
159
|
+
Your own code on usebecky (`functions.md`). Any method; send the publishable key (or, for "servers only" functions, the secret key) and, for "signed-in users only" functions, the user's access token:
|
|
160
|
+
|
|
161
|
+
```sh
|
|
162
|
+
curl -s -X POST "$UB_URL/functions/v1/send-welcome" -H "apikey: $UB_KEY" -H "Authorization: Bearer $ACCESS_TOKEN" \
|
|
163
|
+
-H 'content-type: application/json' -d '{"plan":"pro"}'
|
|
164
|
+
# → whatever the function answers (status, headers, body). Extra path and query are passed on: /functions/v1/api/orders/42?page=2
|
|
165
|
+
# Other services that can't send headers: put the publishable key in the URL, ?apikey=ub_pk_...
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Errors (`{"error": {...}}`, `details.invocation_id` to find the run in Dashboard → Logs): 500 `function_error`, 504 `function_timeout`, 500 `function_out_of_memory`, 502 `function_crashed`, 429 `function_busy`, 503 `functions_unavailable`, 404 `function_not_found`, 423 `function_disabled`, 401 `not_signed_in`, 403 `secret_key_required`, 402 `quota_exceeded`, 413 `payload_too_large` (6 MB).
|
|
169
|
+
|
|
170
|
+
## Realtime WebSocket
|
|
171
|
+
|
|
172
|
+
`wss://<host>/realtime/v1/websocket?apikey=<publishable key>&token=<access token, optional>` (`ws://` for `http://`). JSON messages:
|
|
173
|
+
|
|
174
|
+
```jsonc
|
|
175
|
+
// client → server
|
|
176
|
+
{ "type": "subscribe", "id": "sub1", "table": "messages", "event": "*", "filter": "room_id=eq.42" }
|
|
177
|
+
{ "type": "unsubscribe", "id": "sub1" }
|
|
178
|
+
{ "type": "join", "channel": "room:42" }
|
|
179
|
+
{ "type": "broadcast", "channel": "room:42", "event": "typing", "payload": { "name": "Ada" } }
|
|
180
|
+
{ "type": "presence", "channel": "room:42", "state": { "name": "Ada" } } // null to untrack
|
|
181
|
+
{ "type": "leave", "channel": "room:42" }
|
|
182
|
+
{ "type": "access_token", "token": "<new access token>" } // after each refresh
|
|
183
|
+
{ "type": "ping" } // every ~25 s
|
|
184
|
+
// server → client
|
|
185
|
+
{ "type": "subscribed", "id": "sub1" }
|
|
186
|
+
{ "type": "change", "id": "sub1", "table": "messages", "event": "INSERT", "new": { }, "old": null, "commit_timestamp": "..." }
|
|
187
|
+
{ "type": "joined", "channel": "room:42", "presence_key": "c3f1..." }
|
|
188
|
+
{ "type": "broadcast", "channel": "room:42", "event": "typing", "payload": { } }
|
|
189
|
+
{ "type": "presence_state", "channel": "room:42", "state": { "c3f1...": { "name": "Ada" } } }
|
|
190
|
+
{ "type": "error", "id": "sub1", "error": { "code": "realtime_not_enabled", "message": "...", "hint": "..." } }
|
|
191
|
+
{ "type": "pong" }
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
## Verifying webhooks (events) without the SDK
|
|
195
|
+
|
|
196
|
+
Each delivery is a POST with JSON `{id, type, created_at, project, data}` and headers `usebecky-event-id`, `usebecky-event-type` and `usebecky-signature: t=<unix seconds>,v1=<hex>`. `v1` is HMAC-SHA256 over `"<t>.<raw body>"` keyed with the endpoint's full secret string (`whsec_...`). Compare in constant time, reject timestamps more than 300 s away, verify the raw bytes before parsing JSON, respond 2xx quickly (non-2xx is retried after 10s, 1m, 5m, 30m, 2h) and dedupe by `id`.
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
import hashlib, hmac, json, time
|
|
200
|
+
|
|
201
|
+
def verify_usebecky_event(raw_body: bytes, signature_header: str, secret: str, tolerance: int = 300) -> dict:
|
|
202
|
+
timestamp, signatures = None, []
|
|
203
|
+
for part in signature_header.split(','):
|
|
204
|
+
key, _, value = part.strip().partition('=')
|
|
205
|
+
if key == 't':
|
|
206
|
+
timestamp = int(value)
|
|
207
|
+
elif key == 'v1':
|
|
208
|
+
signatures.append(value)
|
|
209
|
+
if timestamp is None or not signatures:
|
|
210
|
+
raise ValueError('malformed usebecky-signature header')
|
|
211
|
+
expected = hmac.new(secret.encode(), f'{timestamp}.'.encode() + raw_body, hashlib.sha256).hexdigest()
|
|
212
|
+
if not any(hmac.compare_digest(expected, s) for s in signatures):
|
|
213
|
+
raise ValueError('invalid signature')
|
|
214
|
+
if abs(time.time() - timestamp) > tolerance:
|
|
215
|
+
raise ValueError('stale signature')
|
|
216
|
+
return json.loads(raw_body)
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
## Managing the project: dashboard and CLI
|
|
220
|
+
|
|
221
|
+
App code never manages the project: never call `/platform/v1` or use the developer's dashboard token from app code or scripts. Run the CLI yourself where it can do the task (it signs in as the developer); tell the user the dashboard steps for the rest:
|
|
222
|
+
|
|
223
|
+
| Task | Where |
|
|
224
|
+
|---|---|
|
|
225
|
+
| Run SQL (tables, policies on public tables, functions, indexes) | `npx usebecky db new <name>`, write the SQL in `usebecky/migrations/`, then `npx usebecky db push` (`--dry-run` first). You run it, not the user |
|
|
226
|
+
| A table plus standard policies | Dashboard → Database → Tables → New table (presets `owner`, `public_read`, `authenticated`, `private`) |
|
|
227
|
+
| File policies | `presets` of the bucket in `usebecky/config.json` (`public_read`, `user_folder`, `authenticated_read`, `authenticated_upload`), or a custom policy in Dashboard → Storage → the bucket |
|
|
228
|
+
| Project settings: auth (site URL, redirect URLs, providers, email confirmation), captcha, buckets and their access presets, realtime tables, analytics, payments products and prices | `npx usebecky config pull`, edit `usebecky/config.json`, `npx usebecky config push --dry-run`, `npx usebecky config push` (secrets as `"${NAME}"`, values in `.env`) |
|
|
229
|
+
| Payments test → live, own email domain | `npx usebecky payments mode live`, `npx usebecky emails domains add mail.example.com` |
|
|
230
|
+
| Check tables and policies | Dashboard → Database → Tables and Access rules; Dashboard → Database → Advisor (RLS off, RLS without policies, missing indexes) |
|
|
231
|
+
| TypeScript types | `npx usebecky types` |
|
|
232
|
+
| Recent API requests and errors | Dashboard → Logs |
|
|
233
|
+
| Which project, which key, is the API reachable | `npx usebecky status` (`npx usebecky projects` lists projects, `npx usebecky open` opens the dashboard) |
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
# iOS / macOS (Swift SDK)
|
|
2
|
+
|
|
3
|
+
Native Swift package `UseBecky` (iOS 15+, macOS 12+, Swift 5.9+, no dependencies). Same HTTP API and error codes as the JS SDK, but idiomatic Swift: `async throws`, `Codable`, `AsyncStream`. Never use the JS SDK, npm packages, `fetch`-style code or Supabase/Firebase APIs in a Swift app. Full API: https://usebecky.com/docs/reference/sdk-swift; beginner walkthrough with complete files: https://usebecky.com/docs/frameworks/ios.
|
|
4
|
+
|
|
5
|
+
## Hard rules
|
|
6
|
+
|
|
7
|
+
1. One client, created once, at file scope: `let baas = UseBecky(url: "https://...", publishableKey: "ub_pk_...")`. Only the publishable key. Never `ub_sk_` in an app (anyone can extract it). Work that needs the secret key (sending push or emails, admin tasks) runs on a server or in the dashboard.
|
|
8
|
+
2. Every call is `try await` and throws `UseBeckyError` (`code`, `message`, `hint`, `status`): always wrap calls in `do { ... } catch { ... }`; there is no `{ data, error }` result in Swift. Show `error.localizedDescription` (message + hint). Ignore `error.isCancelled` (user closed a sheet).
|
|
9
|
+
3. Struct property names must equal column names (`created_at`, `user_id`); no `CodingKeys` needed for snake_case columns. Optional columns must be optional properties. `uuid` → `UUID` (or `String`), `timestamptz` → `Date`, `int4/int8` → `Int`, `numeric/float8` → `Double`, `bool` → `Bool`, `jsonb` → a `Codable` struct or `JSONValue`.
|
|
10
|
+
4. Separate insert structs (`NewNote: Encodable`) without `id`, `created_at`, `user_id`: the database fills them (`user_id uuid default auth.uid()`). Never send `user_id` from the client for owner tables.
|
|
11
|
+
5. Writes return nothing unless you chain `.select()`. To get the row: `.insert(x).select().single().execute()` with a type annotation.
|
|
12
|
+
6. Never filter by user id "for security": RLS does it. Add `.eq(...)` filters to every `update`/`delete`.
|
|
13
|
+
7. Realtime needs the table enabled (`realtime.tables` in `usebecky/config.json`, then `npx usebecky config push`). Storage needs a bucket + rules (Dashboard → Storage → bucket → Who can access → "Users manage their own folder"; paths start with `"\(user.id)/"`).
|
|
14
|
+
8. Social login redirect: default `com.example.mynotes://auth`. 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. Allow it: Dashboard → Settings → General → Your app’s addresses → `com.example.mynotes://**` (a disallowed one shows an error page in the sheet). Register the scheme in Xcode (target → Info → URL Types → + → URL Schemes `com.example.mynotes`). Never a generic scheme like `myapp`.
|
|
15
|
+
9. Checkout/portal URLs open in `SFSafariViewController` (`.safariSheet(url:)`), never `ASWebAuthenticationSession`. Use app links for `successURL`/`cancelURL`/`returnURL` (`com.example.mynotes://checkout/done`, allowed under the same redirect URLs; the server routes them through its `/payments/v1/return` page, which opens the app). Close the sheet in `.onOpenURL` and re-check `hasAccess`.
|
|
16
|
+
10. Xcode 26 projects default to `@MainActor` isolation: plain `struct Note: Codable` works with `execute()` (decoding runs on the caller's actor). Don't add `Sendable` requirements or `nonisolated` to model types to "fix" warnings.
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
1. Xcode → File → Add Package Dependencies… → paste `https://github.com/usebecky/usebecky-swift` → Add Package (Dependency Rule: Up to Next Major Version).
|
|
21
|
+
2. Tick your app target next to **UseBecky** → Add Package. `import UseBecky` in each file that uses it.
|
|
22
|
+
|
|
23
|
+
In a `Package.swift`: `.package(url: "https://github.com/usebecky/usebecky-swift", from: "0.2.0")` and `.product(name: "UseBecky", package: "usebecky-swift")`. Never `npm install` anything in a Swift app, and never clone or build usebecky itself.
|
|
24
|
+
|
|
25
|
+
## Setup
|
|
26
|
+
|
|
27
|
+
```swift
|
|
28
|
+
// Baas.swift
|
|
29
|
+
import UseBecky
|
|
30
|
+
|
|
31
|
+
let baas = UseBecky(url: "https://api.usebecky.com", publishableKey: "ub_pk_...")
|
|
32
|
+
// or: let baas = UseBecky() // Info.plist keys USEBECKY_URL, USEBECKY_PUBLISHABLE_KEY
|
|
33
|
+
// tests/previews: UseBecky(url: ..., publishableKey: ..., options: .init(sessionStorage: MemorySessionStorage()))
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Values: Dashboard → Settings → API keys (Project URL + publishable key). `npx usebecky init` in the app folder prints this file with both filled in and writes nothing.
|
|
37
|
+
|
|
38
|
+
## Auth
|
|
39
|
+
|
|
40
|
+
```swift
|
|
41
|
+
// inside an async throws function:
|
|
42
|
+
let email = "ada@example.com", password = "correct-horse-battery", code = "123456" // from your text fields
|
|
43
|
+
let result = try await baas.auth.signUp(email: email, password: password, data: ["name": "Ada"]) // SignUpResult; result.needsEmailConfirmation
|
|
44
|
+
let session = try await baas.auth.signIn(email: email, password: password) // Session
|
|
45
|
+
try await baas.auth.sendMagicLink(email: email, createUser: true) // email with link + 6-digit code (recommended on mobile)
|
|
46
|
+
try await baas.auth.verifyCode(email: email, code: code) // type: .magiclink (default) | .signup (after signUp confirmation) | .recovery
|
|
47
|
+
try await baas.auth.signInWithApple() // @MainActor; Apple's native sheet + nonce → POST /auth/v1/token?grant_type=id_token. Offer this first
|
|
48
|
+
try await baas.auth.signIn(with: .google, redirectTo: URL(string: "com.example.mynotes://auth")!) // @MainActor; .github, .apple; PKCE built in
|
|
49
|
+
let idToken = "eyJ...", rawNonce = "raw-nonce" // from the Google Sign-In SDK / your own ASAuthorizationAppleIDRequest
|
|
50
|
+
try await baas.auth.signIn(withIdToken: idToken, provider: .google, nonce: rawNonce)
|
|
51
|
+
try await baas.auth.resetPassword(email: email) // then verifyCode(type: .recovery), then updateUser(password:)
|
|
52
|
+
// Bot protection: signUp, signIn(email:password:), sendMagicLink and resetPassword take captchaToken: String? = nil as the last parameter
|
|
53
|
+
try await baas.auth.updateUser(password: "new-long-password") // or email:, data: (merged into userMetadata)
|
|
54
|
+
let user: User? = baas.auth.currentUser // local, no network; also baas.auth.session, baas.auth.isSignedIn
|
|
55
|
+
let fresh: User? = try await baas.auth.user() // fresh from the server
|
|
56
|
+
try await baas.auth.signOut() // always signs out locally
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
- The 6-digit code type must match the email: a sign-up confirmation code needs `type: .signup`, otherwise `otp_expired`.
|
|
60
|
+
- Session lives in the Keychain and refreshes itself (a minute before expiry, on foreground, on `token_expired`). Don't store tokens yourself.
|
|
61
|
+
- `signIn(with:)` throws `provider_disabled` before opening the sheet when the provider is off (Dashboard → Auth → Sign-in methods).
|
|
62
|
+
- PKCE is automatic: `signIn(with:)` sends a code challenge, keeps the verifier in memory for the open `ASWebAuthenticationSession`, and swaps the one-time `?code=` in the redirect for the session (`exchangeCodeForSession(authCode:)` under the hood). No tokens appear in the redirect URL. Errors come back as `?error=...&error_code=...` and are thrown as `UseBeckyError` (e.g. `provider_disabled`, `invalid_auth_code`).
|
|
63
|
+
- Deep links (magic link tapped in Mail, flows you run yourself): `.onOpenURL { url in Task { try? await baas.auth.session(from: url) } }` on the root view (`session(from:)` handles both `?code=` and `#access_token=`).
|
|
64
|
+
- 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.
|
|
65
|
+
- Apple guideline 4.8: offering Google/GitHub usually requires offering Sign in with Apple too. Recommend Sign in with Apple first: native `signInWithApple()` needs no redirect URL at all. Setup: Xcode → target → Signing & Capabilities → + Capability → Sign in with Apple (paid developer team), and Dashboard → Auth → Sign-in methods → Apple → on + bundle ID in "iOS bundle ID / Android client IDs (for native sign-in)". Errors: `apple_sign_in_failed` (capability missing), `provider_not_configured` (no bundle ID), `invalid_id_token` (bundle ID mismatch; message names it). Name: only on first sign-in, saved to `userMetadata["full_name"]`.
|
|
66
|
+
- Own `SignInWithAppleButton`: set `request.nonce` = SHA-256 hex of a random raw nonce, then `signIn(withIdToken: identityToken, provider: .apple, nonce: raw)`.
|
|
67
|
+
|
|
68
|
+
Root view switching (iOS 15+):
|
|
69
|
+
|
|
70
|
+
```swift
|
|
71
|
+
// ContentView.swift
|
|
72
|
+
import SwiftUI
|
|
73
|
+
import UseBecky
|
|
74
|
+
|
|
75
|
+
struct ContentView: View {
|
|
76
|
+
@StateObject private var auth = AuthObserver(baas) // @Published session; auth.user, auth.isSignedIn, auth.lastEvent
|
|
77
|
+
var body: some View {
|
|
78
|
+
if let user = auth.user {
|
|
79
|
+
Text("Hi \(user.email ?? "there")") // your signed-in screen, e.g. NotesView(user: user)
|
|
80
|
+
} else {
|
|
81
|
+
Text("Please sign in") // your sign-in screen, e.g. SignInView()
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
// Without the helper: .task { for await change in baas.auth.authStateChanges { user = change.user } } // first element: .initialSession
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### Passkeys, phone codes, guests, SSO
|
|
89
|
+
|
|
90
|
+
- Passkeys (iOS 16+): `try await baas.auth.signInWithPasskey()` and, signed in, `try await baas.auth.registerPasskey(name:)`; `passkeys()`, `renamePasskey(id:name:)`, `deletePasskey(id:)`. Needs the Associated Domains capability `webcredentials:<site domain>` and an `apple-app-site-association` file on that domain (passkey domain = Dashboard → Auth → Sign-in methods → Passkeys).
|
|
91
|
+
- Phone: `try await baas.auth.signInWithPhone("+491701234567")` then `try await baas.auth.verifyPhone(phone, code:)`; change with `updatePhone` + `verifyPhoneChange`. Free: only dashboard test numbers.
|
|
92
|
+
- Guests: `try await baas.auth.signInAnonymously()`; later `linkEmail(_:password:)`, `linkIdentity(.google, redirectTo:)`, `linkWithApple()` or `registerPasskey()` keep the same user id.
|
|
93
|
+
- More providers: `OAuthProvider.microsoft`, `.discord`, `.gitlab`, `.linkedin`, `.slack`, `.x` with `signIn(with:redirectTo:)`. Company SSO (Business): `try await baas.auth.signInWithSSO(domain: "acme.com", redirectTo:)`.
|
|
94
|
+
|
|
95
|
+
## Database
|
|
96
|
+
|
|
97
|
+
```swift
|
|
98
|
+
// Notes.swift
|
|
99
|
+
import Foundation
|
|
100
|
+
import UseBecky
|
|
101
|
+
|
|
102
|
+
struct Note: Codable, Identifiable { let id: UUID; let created_at: Date; let user_id: String; var title: String; var done: Bool }
|
|
103
|
+
struct NewNote: Encodable { let title: String }
|
|
104
|
+
struct Post: Decodable { let id: UUID; let title: String; let author: Author? } // embedded row from profiles
|
|
105
|
+
struct Author: Decodable { let name: String }
|
|
106
|
+
|
|
107
|
+
func noteQueries() async throws {
|
|
108
|
+
let notes: [Note] = try await baas.from("notes").select().order("created_at", ascending: false).limit(50).execute()
|
|
109
|
+
try await baas.from("notes").insert(NewNote(title: "Buy milk")).execute()
|
|
110
|
+
let note: Note = try await baas.from("notes").insert(NewNote(title: "Buy milk")).select().single().execute()
|
|
111
|
+
try await baas.from("notes").update(["done": true]).eq("id", note.id).execute()
|
|
112
|
+
let maybe: Note? = try await baas.from("notes").select().eq("id", note.id).maybeSingle().execute() // nil when no row matches
|
|
113
|
+
try await baas.from("notes").delete().eq("id", note.id).execute()
|
|
114
|
+
let page = try await baas.from("notes").select("*", count: .exact).range(from: 0, to: 19).executeResponse(as: [Note].self) // page.value, page.count
|
|
115
|
+
let total: Int = try await baas.from("notes").select("*", count: .exact, head: true).executeCount()
|
|
116
|
+
let rows: [JSONObject] = try await baas.from("notes").select("id, title").execute() // untyped
|
|
117
|
+
let score: Int = try await baas.rpc("add_points", params: ["amount": 5]).execute() // Postgres function
|
|
118
|
+
let withAuthor: [Post] = try await baas.from("posts").select("id, title, author:profiles(name)").execute() // embed via FK
|
|
119
|
+
print(notes.count, maybe?.title ?? "-", page.count ?? 0, total, rows.count, score, withAuthor.count)
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Filters: `eq neq gt gte lt lte like ilike("title", "%milk%") is("deleted_at", nil) in("status", ["a","b"]) contains("tags", ["x"]) containedBy overlaps textSearch("body", "cat & dog", config: "english") not("status", "eq", "done") or("a.eq.1,b.eq.2") match(["done": false]) filter(col, op, value)`. Values: `String Int Double Bool UUID Date` and optionals. Modifiers: `order(col, ascending:, nullsFirst:) limit range(from:to:) single() maybeSingle()`. Dictionary literals work for writes: `.insert(["title": "x", "done": false])`; values from variables need wrapping: `["title": .string(title), "count": .int(n)]`.
|
|
124
|
+
|
|
125
|
+
Common errors: `permission_denied` (RLS: missing policy, or anon user), `table_not_found`, `column_not_found`, `decoding_failed` (message names the field: rename the property or make it optional), `empty_response` (decoded a write without `.select()`), `not_single_row` (`single()` matched 0 or 2+ rows: use `maybeSingle()` + optional type).
|
|
126
|
+
|
|
127
|
+
## Storage
|
|
128
|
+
|
|
129
|
+
```swift
|
|
130
|
+
// inside an async throws function:
|
|
131
|
+
guard let user = baas.auth.currentUser else { return } // signed in
|
|
132
|
+
let data = Data() // e.g. try await item.loadTransferable(type: Data.self)
|
|
133
|
+
let path = "\(user.id)/avatar.jpg" // own folder: required by the "user folder" rule
|
|
134
|
+
try await baas.storage.from("photos").upload(path: path, data: data, contentType: "image/jpeg", upsert: true)
|
|
135
|
+
let url = try await baas.storage.from("photos").createSignedURL(path: path, expiresIn: 3600) // private bucket → AsyncImage(url:)
|
|
136
|
+
let publicURL = baas.storage.from("avatars").publicURL(path: path) // public bucket, no network call
|
|
137
|
+
let downloaded = try await baas.storage.from("photos").download(path: path) // Data → UIImage(data:)
|
|
138
|
+
let files = try await baas.storage.from("photos").list(prefix: user.id) // [FileObject]; folders have id == nil
|
|
139
|
+
try await baas.storage.from("photos").remove(paths: [path])
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
PhotosPicker → `try await item.loadTransferable(type: Data.self)` → `upload`. Upload without `upsert: true` to an existing path fails (409). Add `?v=` cache-busting only to public URLs; signed URLs change every time. Errors: `permission_denied`/403 (path not in the user's folder or no rule), 413 (bucket size limit), 415 (MIME type not allowed).
|
|
143
|
+
|
|
144
|
+
Thumbnails (image transformations, server-side resize, cached; never enlarges; 1-2500 px):
|
|
145
|
+
|
|
146
|
+
```swift
|
|
147
|
+
// inside an async throws function:
|
|
148
|
+
let path = "\(baas.auth.currentUser?.id ?? "guest")/avatar.jpg"
|
|
149
|
+
let thumb = ImageTransform(width: 200, height: 200, resize: .cover, quality: 80, format: .webp) // resize: .cover/.contain/.fill; format: .origin/.webp/.avif/.jpeg/.png
|
|
150
|
+
let thumbURL = baas.storage.from("avatars").publicURL(path: path, transform: thumb) // /storage/v1/render/image/public/...
|
|
151
|
+
let signedThumb = try await baas.storage.from("photos").createSignedURL(path: path, expiresIn: 3600, transform: thumb) // size baked into the token
|
|
152
|
+
let small = try await baas.storage.from("photos").download(path: path, transform: ImageTransform(width: 400)) // read access checked like download
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## Push notifications
|
|
156
|
+
|
|
157
|
+
```swift
|
|
158
|
+
// Push.swift
|
|
159
|
+
// Xcode: target → Signing & Capabilities → + Capability → Push Notifications. Real device + paid Apple Developer account.
|
|
160
|
+
import UIKit
|
|
161
|
+
import UserNotifications
|
|
162
|
+
import UseBecky
|
|
163
|
+
|
|
164
|
+
// In the App struct: @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
|
|
165
|
+
final class AppDelegate: NSObject, UIApplicationDelegate {
|
|
166
|
+
func application(_ app: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
|
|
167
|
+
Task {
|
|
168
|
+
try? await baas.registerForPush(deviceToken: deviceToken) // hex-encodes; PushDevice
|
|
169
|
+
// with tags for targeting (nil keeps the current tags):
|
|
170
|
+
// try? await baas.push.register(deviceToken: deviceToken, tags: ["news"])
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// After sign-in, from a .task or a button's Task (wrap it in do/catch there: .task closures don't throw).
|
|
176
|
+
func enablePushNotifications() async throws {
|
|
177
|
+
let ok = try await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])
|
|
178
|
+
if ok { await UIApplication.shared.registerForRemoteNotifications() }
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// signOut() unregisters the device automatically; by hand: try await baas.unregisterFromPush() // Int removed
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Sending is server-side only (`baas.push.send` in `usebecky/server`, secret key) or Dashboard → Push notifications. The APNs .p8 key, Team ID, Key ID and bundle ID go in Dashboard → Push notifications → Setup; builds run from Xcode use the sandbox environment, TestFlight/App Store use production. Check it works: Dashboard → Push notifications → Devices lists the iPhone. Errors: `not_signed_in` (register after sign-in), `invalid_token`.
|
|
185
|
+
|
|
186
|
+
## Forms and newsletter
|
|
187
|
+
|
|
188
|
+
Contact forms (Dashboard → Forms) and newsletter lists (Dashboard → Newsletter): no table, policy or email code needed. Both use the publishable key and throw `UseBeckyError` like every other call.
|
|
189
|
+
|
|
190
|
+
```swift
|
|
191
|
+
// inside an async throws function:
|
|
192
|
+
let name = "Ada", email = "ada@example.com", message = "Hi!" // from your text fields
|
|
193
|
+
|
|
194
|
+
// Contact form: "contact" is the form's key (or its public id "f_..."); value names must match the form's fields
|
|
195
|
+
let r = try await baas.forms.submit(form: "contact", values: ["name": name, "email": email, "message": message], captchaToken: nil)
|
|
196
|
+
print(r.message) // the form's success message: show it ("Thanks! We'll get back to you soon.")
|
|
197
|
+
let form = try await baas.forms.get(form: "contact") // fields [name, label, type, required, options], success message, enabled, captcha
|
|
198
|
+
|
|
199
|
+
// Newsletter sign-up: list nil = the default list; tags ≤ 10
|
|
200
|
+
let s = try await baas.newsletter.subscribe(email: email, list: nil, name: name, tags: ["ios"], captchaToken: nil)
|
|
201
|
+
print(s.status) // .pending (double opt-in: they must click the emailed link) or .subscribed
|
|
202
|
+
print(s.message) // show it; the answer is the same whether or not they were already on the list
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
- 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.
|
|
206
|
+
- 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.
|
|
207
|
+
- Errors (`error.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).
|
|
208
|
+
- Signed in, `subscribe` also sends the user's access token, so the subscriber is linked to the user (when the email matches).
|
|
209
|
+
- 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.
|
|
210
|
+
|
|
211
|
+
## Functions
|
|
212
|
+
|
|
213
|
+
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:
|
|
214
|
+
|
|
215
|
+
```swift
|
|
216
|
+
// inside an async throws function:
|
|
217
|
+
struct Welcome: Decodable { let sent: Bool }
|
|
218
|
+
let reply = try await baas.functions.invoke("send-welcome", body: ["plan": "pro"]) // POST JSON; also method:, headers:, query:, path:
|
|
219
|
+
let result = try reply.decode(Welcome.self) // or reply.text, reply.json(), reply.status
|
|
220
|
+
let typed = try await baas.functions.invoke("send-welcome", body: ["plan": "pro"], as: Welcome.self)
|
|
221
|
+
print(result.sent, typed.sent)
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
- Throws `UseBeckyError`: `function_error` (500, details in Dashboard → Logs), `function_timeout` (504), `function_busy` (429), `not_signed_in` (401, the function is for signed-in users), `secret_key_required` (403, server-only function: never call those from an app), `function_not_found` (404), `quota_exceeded` (402).
|
|
225
|
+
- Your own `Encodable` structs work as `body:` too; raw bytes: `invoke("x", data: data, contentType: "image/jpeg")`.
|
|
226
|
+
|
|
227
|
+
## Realtime
|
|
228
|
+
|
|
229
|
+
```swift
|
|
230
|
+
// LiveNotesView.swift (Note is the struct from Database above)
|
|
231
|
+
import SwiftUI
|
|
232
|
+
import UseBecky
|
|
233
|
+
|
|
234
|
+
struct LiveNotesView: View {
|
|
235
|
+
let user: User
|
|
236
|
+
@State private var notes: [Note] = []
|
|
237
|
+
@State private var message = ""
|
|
238
|
+
|
|
239
|
+
var body: some View {
|
|
240
|
+
List(notes) { note in Text(note.title) }
|
|
241
|
+
.task { // SwiftUI: stops automatically when the view disappears
|
|
242
|
+
do {
|
|
243
|
+
for try await change in baas.realtime.subscribe(table: "notes", event: .all, filter: .eq("user_id", user.id)) {
|
|
244
|
+
// change.event (.insert/.update/.delete), change.new (JSONObject?, nil on delete), change.old (primary key only)
|
|
245
|
+
if let note = try change.decodeNew(as: Note.self) { print("changed:", note.title) }
|
|
246
|
+
await loadNotes() // simplest correct approach: reload
|
|
247
|
+
}
|
|
248
|
+
} catch {
|
|
249
|
+
message = error.localizedDescription // realtime_not_enabled, table_not_found, column_not_found
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
private func loadNotes() async {
|
|
255
|
+
do { notes = try await baas.from("notes").select().order("created_at", ascending: false).execute() }
|
|
256
|
+
catch { message = error.localizedDescription }
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
```swift
|
|
262
|
+
// inside an async throws function:
|
|
263
|
+
let handle = baas.realtime.subscribe(table: "notes", onSubscribed: { print("listening") }) { change in print(change.event) } // callback on the main actor
|
|
264
|
+
handle.cancel() // keep the handle while you listen
|
|
265
|
+
|
|
266
|
+
let room = baas.realtime.channel("room:42") // broadcast + presence
|
|
267
|
+
room.send("typing", payload: ["name": "Ada"])
|
|
268
|
+
room.track(["name": "Ada"])
|
|
269
|
+
let listener = Task { // streams end when the task is cancelled
|
|
270
|
+
for await msg in room.broadcasts(event: "typing") { print(msg.payload["name"]?.stringValue ?? "") }
|
|
271
|
+
}
|
|
272
|
+
let watcher = Task {
|
|
273
|
+
for await everyone in room.presenceChanges() { print(everyone.count) } // [presenceKey: JSONValue]
|
|
274
|
+
}
|
|
275
|
+
listener.cancel(); watcher.cancel()
|
|
276
|
+
room.leave()
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
RLS applies: users only receive rows they can select. One filter per subscription (`eq neq gt gte lt lte in`). Reconnect, resubscribe, token refresh and foreground recovery are automatic; never build your own reconnect loop.
|
|
280
|
+
|
|
281
|
+
## Payments
|
|
282
|
+
|
|
283
|
+
```swift
|
|
284
|
+
// UpgradeView.swift
|
|
285
|
+
import SwiftUI
|
|
286
|
+
import UseBecky
|
|
287
|
+
|
|
288
|
+
struct UpgradeView: View {
|
|
289
|
+
@State private var checkoutURL: URL?
|
|
290
|
+
@State private var isPro = false
|
|
291
|
+
@State private var message = ""
|
|
292
|
+
|
|
293
|
+
var body: some View {
|
|
294
|
+
VStack {
|
|
295
|
+
Button(isPro ? "You have Pro" : "Upgrade to Pro") { Task { await startCheckout() } }
|
|
296
|
+
.disabled(isPro)
|
|
297
|
+
if !message.isEmpty { Text(message) }
|
|
298
|
+
}
|
|
299
|
+
.safariSheet(url: $checkoutURL) { Task { await refreshAccess() } }
|
|
300
|
+
.onOpenURL { url in if url.host == "checkout" { checkoutURL = nil } } // back from Stripe: close the sheet
|
|
301
|
+
.task { await refreshAccess() }
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
private func startCheckout() async {
|
|
305
|
+
do {
|
|
306
|
+
checkoutURL = try await baas.payments.checkoutURL(price: "pro_monthly",
|
|
307
|
+
successURL: URL(string: "com.example.mynotes://checkout/done")!, // arrives with ?session_id=cs_...
|
|
308
|
+
cancelURL: URL(string: "com.example.mynotes://checkout/cancel")!)
|
|
309
|
+
} catch {
|
|
310
|
+
message = error.localizedDescription
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
private func refreshAccess() async {
|
|
315
|
+
isPro = (try? await baas.payments.hasAccess("pro")) ?? false // false when signed out
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
```swift
|
|
321
|
+
// inside an async throws function:
|
|
322
|
+
let products = try await baas.payments.products() // [Product]; product.prices[i].key, .formattedAmount ("$5.00", localized), .amountDecimal (Decimal), .amount (cents)
|
|
323
|
+
let portal = try await baas.payments.portalURL(returnURL: URL(string: "com.example.mynotes://account")) // manage/cancel; open it like checkout
|
|
324
|
+
let billing = try await baas.payments.me() // subscriptions, purchases, entitlements
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
Checkout requires a signed-in user (`not_signed_in` otherwise). Server errors: `stripe_not_connected`, `price_not_found` (hint lists valid keys), `already_subscribed`, `missing_success_url` (pass `successURL` or set a default in Dashboard → Payments → Stripe connection → Checkout settings), `redirect_not_allowed` (app link not in Settings → General → Your app’s addresses). Access appears a few seconds after paying (webhook). Mention App Store rule 3.1 (digital goods) when adding Stripe to an iOS app.
|
|
328
|
+
|
|
329
|
+
## Analytics
|
|
330
|
+
|
|
331
|
+
```swift
|
|
332
|
+
// inside an async throws function:
|
|
333
|
+
let title = "Groceries"
|
|
334
|
+
baas.analytics.screen("NoteDetail") // $pageview with path "/note-detail"; call in .onAppear
|
|
335
|
+
baas.analytics.track("note_created", props: ["length": .int(title.count)]) // name ≤ 100 chars, no "$"; props ≤ 4 KB
|
|
336
|
+
baas.analytics.identify(["plan": "pro"]) // after sign-in; user id attached automatically
|
|
337
|
+
await baas.analytics.flush() // rarely needed; never throws; returns the number sent (0 offline: events stay queued)
|
|
338
|
+
baas.analytics.disable() // consent / opt-out, remembered on device
|
|
339
|
+
baas.analytics.enable() // opt back in
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
Fire-and-forget: never `await` or `try` on `track`/`screen`/`identify`. Batches every 5 s or 20 events; offline events stay queued.
|
|
343
|
+
|
|
344
|
+
## Testing and previews
|
|
345
|
+
|
|
346
|
+
- Previews and unit tests: `MemorySessionStorage()`; never hit production from previews (guard with `ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"]`).
|
|
347
|
+
- Always use the `https://` Project URL (Dashboard → Settings → API keys), in the Simulator and on a real iPhone.
|
|
348
|
+
|
|
349
|
+
## Checklist for a new iOS feature
|
|
350
|
+
|
|
351
|
+
1. Table exists with the right preset/policies; realtime toggled if live; bucket + rule if files.
|
|
352
|
+
2. `Codable` model matching columns + `Encodable` insert struct.
|
|
353
|
+
3. Calls in `do { try await ... } catch { message = error.localizedDescription }`, inside `.task` or `Task { }` from buttons.
|
|
354
|
+
4. Before any `signIn(with:)`: `com.example.mynotes://**` (your bundle ID) allowed and the scheme registered under URL Types. Sign in with Apple needs neither.
|
|
355
|
+
5. Never the secret key, never `user_id` from the client, always `.eq` on update/delete, never `_gotcha` in form values.
|