@protobase/cli 0.49.2 → 0.50.1

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 (72) hide show
  1. package/bin/protobase.mjs +3 -2
  2. package/dist/build/config-bundle.js +1 -1
  3. package/dist/build/deploy-bundle.js +3 -4
  4. package/dist/build/plugin-build.js +16 -8
  5. package/dist/build/plugin-fields.js +5 -2
  6. package/dist/build/ui-check.js +5 -0
  7. package/dist/build/view-check.js +1 -1
  8. package/dist/cli/package.js +1 -1
  9. package/dist/config/project-files.js +4 -1
  10. package/dist/config/source-config.js +1 -1
  11. package/dist/dev/api-process.js +1 -1
  12. package/dist/dev/app-server.js +43 -35
  13. package/dist/dev/create-db.js +2 -2
  14. package/dist/dev/project.js +3 -2
  15. package/dist/dev/server-package.js +9 -21
  16. package/dist/doctor/run.js +1 -1
  17. package/dist/hand-over.d.ts +15 -0
  18. package/dist/hand-over.js +32 -0
  19. package/dist/main.js +22 -5
  20. package/dist/project/bundled-imports.js +41 -0
  21. package/dist/project/import-project-file.js +28 -8
  22. package/dist/project/load-data-config.js +4 -3
  23. package/dist/project/project-types.js +66 -0
  24. package/dist/run/preload.d.ts +1 -0
  25. package/dist/run/preload.js +20 -0
  26. package/dist/run/run-script.js +36 -0
  27. package/dist/supabase/dump-phase.js +9 -4
  28. package/dist/supabase/load-phase.js +5 -4
  29. package/dist/supabase/realtime-policies.js +60 -0
  30. package/dist/version/project-packages.js +39 -0
  31. package/dist/version/project-version.js +33 -12
  32. package/package.json +9 -8
  33. package/skills/protobase/SKILL.md +1 -1
  34. package/skills/protobase/references/features/build-and-run.md +3 -0
  35. package/skills/protobase/references/features/compatibility.md +1 -1
  36. package/skills/protobase/references/features/releases.md +2 -1
  37. package/skills/protobase/references/getting-started.md +18 -5
  38. package/skills/protobase/references/guides/api-functions.md +1 -1
  39. package/skills/protobase/references/guides/billing-page.md +4 -4
  40. package/skills/protobase/references/guides/create-page.md +2 -2
  41. package/skills/protobase/references/guides/deploy.md +24 -8
  42. package/skills/protobase/references/guides/field-type.md +1 -1
  43. package/skills/protobase/references/guides/first-plugin.md +1 -1
  44. package/skills/protobase/references/guides/plugin-build.md +1 -1
  45. package/skills/protobase/references/guides/remote-resources.md +1 -1
  46. package/skills/protobase/references/guides/table-to-admin.md +8 -8
  47. package/skills/protobase/references/reference/ai.md +1 -1
  48. package/skills/protobase/references/reference/api.md +4 -4
  49. package/skills/protobase/references/reference/architecture.md +11 -6
  50. package/skills/protobase/references/reference/assistant.md +1 -1
  51. package/skills/protobase/references/reference/auth.md +17 -4
  52. package/skills/protobase/references/reference/blocks.md +1 -1
  53. package/skills/protobase/references/reference/bottom-bar.md +2 -2
  54. package/skills/protobase/references/reference/cli.md +51 -22
  55. package/skills/protobase/references/reference/client.md +3 -1
  56. package/skills/protobase/references/reference/config/api.md +2 -2
  57. package/skills/protobase/references/reference/config/app.md +2 -2
  58. package/skills/protobase/references/reference/config/sign-in.md +2 -3
  59. package/skills/protobase/references/reference/config.md +11 -9
  60. package/skills/protobase/references/reference/custom-components.md +3 -2
  61. package/skills/protobase/references/reference/email.md +4 -4
  62. package/skills/protobase/references/reference/events.md +1 -1
  63. package/skills/protobase/references/reference/jobs.md +6 -5
  64. package/skills/protobase/references/reference/layouts.md +2 -2
  65. package/skills/protobase/references/reference/mcp.md +9 -8
  66. package/skills/protobase/references/reference/notifications.md +10 -8
  67. package/skills/protobase/references/reference/plugins.md +3 -3
  68. package/skills/protobase/references/reference/supabase-realtime.md +36 -2
  69. package/skills/protobase/references/reference/ui-config.md +1 -1
  70. package/skills/protobase/references/reference/user-menu.md +3 -3
  71. package/skills/protobase/references/reference/versioning.md +21 -4
  72. package/skills/protobase/references/reference/webhooks.md +5 -5
@@ -26,7 +26,7 @@ export const bookRepair = page(
26
26
  )
27
27
  ```
28
28
 
29
- Its `roles` say who may book: they are the people who get the page, and so **New**.
29
+ Its `roles` say who may book: they are the people who get the page, and so **New**. Protobase finds pages among the exports of `config/index.ts`, so export it there: `export { bookRepair } from './pages/book-repair'`.
30
30
 
31
31
  ## 2. The component
32
32
 
@@ -94,7 +94,7 @@ export const repairsView = view<typeof repairs>('repairs')
94
94
 
95
95
  ## 4. Create through a function
96
96
 
97
- With its own page, the shop can make the [API function](api-functions.md) `book-repair` the only way in: it checks the answers, plans the job and inserts the repair with `db`, which skips the access rules. The resource's API then refuses creates:
97
+ With its own page, the shop can make the [API function](api-functions.md) `book-repair`, the default export of `functions/book-repair.ts`, the only way in: it checks the answers, plans the job and inserts the repair with `db`, which skips the access rules. The resource's API then refuses creates:
98
98
 
99
99
  ```ts
100
100
  // config/repairs/data.ts
@@ -2,9 +2,9 @@
2
2
 
3
3
  # Deploy
4
4
 
5
- Ship a project as one bundle folder and run it with the serve runtime.
5
+ Ship a project as one bundle folder and run it with the serve runtime, on a host of your own or on Protobase Cloud from a push to GitHub.
6
6
 
7
- A project ships as one bundle folder; the host runs protobase around it.
7
+ A project ships as one bundle folder; the host runs protobase around it. An app on Protobase Cloud deploys from a push to its GitHub branch instead, which builds and serves the bundle for it (see [Protobase Cloud](#protobase-cloud)).
8
8
 
9
9
  ```sh
10
10
  bun run --cwd tests/apps/erp protobase build # the bundle to ship: tests/apps/erp/dist/
@@ -28,7 +28,7 @@ dist/
28
28
  plugins and the app's version
29
29
  ```
30
30
 
31
- The host serves `public/` itself and sends only the manifest's `api` paths to the runtime (`/api` and the two OAuth discovery documents of [MCP clients](../reference/auth.md#oauth-for-mcp-clients), and `/.well-known/webauthn`, for an app on [several origins](../reference/auth.md#several-origins)), so loading the UI never needs a running container. With the UI it sends `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'`, as `protobase serve` does, so no other site frames the app's pages. The runtime serves the API alone; `protobase serve dist` serves the whole folder the same way, to check a bundle locally. The host passes `DATABASE_URL`, `PORT` (default 8787) and optionally `PROTOBASE_DB_CONNECTIONS` (the connections the app may open, so its functions and jobs leave one to requests, see [`serve`](../reference/cli.md#serve)), `REQUEST_LOG`, `PROTOBASE_SMTP_URL` and `PROTOBASE_MAIL_FROM` (the mail server and sender for [password reset](../reference/auth.md#password-reset) and emailed sign-in codes) `PROTOBASE_APP_NAME` (the app's name in that mail, see [`appName`](../reference/auth.md#configuration)) `PROTOBASE_SIGN_IN_*` (a provider people with an account sign in with, the [platform sign-in provider](../reference/auth.md#platform-sign-in-provider)) `PROTOBASE_OPERATOR_*` (the provider its staff sign in with for [staff sign-in](../reference/auth.md#staff-sign-in)), `PROTOBASE_ORIGINS` and `PROTOBASE_PASSKEY_DOMAIN` (the app's [other origins](../reference/auth.md#several-origins) and its passkey domain) `PROTOBASE_CORS_ORIGINS` (the websites that may call its API, see [CORS](../reference/api.md#cors)), `PROTOBASE_TRUSTED_PROXIES` (the proxies in front of the runtime, whose `X-Forwarded-For` names the client the sign-in limits count, see [Client addresses](../reference/auth.md#client-addresses)) and `PROTOBASE_SENTRY_DSN` (the app's [error tracker](../reference/api.md#error-reporting)), `PROTOBASE_URL` and `PROTOBASE_SECRET` (the app's address and secret, unless its config sets [`url` and `secret`](../reference/config/app.md)), plus the project's own settings, which its config reads where it serves. The runtime and the config module are plain JavaScript for Bun: no install, no TypeScript, no writes. The runtime supplies protobase and the dependencies it runs on the server (`pg`, `postgres`, `kysely`, `better-auth`, ...), so the config module carries only the project's code and the other packages it uses. The manifest's `protobase` is the version the project is pinned to, and the host serves the bundle on the runtime of that version (see [Versioning](../reference/versioning.md#bundles-and-runtimes)). The manifest format and the routing rules are in the CLI reference: [`build`](../reference/cli.md#build), [`build-serve`](../reference/cli.md#build-serve) and [`serve`](../reference/cli.md#serve).
31
+ The host serves `public/` itself and sends only the manifest's `api` paths to the runtime (`/api` and the two OAuth discovery documents of [MCP clients](../reference/auth.md#oauth-for-mcp-clients)), and `/.well-known/webauthn` for an app on [several origins](../reference/auth.md#several-origins), which the manifest does not list, so loading the UI never needs a running container. With the UI it sends `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'`, as `protobase serve` does, so no other site frames the app's pages. The runtime serves the API alone; `protobase serve dist` serves the whole folder the same way, to check a bundle locally. The host passes `DATABASE_URL`, `PORT` (default 8787) and optionally `PROTOBASE_DB_CONNECTIONS` (the connections the app may open, so its functions and jobs leave one to requests, see [`serve`](../reference/cli.md#serve)), `REQUEST_LOG`, `PROTOBASE_SMTP_URL` and `PROTOBASE_MAIL_FROM` (the mail server and sender for [password reset](../reference/auth.md#password-reset) and emailed sign-in codes) `PROTOBASE_APP_NAME` (the app's name in that mail, see [`name`](../reference/config/app.md#name)) `PROTOBASE_SIGN_IN_*` (a provider people with an account sign in with, the [platform sign-in provider](../reference/auth.md#platform-sign-in-provider)) `PROTOBASE_OPERATOR_*` (the provider its staff sign in with for [staff sign-in](../reference/auth.md#staff-sign-in)), `PROTOBASE_ORIGINS` and `PROTOBASE_PASSKEY_DOMAIN` (the app's [other origins](../reference/auth.md#several-origins) and its passkey domain) `PROTOBASE_CORS_ORIGINS` (the websites that may call its API, see [CORS](../reference/api.md#cors)), `PROTOBASE_TRUSTED_PROXIES` (the proxies in front of the runtime, whose `X-Forwarded-For` names the client the sign-in limits count, see [Client addresses](../reference/auth.md#client-addresses)) and `PROTOBASE_SENTRY_DSN` (the app's [error tracker](../reference/api.md#error-reporting)), `PROTOBASE_URL` and `PROTOBASE_SECRET` (the app's address and secret, unless its config sets [`url` and `secret`](../reference/config/app.md)), plus the project's own settings, which its config reads where it serves. The runtime and the config module are plain JavaScript for Bun: no install, no TypeScript, no writes. The runtime supplies protobase and the dependencies it runs on the server (`pg`, `postgres`, `kysely`, `better-auth`, ...), so the config module carries only the project's code and the other packages it uses. The manifest's `protobase` is the version the bundle was built with, the building CLI's in a [bundled project](../reference/versioning.md#bundled-and-locked-projects) and the installed one in a locked project, and the host serves the bundle on the runtime of that version (see [Versioning](../reference/versioning.md#bundles-and-runtimes)). The manifest format and the routing rules are in the CLI reference: [`build`](../reference/cli.md#build), [`build-serve`](../reference/cli.md#build-serve) and [`serve`](../reference/cli.md#serve).
32
32
 
33
33
  ## Migrations
34
34
 
@@ -41,10 +41,10 @@ Every release pushes two public images to GitHub's registry, for `linux/amd64` a
41
41
  | Image | What it holds |
42
42
  | --- | --- |
43
43
  | `ghcr.io/prototeamhq/protobase:<version>` | the serve runtime, compiled with Bun into `/opt/protobase/protobase-serve`, which serves the API of the bundle mounted at `/app` (and, given the folder, its app too, see [a self-hosted image](#a-self-hosted-image)); the release's prebuilt admin app at `/opt/protobase/shell`, which a host may serve for the bundle's [shell paths](../reference/plugins.md#the-shell) instead of the bundle's copy; Bun for its healthcheck on `/health`, and the C++ runtime native add-ons link. It runs as `nonroot` (65532) and writes nothing, so it runs with a read-only root filesystem |
44
- | `ghcr.io/prototeamhq/protobase-dev:<version>` | Bun and the presets at `/opt/protobase/presets/<name>` (`erp`, `real-estate`, `scratch`), with the dependencies they share installed in `/workspace` and Bun's cache in `/opt/bun-cache`. It has no Node: the presets' scripts and the `protobase` command run on Bun. It runs as `bun` (1000) |
44
+ | `ghcr.io/prototeamhq/protobase-dev:<version>` | Bun, the `protobase` command of that version installed globally (in `/opt/protobase/cli`, on `PATH`), and the presets at `/opt/protobase/presets/<name>` (`erp`, `real-estate`, `scratch`), with the dependencies they share installed in `/workspace` and Bun's cache in `/opt/bun-cache`. The global `protobase` builds a bundled project with nothing installed and hands a locked one over to the CLI it installed (see [Bundled and locked projects](../reference/versioning.md#bundled-and-locked-projects)). It has no Node: the presets' scripts and the `protobase` command run on Bun. It runs as `bun` (1000) |
45
45
 
46
46
  ```sh
47
- docker run -v "$PWD/dist:/app:ro" -p 127.0.0.1:8787:8787 -e DATABASE_URL -e PROTOBASE_URL -e PROTOBASE_SECRET ghcr.io/prototeamhq/protobase:0.2.0
47
+ docker run -v "$PWD/dist:/app:ro" -p 127.0.0.1:8787:8787 -e DATABASE_URL -e PROTOBASE_URL -e PROTOBASE_SECRET ghcr.io/prototeamhq/protobase:"$VERSION" # the version of the @protobase/cli that built dist/
48
48
  ```
49
49
 
50
50
  In `protobase-dev`, copy a preset into `/workspace` and `bun install --frozen-lockfile` has nothing to do; installed anywhere else, it comes from the cache, without the network.
@@ -54,7 +54,7 @@ The Dockerfiles are `docker/protobase/Dockerfile` and `docker/protobase-dev/Dock
54
54
  ```sh
55
55
  bun run images:context # dist/images/protobase and dist/images/protobase-dev
56
56
  docker build -f docker/protobase/Dockerfile -t protobase dist/images/protobase
57
- docker build -f docker/protobase-dev/Dockerfile -t protobase-dev dist/images/protobase-dev
57
+ docker build -f docker/protobase-dev/Dockerfile --build-arg PROTOBASE_VERSION="$(bun -p "require('./package.json').version")" -t protobase-dev dist/images/protobase-dev
58
58
  ```
59
59
 
60
60
  ## A self-hosted image
@@ -62,8 +62,9 @@ docker build -f docker/protobase-dev/Dockerfile -t protobase-dev dist/images/pro
62
62
  A product built on Protobase ships to self-hosters as one image: the runtime image with the bundle inside. Build the bundle with `protobase build --bun`, then:
63
63
 
64
64
  ```dockerfile
65
- # The runtime of the @protobase/cli version that built dist/.
66
- FROM ghcr.io/prototeamhq/protobase:0.2.0
65
+ # The runtime of the @protobase/cli version that built dist/: docker build --build-arg VERSION=<that version> .
66
+ ARG VERSION
67
+ FROM ghcr.io/prototeamhq/protobase:${VERSION}
67
68
  COPY dist /app
68
69
  CMD ["/app"]
69
70
  ```
@@ -189,3 +190,18 @@ docker compose up -d
189
190
  Stop any `protobase worker` processes before `migrate` too.
190
191
 
191
192
  When a migration fails, `migrate` exits with an error and its transaction is rolled back, so the schema is unchanged. Set `APP_VERSION` back and `docker compose start app` brings the old version back on it. A plain `docker compose up -d` with the new version also stops the old one before `migrate`, but after a failure nothing serves until `APP_VERSION` is set back and `up -d` runs again. Going back after a migration that succeeded needs the backup.
193
+
194
+ ## Protobase Cloud
195
+
196
+ An app on Protobase Cloud whose code is on GitHub follows one branch of its repository, the default branch unless the app was linked to another. A push to that branch deploys it; nothing else does, and a change on another branch, a tag or a pull request deploys nothing.
197
+
198
+ 1. Protobase Cloud builds the branch's newest commit. While a build runs, later pushes wait, and the next build takes the newest commit then, so quick pushes give one build.
199
+ 2. The build installs the packages with `bun install --frozen-lockfile` and runs `protobase build`. It runs neither the project's typecheck nor its tests.
200
+ 3. The deploy stops the app's writes, then runs the project's `db:migrate`, the auth schema's migration and `protobase doctor --env DATABASE_URL` in one database transaction, which commits only when all of them pass. Pages keep reading meanwhile; a write, sign-in included, answers that the app is being updated.
201
+ 4. Writes come back, the new version starts on its own and must answer `/health` with its startup checks, and only then does the app switch to it.
202
+
203
+ When a step fails, the previous version keeps serving on the database as it was, except after a failed start, which comes after the migrations committed: they stay applied. Each build reports on GitHub as the check run `Protobase deploy` on the commit it built, with the step that failed and the end of its output. A commit whose build failed is not built again: the fix is a new push.
204
+
205
+ Since the deploy runs neither the typecheck nor the tests, and refuses what `doctor` refuses, check a change before pushing it: the project's typecheck and tests, `protobase doctor --env DATABASE_URL` on a database with the migrations applied, and `protobase build`. The migrations run in one transaction, so a statement Postgres refuses in one, such as `create index concurrently`, fails the deploy. Protobase Cloud also pushes to the branch itself, for an update of the app's Protobase packages, so pull before pushing.
206
+
207
+ [`protobase skill install`](../reference/cli.md#skill) writes the `protobase-cloud` agent skill into the project, with how to check that a change went live and why a deploy failed, step by step.
@@ -77,7 +77,7 @@ import { StepsDisplay, StepsEditor } from './components/order-steps'
77
77
  export { OrdersPerDay } from './components/orders-per-day'
78
78
 
79
79
  export default definePlugin({
80
- actions: { send },
80
+ // ...the plugin's other entries, such as its actions
81
81
  fields: { steps: { of: ['enum'], display: StepsDisplay, editor: StepsEditor } },
82
82
  })
83
83
  ```
@@ -143,7 +143,7 @@ export const salesOverview = page(
143
143
  )
144
144
  ```
145
145
 
146
- `{ plugin: 'sales-tools' }` tells `protobase build` that the project's own `protobase.ui.tsx` does not have the component, so it does not fail on it. Start the app with `bun run protobase dev` and sign in: the start page shows the card with the five newest drafts, and `sales-tools 1.0.0` under them. `/api/meta` named the plugin, the app read its `plugin.json`, saw that it fits, and loaded its module and stylesheet.
146
+ `{ plugin: 'sales-tools' }` tells `protobase build` that the project's own `protobase.ui.tsx` does not have the component, so it does not fail on it. The ERP exports the page from `config/index.ts` already (`export { salesOverview } from './overview/page'`); in another app, add that export, since Protobase finds pages there. Start the app with `bun run protobase dev` and sign in: the start page shows the card with the five newest drafts, and `sales-tools 1.0.0` under them. `/api/meta` named the plugin, the app read its `plugin.json`, saw that it fits, and loaded its module and stylesheet.
147
147
 
148
148
  ## 6. Change the plugin, not the app
149
149
 
@@ -8,7 +8,7 @@ Until 0.12, `protobase build` built the whole admin app into each bundle, with t
8
8
 
9
9
  ## 1. Update and rebuild
10
10
 
11
- Move the project's `@protobase` packages to 0.12 or newer, as for any release, and build:
11
+ Move the project's `@protobase` packages to 0.12, as for any release, and build; `^0.12` takes 0.12's patches only, since below 1.0 a new minor is a release of its own, moved to the same way once the project builds on 0.12:
12
12
 
13
13
  ```sh
14
14
  bun add @protobase/cli@^0.12 @protobase/server@^0.12 @protobase/schema@^0.12 @protobase/layout@^0.12 @protobase/ui@^0.12
@@ -53,7 +53,7 @@ export const ticketNotes = resource('ticket_notes')
53
53
  .access({ delete: deskOnly })
54
54
  ```
55
55
 
56
- Only the desk's own admins delete: the [access rule](../reference/access.md) holds for everyone who reaches the desk's API, the shop's people included.
56
+ The tables come first, as a migration of the desk's (a new file in `db/migrations/`, applied with `bun run db:migrate`), and the resources are exported from the desk's `config/index.ts`, where Protobase finds them: `export * from './tickets/data'`. Only the desk's own admins delete: the [access rule](../reference/access.md) holds for everyone who reaches the desk's API, the shop's people included.
57
57
 
58
58
  ```ts
59
59
  // desk: config/tickets/ui.ts
@@ -12,7 +12,7 @@ This guide follows that admin from nothing to something the front desk and the w
12
12
 
13
13
  Everything starts with the data config: what the tables are, as they are. `protobase scaffold` writes it from the database, and Pip tidies it up:
14
14
 
15
- ```ts title="config/data.ts"
15
+ ```ts title="config/bike-shop/data.ts"
16
16
  import { f, resource } from '@protobase/schema'
17
17
 
18
18
  // Pip's bike shop: customers bring bikes in, the workshop repairs them. Two tables of a Postgres database the
@@ -56,11 +56,11 @@ export const repairs = resource('repairs')
56
56
  .validate((repair) => (repair.status === 'collected' && !repair.paid ? [{ field: 'paid', message: 'A bike leaves the shop paid' }] : undefined))
57
57
  ```
58
58
 
59
- The fields follow the columns, with what the database does not say added: which fields can be filtered and sorted, which ones the database fills in (`dbDefault`), which are read-only. `notes` lives in a column called `internal_notes`, and `legacy_ref: null` keeps an old column out for good. The `validate` rule holds the shop's one firm rule: a bike does not leave unpaid.
59
+ `scaffold` writes a file per table, `config/repairs/data.ts` and `config/customers/data.ts`, and exports each from `config/index.ts`, where Protobase finds the resources; Pip keeps both in one file, exported the same way: `export * from './bike-shop/data'`. The fields follow the columns, with what the database does not say added: which fields can be filtered and sorted, which ones the database fills in (`dbDefault`), which are read-only. `notes` lives in a column called `internal_notes`, and `legacy_ref: null` keeps an old column out for good. The `validate` rule holds the shop's one firm rule: a bike does not leave unpaid.
60
60
 
61
- For the admin to list repairs, a view is enough, even an empty one:
61
+ For the admin to list repairs, a view is enough, even an empty one. A `ui.ts` in a folder of `config/` is found by its path, without an export:
62
62
 
63
- ```ts title="config/ui.ts"
63
+ ```ts title="config/bike-shop/ui.ts"
64
64
  import { view } from '@protobase/schema'
65
65
  import type { customers, repairs } from './data'
66
66
 
@@ -77,7 +77,7 @@ That is already a working admin: every column, sorting, paging, a record page an
77
77
 
78
78
  The list shows everything, including the problem descriptions nobody reads in a list. The front desk wants the repair number, whose bike, what state it is in, and who is on it, newest first.
79
79
 
80
- ```ts title="config/ui.ts"
80
+ ```ts title="config/bike-shop/ui.ts"
81
81
  import { view } from '@protobase/schema'
82
82
  import type { customers, repairs } from './data'
83
83
 
@@ -111,7 +111,7 @@ export const repairsView = view<typeof repairs>('repairs')
111
111
 
112
112
  On Saturdays the desk asks the same questions over and over: what is ready, what is Sem working on, what came in this week, what is not paid. Filters answer them in one click.
113
113
 
114
- ```ts title="config/ui.ts"
114
+ ```ts title="config/bike-shop/ui.ts"
115
115
  import { customersView, repairsView as named } from './step-2'
116
116
 
117
117
  // Step 3: the filters the front desk reaches for, and a chart of bookings above the list.
@@ -135,7 +135,7 @@ From here on each step starts from the view of the step before (`named` is step
135
135
 
136
136
  The record page still lists every field in one long column. The paper card the desk uses has three parts: the bike and its problem, the workshop's side, and the money. The layout copies it.
137
137
 
138
- ```ts title="config/ui.ts"
138
+ ```ts title="config/bike-shop/ui.ts"
139
139
  import { l } from '@protobase/schema'
140
140
  import { customersView, repairsView as filtered } from './step-3'
141
141
 
@@ -170,7 +170,7 @@ l.related('Parts used', { resource: 'repair_parts', field: 'repair_id', when: 'e
170
170
 
171
171
  Two things happen to every repair: it becomes ready, and it gets collected (and paid). Typing a status into a dropdown is how mistakes happen, so they become buttons. And the mechanics would rather not see prices at all.
172
172
 
173
- ```ts title="config/ui.ts"
173
+ ```ts title="config/bike-shop/ui.ts"
174
174
  import { l } from '@protobase/schema'
175
175
  import { customersView, repairsView as laidOut } from './step-4'
176
176
 
@@ -80,7 +80,7 @@ The action runs at `POST /api/v1/{resource}/{key}:generate` with `{ "action": "<
80
80
  | `404` | `not-found` | The caller's view has no AI action of that name, or there is no such record. |
81
81
  | `403` | `ai-forbidden` | The caller may not read a field the prompt reads, or update the field it writes. |
82
82
  | `422` | `ai-no-value` | Every field the prompt reads is empty, or the model answered nothing. |
83
- | `502` | `ai-unavailable` | The model failed or took more than 60 seconds. The user sees only that; the endpoint's message goes to the app's error reporting (`onUnhandledError`). |
83
+ | `502` | `ai-unavailable` | The model failed or took more than 60 seconds. The user sees only that; the endpoint's message goes to the app's error reporting (its [`hooks/error.ts`](config/api.md#code-of-the-api)). |
84
84
  | `503` | `ai-not-configured` | No model is set; startup normally catches this first. |
85
85
 
86
86
  Every check is made before the model is asked.
@@ -4,7 +4,7 @@
4
4
 
5
5
  The REST API that @protobase/server generates, with its routes, access, filters, writes, batches and errors.
6
6
 
7
- `@protobase/server` turns resource definitions into a Hono app that follows Google's API design conventions ([AIP-131 to 136](https://google.aip.dev/131), [158](https://google.aip.dev/158), [160](https://google.aip.dev/160)). It uses Web APIs only and runs on Node and Workers; the Node adapter lives in the example.
7
+ `@protobase/server` turns resource definitions into a Hono app that follows Google's API design conventions ([AIP-131 to 136](https://google.aip.dev/131), [158](https://google.aip.dev/158), [160](https://google.aip.dev/160)). It uses Web APIs only and runs on Node, Bun and Workers; `protobase dev` and `serve` serve it on Node or Bun.
8
8
 
9
9
  `protobase dev` and `serve` build it from the project: the resources of `config/`, the functions of `functions/`, sign-in from `auth`, and the API's settings from the top-level keys of [`protobase.config.ts`](config.md), such as `statementTimeoutMs` and `scanGuard`. In code of its own, an app builds it with `createAdmin`, whose `options` take the same settings:
10
10
 
@@ -23,7 +23,7 @@ const admin = createAdmin({
23
23
  })
24
24
  ```
25
25
 
26
- Run the ERP example with `bun run --cwd tests/apps/erp serve` (port 8787, Better Auth login, organization 1 as tenant; `REQUEST_LOG=true` logs requests). Interactive reference: `/api/docs`; like `/api/openapi.json` it needs a bearer token, because the document lists what the caller may see and do. Every route answers `401` without a valid token; get one with `protobase token you@example.com`. A project whose roles define [`anonymous`](access.md#anonymous-access) serves the resources API to requests without a token as that role.
26
+ Run the ERP example with `bun run --cwd tests/apps/erp serve` (port 8787, Better Auth login, the user's active [organization](auth.md#organizations) as tenant; `REQUEST_LOG=true` logs requests). Interactive reference: `/api/docs`; like `/api/openapi.json` it needs a bearer token, because the document lists what the caller may see and do. Every route answers `401` without a valid token; get one with `protobase token you@example.com`. A project whose roles define [`anonymous`](access.md#anonymous-access) serves the resources API to requests without a token as that role.
27
27
 
28
28
  ## Routes
29
29
 
@@ -196,7 +196,7 @@ The API sends no CORS headers until it has something to allow: other websites in
196
196
 
197
197
  ## Safety
198
198
 
199
- - Every request runs in a transaction with `SET LOCAL statement_timeout` (`statementTimeoutMs`, default 1 s), so a slow query fails where it runs instead of holding a connection that other requests wait for. List, search, get, histogram, series, map and seek transactions are read-only. A query that runs longer is stopped: a `504` `statement-timeout` that names the request, its limit and the ways out, such as `GET /api/v1/orders ran a query longer than 1 s, so the database stopped it. Make the query faster, such as with an index or a narrower filter, or move the work into a function or job with longQueries: true, whose queries may run up to 30 s.` It goes to `options.onUnhandledError` and the [error tracker](#error-reporting) like a `500`. A read that needs longer has no way to opt out: give it an index, or move it into a [function](../guides/api-functions.md#long-queries) or [job](jobs.md) with `longQueries`.
199
+ - Every request runs in a transaction with `SET LOCAL statement_timeout` (`statementTimeoutMs`, default 1 s), so a slow query fails where it runs instead of holding a connection that other requests wait for. List, search, get, histogram, series, map and seek transactions are read-only. A query that runs longer is stopped: a `504` `statement-timeout` that names the request, its limit and the ways out, such as `GET /api/v1/orders ran a query longer than 1 s, so the database stopped it. Make the query faster, such as with an index or a narrower filter, or move the work into a function or job with longQueries: true, whose queries may run up to 30 s.` It goes to the app's error hook (`hooks/error.ts`, `createAdmin`'s `options.onUnhandledError`) and the [error tracker](#error-reporting) like a `500`. A read that needs longer has no way to opt out: give it an index, or move it into a [function](../guides/api-functions.md#long-queries) or [job](jobs.md) with `longQueries`.
200
200
  - Under `protobase dev` and `serve`, a request waits at most 2 seconds for a free database connection. When every connection stays busy that long, it is a `503` `connections-busy` with `Retry-After: 1` that names the request, reported the same way, rather than a request that hangs behind slow ones.
201
201
  - **Scan guard**: a list, `:search`, `:seek`, `:map` page, card photos, `:facets` and `:aggregate` read only columns an index serves, so they stay cheap however many rows match. The server reads each table's valid indexes from the catalog once, then checks every column the caller's filter, the role's row filter, the sort's first field and a facet's or an aggregate's grouped field read:
202
202
  - Comparisons, `in`, null checks, sorts and facets need a btree index with the column as a key, every key before it pinned by the query: by `=` or `in` in the filter (outside `OR` and `NOT`), by the tenant or by soft delete. `(for_sale, status, published_at desc)` serves `for_sale = true AND status = "available"` sorted by `published_at desc`, but not `status` alone. `=` on text may use a pg_trgm index instead.
@@ -207,7 +207,7 @@ The API sends no CORS headers until it has something to allow: other websites in
207
207
 
208
208
  ## Errors
209
209
 
210
- Every error is `application/problem+json` (RFC 9457) with `type` (`urn:protobase:problem:<slug>`), `title`, `status`, `detail`, `instance`. Filter and `order_by` errors add `parameter` and `errors: [{ code, message, hint, span: { start, end } }]`; invalid parameters add `errors: [{ parameter, message }]`. A create or update whose body fails the checks is `invalid-record` with `errors: [{ field, code, message, params }]`, `code` one of `required`, `invalid-value`, `read-only`, `unknown-field` and `invalid-record` (a `.validate()` rule); `params` is the limit an invalid value broke, such as `{ min }`, `{ max }` or a decimal's `{ precision, scale }`. Database constraint failures map to `409` or `400` without the raw message. A create or update that writes the position of a resource with `after` so a record ranks at or above one it depends on is a `409` `ranks-above-dependency`, as in a [`reorder`](#batch-writes). A delete that other records still point at is a `409` `conflict` with `blockedBy: { resource, field? }`: their resource, when the caller may list it, and its relation field pointing at the record, when they may filter by it, so a client can open those records; the admin app's toast names them, such as "Orders still point at this company.", with a link to that list. Postgres names one table of them only, so `blockedBy` holds one resource; anything unexpected is a `500` with a fixed detail, reported to `options.onUnhandledError` and, when it is set, the [error tracker](#error-reporting).
210
+ Every error is `application/problem+json` (RFC 9457) with `type` (`urn:protobase:problem:<slug>`), `title`, `status`, `detail`, `instance`. Filter and `order_by` errors add `parameter` and `errors: [{ code, message, hint, span: { start, end } }]`; invalid parameters add `errors: [{ parameter, message }]`. A create or update whose body fails the checks is `invalid-record` with `errors: [{ field, code, message, params }]`, `code` one of `required`, `invalid-value`, `read-only`, `unknown-field` and `invalid-record` (a `.validate()` rule); `params` is the limit an invalid value broke, such as `{ min }`, `{ max }` or a decimal's `{ precision, scale }`. Database constraint failures map to `409` or `400` without the raw message. A create or update that writes the position of a resource with `after` so a record ranks at or above one it depends on is a `409` `ranks-above-dependency`, as in a [`reorder`](#batch-writes). A delete that other records still point at is a `409` `conflict` with `blockedBy: { resource, field? }`: their resource, when the caller may list it, and its relation field pointing at the record, when they may filter by it, so a client can open those records; the admin app's toast names them, such as "Orders still point at this company.", with a link to that list. Postgres names one table of them only, so `blockedBy` holds one resource; anything unexpected is a `500` with a fixed detail, reported to the app's error hook (`hooks/error.ts`, `createAdmin`'s `options.onUnhandledError`) and, when it is set, the [error tracker](#error-reporting).
211
211
 
212
212
  | Status | Slugs |
213
213
  | --- | --- |
@@ -10,26 +10,31 @@ A Bun workspace of npm packages under the `@protobase` scope, in `packages/<name
10
10
 
11
11
  | Package | Folder | Entry points | Runs in | Depends on |
12
12
  | --- | --- | --- | --- | --- |
13
- | `@protobase/schema` | `packages/schema` | `@protobase/schema` | anywhere | no other `@protobase` package |
13
+ | `@protobase/schema` | `packages/schema` | `@protobase/schema`, `@protobase/schema/png-icons`; `@protobase/schema/internal` for the other packages only | anywhere | no other `@protobase` package |
14
14
  | `@protobase/layout` | `packages/layout` | `@protobase/layout`, `@protobase/layout/jsx-runtime`, `@protobase/layout/jsx-dev-runtime` | anywhere | `schema` |
15
15
  | `@protobase/query` | `packages/query` | `@protobase/query` | server | `schema` |
16
16
  | `@protobase/client` | `packages/client` | `@protobase/client` | anywhere with `fetch` | `schema`, `layout` |
17
- | `@protobase/ui` | `packages/ui` | `@protobase/ui`; the admin app in `src/app` | browser | `schema`, `layout`, `client` |
18
- | `@protobase/server` | `packages/server` | `@protobase/server` | server | `schema`, `layout`, `query` |
19
- | `@protobase/cli` | `packages/cli` | the `protobase` command (`bin/protobase.mjs`) | Node and Bun | `schema`, `layout`, `query`, `server`, `ui` |
17
+ | `@protobase/ui` | `packages/ui` | `@protobase/ui`, `@protobase/ui/theme.css`, `@protobase/ui/styles.css`; the admin app in `src/app` | browser | `schema`, `layout`, `client` |
18
+ | `@protobase/server` | `packages/server` | `@protobase/server`, `@protobase/server/auth-store`, `@protobase/server/config-exports`, `@protobase/server/email`, `@protobase/server/vapid`; `@protobase/server/internal` for the other packages only | server | `schema`, `layout`, `query` |
19
+ | `@protobase/config` | `packages/config` | `@protobase/config`, `@protobase/config/schema.json` | anywhere | types of `server` only: it runs nothing besides `defineConfig` |
20
+ | `@protobase/cli` | `packages/cli` | the `protobase` command (`bin/protobase.mjs`), `@protobase/cli/auth`, `@protobase/cli/runner` | Node and Bun | `config`, `schema`, `layout`, `query`, `server`, `ui` |
21
+ | `@protobase/mobile` | `packages/mobile` | none: the Capacitor packages and native plugins `protobase mobile` installs on first use | the app's iOS and Android projects | none |
22
+ | `create-protobase` | `packages/create-protobase` | the `create-protobase` command, for `npm create protobase` | Node | none |
20
23
  | `@protobase/presets` | `packages/presets` | none: private, `bun run presets:write` writes a project per preset | Bun | none; each preset depends on the `@protobase` packages of the major it is written at, locked at that version |
21
24
  | `tests/apps/*` | | none | any | `@protobase/*` entry points only |
22
25
 
23
- The presets are written from `tests/apps/erp`, `tests/apps/real-estate` and `tests/apps/scratch` (from scratch) by `bun run presets:write <version> <dir>`, run from a clone of this repository; `npm create protobase` (`packages/create-protobase`) writes them too, without a lockfile. Each is a standalone copy with the `@protobase` packages in the caret range of `<version>`, `^x.y.z`, so an app takes the updates semver calls compatible: within that major from 1.0 on, and within that minor below 1.0, where a minor may break, and its own `bun.lock` at exactly `<version>`. The three declare the same dependencies, so one `node_modules` fits them all, and their `db:migrate` (the auth schema's migrations included), `typecheck` and `test` scripts take their settings from the environment, or a `.env` beside them, and reach nothing outside the project.
26
+ The presets are written from `tests/apps/erp`, `tests/apps/real-estate` and `tests/apps/scratch` (from scratch) by `bun run presets:write <version> <dir>`, run from a clone of this repository; `npm create protobase` (`packages/create-protobase`) writes them too, without a lockfile. Each is a standalone copy with the `@protobase` packages in `devDependencies`, so an app made from it is [bundled](versioning.md#bundles-and-runtimes) and runs on the CLI's own copies, in the caret range of `<version>`, `^x.y.z`, so an app takes the updates semver calls compatible: within that major from 1.0 on, and within that minor below 1.0, where a minor may break, and its own `bun.lock` at exactly `<version>`. Its `tsconfig.json` extends `.protobase/tsconfig.json`, which [`protobase types`](cli.md#types) writes, as `dev`, `build` and its `typecheck` and `test` scripts do first, and its database scripts run with [`protobase run`](cli.md#run). The examples in this repository list the packages in `dependencies`, locked to the workspace's, and their `tsconfig.json` extends nothing: Vite reads it when it transforms their files, and would fail before the file it extends is written. The three declare the same dependencies, so one `node_modules` fits them all, and their `db:migrate` (the auth schema's migrations included), `typecheck` and `test` scripts take their settings from the environment, or a `.env` beside them, and reach nothing outside the project.
24
27
 
25
28
  The JSX runtime belongs to `@protobase/layout` because a layout file names one package in `@jsxImportSource @protobase/layout`, and TypeScript and Vite look up `jsx-runtime` and `jsx-dev-runtime` under it. Each field type is split along the same lines: its Zod builder is `packages/schema/src/fields/<type>.ts` and its SQL parameter conversion `packages/query/src/fields/<type>.ts`.
26
29
 
27
30
  Every package lists the packages it imports in its `package.json` (`workspace:*` for its `@protobase` dependencies), so it installs and works on its own. Rules, enforced by `bun run check:boundaries` (`.dependency-cruiser.cjs`):
28
31
 
29
32
  - A package imports only the `@protobase` packages in the table above, so `@protobase/ui` never reaches `query`, `server` or `cli`, and `@protobase/layout` only `schema`: layouts are built in the config, checked on the server and rendered in the browser.
33
+ - `@protobase/config` imports types only, so reading a config loads nothing but it and the config.
30
34
  - A package imports another by its name and entry point, never by a path into its source.
31
35
  - A package's code (not its tests and stories) imports only what its `package.json` lists in `dependencies`.
32
36
  - Examples, their tests and `test-support/` import the packages by name, never by path.
37
+ - Only an encrypted field's reveal and the `encryption` commands decrypt its values.
33
38
  - No circular dependencies.
34
39
 
35
40
  In this repository, entry points export TypeScript source directly and the CLI runs its source on Bun, or on Node through [tsx](https://tsx.is), so nothing needs a build. The published packages are built to JavaScript in `dist` by `bun run build` and `bun pm pack` (`scripts/publish.mjs`) (see [CLI](cli.md#how-it-runs)). The other builds are for deployment: the serve runtime, `packages/cli/src/serve/main.ts` bundled with its dependencies into `dist/protobase-serve.js` by `protobase build-serve`, the shell, a production build of the admin app (`packages/ui/src/app`) shipped in `@protobase/ui`'s `dist/shell` and the protobase image, and a project's bundle, its config module plus a copy of the shell and the project's `protobase.ui.tsx` built as a [plugin](plugins.md), by `protobase build` (see [CLI](cli.md#build)).
@@ -58,6 +63,6 @@ Filters are Google AIP-160 text. Parsing, printing, `order_by` and the generic c
58
63
 
59
64
  ## Documentation
60
65
 
61
- `website/` is this site. `bun run docs:dev` serves it on port 4321; `bun run docs:build` writes `website/dist/` and fails on a broken internal link or anchor, so CI runs it on every pull request, followed by `bun run docs:check`, which opens every page in Chromium and fails on a console error or a failed request. Pages are Markdown or MDX in `website/src/content/docs/`, and the sidebar is listed in `website/astro.config.mjs`.
66
+ `website/` is this site. `bun run docs:dev` serves it on port 4321; `bun run docs:build` writes `website/dist/` and fails on a broken internal link or anchor, so CI runs it on every pull request, followed by `bun run docs:check`, which opens every page in Chromium and fails on a console error or a failed request. Pages are Markdown or MDX in `website/src/content/docs/`, and the sidebar is listed in `website/sidebar.mjs`.
62
67
 
63
68
  Every push to `main` builds the site and deploys it, and so does running the workflow by hand (`gh workflow run docs.yml`); either way it deploys to the Cloudflare Pages project `protobase-docs`, served at `docs.protobase.net` (`.github/workflows/docs.yml`). The workflow reads the Cloudflare account id from the repository variable `CLOUDFLARE_ACCOUNT_ID` and a token with Cloudflare Pages edit permission from the repository secret `CLOUDFLARE_API_TOKEN`.
@@ -68,7 +68,7 @@ Making the query role needs `CREATEROLE` once, for the role that applies the mig
68
68
 
69
69
  `assistant/tools.ts` adds tools of the app's own, which the built-in backend offers after its two: its default export is an array of tools, found by that path when the app starts. A tool is `defineTool({ name, description, parameters, run })` from `@protobase/server`: `parameters` is the JSON Schema of its arguments, and `run(args, context)` returns the text the model reads. A name must be 1 to 64 letters, digits, `_` or `-`, and a name taken twice stops the server at startup. A backend elsewhere has its own tools, so the file does nothing there, nor with `assistant: false`. A tool's `annotations` are MCP's tool hints (`readOnlyHint`, `destructiveHint`, ...), which the dock ignores; the same tools can be offered over the app's [MCP endpoint](mcp.md#building-on-it).
70
70
 
71
- `context` holds the user's `session`, `show(part)` to add a part to the answer, `approve(request)` for an approval card, `conversation` (the dock's, absent over MCP), `resources()` (the resources the user may read, restricted to their fields, with their views), and `records`: `list(resource, params)` with the REST API's list parameters, `get(resource, key)`, `create(resource, data)`, `update(resource, key, data, { etag? })` (without an ETag it updates any version), `delete(resource, key, { etag? })` (soft on a resource with `.softDelete()`) and `softDeleteField(resource)` (the field a delete sets, or `undefined` when a delete removes the record) on the app's resources **as the user**, through their access rules, tenant scope, validation and write hooks, as in the REST API. Each answers `{ record, etag }`. `batch(operations)` runs the operations of a REST [batch write](api.md#batch-writes) in one transaction and answers its `results`; a refusal or a missing record rejects with an `HttpProblem`, whose `detail` a tool can return to the model as text.
71
+ `context` holds the user's `session`, `show(part)` to add a part to the answer, `approve(request)` for an approval card, `conversation` (the dock's, absent over MCP), `resources()` (the resources the user may read, restricted to their fields, with their views), and `records`: `list(resource, params)` with the REST API's list parameters, `get(resource, key)`, `create(resource, data)`, `update(resource, key, data, { etag? })` (without an ETag it updates any version), `delete(resource, key, { etag? })` (soft on a resource with `.softDelete()`) and `softDeleteField(resource)` (the field a delete sets, or `undefined` when a delete removes the record) on the app's resources **as the user**, through their access rules, tenant scope, validation and write hooks, as in the REST API. `get`, `create`, `update` and `delete` each answer `{ record, etag }`, and `list` a page of records. `batch(operations)` runs the operations of a REST [batch write](api.md#batch-writes) in one transaction and answers its `results`; a refusal or a missing record rejects with an `HttpProblem`, whose `detail` a tool can return to the model as text.
72
72
 
73
73
  A tool with a [widget](#widget-parts) creates or finds what it is about, shows a widget with its id, and returns the id and the state at that moment:
74
74
 
@@ -38,7 +38,7 @@ Each version's statements are followed by its row in `auth_migrations`. The file
38
38
 
39
39
  Every store has the tables of every feature, whether the app turns the feature on or not: [passkeys](#passkeys), [two-factor authentication](#two-factor-authentication), [organizations](#organizations) and the [OAuth provider for MCP](#oauth-for-mcp-clients). Turning a feature on or off needs no migration and drops nothing; the columns a feature adds to the user and session tables are empty until it is on. SAML providers and open sign-up keep nothing in the store.
40
40
 
41
- The store's tables and columns are snake_case, like the app's (`sign_in_policy.platform_sign_in`, `session.user_id`); the code and the API keep Better Auth's camelCase names. The names the app configures, the store's schema (`schemaName`), the [user table](#an-existing-users-table) and its columns, and uuid ids (`generateUserId: 'uuid'`), are the ones in effect when the file is written. Changing one later is a migration of the project's own, such as a rename.
41
+ The store's tables and columns are snake_case, like the app's (`sign_in_policy.platform_sign_in`, `session.user_id`); the code and the API keep Better Auth's camelCase names. The names the app configures, the store's schema ([`auth.schema`](config/sign-in.md#authschema)), the [user table](#an-existing-users-table) and its columns, and uuid ids (`generateUserId: 'uuid'`), are the ones in effect when the file is written. Changing one later is a migration of the project's own, such as a rename.
42
42
 
43
43
  The server never changes the schema, and never compares it with what Better Auth needs. `protobase serve` and `protobase dev` read `auth_migrations` at startup and refuse to start while a version of this Protobase is not applied, naming it and `protobase auth migration`, or while the store has a version newer than this Protobase knows. The examples' `db:migrate` applies all pending files in one transaction, so a migration that fails leaves the database as the running version expects it. The host must guarantee the rest: nothing but the migrations writes while they run, and the new version serves only after they succeeded. Only [`protobase dev`](cli.md#dev), on the developer's machine, compares the store's tables with what the app's Better Auth needs, and warns at startup about each table, column or index that drifted, such as one changed by hand.
44
44
 
@@ -72,7 +72,7 @@ The store's migrations make the user table only when it is missing, and add each
72
72
  | `PROTOBASE_SECRET` | the app's secret, the default of `secret`: signs cookies and encrypts the token keys; `openssl rand -base64 32`; never committed (`.env.example` has a placeholder) |
73
73
  | `PROTOBASE_PREVIOUS_SECRETS` | the app's secrets before `PROTOBASE_SECRET`, newest first, comma separated, the default of `previousSecrets`; see [Changing the secret](#changing-the-secret) |
74
74
  | `PROTOBASE_URL` | the app's public URL, the default of `url` (in `protobase dev`, the dev server's own); issuer and audience of the tokens; when tunnelling, the https tunnel URL |
75
- | `PROTOBASE_TRUSTED_ORIGINS` | extra comma separated origins, the default of `auth.trustedOrigins`; a dev tunnel needs its exact host here, such as `https://my-tunnel.trycloudflare.com`, since no wildcard is trusted |
75
+ | `PROTOBASE_TRUSTED_ORIGINS` | extra comma separated origins, the default of `auth.trustedOrigins`; a dev tunnel needs its exact host here, such as `https://my-tunnel.trycloudflare.com`, since none is trusted by default; an entry with `*` trusts every host it matches |
76
76
  | `PROTOBASE_ORIGINS` | the other origins the app is served on, comma separated, passed by the platform; see [Several origins](#several-origins) |
77
77
  | `PROTOBASE_PASSKEY_DOMAIN` | the host new [passkeys](#passkeys) are made for, passed by the platform; default the host of the app's `url` |
78
78
  | `PROTOBASE_CORS_ORIGINS` | other websites whose browser code may call the API, `*` or comma separated http and https origins, passed by the platform; see [CORS](api.md#cors) |
@@ -128,14 +128,14 @@ Accounts are never created over the web while the store is empty: there is no se
128
128
 
129
129
  ```ts
130
130
  import { loadProjectAuth } from '@protobase/cli/auth'
131
- import { createUser, hasUsers, listUsers } from '@protobase/server'
131
+ import { createUser, deleteUser, hasUsers, listUsers, setUserBanned, setUserRole } from '@protobase/server'
132
132
 
133
133
  const auth = await loadProjectAuth(process.cwd()) // the project's folder; its .env is loaded too
134
134
 
135
135
  await createUser(auth, { email, password?, name?, role? }) // the first user is always an admin; later ones default to `user`
136
136
  await hasUsers(auth) // boolean
137
137
  await listUsers(auth) // [{ id, email, role, banned, createdAt }], never passwords
138
- await setUserRole(auth, { email, role }) // 'admin' | 'user'
138
+ await setUserRole(auth, { email, role }) // a role of auth.roles, or several comma separated
139
139
  await setUserBanned(auth, { email, banned }) // banning ends the user's sessions and blocks sign-in
140
140
  await deleteUser(auth, email) // with sessions and accounts
141
141
  ```
@@ -587,6 +587,19 @@ It is Better Auth's organization plugin, with its tables named in snake_case (`o
587
587
 
588
588
  **Ids.** The `generateOrganizationId` [hook](#hooks) makes a new organization's id, by default a UUID; `.tenant` columns hold it, so `text` or `uuid`. An app whose tenant columns are integers takes the next value of its own organizations sequence instead, and adds its own row in `onOrganizationCreated`, as the ERP example does (`tests/apps/erp/auth/hooks.ts`). An app that ran as one organization keeps its tenant value: `protobase organizations create "Acme" --owner you@example.com --id 1 --members all` makes that organization, with every user in it: superusers as owners, everyone else as a member, their global roles moved onto the membership.
589
589
 
590
+ **On the host.** The [`protobase organizations`](cli.md#organizations) commands call these functions of `@protobase/server`, which a script of the project's own, such as a seed, calls with the sign-in of [`loadProjectAuth`](#first-run). The host acts as a superuser, so it may give any role; `organization` is a slug or an id:
591
+
592
+ ```ts
593
+ import { addAppRoleToOwners, addMember, createOrganization, listOrganizations, removeMember, setMemberRoles } from '@protobase/server'
594
+
595
+ await createOrganization(auth, { name, slug, owner: email, id? }) // the owner holds every app role
596
+ await addMember(auth, { organization, email, role?, appRoles? }) // role: owner, admin or member (default)
597
+ await setMemberRoles(auth, { organization, email, role?, appRoles? })
598
+ await removeMember(auth, { organization, email }) // refuses the last owner
599
+ await listOrganizations(auth) // oldest first, with members' emails and roles
600
+ await addAppRoleToOwners(auth, appRole) // a role the project added later, to every owner
601
+ ```
602
+
590
603
  The app's own pages are under the profile menu: the switcher, "Manage organizations" (theirs, a new one, and for global roles any one), "Organization" (details, leaving, handing over, deleting), and for owners and admins "Members" and "Invitations". The client has them as `session.organizations` (`list`, `current`, `switchTo`, `members`, `invite`, ...).
591
604
 
592
605
  ## Tokens and roles
@@ -4,7 +4,7 @@
4
4
 
5
5
  Every built-in layout block, its props and what it does, with examples from the ERP's sales overview.
6
6
 
7
- Blocks are imported from `@protobase/layout`. "Record" below means the record of the `RecordCard` or `CardRow` card around a block (see [Data](layouts.md#data)); `filter` is AIP-160 and `sort` AIP-132, as in the list API. Every block below but `RecordRow`, which the property portal's home uses, `RecordCards`, `Tabs` and `Tab`, `Settings`, and `Users`, which the [Users page](auth.md#users-page) uses, appears in the ERP example's sales overview:
7
+ Blocks are imported from `@protobase/layout`. "Record" below means the record of the `RecordCard` or `CardRow` card around a block (see [Data](layouts.md#data)); `filter` is AIP-160 and `sort` AIP-132, as in the list API. The ERP example's sales overview uses `Page`, `Grid`, `Card`, `Stat`, `Table`, `RecordCard`, `CardRow`, `Field`, `Chart`, `Action`, `ModalForm` and `Show`; of the others, the property portal's home uses `RecordRow`, and the [Users page](auth.md#users-page) `Users`:
8
8
 
9
9
  ```tsx title="tests/apps/erp/config/overview/page.tsx"
10
10
  /** @jsxImportSource @protobase/layout */
@@ -6,7 +6,7 @@ Tabs along the bottom of a phone, as on iOS, for the roles that work from one.
6
6
 
7
7
  On phones the sidebar is a drawer behind the top bar's menu button. For people who work from a phone, such as on a warehouse floor, a bottom bar puts their few screens one tap away: up to four tabs, each an icon above its label, the current one highlighted, and "More" last, which opens the drawer with the rest. The bar keeps clear of the iPhone home indicator. From the `md` breakpoint (768px) up there is no bar; the sidebar shows instead.
8
8
 
9
- Export a [`bottomBar(...)`](https://docs.protobase.net/api/schema/functions/bottombar/) from the config module for each group of roles that gets one:
9
+ Export a [`bottomBar(...)`](https://docs.protobase.net/api/schema/functions/bottombar/) from `config/index.ts` for each group of roles that gets one:
10
10
 
11
11
  ```ts
12
12
  // tests/apps/erp/config/bottom-bar.ts, re-exported from config/index.ts
@@ -36,7 +36,7 @@ Each bar names its roles, and a role belongs to one bar. A caller gets the bar t
36
36
 
37
37
  `createAdmin` refuses to start when a bar names a resource or page that does not exist, has no roles, no items or more than four, names a role the app does not have (the roles of [`auth.roles`](auth.md#roles) and [`defineRoles`](access.md); without either, any role is accepted), shares a role with another bar, or has the label of another bar. The checks are [`bottomBarErrors`](https://docs.protobase.net/api/schema/functions/bottombarerrors/) from `@protobase/schema`, a pure function of the bars and the app's names.
38
38
 
39
- `protobase dev`, `protobase build` and `protobase serve` pick the bars up from the config module. With `createAdmin` directly, pass them as `bottomBars`:
39
+ `protobase dev`, `protobase build` and `protobase serve` pick the bars up from `config/index.ts`. With `createAdmin` directly, pass them as `bottomBars`:
40
40
 
41
41
  ```ts
42
42
  const { resources, views, bottomBars } = configExports(config)