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,210 @@
1
+ # Storage
2
+
3
+ Files live in buckets. Each file's metadata is a row in `storage.objects` (`bucket_id`, `name` = path inside the bucket, `owner` = uploader's user id, `metadata`), protected by RLS like your tables. Default upload limit: 50 MB per file; a bucket's own `file_size_limit` (up to 5 GB) replaces it, and the plan caps every file (per project: Free 5 MB, Pro 100 MB, Business 5 GB, `quota_exceeded`) and all files together (the team's total across its projects: Free 50 MB, Pro 10 GB, Business 100 GB), and `allowed_mime_types` restricts file types.
4
+
5
+ ## 1. Create the bucket
6
+
7
+ - Dashboard → Storage → New bucket (choose public or private), or on the server with the secret key:
8
+
9
+ ```ts
10
+ // Server only (secret key from USEBECKY_SECRET_KEY)
11
+ import { baas } from 'usebecky/server'
12
+
13
+ const { data, error } = await baas.admin.storage.createBucket('avatars', { public: true, fileSizeLimit: 5 * 1024 * 1024, allowedMimeTypes: ['image/png', 'image/jpeg', 'image/webp'] })
14
+ // data: { id: 'avatars', name: 'avatars', public: true, file_size_limit: 5242880, allowed_mime_types: ['image/png', 'image/jpeg', 'image/webp'], created_at, updated_at }
15
+ ```
16
+
17
+ Bucket ids: letters, digits, `_ . -`, up to 40 characters; not `public`, `sign`, `info`, `list`, `upload`, `move`, `copy`, `authenticated`, `render`. Calling bucket management from the browser fails with `secret_key_required`.
18
+
19
+ Public vs private:
20
+
21
+ | | Public bucket | Private bucket |
22
+ |---|---|---|
23
+ | `getPublicUrl(path)` link | Works for anyone, no policy needed | `bucket_not_public` (403) |
24
+ | `download`, `list`, `upload`, `remove` through the API | Need policies | Need policies |
25
+ | Share a file | Public URL | `createSignedUrl(path, seconds)` |
26
+
27
+ ## 2. Add file policies
28
+
29
+ Without policies nobody (except the secret key) can upload, list or download through the API. Apply a preset per bucket in Dashboard → Storage → bucket → policies:
30
+
31
+ | Preset | Allows |
32
+ |---|---|
33
+ | `public_read` | anyone lists and downloads files in the bucket |
34
+ | `user_folder` | signed-in users upload, download, overwrite and delete files under `<their user id>/...` |
35
+ | `authenticated_read` | signed-in users list and download |
36
+ | `authenticated_upload` | signed-in users upload new files (overwriting also needs an update policy) |
37
+
38
+ Create buckets with their presets in `usebecky/config.json` and run `npx usebecky config push` yourself: `{"storage": {"buckets": {"media": {"public": false, "file_size_limit": 52428800, "allowed_mime_types": ["image/*"], "presets": ["user_folder"]}}}}`. Migrations cannot create policies on `storage.objects`. For custom rules (paid files, file types) use the platform policies API with `"table": "storage.objects"` (`http-api.md`); rule examples are in `access-rules.md` section 11.
39
+
40
+ ## 3. Upload
41
+
42
+ ```ts
43
+ // inside an async function:
44
+ const file = document.querySelector<HTMLInputElement>('input[type=file]')?.files?.[0]
45
+ const user = baas.auth.getSession().data.session?.user
46
+ if (!file || !user) return
47
+ const path = `${user.id}/avatar.png` // user_folder: first folder = user id
48
+ const { data, error } = await baas.storage.from('avatars').upload(path, file, { upsert: true, contentType: file.type, cacheControl: '3600' })
49
+ // data: { path: '0b6f3c2e-.../avatar.png', fullPath: 'avatars/0b6f3c2e-.../avatar.png', id: 'c41e5d2a-...' }
50
+ ```
51
+
52
+ - `file`: `File`, `Blob`, `ArrayBuffer`, typed array or Node `Buffer`, `ReadableStream`, `FormData` or `string`.
53
+ - Without `upsert: true` an existing path fails with `already_exists` (409). With it, the user needs SELECT and UPDATE policies too (`user_folder` has them).
54
+ - Content type: `contentType`, else the file's own type, else guessed from the extension.
55
+ - Unique names avoid collisions: `` `${user.id}/${crypto.randomUUID()}-${file.name}` ``. Store the returned `path` in your table (for example `avatar_path text`), not a URL.
56
+
57
+ ```tsx
58
+ // src/AvatarInput.tsx: a React file input (public "avatars" bucket, user_folder policies)
59
+ import { useState, type ChangeEvent } from 'react'
60
+ import { baas } from './lib/usebecky'
61
+
62
+ export function AvatarInput() {
63
+ const [error, setError] = useState<string | null>(null)
64
+
65
+ async function onChange(e: ChangeEvent<HTMLInputElement>) {
66
+ const file = e.target.files?.[0]
67
+ const user = baas.auth.getSession().data.session?.user
68
+ if (!file || !user) return
69
+ const { data, error } = await baas.storage.from('avatars').upload(`${user.id}/avatar-${Date.now()}.${file.name.split('.').pop()}`, file, { contentType: file.type })
70
+ if (error) return setError(error.message)
71
+ const { publicUrl } = baas.storage.from('avatars').getPublicUrl(data.path).data
72
+ const saved = await baas.from('profiles').update({ avatar_url: publicUrl }).eq('id', user.id)
73
+ setError(saved.error ? saved.error.message : null)
74
+ }
75
+
76
+ return (
77
+ <label>
78
+ Avatar <input type="file" accept="image/*" onChange={onChange} />
79
+ {error && <p role="alert">{error}</p>}
80
+ </label>
81
+ )
82
+ }
83
+ ```
84
+
85
+ ## 4. Show or download
86
+
87
+ ```ts
88
+ // inside an async function:
89
+ const path = '0b6f3c2e-.../avatar.png' // the path upload() returned (stored in your table)
90
+
91
+ // Public bucket: synchronous, no request; the URL includes ?apikey=<publishable key>
92
+ const { data: { publicUrl } } = baas.storage.from('avatars').getPublicUrl(path)
93
+ baas.storage.from('avatars').getPublicUrl(path, { download: 'avatar.png' }) // forces a download with that name
94
+
95
+ // Private bucket: a link that works for anyone holding it until it expires (max 1 year)
96
+ const { data, error } = await baas.storage.from('documents').createSignedUrl(path, 60 * 60) // { signedUrl, path }
97
+ const { data: many } = await baas.storage.from('documents').createSignedUrls(['a.pdf', 'b.pdf'], 600) // [{ path, signedUrl, error }]
98
+
99
+ // Bytes, with the caller's permissions
100
+ const { data: blob } = await baas.storage.from('documents').download(path) // Blob → await blob.text(), URL.createObjectURL(blob)
101
+ ```
102
+
103
+ `createSignedUrl` needs a SELECT policy for the caller on that file. A file the caller cannot read returns `object_not_found` (404), the same as a missing file.
104
+
105
+ ### Resized images (image transformations)
106
+
107
+ Never resize images in the browser just to display them, and never upload several sizes: ask for the size in the URL.
108
+
109
+ ```ts
110
+ // inside an async function:
111
+ const path = '0b6f3c2e-.../photo.jpg'
112
+ const transform = { width: 400, height: 300, resize: 'cover', quality: 80, format: 'webp' } as const
113
+ // Public bucket → /storage/v1/render/image/public/<bucket>/<path>?apikey=...&width=400&height=300&format=webp
114
+ const { data: { publicUrl } } = baas.storage.from('avatars').getPublicUrl(path, { transform })
115
+ // Private bucket → /storage/v1/render/image/sign/...?token=... (the options are signed; query params can't change them)
116
+ const { data: signed } = await baas.storage.from('photos').createSignedUrl(path, 3600, { transform })
117
+ // Bytes with the caller's permissions → /storage/v1/render/image/authenticated/...
118
+ const { data: blob } = await baas.storage.from('photos').download(path, { transform: { width: 200 } })
119
+ ```
120
+
121
+ - Options: `width`/`height` 1-2500 (one of them keeps proportions), `resize` `cover` (default, crop to fill) / `contain` (fit inside) / `fill` (stretch), `quality` 20-100 (default 80), `format` `origin` (default) / `webp` / `avif` / `jpeg` / `png`. Never enlarged. `transform: {}` → the normal file URL.
122
+ - Input JPEG, PNG, WebP, AVIF, GIF (first frame), TIFF; up to 25 MB and 50 megapixels; 15 s per image. Each size is made once and cached (ETag, the file's Cache-Control); a new upload under the same path makes new images.
123
+ - Plan limit `image_transformations_per_month` (Free 100, Pro 5,000, Business 100,000, the team's total across its projects) counts only new sizes. Over the limit the original image is served (header `x-usebecky-transform`), so pages keep working.
124
+ - Swift: `publicURL(path:transform: ImageTransform(width: 400, format: .webp))`; Kotlin: `publicUrl(path, transform = ImageTransform(width = 400, format = ImageFormat.WEBP))`.
125
+
126
+ ## 5. List, inspect, move, delete
127
+
128
+ ```ts
129
+ // inside an async function:
130
+ const user = baas.auth.getSession().data.session?.user
131
+ if (!user) return
132
+ const avatars = baas.storage.from('avatars')
133
+ const { data: items } = await avatars.list(user.id, { limit: 100, offset: 0, sortBy: { column: 'created_at', order: 'desc' }, search: 'png' })
134
+ // [{ name: 'photos', id: null, metadata: null, ... }, ← folder
135
+ // { name: 'avatar.png', id: 'c41e...', metadata: { size: 48213, mimetype: 'image/png', etag: '"9b2c..."', cacheControl: 'max-age=3600' }, created_at: '...', updated_at: '...' }]
136
+ await avatars.info(`${user.id}/avatar.png`) // data: ObjectInfo { id, bucket_id, name, owner, metadata, created_at, updated_at }
137
+ await avatars.exists(`${user.id}/avatar.png`) // data: true | false
138
+ await avatars.move(`${user.id}/avatar.png`, `${user.id}/old/avatar.png`) // data: { message }
139
+ await avatars.copy(`${user.id}/old/avatar.png`, `${user.id}/avatar.png`) // data: { message, path }
140
+ await avatars.remove([`${user.id}/old/avatar.png`, `${user.id}/avatar.png`]) // data: ObjectInfo[] actually deleted (max 1000 per call)
141
+ ```
142
+
143
+ `list(prefix)` returns direct children of that folder: names are relative, folders come first with `id: null`. Names in `storage.objects` are full paths.
144
+
145
+ ## 6. Uploads without a signed-in user
146
+
147
+ ```ts
148
+ // server.ts (server only: the secret key stays here). Creates a one-time upload URL and hands it to the client.
149
+ import express from 'express'
150
+ import { baas } from 'usebecky/server'
151
+
152
+ const app = express()
153
+ app.post('/api/upload-url', async (req, res) => {
154
+ const { data, error } = await baas.admin.storage.from('inbox').createSignedUploadUrl(`submissions/${crypto.randomUUID()}.pdf`)
155
+ if (error) return res.status(error.status).json({ error: error.message })
156
+ res.json(data) // { signedUrl, token, path }
157
+ })
158
+ app.listen(3000)
159
+ ```
160
+
161
+ ```ts
162
+ // inside an async function:
163
+ // Client: PUT the file to signedUrl (no auth headers needed)
164
+ const file = document.querySelector<HTMLInputElement>('input[type=file]')?.files?.[0]
165
+ const { signedUrl } = await (await fetch('/api/upload-url', { method: 'POST' })).json()
166
+ await fetch(signedUrl, { method: 'PUT', headers: { 'content-type': 'application/pdf' }, body: file })
167
+ ```
168
+
169
+ ## 7. Server-side files
170
+
171
+ ```ts
172
+ // server.ts (server only: secret key). Node Buffers upload directly.
173
+ import { readFile } from 'node:fs/promises'
174
+ import express from 'express'
175
+ import { baas } from 'usebecky/server'
176
+
177
+ const pdfBuffer = await readFile('invoice-1042.pdf')
178
+ await baas.admin.storage.from('invoices').upload('0b6f3c2e-.../invoice-1042.pdf', pdfBuffer, { contentType: 'application/pdf' }) // bypasses policies
179
+
180
+ const app = express()
181
+ app.get('/api/my-files', async (req, res) => {
182
+ const user = await baas.auth.getUser(req)
183
+ if (!user) return res.status(401).json({ error: 'Sign in first' })
184
+ const { data, error } = await baas.as(req).storage.from('avatars').list(user.id) // as the user, policies apply
185
+ res.json(error ? { error: error.message } : data)
186
+ })
187
+ app.listen(3000)
188
+ ```
189
+
190
+ Paid file downloads for products with a download file use `baas.payments.download(productKey)` instead (`payments.md`).
191
+
192
+ ## Errors
193
+
194
+ | Code | Status | Fix |
195
+ |---|---|---|
196
+ | `permission_denied` | 403 | Add the matching policy on `storage.objects` (message names the action: upload, overwrite, read, delete, move, copy) |
197
+ | `object_not_found` | 404 | Wrong path, or no SELECT policy for this user |
198
+ | `already_exists` | 409 | Pass `upsert: true` or choose another path |
199
+ | `bucket_not_found` | 404 | Create the bucket |
200
+ | `bucket_not_public` | 403 | Make it public, or use `createSignedUrl` |
201
+ | `file_too_large` | 413 | File exceeds the bucket or server limit |
202
+ | `invalid_mime_type` | 415 | Type not in the bucket's `allowed_mime_types` |
203
+ | `invalid_expires_in` | 400 | `expiresIn` must be a whole number of seconds, 1 to 31536000 |
204
+ | `invalid_signature` | 400 | Signed URL expired or tampered with; create a new one |
205
+ | `secret_key_required` | 403 | Bucket management needs `baas.admin.storage` on the server |
206
+ | `invalid_transform` | 400 | Transform option out of range (sizes 1-2500, quality 20-100, known `resize`/`format`) |
207
+ | `unsupported_image_type` | 415 | Only JPEG, PNG, WebP, AVIF, GIF and TIFF can be resized; use the normal URL for other files |
208
+ | `image_too_large` | 413 | Source image over 25 MB or 50 megapixels; link the original |
209
+ | `transform_timeout` | 504 | Resizing took over 15 s; ask for a smaller size |
210
+ | `image_transformations_unavailable` | 501 | The server has no image library; use the normal file URL |
@@ -0,0 +1,191 @@
1
+ # Ready-made setups (project templates)
2
+
3
+ A ready-made setup (API name: template) is optional. The dashboard offers it on a new project's Home (What do you want to do first? → Use a ready-made setup) and in Dashboard → Database → Tables while it is empty; `npx usebecky create` / `npx usebecky init` → Create a new project picks the one a starter needs. It creates tables, policies, functions, buckets, realtime triggers and payment products in one go (products reach Stripe once Stripe is connected). It goes only into a project with no tables or functions of its own in `public` (`POST /platform/v1/projects/:ref/setup {template}` answers `409 project_not_empty` otherwise) and never changes what a project already has.
4
+
5
+ Find out what a project has before writing code: look for the tables below (Dashboard → Database → Tables, or `npx usebecky types`, which writes every table and column to `usebecky.types.ts`). Build on what exists instead of recreating it.
6
+
7
+ Shared pieces:
8
+
9
+ - profiles: `public.profiles (id uuid pk → auth.users, display_name, avatar_url, created_at, updated_at)`. A trigger on `auth.users` calls `public.handle_new_user()`, which inserts a row at sign-up with `display_name` = `user_metadata.name`, else `full_name`, else `user_name`, else the part of the email before `@`, and `avatar_url` = `user_metadata.avatar_url` (else `picture`). A failed insert never blocks the sign-up (it becomes a warning; Dashboard → Database → Tables → profiles → Settings counts people without a profile and can create them). The trigger can be turned off there. The function belongs to the project owner: to fill extra profile columns, add them and `create or replace function public.handle_new_user()` in the SQL editor (keep the name, `security definer` and `returns trigger`). Policies: signed-in users read all profiles; users update their own. There is no insert or delete policy (the trigger inserts).
10
+ - owner-only table: `id uuid pk, user_id uuid not null default auth.uid() → auth.users, <columns>, created_at`, index on `user_id`, and select/insert/update/delete policies `user_id = auth.uid()` for `authenticated`.
11
+ - user-folder bucket policy: one `for all to authenticated` policy on `storage.objects`: `bucket_id = '<bucket>' and (storage.foldername(name))[1] = auth.uid()::text`. Upload to `` `${user.id}/file.ext` ``.
12
+ - Products are created in usebecky and pushed to Stripe once Stripe is connected (Dashboard → Payments).
13
+
14
+ | id | Name | Creates |
15
+ |---|---|---|
16
+ | `blank` | Blank project | nothing |
17
+ | `saas` | SaaS with subscriptions | profiles, `projects` (owner-only), `premium_content` (Premium only), `premium` product, `avatars` bucket |
18
+ | `downloads` | Digital downloads store | profiles, private `downloads` bucket, `ebook` product with a file, `reviews` (buyers only) |
19
+ | `mobile` | Mobile app | profiles, `todos` (owner-only, realtime), `avatars` bucket |
20
+ | `blog` | Blog & CMS | profiles, `posts` (public when published), `comments` (realtime), `images` bucket |
21
+ | `team` | Team workspace (B2B) | profiles, `teams`, `team_members`, `team_invites`, `team_projects`, helper functions |
22
+ | `course` | Online course / membership | `courses`, `lessons` (free previews), `lesson_progress`, Membership + Lifetime products, `course-files` bucket |
23
+ | `community` | Community chat | profiles, `channels`, `messages` and `reactions` (realtime), `avatars` bucket |
24
+ | `bookings` | Bookings & appointments | profiles, `services`, `availability`, `bookings` (no overlaps), `booked_times()` |
25
+ | `waitlist` | Waitlist & landing page | `waitlist` (insert-only, referral codes), `feedback`, `waitlist_count()` |
26
+
27
+ ## `saas`: SaaS with subscriptions
28
+
29
+ - profiles.
30
+ - `projects` (owner-only): `name text not null, description text, status text not null default 'active'`.
31
+ - `premium_content (id, title text not null, body text, created_at)`: select for `authenticated` using `billing.has_access('premium')`; 2 seed rows. No write policies (edit in the dashboard).
32
+ - Product `premium` named "Premium" (subscription, features `['premium']`): prices `premium_monthly` 900 usd/month, `premium_yearly` 9000 usd/year, both `trial_days: 14`. (Not "Pro": that is the name of usebecky' own paid plan for the project.)
33
+ - Bucket `avatars` (public) with the user-folder policy.
34
+
35
+ ```ts
36
+ // inside an async function:
37
+ await baas.from('projects').insert({ name: 'Website relaunch' })
38
+ const { data: premium } = await baas.from('premium_content').select('id, title, body') // [] unless Premium
39
+ await baas.payments.checkout('premium_monthly', { successUrl: `${location.origin}/premium`, cancelUrl: location.href })
40
+ const { data: isPremium } = await baas.payments.hasAccess('premium')
41
+ ```
42
+
43
+ ## `downloads`: Digital downloads store
44
+
45
+ - profiles.
46
+ - Bucket `downloads` (private, no policies: only the purchase flow and the secret key reach it). Upload the real file as `ebook.pdf`.
47
+ - Product `ebook` (one_time, features `['ebook']`, download `{ bucket: 'downloads', path: 'ebook.pdf' }`): price `ebook_once` 1900 usd.
48
+ - `reviews (id, user_id default auth.uid(), product_key text, rating int 1..5, body, created_at, unique (user_id, product_key))`: anyone reads; insert for `authenticated` with `user_id = auth.uid() and billing.has_purchased(product_key)`; users update their own. No delete policy.
49
+
50
+ ```ts
51
+ // inside an async function:
52
+ await baas.payments.checkout('ebook_once', { successUrl: `${location.origin}/thanks`, cancelUrl: location.href })
53
+ const { data, error } = await baas.payments.download('ebook') // data: { url, expiresIn }, or error not_purchased
54
+ await baas.from('reviews').insert({ product_key: 'ebook', rating: 5, body: 'Great read' })
55
+ ```
56
+
57
+ ## `mobile`: Mobile app
58
+
59
+ - profiles.
60
+ - `todos` (owner-only): `title text not null, done boolean not null default false`. Realtime enabled.
61
+ - Bucket `avatars` (public) with the user-folder policy.
62
+
63
+ ```ts
64
+ // inside an async function:
65
+ const reload = () => baas.from('todos').select('id, title, done').order('created_at')
66
+ const stop = baas.realtime.subscribe('todos', () => reload()) // call stop() when the screen closes
67
+ const { data: todos } = await reload()
68
+ if (todos?.length) await baas.from('todos').update({ done: true }).eq('id', todos[0].id)
69
+ ```
70
+
71
+ ## `blog`: Blog & CMS
72
+
73
+ - profiles, plus a policy letting anyone (signed out too) read the profiles of authors of published posts and of commenters.
74
+ - `posts (id, author_id uuid default auth.uid() → profiles, slug text unique (lowercase-dashes format), title text not null, body text not null default '' (Markdown), cover_url, published boolean default false, published_at timestamptz, created_at)`. A trigger fills `published_at` the first time `published` becomes true. Policies: anyone reads published posts; authors read their own drafts; signed-in users insert with `author_id = auth.uid()`; authors update and delete their own. One seed post `hello-world`.
75
+ - `comments (id, post_id → posts, user_id default auth.uid() → profiles, body text 1..5000 chars, created_at)`: anyone reads comments on published posts; signed-in users comment on published posts as themselves; users delete their own. Realtime enabled.
76
+ - Bucket `images` (public) with the user-folder policy.
77
+
78
+ ```ts
79
+ // inside an async function:
80
+ const slug = 'hello-world'
81
+ const { data: posts } = await baas.from('posts').select('slug, title, published_at, author:profiles(display_name)').eq('published', true).order('published_at', { ascending: false })
82
+ const { data: post } = await baas.from('posts').select('*, comments(id, body, created_at, user:profiles(display_name))').eq('slug', slug).maybeSingle()
83
+ await baas.from('posts').insert({ slug: 'my-first-post', title: 'My first post', body: '# Hi', published: true })
84
+ if (post) baas.realtime.subscribe('comments', { event: 'INSERT', filter: `post_id=eq.${post.id}` }, (c) => post.comments.push(c.new))
85
+ ```
86
+
87
+ ## `team`: Team workspace (B2B)
88
+
89
+ - profiles.
90
+ - `teams (id, name text 1..100 chars, created_by default auth.uid(), created_at)`. A trigger makes the creator an `owner` in `team_members`. Policies: members and the creator read; signed-in users insert with `created_by = auth.uid()`; owners and admins rename; owners delete.
91
+ - `team_members (team_id → teams, user_id → profiles, role 'owner' | 'admin' | 'member' default 'member', created_at, pk (team_id, user_id))`. Members see their team's members; owners add/change/remove anyone, admins anyone except owners; anyone can leave. A trigger blocks removing or demoting the last owner (raises "A team needs at least one owner...").
92
+ - `team_invites (id, team_id, email, role 'admin' | 'member', token text unique (random), invited_by default auth.uid(), expires_at default now() + 7 days, accepted_at, created_at)`: owners and admins read, create (`invited_by = auth.uid()`), update and delete. The app emails the token (for example as a link); the template sends no email.
93
+ - `team_projects (id, team_id, name, description, created_by default auth.uid(), created_at)`: members read, create (`created_by = auth.uid()`) and edit; owners and admins delete. Copy this pattern for other team-scoped tables.
94
+ - Functions (security definer, callable by `authenticated` only): `is_team_member(team uuid) → boolean`, `team_role(team uuid) → text | null`, `accept_team_invite(invite_token text) → uuid` (joins the signed-in user to the invite's team and returns the team id).
95
+
96
+ ```ts
97
+ // inside an async function:
98
+ const { data: team, error } = await baas.from('teams').insert({ name: 'Acme' }).select().single() // you are now its owner
99
+ if (error) return
100
+ const { data: invite } = await baas.from('team_invites').insert({ team_id: team.id, email: 'grace@example.com', role: 'member' }).select('token').single()
101
+ // The invited user, signed in, with the token from your invite email:
102
+ const { data: teamId, error: joinError } = await baas.rpc('accept_team_invite', { invite_token: invite.token }) // raised_exception if expired or used
103
+ const { data: members } = await baas.from('team_members').select('role, user:profiles(display_name, avatar_url)').eq('team_id', team.id)
104
+ ```
105
+
106
+ ```sql
107
+ -- Your own team-scoped table, same rules as team_projects
108
+ create table public.documents (id uuid primary key default gen_random_uuid(), team_id uuid not null references public.teams (id) on delete cascade, title text not null, created_at timestamptz not null default now());
109
+ create index on public.documents (team_id);
110
+ alter table public.documents enable row level security;
111
+ create policy "Team members read documents" on public.documents for select to authenticated using (public.is_team_member(team_id));
112
+ create policy "Team members write documents" on public.documents for insert to authenticated with check (public.is_team_member(team_id));
113
+ create policy "Team members edit documents" on public.documents for update to authenticated using (public.is_team_member(team_id)) with check (public.is_team_member(team_id));
114
+ create policy "Owners and admins delete documents" on public.documents for delete to authenticated using (public.team_role(team_id) in ('owner', 'admin'));
115
+ ```
116
+
117
+ ## `course`: Online course / membership
118
+
119
+ - No profiles table.
120
+ - `courses (id, slug unique, title, description, cover_url, created_at)`: anyone reads. Seed course `getting-started`.
121
+ - `lessons (id, course_id → courses, position int, title, body, video_url, free_preview boolean default false, created_at, unique (course_id, position))`: anyone reads `free_preview` lessons; `authenticated` with `billing.has_access('members')` read all. Seed: 3 lessons, the first a free preview.
122
+ - `lesson_progress` (owner-only): `lesson_id → lessons, completed_at timestamptz default now(), unique (user_id, lesson_id)`.
123
+ - Product `membership` (subscription, features `['members']`): `membership_monthly` 1900 usd/month, `membership_yearly` 19000 usd/year, both `trial_days: 7`.
124
+ - Product `lifetime` (one_time, features `['members']`): `lifetime_once` 29900 usd.
125
+ - Bucket `course-files` (private): members (`billing.has_access('members')`) download everything; anyone downloads files under `free/`.
126
+
127
+ ```ts
128
+ // inside an async function:
129
+ const { data: course } = await baas.from('courses').select('id').eq('slug', 'getting-started').single()
130
+ const { data: lessons } = await baas.from('lessons').select('id, position, title, free_preview').eq('course_id', course.id).order('position')
131
+ // Locked lessons are simply absent for non-members. To show them as locked, list titles from a public view or a definer function.
132
+ const { data: isMember } = await baas.payments.hasAccess('members')
133
+ if (lessons?.length) await baas.from('lesson_progress').upsert({ lesson_id: lessons[0].id }, { onConflict: 'user_id,lesson_id', ignoreDuplicates: true }) // mark done
134
+ const { data: link } = await baas.storage.from('course-files').createSignedUrl('module-1/slides.pdf', 3600)
135
+ ```
136
+
137
+ ## `community`: Community chat
138
+
139
+ - profiles.
140
+ - `channels (id, name text unique matching ^[a-z0-9][a-z0-9_-]{0,49}$, description, created_by default auth.uid(), created_at)`: signed-in users read and create (`created_by = auth.uid()`). Seed channel `general`.
141
+ - `messages (id, channel_id → channels, user_id default auth.uid() → profiles, body text 1..4000 chars, created_at)`: signed-in users read all and post as themselves; authors edit and delete their own. Realtime enabled.
142
+ - `reactions (id, message_id → messages, user_id default auth.uid() → profiles, emoji text 1..32 chars, created_at, unique (message_id, user_id, emoji))`: signed-in users read, add and remove their own. Realtime enabled.
143
+ - Bucket `avatars` (public) with the user-folder policy.
144
+
145
+ ```ts
146
+ // inside an async function:
147
+ const { data: general } = await baas.from('channels').select('id').eq('name', 'general').single()
148
+ const { data: history } = await baas.from('messages').select('id, body, created_at, user:profiles(display_name, avatar_url), reactions(emoji, user_id)').eq('channel_id', general.id).order('created_at').limit(100)
149
+ baas.realtime.subscribe('messages', { filter: `channel_id=eq.${general.id}` }, (change) => console.log(change.event, change.new))
150
+ const { data: sent } = await baas.from('messages').insert({ channel_id: general.id, body: 'Hello!' }).select('id').single()
151
+ await baas.from('reactions').insert({ message_id: sent.id, emoji: '\u{1F389}' })
152
+ ```
153
+
154
+ ## `bookings`: Bookings & appointments
155
+
156
+ - profiles.
157
+ - `services (id, name, description, duration_minutes int 5..1440, price_cents int default 0, active boolean default true, created_at)`: anyone reads active services. Seed: "Intro call" (30 min, 0) and "Consultation" (60 min, 4500).
158
+ - `availability (id, weekday smallint 0..6 (0 = Sunday), start_time time, end_time time)`: anyone reads. Seed: Monday to Friday 09:00 to 17:00.
159
+ - `bookings (id, service_id → services, user_id default auth.uid(), starts_at timestamptz, ends_at timestamptz, status 'pending' | 'confirmed' | 'cancelled' default 'pending', notes, created_at)`. A trigger sets `ends_at` from the service duration. An exclusion constraint `bookings_must_not_overlap` rejects any booking overlapping another non-cancelled booking (one calendar for all services). Policies: customers see their own; insert for themselves with `status = 'pending'`; update only to cancel (`status = 'cancelled'`), and the column grant allows changing only `status`. Confirm bookings in the dashboard or with `baas.admin`.
160
+ - Function `booked_times(from_time timestamptz, to_time timestamptz) → table (starts_at, ends_at)`: busy ranges without customer details; callable by `anon` and `authenticated`.
161
+
162
+ ```ts
163
+ // inside an async function:
164
+ const weekStart = new Date('2026-11-16T00:00:00Z')
165
+ const weekEnd = new Date('2026-11-23T00:00:00Z')
166
+ const { data: busy } = await baas.rpc('booked_times', { from_time: weekStart.toISOString(), to_time: weekEnd.toISOString() }) // [{ starts_at, ends_at }]
167
+ const { data: service } = await baas.from('services').select('id').eq('name', 'Intro call').single()
168
+ const slot = new Date('2026-11-17T10:00:00Z')
169
+ const { data: booking, error } = await baas.from('bookings').insert({ service_id: service.id, starts_at: slot.toISOString(), notes: 'First call' }).select().single()
170
+ if (error?.code === 'overlaps_existing') return // 409: the slot was just taken, reload free slots
171
+ if (booking) await baas.from('bookings').update({ status: 'cancelled' }).eq('id', booking.id)
172
+ ```
173
+
174
+ ## `waitlist`: Waitlist & landing page
175
+
176
+ - No profiles; no accounts needed.
177
+ - `waitlist (id, email text unique (max 320 chars, must look like an email, stored lowercase by a trigger), referral_code text unique matching ^[A-Za-z0-9_-]{4,32}$ default random 10 chars, referred_by text, created_at)`: anyone may insert, and only the columns `email`, `referral_code`, `referred_by`. Nobody can read, update or delete through the API (dashboard or secret key only). A malformed email fails with `check_violation` (400).
178
+ - `feedback (id, message text 1..5000 chars, email, page, created_at)`: anyone may insert `message`, `email`, `page`; nobody reads through the API.
179
+ - Function `waitlist_count() → bigint`: callable by `anon` and `authenticated`, returns only the number.
180
+
181
+ ```ts
182
+ // inside an async function:
183
+ const email = 'ada@example.com'
184
+ const code = crypto.randomUUID().replace(/-/g, '').slice(0, 10) // to show the share link right away
185
+ const { error } = await baas.from('waitlist').insert({ email, referral_code: code, referred_by: new URLSearchParams(location.search).get('ref') })
186
+ if (error?.code === 'already_exists') alert('You are already on the list.') // or, very rarely, the generated code was taken
187
+ if (error?.code === 'check_violation') alert('Please enter a valid email address.')
188
+ const { data: count } = await baas.rpc('waitlist_count')
189
+ await baas.from('feedback').insert({ message: 'Love it!', email: email || null, page: location.pathname })
190
+ // Never chain .select() here: the caller cannot read these rows.
191
+ ```
@@ -0,0 +1,87 @@
1
+ # WordPress sites (Hosting for WordPress and the usebecky plugin)
2
+
3
+ A team on Business can host one WordPress site, in one of its projects (**Hosting → New site → WordPress**). The site runs the **usebecky** plugin, already connected to the project, and a usebecky must-use plugin that handles sign-in, email, caching and security. Customer guide: https://usebecky.com/docs/guides/wordpress
4
+
5
+ Use this file when the user works on a WordPress site connected to usebecky: adding forms, newsletter, payments or analytics to pages, writing theme or plugin code, or asking why something in wp-admin behaves differently.
6
+
7
+ ## What is already there (don't rebuild it)
8
+
9
+ | Need | Use | Not |
10
+ |---|---|---|
11
+ | Contact form | Block **Contact form** or `[usebecky_contact_form form="f_..."]` (form created in usebecky → Forms) | Contact Form 7 + SMTP plugin, a hand-written `<form>` |
12
+ | Newsletter signup | Block **Newsletter signup** or `[usebecky_newsletter]` | Mailchimp embed |
13
+ | Waitlist | Block **Waitlist** or `[usebecky_waitlist]` (table `waitlist` from the Waitlist template) | a custom table + PHP |
14
+ | Pricing page | Block **Pricing table** or `[usebecky_pricing_table]` (products from usebecky → Payments) | hard-coded prices with Stripe links |
15
+ | One buy button | Block **Checkout button** or `[usebecky_checkout_button price="<price key>"]Label[/usebecky_checkout_button]` | Stripe Payment Links |
16
+ | Manage subscription | Block **Customer portal button** or `[usebecky_portal_button]` (shows only for signed-in customers) | |
17
+ | Members-only content | Block **Paywall** or `[usebecky_paywall feature="pro"]...[/usebecky_paywall]`: **visual only**, the content is still in the HTML; never put secrets or paid files in it (use Payments downloads) | |
18
+ | Visitor analytics | Automatic on every page (cookie-free, 404 pages reported, signed-in editors not counted) | Google Analytics snippets, a second usebecky script tag |
19
+ | Emails | `wp_mail()` already goes through the project's email sender (Emails → Sent, tag `source: wordpress`) | SMTP plugins (port 25 is blocked; they won't deliver) |
20
+ | Admin sign-in | **Open WordPress admin** in usebecky (team owner/admin/developer → administrator, viewer → none) | sharing WordPress passwords with team members |
21
+
22
+ ## Shortcode attributes
23
+
24
+ Two-word settings use `_` (or `-`). Values are checked; wrong ones are left out.
25
+
26
+ ```text
27
+ [usebecky_contact_form form="f_abc123def456" heading="Write to us" description="" submit_label="Send"]
28
+ [usebecky_newsletter list="newsletter" tags="home,blog" variant="card|inline" heading="" description="" button_label="" fine_print="" collect_name="true"]
29
+ [usebecky_waitlist table="waitlist" count_function="waitlist_count|false" referrals="true" variant="card|inline" heading="" button_label=""]
30
+ [usebecky_pricing_table products="basic,pro" highlight="pro" default_interval="month|year" mode="hosted|embedded" feature="" success_url="/thanks" cancel_url="" sign_in_url=""]
31
+ [usebecky_checkout_button price="pro_monthly" quantity="1" variant="primary|secondary" block="true" promotion_codes="false" success_url="" cancel_url="" sign_in_url=""]Buy Pro[/usebecky_checkout_button]
32
+ [usebecky_portal_button return_url="" variant="primary|secondary" block="true"]Manage billing[/usebecky_portal_button]
33
+ [usebecky_paywall feature="pro"]Content for customers[/usebecky_paywall]
34
+ ```
35
+
36
+ Relative URLs (`/thanks`) become full addresses of the site. Each renders the matching `<ub-...>` Web Component (see `references/components.md` for what each one does); the plugin adds the project URL and publishable key and loads the components only on pages that use them.
37
+
38
+ ## Custom analytics events from a theme or plugin
39
+
40
+ The analytics script is on every page (handle `usebecky-analytics`). Track clicks without JavaScript by adding attributes in templates, or queue calls before the script loads:
41
+
42
+ ```php
43
+ // functions.php: a click event on any element.
44
+ echo '<a href="/menu.pdf" data-ub-event="menu_download" data-ub-prop-season="winter">Menu</a>';
45
+
46
+ // functions.php: an event from PHP-rendered pages (queued until the script runs).
47
+ add_action( 'wp_enqueue_scripts', function () {
48
+ if ( is_page( 'thank-you' ) ) {
49
+ wp_add_inline_script( 'usebecky-analytics', 'window.usebecky=window.usebecky||function(){(usebecky.q=usebecky.q||[]).push(arguments)};usebecky("track","signed_up",{plan:"pro"});', 'before' );
50
+ }
51
+ }, 20 );
52
+ ```
53
+
54
+ - WooCommerce orders are already tracked as `purchase` with `value`, `currency`, `items`: don't add a second purchase event.
55
+ - Never put email addresses or names into event props.
56
+ - Consent: privacy mode needs none. With a WP Consent API banner plugin (Complianz, ...), visitors who allow "statistics" are remembered automatically when the project has **Analytics → Settings → Returning visitors** on. Without such a plugin, call `usebecky('consent', true)` from the banner's accept callback.
57
+
58
+ ## Calling usebecky from PHP
59
+
60
+ - Public data and forms: use the blocks. For your own server calls, use the HTTP API (`references/http-api.md`) with `wp_remote_post()`.
61
+ - The secret key (`ub_sk_...`) goes into a constant in `wp-config.php` (never into a theme file, a block, JavaScript or the database) and is used only in PHP. The publishable key is in `USEBECKY_PUBLISHABLE_KEY`, the project URL in `USEBECKY_URL` (both constants are defined on usebecky sites).
62
+
63
+ ```php
64
+ // A server-side insert with the secret key (wp-config.php: define( 'MYSITE_USEBECKY_SECRET', 'ub_sk_...' );).
65
+ $response = wp_remote_post(
66
+ USEBECKY_URL . '/rest/v1/orders',
67
+ array(
68
+ 'headers' => array( 'apikey' => MYSITE_USEBECKY_SECRET, 'Content-Type' => 'application/json', 'Prefer' => 'return=minimal' ),
69
+ 'body' => wp_json_encode( array( 'customer_email' => $email, 'total' => 1900 ) ),
70
+ 'timeout' => 10,
71
+ )
72
+ );
73
+ ```
74
+
75
+ ## Rules of a usebecky WordPress site (explain them, don't work around them)
76
+
77
+ - WordPress core is updated by usebecky; there is no update button for it. Plugins and themes update automatically by default (switchable per plugin).
78
+ - The theme/plugin file editor in wp-admin is off: change code in a child theme or a small plugin, upload it as a zip (**Plugins → Add New → Upload**).
79
+ - No PHP files in uploads; total files 20 GB, database 2 GB (Business).
80
+ - XML-RPC is off; Jetpack needs it switched on in the site's settings in usebecky.
81
+ - WP-Cron runs every minute from usebecky (not on page views); scheduled events still work as usual (`wp_schedule_event`).
82
+ - Page cache: visitors get cached pages; it empties on every content change. Anything per visitor must happen in the browser (the components already do) or on pages with a query string, a logged-in cookie, cart/checkout/my-account.
83
+ - Emails: up to 10 MB of attachments; larger emails are refused (logged). Use download links.
84
+ - Team members can't sign in with a password, reset it or use application passwords; they use **Open WordPress admin**. Other people (authors, shop managers) get normal WordPress accounts.
85
+ - Too many wrong passwords (5 per username or 20 per network in 15 minutes) pause password sign-in for 15 minutes.
86
+
87
+ The usebecky plugin for WordPress sites hosted elsewhere comes later; until then, those sites add the analytics script tag and the Web Components by hand (`references/analytics.md`, `references/components.md`).
@@ -0,0 +1,74 @@
1
+ // Starter manifests. Every folder in templates/ with a `usebecky.template.json` is a starter:
2
+ // the bootstrapper lists it, copies the folder (without the manifest), and does what the manifest
3
+ // asks: create a project from `serverTemplate`, write the keys, create extra tables and buckets.
4
+ //
5
+ // `project: false` marks a starter that is not an app on a usebecky project (the extension starter): it is copied
6
+ // and installed, but never connected, and gets the AI skill named in `skill`.
7
+ //
8
+ // `kind` says how the starter is built and run:
9
+ // node package.json app (Next.js, Vite, Expo...). Packages are installed and the env file is
10
+ // written with the same rules as `npx usebecky init` (envPlanFor(framework)).
11
+ // xcode iOS/macOS app. No install step; keys go to `config.file` (e.g. an .xcconfig).
12
+ // gradle Android app. No install step; keys go to `config.file` (e.g. a .properties file).
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+ export const MANIFEST = 'usebecky.template.json';
17
+ export const KINDS = ['node', 'xcode', 'gradle'];
18
+ export const SKILLS = ['usebecky', 'usebecky-extension'];
19
+ /** templates/ next to src/ (dev) or dist/ (installed). */
20
+ export function templatesDir() {
21
+ return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'templates');
22
+ }
23
+ export function validateManifest(m, dir) {
24
+ const where = path.join(path.basename(dir), MANIFEST);
25
+ const fail = (msg) => {
26
+ throw new Error(`${where}: ${msg}`);
27
+ };
28
+ if (!m || typeof m !== 'object')
29
+ fail('must be a JSON object');
30
+ if (m.project !== undefined && typeof m.project !== 'boolean')
31
+ fail('"project" must be true or false');
32
+ const keys = m.project === false ? ['id', 'name', 'description', 'stack'] : ['id', 'name', 'description', 'stack', 'serverTemplate'];
33
+ for (const key of keys) {
34
+ if (typeof m[key] !== 'string' || !m[key])
35
+ fail(`"${key}" must be a non-empty string`);
36
+ }
37
+ if (m.project === false && (m.setup || m.requires || m.config))
38
+ fail('"setup", "requires" and "config" need a project: remove them, or remove "project": false');
39
+ if (m.skill !== undefined && !SKILLS.includes(m.skill))
40
+ fail(`"skill" must be one of ${SKILLS.join(', ')}`);
41
+ if (m.id !== path.basename(dir))
42
+ fail(`"id" must match the folder name ("${path.basename(dir)}")`);
43
+ if (!KINDS.includes(m.kind))
44
+ fail(`"kind" must be one of ${KINDS.join(', ')}`);
45
+ if (m.kind === 'node' && typeof m.framework !== 'string')
46
+ fail('node starters need "framework" (next, vite, expo...)');
47
+ if (m.kind !== 'node' && !m.config)
48
+ fail(`${m.kind} starters need "config" (where to write the URL and key)`);
49
+ if (!m.run || typeof m.run !== 'object')
50
+ fail('"run" is required');
51
+ if (m.kind === 'node' && typeof m.run.script !== 'string')
52
+ fail('node starters need "run.script" (the package.json script that starts it, e.g. "dev")');
53
+ if (m.kind !== 'node' && typeof m.run.command !== 'string')
54
+ fail(`${m.kind} starters need "run.command" (e.g. "open App.xcodeproj")`);
55
+ for (const key of ['first', 'note', 'localNote']) {
56
+ if (m.run[key] !== undefined && typeof m.run[key] !== 'string')
57
+ fail(`"run.${key}" must be a string`);
58
+ }
59
+ return m;
60
+ }
61
+ export function loadTemplates(dir = templatesDir()) {
62
+ if (!fs.existsSync(dir))
63
+ return [];
64
+ const out = [];
65
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
66
+ if (!entry.isDirectory())
67
+ continue;
68
+ const file = path.join(dir, entry.name, MANIFEST);
69
+ if (!fs.existsSync(file))
70
+ continue;
71
+ out.push(validateManifest(JSON.parse(fs.readFileSync(file, 'utf8')), path.join(dir, entry.name)));
72
+ }
73
+ return out.sort((a, b) => (a.order ?? 99) - (b.order ?? 99) || a.id.localeCompare(b.id));
74
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "create-usebecky",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Create a beautiful, working app connected to usebecky with one command: npm create usebecky@latest",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "bin": {
8
+ "create-usebecky": "./dist/index.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "templates",
13
+ "README.md"
14
+ ],
15
+ "scripts": {
16
+ "build": "node scripts/build.mjs",
17
+ "sync": "node scripts/sync-shared.mjs",
18
+ "test": "node --test 'test/**/*.test.ts'",
19
+ "typecheck": "tsc -p .",
20
+ "prepack": "npm run build"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^26.6.6",
24
+ "typescript": "5.9"
25
+ },
26
+ "keywords": [
27
+ "usebecky",
28
+ "create",
29
+ "starter",
30
+ "template",
31
+ "nextjs",
32
+ "vite",
33
+ "expo",
34
+ "backend"
35
+ ],
36
+ "engines": {
37
+ "node": ">=22.18"
38
+ }
39
+ }