@protobase/cli 0.22.12 → 0.23.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 (49) hide show
  1. package/dist/main.js +2 -0
  2. package/dist/package.js +1 -1
  3. package/dist/skill/install.js +29 -0
  4. package/dist/skill/register.js +14 -0
  5. package/package.json +8 -7
  6. package/skills/protobase/SKILL.md +89 -0
  7. package/skills/protobase/references/getting-started.md +78 -0
  8. package/skills/protobase/references/guides/api-functions.md +240 -0
  9. package/skills/protobase/references/guides/billing-page.md +288 -0
  10. package/skills/protobase/references/guides/create-page.md +108 -0
  11. package/skills/protobase/references/guides/deploy.md +52 -0
  12. package/skills/protobase/references/guides/export-a-list.md +44 -0
  13. package/skills/protobase/references/guides/field-type.md +131 -0
  14. package/skills/protobase/references/guides/first-composed-page.md +230 -0
  15. package/skills/protobase/references/guides/first-plugin.md +166 -0
  16. package/skills/protobase/references/guides/import-records.md +43 -0
  17. package/skills/protobase/references/guides/plugin-build.md +64 -0
  18. package/skills/protobase/references/guides/record-card.md +70 -0
  19. package/skills/protobase/references/guides/remote-resources.md +185 -0
  20. package/skills/protobase/references/guides/table-to-admin.md +205 -0
  21. package/skills/protobase/references/guides/theme-an-app.md +87 -0
  22. package/skills/protobase/references/reference/access.md +115 -0
  23. package/skills/protobase/references/reference/ai.md +106 -0
  24. package/skills/protobase/references/reference/api.md +231 -0
  25. package/skills/protobase/references/reference/architecture.md +63 -0
  26. package/skills/protobase/references/reference/assistant.md +157 -0
  27. package/skills/protobase/references/reference/auth.md +462 -0
  28. package/skills/protobase/references/reference/blocks.md +341 -0
  29. package/skills/protobase/references/reference/bottom-bar.md +44 -0
  30. package/skills/protobase/references/reference/cli.md +493 -0
  31. package/skills/protobase/references/reference/client.md +38 -0
  32. package/skills/protobase/references/reference/comments.md +83 -0
  33. package/skills/protobase/references/reference/custom-components.md +285 -0
  34. package/skills/protobase/references/reference/data-config.md +266 -0
  35. package/skills/protobase/references/reference/email.md +166 -0
  36. package/skills/protobase/references/reference/events.md +121 -0
  37. package/skills/protobase/references/reference/files.md +291 -0
  38. package/skills/protobase/references/reference/forms.md +133 -0
  39. package/skills/protobase/references/reference/history.md +86 -0
  40. package/skills/protobase/references/reference/jobs.md +174 -0
  41. package/skills/protobase/references/reference/layouts.md +126 -0
  42. package/skills/protobase/references/reference/plugins.md +328 -0
  43. package/skills/protobase/references/reference/remote-resources.md +198 -0
  44. package/skills/protobase/references/reference/sidebar.md +51 -0
  45. package/skills/protobase/references/reference/theme.md +132 -0
  46. package/skills/protobase/references/reference/ui-config.md +880 -0
  47. package/skills/protobase/references/reference/user-menu.md +38 -0
  48. package/skills/protobase/references/reference/versioning.md +91 -0
  49. package/skills/protobase/references/reference/webhooks.md +136 -0
@@ -0,0 +1,133 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/forms.mdx: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Public forms
4
+
5
+ A form that creates a record for people without an account, such as a contact form, at its own address, behind a rate limit and a bot check.
6
+
7
+ A public form creates a record of a resource for anyone, signed in or not: a contact form, a quote request, a sign-up for an event. `.form(...)` on the resource's view declares it, and the [anonymous role](access.md#anonymous-access)) grants `create` of its fields. Visitors never read the records back, and the form is the only way an anonymous caller creates.
8
+
9
+ ```ts title="config/contact_requests.ts"
10
+ import { f, resource, view } from '@protobase/schema'
11
+
12
+ // A shop's contact form: anyone, signed in or not, sends a request at /-/forms/contact; staff answer them in the app.
13
+
14
+ /** contact_requests */
15
+ export const contactRequests = resource('contact_requests')
16
+ .table('contact_requests')
17
+ .fields({
18
+ id: f.integer().readOnly().filterable().sortable(),
19
+ name: f.text().max(100),
20
+ email: f.text().max(200),
21
+ topic: f.enum(['order', 'repair', 'other']).default('other'),
22
+ message: f.text().max(4000),
23
+ handled: f.boolean().default(false).filterable(),
24
+ created_at: f.timestamp().readOnly().sortable(),
25
+ })
26
+ .primaryKey((r) => r.id)
27
+ .validate((request) => (request.email.includes('@') ? undefined : [{ field: 'email', message: 'Enter an email address' }]))
28
+ // contact_requests.created: a job emails the shop about each one (see notify.ts)
29
+ .events((e) => [e.created()])
30
+
31
+ export const contactRequestsView = view<typeof contactRequests>('contact_requests')
32
+ .names({ singular: 'Contact request', plural: 'Contact requests' })
33
+ .fields((r) => ({ name: r.name.label('Your name'), topic: r.topic.valueLabels({ order: 'An order', repair: 'A repair', other: 'Something else' }), message: r.message.multiline() }))
34
+ .list((r) => ({ columns: [r.created_at, r.name, r.topic, r.handled], sort: [[r.created_at, 'desc']] }))
35
+ .form((r) => ({
36
+ name: 'contact',
37
+ title: 'Contact us',
38
+ fields: [r.name, r.email, r.topic, r.message],
39
+ thanks: 'Thanks, we will reply within a day.',
40
+ }))
41
+ ```
42
+
43
+ ```ts title="config/roles.ts"
44
+ import { defineRoles } from '@protobase/schema'
45
+
46
+ export const roles = defineRoles<'contact_requests'>({
47
+ admin: ['*'],
48
+ // Visitors create a contact request through the form, with these fields only, and never read one back
49
+ anonymous: [{ 'contact_requests.create': ['name', 'email', 'topic', 'message'] }],
50
+ })
51
+ ```
52
+
53
+ `.form({ name, fields, thanks, title?, perMinute? })` takes:
54
+
55
+ | | |
56
+ | --- | --- |
57
+ | `name` | Its address, `/-/forms/<name>`: lowercase letters, digits, `-` and `_`, unique across the app. |
58
+ | `fields` | The fields a visitor fills in, in order. |
59
+ | `thanks` | What the page shows once the form is sent. |
60
+ | `title` | The page's heading; the view's singular name by default. |
61
+ | `perMinute` | How many submissions one client may send per minute; 5 by default. |
62
+
63
+ Each call adds a form, so a view can have several.
64
+
65
+ ## What the visitor sees
66
+
67
+ `/-/forms/<name>` in the admin app shows the form's title over a card with its fields, labelled, with their help and checks as the view gives them, and a **Send** button. It needs no sign-in and opens the same for someone who is signed in; link to it from your website. On **Send** the browser solves the bot check, about a second of work, then sends the form; the card then shows the `thanks` text. A field the server refuses shows its problem under the field, and any other refusal, such as too many submissions, shows above the button with what was typed kept.
68
+
69
+ ## What a form accepts
70
+
71
+ A form takes plain fields: text, numbers, booleans, dates, enums, currencies and countries. The server refuses to start on a form with:
72
+
73
+ - a relation, since a visitor cannot read the records to pick one;
74
+ - a file field, since a visitor cannot upload;
75
+ - a sensitive, read-only or generated field;
76
+ - a field the anonymous role's `<resource>.create` does not list; the error names the entry to add;
77
+ - a field the resource does not have, or two forms of the same name;
78
+ - a field every create must give left out, since no submission could then be saved.
79
+
80
+ ## The record
81
+
82
+ A submission is a create like any other, made by the anonymous role and limited to the form's fields: the resource's `.validate()` rules, record rules and write hooks run, and [events](events.md)), [webhooks](webhooks.md)) and [history](history.md)) see it. History names its maker **Visitor**.
83
+
84
+ ### Email me on a new submission
85
+
86
+ There is no mail built into forms: the record's `created` event enqueues a [job](jobs.md)), and the job [sends the mail](jobs.md#mail)).
87
+
88
+ ```ts title="config/notify.ts"
89
+ import { defineJob, FatalJobError, subscription } from '@protobase/server'
90
+ import { z } from 'zod'
91
+
92
+ // Email me on a new submission: the record's event enqueues a job, and the job sends the mail.
93
+
94
+ export const emailContactRequest = defineJob({
95
+ name: 'email-contact-request',
96
+ payload: z.object({ id: z.number() }),
97
+ run: async ({ id }, { db, mail }) => {
98
+ if (!mail) throw new FatalJobError('Mail is off: set PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM')
99
+ const request = await db.selectFrom('contact_requests').select(['name', 'email', 'message']).where('id', '=', id).executeTakeFirst()
100
+ if (!request) return
101
+ await mail.send({ to: 'shop@example.com', subject: `Contact request from ${request.name}`, text: `${request.email} wrote:\n\n${request.message}` })
102
+ },
103
+ })
104
+
105
+ export const newContactRequests = subscription('newContactRequests', {
106
+ events: ['contact_requests.created'],
107
+ run: async (event, { db }) => {
108
+ await emailContactRequest.enqueue(db, { id: Number(event.data.key) }, { key: `contact-request:${event.data.key}` })
109
+ },
110
+ })
111
+ ```
112
+
113
+ ## Rate limit
114
+
115
+ Each client may send a form `perMinute` times a minute, 5 by default, as many as it may try to sign in. Past that, the form answers `429` with `Retry-After`. A client is known by its address in `X-Forwarded-For`, read as the sign-in limit reads it: a header with one address, an IPv6 address by its /64. Requests without one, or with several addresses, as a proxy makes when it appends to a header the client sent, share a single limit. The count is kept in each server process's memory, so with several instances each counts on its own, and a restart starts over.
116
+
117
+ ## Bot check
118
+
119
+ Every submission carries a solved proof-of-work challenge ([ALTCHA](https://altcha.org)): the browser fetches a fresh one when the visitor presses **Send** and counts SHA-256 hashes until it finds the one the challenge asks for, about a second on a current laptop. There is no third-party service, cookie or visible puzzle, and it works offline. Sending many forms costs a bot that second each time, on top of the rate limit.
120
+
121
+ A challenge is made for one form, expires after 5 minutes and verifies once. The server signs challenges with `PROTOBASE_FORMS_SECRET`, or `BETTER_AUTH_SECRET` when it is not set, and does not start with a form and neither variable, so give every instance of an app the same one. The browser solves the check with Web Crypto, which needs `https` or `localhost`.
122
+
123
+ ## Routes
124
+
125
+ The form's page reads and sends it through three routes beside the API, which need no token:
126
+
127
+ | Route | |
128
+ | --- | --- |
129
+ | `GET /api/forms/<name>` | `{ name, title?, fields, thanks, resource, view }`: the resource restricted to the form's fields and the view's hints for them, as `/api/meta` gives them; `404` for a form that does not exist. |
130
+ | `GET /api/forms/<name>:challenge` | A fresh bot check. |
131
+ | `POST /api/forms/<name>` | `{ values, proof: { challenge, solution } }` creates the record: `204`, or the `400` with field errors a create answers; `400` `bot-check-failed` for a missing, wrong, expired or used check; `429` `too-many-submissions`. |
132
+
133
+ From code, [`@protobase/client`](client.md)) has `form(name)`, `formChallenge(name)` and `submitForm(name, values, proof)`; solve the challenge with `solveChallenge` from `altcha-lib`, as the page does.
@@ -0,0 +1,86 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/history.mdx: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Record history
4
+
5
+ Every change of a resource's records kept with who made it, through the API or not, shown on the record page and listed for admins as Activity.
6
+
7
+ A resource with [`.history()`](https://docs.protobase.net/api/schema/interfaces/resourcebuilder/#history)) keeps every change of its records: what each field was before and after, who made it and when. The changes are captured by the same database triggers as [events](events.md)), so writes from psql, other services and cron SQL are kept too, not only those through the API.
8
+
9
+ ```ts title="config/orders.ts"
10
+ import { f, l, resource, view } from '@protobase/schema'
11
+
12
+ // A webshop's orders, each change kept with who made it: History on the order page, and Activity for admins.
13
+
14
+ /** sales.orders */
15
+ export const orders = resource('orders')
16
+ .table('sales.orders')
17
+ .fields({
18
+ id: f.integer().readOnly().filterable().sortable(),
19
+ number: f.text().readOnly(),
20
+ status: f.enum(['open', 'paid', 'shipped', 'cancelled']).default('open'),
21
+ total: f.decimal({ precision: 12, scale: 2 }),
22
+ iban: f.text().optional().sensitive(),
23
+ })
24
+ .primaryKey((r) => r.id)
25
+ .history()
26
+
27
+ export const ordersView = view<typeof orders>('orders')
28
+ .title((r) => r.number)
29
+ .layout((r) => [
30
+ l.section('Order', [r.number, r.status, r.total, r.iban]),
31
+ // the last 10 changes, newest first, with Show more for the rest
32
+ l.history(),
33
+ ])
34
+ ```
35
+
36
+ ```ts title="protobase.config.ts"
37
+ import { defineConfig } from '@protobase/server'
38
+ import * as config from './orders'
39
+
40
+ // Changes older than 90 days are deleted every night.
41
+ export default defineConfig({ config, history: { days: 90 } })
42
+ ```
43
+
44
+ ## What a change holds
45
+
46
+ A change is what an event sees: one per record and transaction, with the record as it was at the start of the transaction and as it is at commit (see [What one change is](events.md#what-one-change-is))).
47
+
48
+ | | |
49
+ | --- | --- |
50
+ | `operation` | `create`, `update`, `delete` or `undelete`. Setting a `.softDelete()` field is a delete, clearing it an undelete. |
51
+ | `before`, `after` | The fields by name, without sensitive ones. None before a create, or after a delete. |
52
+ | `changed` | The fields an update changed, sensitive ones included: an IBAN that changed is named, never its value. |
53
+ | Who | For a write through the API, the caller's id and roles. For a write from elsewhere, none; the database role that wrote is kept either way: the one `set role` chose, else the session's. |
54
+ | `at` | When the writing transaction started. |
55
+
56
+ ## On the record page
57
+
58
+ [`l.history(title?, { limit, when })`](https://docs.protobase.net/api/schema/variables/l/#history)) shows the record's changes newest first: who made each, how long ago, and each changed field before and after, formatted and labelled as the view shows the field. `limit` changes show at first (default 10), and Show more loads the next ones. A view without a layout shows History last by itself. A view that names `l.history()` for a resource without `.history()` stops startup.
59
+
60
+ The section reads `GET /api/v1/{resource}/{key}:history` (see [REST API](api.md#record-history))). It answers whoever may read the record, with the same tenant, row filter and record-level rule as a get, a soft-deleted record included, and each change carries only the fields that caller may read. An update of only fields they may not read is left out. A change made through the API names its user, with their name when the project signs people in with Better Auth; a change from elsewhere shows as Database with the database role.
61
+
62
+ A save shows up within a moment: the server keeps a change just after its write commits, and the section looks again shortly after each save.
63
+
64
+ ## Activity
65
+
66
+ Once a resource has history, admins get **Activity** (the built-in resource `record_history`): every kept change of every resource with history, newest first, filterable by resource, record, operation, user and database role. It lists `before` and `after` whole, so only the `admin` role reads it, whatever the project's roles say, and nobody writes it. When a resource with history has a [tenant](data-config.md#resource)), Activity is scoped to the caller's tenant, like the app's own resources.
67
+
68
+ ## Keeping it
69
+
70
+ `history: { days }` in `protobase.config.ts` keeps changes for that many days: a daily job, `history.prune`, deletes older ones. Without it, changes are kept until deleted by hand.
71
+
72
+ ## The table
73
+
74
+ [`protobase migration`](cli.md#migration)) adds the table `changes.history` to the `changes` schema of the event capture (renamed with `events: { schema }`), and the capture triggers of each resource with history; apply it with the project's other migrations. `protobase dev` and `protobase serve` do not start while the table or a trigger is missing. A resource that drops `.history()` loses its triggers, unless it has events, at the next migration; its changes stay in the table.
75
+
76
+ | Column | |
77
+ | --- | --- |
78
+ | `id` | Grows with every change, so a record's changes are in commit order. |
79
+ | `resource`, `record_key` | The resource and the record's key as its URL has it. |
80
+ | `tenant_id` | The record's tenant, as text. |
81
+ | `operation`, `before`, `after`, `changed` | As above, by field name. |
82
+ | `actor_id`, `actor_roles` | The API's caller; `null` for a write from elsewhere. |
83
+ | `database_role` | The role that wrote. |
84
+ | `transaction`, `at` | The writing transaction's id and when it started. |
85
+
86
+ The changes are written by the `changes.dispatch` job, in the transaction that removes them from the outbox, so each is kept exactly once; a resource with history therefore needs the [`jobs` schema](jobs.md#the-jobs-schema)) and the app's workers. Turning the capture off for a transaction (`set local changes.capture = 'off'`) keeps nothing of it.
@@ -0,0 +1,174 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/jobs.mdx: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Jobs
4
+
5
+ Background jobs in the app's own database, enqueued with its writes, retried with backoff, run in order per group, and checked at startup.
6
+
7
+ A job is work the app does after a request, or that a request should not wait for: mail an invoice, push a change to another system, recompute a report. Jobs live in the app's own Postgres database, in a schema named `jobs`, so a job can commit in the same transaction as the write that asks for it. The queue underneath is [pg-boss](https://github.com/timgit/pg-boss), pinned to one version; Protobase's own API in front of it is what the app uses.
8
+
9
+ ```ts title="config/jobs.ts"
10
+ import { defineJob, FatalJobError } from '@protobase/server'
11
+ import { z } from 'zod'
12
+
13
+ export const sendInvoice = defineJob({
14
+ name: 'send-invoice',
15
+ payload: z.object({ invoiceId: z.number() }),
16
+ maxAttempts: 10, // then kept as failed, with its last error
17
+ retryDelay: '30 seconds', // doubling with each retry, up to maxRetryDelay
18
+ run: async ({ invoiceId }, { db }) => {
19
+ const invoice = await db.selectFrom('sales.invoices').select(['id', 'status']).where('id', '=', invoiceId).executeTakeFirst()
20
+ // Retrying will not bring it back: fail for good.
21
+ if (!invoice) throw new FatalJobError(`Invoice ${invoiceId} is gone`)
22
+ // ... render the PDF and mail it
23
+ },
24
+ })
25
+
26
+ // One at a time per customer, in the order the changes were made.
27
+ export const syncCustomer = defineJob({
28
+ name: 'sync-customer',
29
+ ordered: true,
30
+ payload: z.object({ customerId: z.number(), fields: z.array(z.string()) }),
31
+ run: async ({ customerId, fields }) => {
32
+ // ... push the changed fields to the CRM
33
+ },
34
+ })
35
+
36
+ // Every morning at 7 in Amsterdam: one run per time, however many workers run.
37
+ export const remindOverdue = defineJob({
38
+ name: 'remind-overdue',
39
+ schedule: '0 7 * * *',
40
+ timezone: 'Europe/Amsterdam',
41
+ run: async (_, { db }) => {
42
+ // ... mail a reminder for every invoice past its due date
43
+ },
44
+ })
45
+ ```
46
+
47
+ ```ts title="protobase.config.ts"
48
+ import { defineConfig } from '@protobase/server'
49
+ import * as jobs from './jobs'
50
+
51
+ export default defineConfig({
52
+ config: {},
53
+ jobs, // run by the worker in `protobase dev` and `protobase serve`
54
+ options: {
55
+ writeHooks: [
56
+ // In the write's own transaction: the invoice and its job commit together or not at all.
57
+ async (event, trx) => {
58
+ if (event.resource.name !== 'invoices' || event.after?.status !== 'sent' || event.before?.status === 'sent') return
59
+ const invoiceId = Number(event.after.id)
60
+ await jobs.sendInvoice.enqueue(trx, { invoiceId }, { key: `invoice:${invoiceId}` })
61
+ },
62
+ ],
63
+ },
64
+ })
65
+ ```
66
+
67
+ | `defineJob` option | |
68
+ | --- | --- |
69
+ | `name` | Letters, digits, `_`, `-`, `.` and `/`. Two jobs may not share a name. |
70
+ | `payload` | A [Standard Schema](https://standardschema.dev) such as a zod schema, checked when the job is enqueued and again before it runs. A payload it refuses at run time fails the job for good. |
71
+ | `run(payload, { db, job, signal, mail })` | The work. `db` is the app's pool: the enqueuer's transaction has committed by then. `job` holds its `id`, `name`, `attempt` and `maxAttempts`. `signal` aborts when the try times out or the worker shuts down. `mail` sends mail, see [Mail](#mail). |
72
+ | `maxAttempts` | Tries before the job is kept as failed; default 10. |
73
+ | `retryDelay`, `maxRetryDelay` | The wait before the first retry, doubling with each one (with some jitter), and its ceiling; default `2s` and `1 hour`. Milliseconds or text such as `30 seconds`. |
74
+ | `timeout` | How long one try may run before it counts as failed; default `15 minutes`. |
75
+ | `concurrency` | Jobs of this name running at once in each worker process; default 1. |
76
+ | `ordered` | Jobs run one at a time per group, in the order they were enqueued; see [Ordered groups](#ordered-groups). |
77
+ | `schedule`, `timezone` | Runs the job on a cron schedule, in a time zone (default `UTC`); see [Recurring jobs](#recurring-jobs). |
78
+
79
+ A job runs **at least once**: a worker that dies mid-job, or a try cut off by a shutdown, means it runs again. Write `run` so that running twice does no harm, for example by checking the state it is about to change.
80
+
81
+ ## Enqueueing
82
+
83
+ ```ts
84
+ await sendInvoice.enqueue(db, { invoiceId: 7 }, { delay: '5 minutes', key: 'invoice:7', priority: 10 })
85
+ ```
86
+
87
+ `db` is the app's database, or the transaction of a write hook or an [API function](../guides/api-functions.md)): there, the job commits with the caller's writes, or not at all. It returns the job's id.
88
+
89
+ | Option | |
90
+ | --- | --- |
91
+ | `runAt` or `delay` | When the job may run first: a `Date`, or milliseconds or text from now. Default now. |
92
+ | `priority` | Higher runs first; default 0. |
93
+ | `key` and `mode` | One waiting job per key: with `mode: 'dedupe'` (the default) an enqueue while one waits returns that one's id and leaves it as it is; with `mode: 'replace'` the waiting job takes this payload and these options. A job that is running does not count, so a change made while it runs gets a job of its own. |
94
+ | `group` | The group of an [ordered](#ordered-groups) job: required there, refused elsewhere. |
95
+
96
+ A job enqueued outside a transaction starts at once when this process runs its jobs. One enqueued in a transaction, or by another process, is picked up within the poll interval, 2 seconds.
97
+
98
+ ### From SQL
99
+
100
+ A trigger or a migration can enqueue in its own transaction:
101
+
102
+ ```sql
103
+ select jobs.enqueue('send-invoice', '{"invoiceId": 7}');
104
+ select jobs.enqueue('send-invoice', '{"invoiceId": 7}', run_at => now() + interval '1 hour', key => 'invoice:7');
105
+ select jobs.enqueue('sync-customer', '{"customerId": 3, "fields": ["email"]}', group_key => 'customer:3');
106
+ ```
107
+
108
+ `jobs.enqueue(job_name, payload, run_at, key, group_key, priority)` returns the job's id. A `key` dedupes as `mode: 'dedupe'` does. The job takes its retry settings from its definition, as the workers last saw it; a job no worker has started yet gets pg-boss's defaults until one does.
109
+
110
+ ## Mail
111
+
112
+ `mail.send({ to, subject, text, html })` sends one message, with an optional HTML part beside the plain text, through the app's SMTP server, the one that also sends password resets and sign-in codes: `PROTOBASE_SMTP_URL` and `PROTOBASE_MAIL_FROM` (see [Email](email.md#configuration))). An [email template](email.md#templates)) sends through it with `template.send(to, data, mail)`. It rejects when the server refuses the message, so the try fails and is retried. Without those variables `mail` is `undefined`: a job that must send fails for good with `FatalJobError`, and one that may skip mail leaves it out.
113
+
114
+ ```ts
115
+ run: async ({ invoiceId }, { db, mail }) => {
116
+ if (!mail) throw new FatalJobError('Mail is off: set PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM')
117
+ await mail.send({ to: 'customer@example.com', subject: `Invoice ${invoiceId}`, text: 'Your invoice is attached in the portal.' })
118
+ }
119
+ ```
120
+
121
+ A message is sent once per try, so a try that sends and then fails sends again: record what was sent in the same run, and check it first.
122
+
123
+ ## Failures
124
+
125
+ A try that throws is retried after its backoff, until `maxAttempts`. Then the job is kept as **failed** with its last error, for 7 days. `throw new FatalJobError('410 Gone')` fails it at once, without the attempts it has left.
126
+
127
+ A job that has waited 14 days past its start time without running is deleted.
128
+
129
+ While the database is read-only, as during a deploy's write freeze, a write in `run` fails with SQLSTATE `25006`: the try waits 5 seconds and runs `run` again, without using an attempt, until the database takes writes or the try times out.
130
+
131
+ ## Ordered groups
132
+
133
+ With `ordered: true`, every enqueue names a `group`, and the jobs of one group run one at a time, in the order they were enqueued; different groups run side by side, up to `concurrency`. A job that is waiting for a retry, or has failed, holds back the rest of its group until it succeeds or is retried or deleted: that is what keeps the order. An ordered job takes no `key`: its group is how pg-boss finds its jobs.
134
+
135
+ Turning `ordered` on or off for a job whose queue exists stops startup: let its jobs finish or delete them, then drop the queue with `select jobs.delete_queue('<name>')`.
136
+
137
+ ## Recurring jobs
138
+
139
+ `schedule: '0 7 * * *'` runs a job on that cron schedule, with no payload; a seconds field may come first (`*/30 * * * * *`). `timezone` reads it in a zone such as `Europe/Amsterdam`, so 07:00 stays 07:00 across daylight saving time.
140
+
141
+ Each run is a job of its own, enqueued ahead for its time by the workers: its id is made from the job's name and the time, so however many workers enqueue a run, it is one job and runs once. As a run starts, the next one is enqueued. A run that came due while no worker ran, as when the app slept or was deployed, runs once as soon as one does; the times missed after it are skipped. Changing the schedule drops the waiting run that is no longer one of its times, and a job that loses its schedule, or is removed, loses its waiting run.
142
+
143
+ Because the next run waits in the database like any delayed job, [`jobs.next_due()`](#hosts-that-sleep) sees it, and a host that wakes the app for due jobs wakes it for its recurring jobs too. That is why Protobase does not use pg-boss's own scheduler, which keeps no next run in the database and works the time out in a running process.
144
+
145
+ ## Failed jobs page
146
+
147
+ With jobs, the admin app has a **Failed jobs** page, for admins only: each job that used up its attempts or failed for good, with its payload and last error. **Retry** gives a job one more attempt, from now, and **Delete** removes it. It reads the `jobs.failed` view, which a project's SQL can query too.
148
+
149
+ ## Where jobs run
150
+
151
+ - **`protobase dev`** runs them in its process. An edited job runs its new code from the next job on.
152
+ - **`protobase serve`** runs them in its process, beside the API, unless `PROTOBASE_JOBS=false`; it enqueues them either way. On SIGTERM it stops taking jobs and gives running ones 30 seconds to finish. A job still running then is failed, to be retried.
153
+ - **[`protobase worker <bundle>`](cli.md#worker))** runs the same jobs from the same bundle in a process of its own, with the same shutdown, for a `serve` with `PROTOBASE_JOBS=false`.
154
+ - Each worker checks every job name for due jobs every 2 seconds: one indexed query per job name and interval. Once a minute, one of the workers also counts the queues and retries the jobs whose worker died (their `timeout` passed); once a day it deletes completed and failed jobs older than 7 days.
155
+
156
+ ### Hosts that sleep
157
+
158
+ A host that stops an idle app needs to know when a job is due, and to have it run:
159
+
160
+ - `select jobs.next_due()` answers when the next job is due, or `null` when none waits: a waiting job's start time, a recurring job's next run, or the timeout of a job that was running when the app stopped. It is one read-only statement, through any pooler.
161
+ - `POST /api/jobs/drain?seconds=25` runs the due jobs until none is due or running, or the seconds have passed, and answers `{ "drained": true, "remaining": 0, "nextDue": "2026-10-12T05:00:00.000Z" }`. It takes the operator's token, `PROTOBASE_JOBS_DRAIN_TOKEN`, as a bearer token; without that variable there is no such endpoint. A process with `PROTOBASE_JOBS=false` answers `409`.
162
+
163
+ ## The `jobs` schema
164
+
165
+ The schema is pg-boss's tables at its pinned schema version, plus Protobase's `jobs.enqueue`, `jobs.next_due` and `jobs.failed`. It is created and upgraded like the [auth schema](auth.md#migrations)), by the project's migrations:
166
+
167
+ ```sh
168
+ bun run protobase migration # writes db/migrations/NNN_jobs.sql when the jobs schema is missing or behind
169
+ bun run db:migrate
170
+ ```
171
+
172
+ [`protobase migration`](cli.md#migration)) writes what the database lacks, taken from pg-boss's own construction and migration plans for the pinned version, without their `BEGIN` and `COMMIT` and with any `CONCURRENTLY` index build made a plain one, so the file runs in the project's migration transaction. The server never creates or migrates it: `protobase dev` and `protobase serve` read its version at startup and refuse to start while it is missing or behind, naming the command. A database whose jobs schema is newer than the running Protobase is refused too.
173
+
174
+ pg-boss runs here without what needs a session of its own: no `LISTEN`/`NOTIFY` (a job enqueued in the same process wakes its worker directly, the rest is polled), only transaction-scoped advisory locks, unnamed prepared statements, no index rebuilds and no instance registry. It works through PgBouncer in transaction mode and on PGlite, over the app's own connection pool.
@@ -0,0 +1,126 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/layouts.md: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Layouts
4
+
5
+ Composed pages from JSX layouts, the element tree they compile to, what they may hold, and how data, conditions, actions and access work in them.
6
+
7
+ A composed page is a layout file in the config, written in JSX and compiled to plain data. The server checks it against the resources, serves it to each user in `/api/meta` without what they may not see, and the admin renders it from blocks that read the regular API. [Your first composed page](../guides/first-composed-page.md)) builds one step by step; this page is the reference.
8
+
9
+ ## Setup
10
+
11
+ A layout file is `.tsx` and starts with the JSX import source:
12
+
13
+ ```tsx
14
+ /** @jsxImportSource @protobase/layout */
15
+ import { Page, Stat, page } from '@protobase/layout'
16
+
17
+ export const overview = page('overview', <Page title="Overview"><Stat label="Orders" resource="orders" /></Page>, { nav: { group: 'Sales', order: 0 } })
18
+ ```
19
+
20
+ The comment makes `@protobase/layout/jsx-runtime` compile the file instead of React's runtime, and it is how the build recognises a layout file, so every layout file needs it. Export the page from the config module like a resource or view, for example `export { overview } from './overview/page'` in `config/index.ts`; `configExports` tells pages from views.
21
+
22
+ `page(name, tree, options?)`:
23
+
24
+ | | |
25
+ | --- | --- |
26
+ | `name` | The address: the page is at `/<name>`, beside the resources, so a resource may not have the same name. Lowercase first letter, then letters, digits and dashes. |
27
+ | `tree` | One `<Page>` element. |
28
+ | `options.nav` | `{ group, order, hidden }`, as for views. A page without a group is in "Pages"; groups that hold pages come first in the sidebar. |
29
+ | `options.icon` | One of the [user menu icons](user-menu.md)), or `layout-dashboard` (the default). |
30
+ | `options.roles` | Only users with one of these roles get the page. Without it, everyone who can sign in does. |
31
+
32
+ A page can also sit in the [user menu](user-menu.md)) with `m.page(name)`; it then leaves the sidebar. The first page is where the admin opens.
33
+
34
+ ## The element tree
35
+
36
+ Every element compiles to `{ type, props, children }`, and a custom component also carries `custom: true`:
37
+
38
+ ```json
39
+ {
40
+ "type": "Page",
41
+ "props": { "title": "Overview" },
42
+ "children": [{ "type": "Stat", "props": { "label": "Orders", "resource": "orders" }, "children": [] }]
43
+ }
44
+ ```
45
+
46
+ Children are elements and text. `null`, `undefined` and booleans render nothing and numbers become text, as in React, so `{isBeta && <Card />}` and `.map()` over a constant list work. Fragments are flattened. An element may be a prop value too: `actions={<Action name="cancel" />}` or a list of them.
47
+
48
+ ## What a layout may hold
49
+
50
+ A prop is a string, a finite number, a boolean, `null`, or an array or plain object of those (elements included). It is JSON in the end, so the rules are checked twice:
51
+
52
+ - **At build time.** `protobase build` and `protobase dev` read every file with the `@jsxImportSource @protobase/layout` comment and refuse a function, class or `new` value in a prop or child, and any call to a hook (`useState`, ...), with the file, line and column. No project code runs for this.
53
+ - **When the config loads.** The JSX runtime refuses anything else that is not plain data (a function in a variable, a `Date`, a `Map`, `NaN`), `page()` checks every element's props against its block (unknown, missing and mistyped props, children where none are allowed, elements that need a record outside one), and `createAdmin` checks every resource, field, filter, sort, action and condition against the models. Each problem names its place, such as `Page "overview": <Page> › <Table resource="invoices">: unknown column "amount" on invoices`.
54
+
55
+ Behaviour comes from [named actions](#named-actions); React code from [custom components](custom-components.md)).
56
+
57
+ ## Data
58
+
59
+ `Stat`, `RecordCard`, `Table`, `CardRow` and `RecordRow` read records of a `resource`. `filter` is AIP-160 and `sort` AIP-132, exactly as the list API's `filter` and `order_by`, so a filter that works in the list's URL works here.
60
+
61
+ A `RecordCard` (its first match) and each card of a `CardRow` hold a **record**. Inside one, `Field`, `Progress`, `Stat field`, `Show`, `Action` and `ModalForm mode="edit"` work on that record, and a `RecordCard`'s header `actions` do too. A field name may follow relations: `company_id.city` is the city of the record's company, fetched like the record page fetches it and cached.
62
+
63
+ ## Conditions
64
+
65
+ `<Show when="...">` keeps its children while the condition holds. It is AIP-160 over named values:
66
+
67
+ | Name | Value |
68
+ | --- | --- |
69
+ | `status`, `plan.name` | A field of the record around it, through relations. |
70
+ | `invoices.count` | How many `invoices` the user can see (an exact count from the list API). |
71
+
72
+ Comparisons, `AND`, `OR`, `NOT` and parentheses work; functions such as `now()` do not. A field that is missing or that the user cannot read makes the comparison false, and a `Show` that names a resource or field the user cannot see is left out of their page.
73
+
74
+ Record pages take the same conditions in the `when` of `l.section`, `l.related` and `l.sidebar`; see [Form and read view](ui-config.md#form-and-read-view)).
75
+
76
+ ## Named actions
77
+
78
+ `<Action name="..." />` is a button for an action of the resource's view (the record's resource, or `resource="..."` outside a record). The view declares what it does:
79
+
80
+ | Builder | Does |
81
+ | --- | --- |
82
+ | `a.update(name, { label, set, confirm?, icon?, inputs? })` | Updates the record with `set`, with its ETag; not offered on a record that holds those values already, unless it asks for `inputs`, whose answers it writes where `set` says `'{name}'`. |
83
+ | `a.remove(name, { label, confirm?, icon? })` | Deletes the record (soft delete when the resource has one). |
84
+ | `a.link(name, { label, to, icon? })` | Goes `to` an [address](#addresses) in the app, with `{field}` in its key, filter, order or create values replaced by the record's value. |
85
+ | `a.link(name, { label, href, icon? })` | Opens an `href` that leaves the app (`https:`, `mailto:`), with `{field}` replaced by the record's value (percent-encoded); an `https:` or `http:` link opens in a new tab without the referrer. An `href` that is only a field, `'{website}'`, opens the URL the record holds, as it is: see [links to a record's URL](#links-to-a-records-url). A path in the app is refused when the config loads: give it as `to`. |
86
+ | `a.ai(name, { label, prompt, writes, confirm?, icon? })` | Has the model write the field `writes` of the record from `prompt`, `{field}` replaced by the record's values, as the user, on the server; see [AI fields and actions](ai.md#ai-actions)). |
87
+ | `a.action(name, { label, confirm?, icon?, bulk?, inputs? })` | Runs the handler the app registers under `name` in [`protobase.ui.tsx`](custom-components.md#action-handlers)), after asking for its [`inputs`](ui-config.md#actions-that-ask-for-input)) in a dialog when it has some. |
88
+
89
+ `icon` is one of `bath`, `bed`, `bell`, `bookmark`, `calendar`, `door-open`, `external-link`, `file-text`, `heart`, `house`, `key`, `land-plot`, `leaf`, `ruler`, `send`, `tag` or `wallet`; another name shows a lightning bolt. With `confirm` the button asks first. The button is disabled, with the reason as its tooltip, when the user may not update or delete the record (or, for an AI action, the field it writes), when an `a.action` has no handler, or when an update, delete or AI action has no record. After an action, everything shown of that resource reloads. The record page's action rail runs the same actions the same way.
90
+
91
+ ### Links to a record's URL
92
+
93
+ A link whose `href` is a single `{field}` opens the address that field holds, such as the page a listing came from:
94
+
95
+ ```ts
96
+ a.link('source', { label: 'View on {host}', icon: 'external-link', href: '{source_url}' })
97
+ ```
98
+
99
+ The value is used as it is, not percent-encoded, and must be an absolute `https:` or `http:` URL: on a record whose field is empty or holds anything else the button does not show. It opens in a new tab that gets neither the app's window nor its address. `{host}` in the label becomes the URL's host without `www.`, so the button above reads "View on example.com". The field must be one of the resource's, and the button shows to whoever the view grants the field, a visitor who is not signed in included; for anyone it hides the field from, the action is left out.
100
+
101
+ ## Addresses
102
+
103
+ Every place in the app has an address, and the app writes and reads them in one way, so no link or component spells out a path:
104
+
105
+ | Address | Is |
106
+ | --- | --- |
107
+ | `{ kind: 'list', resource, filter?, orderBy?, display? }` | A resource's list, with the filter, order and [display](ui-config.md#list-displays)) the list page would show. |
108
+ | `{ kind: 'record', resource, key, edit?, open? }` | One record; `key` is its value, or its parts for a composite key. `edit: true` is its form (`?edit=true`), on a view whose record page opens as a [read view or locked](ui-config.md#read-view-and-edit)). `open` lists the titles of the record page's collapsed [groups](ui-config.md#groups)) that are open (`?open=<title>`, once per group). |
109
+ | `{ kind: 'create', resource, values? }` | The form for a new record, with `values` filled in by field name, as text: `{ kind: 'create', resource: 'notes', values: { listing_id: '{id}' } }` on a listing's page starts a note about that listing. A relation shows the name of the record it points at. The values are a start the person can change, not a rule: what they may write is still up to the access rules. A view with a [create page](ui-config.md#create-pages)) shows that page here instead, with the values in the address. |
110
+ | `{ kind: 'page', page }` | A composed page. |
111
+
112
+ The resources, pages and fields an address names are checked when the server starts, like every other name.
113
+
114
+ ## Access
115
+
116
+ Every block reads the regular API with the user's token, so the access rules apply to each request exactly as on the list and record pages: row filters such as `.own` narrow every count, table and card, and hidden fields never arrive.
117
+
118
+ `/api/meta` also gives each user the page without what they cannot use, the way views lose hidden fields:
119
+
120
+ - a page whose `roles` leave the user out is not sent;
121
+ - an element whose resource they cannot see, or whose filter or sort names a field they cannot read, is left out with everything inside it;
122
+ - `Field`, `Progress` and `Stat field` on a field they cannot read are left out, and table columns are narrowed;
123
+ - `ModalForm` needs create or update permission and keeps only the fields they may write;
124
+ - an `Action` missing from their view of the resource is left out, and so is a `Show` that names something they cannot see.
125
+
126
+ Custom components are kept: they get only their props, and fetch through the same API.