@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,166 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/email.mdx: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Email
4
+
5
+ The SMTP server and sender an app's mail goes out through, and emails of the app's own, written as React components with typed data and sent from jobs, hooks and API functions.
6
+
7
+ An app sends mail through one SMTP server: Protobase's own mail ([password reset](auth.md#password-reset)), [emailed sign-in codes](auth.md#emailed-sign-in-codes)), [invitations](auth.md#organizations)), staff sign-in notices and [mentions in comments](comments.md#mentions))) and the emails the app defines itself. Both are React components, rendered to HTML with a plain-text part beside it.
8
+
9
+ ## Configuration
10
+
11
+ | Variable | |
12
+ | --- | --- |
13
+ | `PROTOBASE_SMTP_URL` | The SMTP server, credential included: `smtp://user:password@host:587` (STARTTLS when the server offers it) or `smtps://user:password@host:465` (TLS from the start). |
14
+ | `PROTOBASE_MAIL_FROM` | The sender, a plain address such as `noreply@shop.example.com`. The client greets the server with its domain; a `?name=` on the URL overrides that. |
15
+ | `PROTOBASE_APP_NAME` | Optional: the app's name, such as `Shop`, which mail clients show as the sender's name (`Shop <noreply@shop.example.com>`). [`createAuth`'s `appName`](auth.md#configuration)), when set, takes its place. Without either the sender has no name. |
16
+
17
+ Set both or neither. One without the other, a URL that is not `smtp://` or `smtps://`, or a sender that is not a plain address stops the app at startup. Without them mail is off: password reset and emailed codes are not offered, a job's `mail` is `undefined`, and sending an app's email rejects.
18
+
19
+ `protobase dev` and `protobase serve` read them from the environment or the nearest `.env`; a host passes them like `DATABASE_URL`. In development, a mail catcher such as [Mailpit](https://mailpit.axllent.org) shows what the app sends without delivering it:
20
+
21
+ ```sh
22
+ docker run -d -p 8025:8025 -p 1025:1025 axllent/mailpit # its inbox is http://localhost:8025
23
+
24
+ # .env
25
+ PROTOBASE_SMTP_URL=smtp://localhost:1025
26
+ PROTOBASE_MAIL_FROM=noreply@shop.example.com
27
+ ```
28
+
29
+ A project that delivers mail another way passes a `mailer`, `{ send({ to, subject, text, html }) }`, to [`createAuth`](auth.md#password-reset)) and `startJobs`, or `mailer: false` to turn mail off whatever the environment says. A template's `send` takes one too, see [Templates](#templates).
30
+
31
+ ## Protobase's own mail
32
+
33
+ The auth emails (sign-in, two-factor and sign-up codes, the note to an address that asked to sign up while it has an account, password reset, invitations and staff sign-in notices) and the email to someone a [comment mentions](comments.md#mentions)) are built with React Email's components: a heading, the message, one code or button, and a footer naming the app.
34
+
35
+ - They name the app by [`appName`](auth.md#configuration)), and link it on the origin the request came to: the footer links its home page, and the note to an address that has an account links its sign-in page.
36
+ - The plain-text part has each code on a line of its own and each link in full.
37
+ - React Email and the templates are loaded when the first auth email is sent, so an app that sends none never loads them and the server starts as fast without them.
38
+
39
+ ## Templates
40
+
41
+ An email of the app's own is `defineEmail`: a name, a subject, and a React component whose props are the email's data. The components of [React Email](https://react.email) render the tables and inline styles email clients need. `@protobase/server` brings React's renderer; the project adds the components, and React for its JSX, which a project with a UI has already:
42
+
43
+ ```sh
44
+ bun add react-email react
45
+ bun add -d @types/react
46
+ ```
47
+
48
+ ```tsx title="config/emails/repair-ready.tsx"
49
+ import { defineEmail } from '@protobase/server'
50
+ import { Body, Button, Container, Head, Heading, Html, Preview, Text } from 'react-email'
51
+
52
+ export type RepairReady = { customer: string; bike: string; number: string; url: string }
53
+
54
+ // The email's data is the component's props: `send` and `render` take exactly these.
55
+ const RepairReadyEmail = ({ customer, bike, number, url }: RepairReady) => (
56
+ <Html lang="en">
57
+ <Head />
58
+ <Preview>Your {bike} is ready for pickup</Preview>
59
+ <Body style={{ backgroundColor: '#f4f4f5', fontFamily: 'Helvetica, Arial, sans-serif' }}>
60
+ <Container style={{ backgroundColor: '#ffffff', padding: '24px', maxWidth: '480px' }}>
61
+ <Heading as="h1">Ready for pickup</Heading>
62
+ <Text>Hi {customer}, your {bike} is ready. Bring repair number {number} when you come by.</Text>
63
+ <Button href={url} style={{ backgroundColor: '#0f766e', color: '#ffffff', padding: '12px 20px', borderRadius: '6px' }}>
64
+ See the repair
65
+ </Button>
66
+ </Container>
67
+ </Body>
68
+ </Html>
69
+ )
70
+
71
+ export const repairReady = defineEmail({
72
+ name: 'repair-ready',
73
+ subject: ({ bike }: RepairReady) => `Your ${bike} is ready for pickup`,
74
+ component: RepairReadyEmail,
75
+ })
76
+ ```
77
+
78
+ | `defineEmail` option | |
79
+ | --- | --- |
80
+ | `name` | Names the email in errors. |
81
+ | `subject` | The subject line, or a function of the data that makes it. |
82
+ | `component` | The body, a React component of the data. It is rendered with React Email's `render` to the HTML part; the plain-text part is made from that HTML, leaving out what React Email marks to skip, such as `<Preview>`. |
83
+
84
+ The template that comes back has two methods, both typed by the component's props:
85
+
86
+ - `render(data)` gives `{ subject, html, text }` without sending anything: for a test, or to look at the result.
87
+ - `send(to, data, mailer?)` renders and sends it, through `mailer` when given (a job's `mail`), otherwise through `PROTOBASE_SMTP_URL`. It rejects when mail is off or the server refuses the message.
88
+
89
+ React and React Email's renderer are loaded on the first email rendered, not when the app starts.
90
+
91
+ ## Sending
92
+
93
+ A **job** is the usual place: it runs after the write that asked for it has committed, and a message the server refuses fails the try, which is retried. Pass the job's `mail`, so a job runtime started with a mailer of its own sends through it:
94
+
95
+ ```ts title="config/jobs.ts"
96
+ import { defineJob, FatalJobError } from '@protobase/server'
97
+ import { z } from 'zod'
98
+ import { repairReady } from './repair-ready'
99
+
100
+ // Enqueued by the write hook of a repair that became ready (see protobase.config.ts), so the email goes out only once
101
+ // the write has committed, and a refused message is retried.
102
+ export const emailRepairReady = defineJob({
103
+ name: 'email-repair-ready',
104
+ payload: z.object({ repairId: z.number() }),
105
+ run: async ({ repairId }, { db, mail }) => {
106
+ if (!mail) throw new FatalJobError('Mail is off: set PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM')
107
+ const repair = await db
108
+ .selectFrom('repairs')
109
+ .innerJoin('customers', 'customers.id', 'repairs.customer_id')
110
+ .select(['repairs.number', 'repairs.bike', 'customers.name', 'customers.email'])
111
+ .where('repairs.id', '=', repairId)
112
+ .executeTakeFirst()
113
+ if (!repair?.email) return
114
+ const url = `https://bikeshop.example.com/repairs/${repair.number}`
115
+ await repairReady.send(repair.email, { customer: repair.name, bike: repair.bike, number: repair.number, url }, mail)
116
+ },
117
+ })
118
+ ```
119
+
120
+ A **write hook** runs in the write's transaction, which may still roll back. It enqueues the job rather than sending, so the email goes out only for a write that committed:
121
+
122
+ ```ts title="protobase.config.ts"
123
+ import { defineConfig } from '@protobase/server'
124
+ import * as jobs from './jobs'
125
+
126
+ export default defineConfig({
127
+ config: {},
128
+ jobs,
129
+ options: {
130
+ writeHooks: [
131
+ // The job commits with the write, or not at all: no email about a change that was rolled back.
132
+ async (event, trx) => {
133
+ if (event.resource.name !== 'repairs' || event.after?.status !== 'ready' || event.before?.status === 'ready') return
134
+ await jobs.emailRepairReady.enqueue(trx, { repairId: Number(event.after.id) })
135
+ },
136
+ ],
137
+ },
138
+ })
139
+ ```
140
+
141
+ An **[API function](../guides/api-functions.md))** may send directly, as the answer to a request:
142
+
143
+ ```ts title="functions/resend-repair-ready.ts"
144
+ import { z } from 'zod'
145
+ import { defineFunction, readJson } from '@protobase/server'
146
+ import { repairReady } from './repair-ready'
147
+
148
+ const Input = z.object({ repairId: z.number().int().positive() })
149
+
150
+ // POST /api/functions/resend-repair-ready { "repairId": 7 }: the desk sends the email again, as the answer to the request.
151
+ export default defineFunction({ roles: ['desk'] }, async (request, { records }) => {
152
+ const { repairId } = await readJson(request, Input)
153
+ const { record: repair } = await records.get('repairs', repairId)
154
+ const { record: customer } = await records.get('customers', repair.customer_id as number)
155
+ if (!customer.email) return Response.json({ sent: false, reason: 'The customer has no email address' })
156
+ const number = repair.number as string
157
+ await repairReady.send(customer.email as string, { customer: customer.name as string, bike: repair.bike as string, number, url: `https://bikeshop.example.com/repairs/${number}` })
158
+ return Response.json({ sent: true })
159
+ })
160
+ ```
161
+
162
+ A message is sent once per call, so a job try that sends and then fails sends again: record what was sent, and check it first.
163
+
164
+ ## In a bundle
165
+
166
+ A [bundle](cli.md#the-config-module)) gets React and React Email's renderer from the serve runtime, as it gets `@protobase/server`, so an email's component and the renderer share one React and hooks such as `useContext` work. React Email's other components are inlined, though `@protobase/server` uses them too: it loads them only to send its own mail, so the runtime does not supply them. Its `<Tailwind>` component needs `tailwindcss`, which the runtime does not supply, so a served config cannot use it: style with `style` props instead.
@@ -0,0 +1,121 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/events.mdx: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Events
4
+
5
+ Events a resource declares, and how the database captures every change they are raised from, through the API or not.
6
+
7
+ A resource can declare **events**: what a change of its records means, such as an order that was created or became large. The changes are captured in the database itself, by triggers, in the transaction that writes them. Writes through the API count, and so do writes from psql, other services, cron SQL and the database's own triggers and generated columns.
8
+
9
+ The app's [jobs](jobs.md)) then turn the captured changes into events and deliver them to [subscriptions](webhooks.md)): URLs, the app's API functions or code of its own. A resource with [history](history.md)) is captured the same way, and its changes are kept.
10
+
11
+ ```ts title="docs-examples/events/orders.ts"
12
+ import { f, resource } from '@protobase/schema'
13
+
14
+ // The events of a webshop's orders: every create, update and delete, and a few that mean something to the business.
15
+
16
+ /** sales.orders */
17
+ export const orders = resource('orders')
18
+ .table('sales.orders')
19
+ .fields({
20
+ id: f.integer().readOnly().filterable().sortable(),
21
+ number: f.text().readOnly(),
22
+ status: f.enum(['open', 'paid', 'shipped', 'cancelled']).default('open'),
23
+ total: f.decimal({ precision: 12, scale: 2 }),
24
+ notes: f.text().optional(),
25
+ iban: f.text().optional().sensitive(),
26
+ deleted_at: f.timestamp().optional().readOnly(),
27
+ })
28
+ .primaryKey((r) => r.id)
29
+ .softDelete((r) => r.deleted_at)
30
+ .events((e, r) => [
31
+ // orders.created, orders.updated, orders.deleted and, since it soft deletes, orders.undeleted
32
+ ...e.crud(),
33
+ // created with a total over 1000, or updated from 1000 or less to more
34
+ e.becomes('large', 'total > 1000'),
35
+ // the status changed, whatever it was and became
36
+ e.updated('statusChanged', { changed: [r.status] }),
37
+ // the refund account changed: a sensitive field, so `changed` is the only condition that can use it
38
+ e.updated('refundAccountChanged', { changed: [r.iban] }),
39
+ // a cancelled order that is no longer cancelled
40
+ e.updated('reopened', { from: 'status = "cancelled"', when: 'status != "cancelled"' }),
41
+ // a condition in code, for what a filter cannot say
42
+ e.created('rush', { match: ({ after }) => String(after?.notes ?? '').includes('RUSH') }),
43
+ ])
44
+ ```
45
+
46
+ ## Declaring events
47
+
48
+ [`.events((e, r) => [...])`](https://docs.protobase.net/api/schema/interfaces/resourcebuilder/#events)) returns the resource's events, built with the [helpers of `e`](https://docs.protobase.net/api/schema/type-aliases/eventhelpers/)). Each is named `<resource>.<name>`, such as `orders.statusChanged`; names are camelCase and unique per resource.
49
+
50
+ | | |
51
+ | --- | --- |
52
+ | `e.crud()` | `created`, `updated` and `deleted`, plus `undeleted` when the resource has a `.softDelete()` field. |
53
+ | `e.created(name?, { when, match })` | A record was created. The name defaults to `created`. |
54
+ | `e.updated(name?, { when, from, changed, match })` | A record was updated. The name defaults to `updated`. |
55
+ | `e.deleted(name?, { from, match })` | A record was deleted, or its soft delete field was set. |
56
+ | `e.undeleted(name?, { when, from, match })` | A record's soft delete field was cleared; needs `.softDelete()`. |
57
+ | `e.becomes(name, condition)` | The condition turned true: a create that meets it, or an update after which it holds and before which it did not. |
58
+
59
+ The options combine with AND:
60
+
61
+ | Option | |
62
+ | --- | --- |
63
+ | `when` | A filter on the record after the change. |
64
+ | `from` | A filter on the record before the change. |
65
+ | `changed: [r.status]` | One of these fields changed. It works on sensitive fields too. |
66
+ | `match` | A function of the change that returns `true` for the event, for what a filter cannot say. |
67
+
68
+ Filters use the language of [access rules](access.md)) and views, on any field, filterable or not. They are checked against the resource when the config loads, so a typo stops startup. A filter cannot use a sensitive field, since captured records never hold their values (use `changed`), nor `search()`, `similar()` or a field of another resource.
69
+
70
+ `match` sees the change as the event does: `operation` (`create`, `update`, `delete` or `undelete`), `before` and `after` (the records by field name, without sensitive fields), `changed` (field names), `actor` (`{ id, roles }` for a write through the API, `null` otherwise), `source` (`api` or `database`), `tenant` and `transaction`.
71
+
72
+ ## What one change is
73
+
74
+ - **One per record and transaction.** A batch or a transaction of several statements gives one change per record, with `before` as it was at the start and `after` as it is at commit.
75
+ - **What leaves nothing:** an update that changes no field, an update that ends where it started, an insert deleted in the same transaction, a rolled-back transaction or savepoint, and a change to a column that is not a field.
76
+ - **A delete and an insert of the same key** in one transaction is an update.
77
+ - **Soft deletes:** setting the soft delete field is a delete, clearing it an undelete.
78
+ - Time passing is not a change. Something that should happen when a date is reached is a scheduled job.
79
+
80
+ ## How changes are captured
81
+
82
+ `protobase migration` adds a `changes` schema to the database, with:
83
+
84
+ - **`changes.outbox`**, one row per changed row, written in the writer's transaction, so it commits or rolls back with the change. A dispatch job reads the committed rows and deletes them once their events are delivered or queued.
85
+ - **`changes.capture()`**, the trigger function. It runs as its owner, with a fixed search path, so a role that writes the table needs no rights on `changes`: another service writing as its own role keeps working once a resource has events.
86
+ - **Two triggers per resource with events or history**, on its table: `<table>_changes` for inserts and deletes, and `<table>_changes_update` for updates that change the row.
87
+
88
+ The first row a transaction captures also enqueues a `changes.dispatch` job with `jobs.enqueue()`, in the same transaction, so a resource with events needs the [`jobs` schema](jobs.md#the-jobs-schema)) too. Dispatch jobs run one at a time, in the app's workers. After a write through the API commits, the server has its own worker look for that job at once, so its events usually go out within milliseconds; a write from elsewhere waits for the next poll, two seconds at most.
89
+
90
+ A trigger keeps the columns of the resource's fields, minus sensitive ones, whose names it lists in `changed` when they change. Columns that are not fields, such as a password hash, are never captured. One table can have events for one resource.
91
+
92
+ Two transaction settings steer the capture:
93
+
94
+ - **`changes.actor`**: the API sets it in every write transaction, to the caller's id and roles. A write without it has no actor.
95
+ - **`changes.capture`**: `set local changes.capture = 'off'` captures nothing for the rest of the transaction, for a script such as a recount whose changes mean nothing to anyone.
96
+
97
+ For a database that already has a schema named `changes`, pick another name in `protobase.config.ts`; the settings take the same prefix:
98
+
99
+ ```ts
100
+ export default defineConfig({ config, auth, authenticate, events: { schema: 'row_changes' } })
101
+ ```
102
+
103
+ ## Migrations and startup
104
+
105
+ [`protobase migration`](cli.md#migration)) compares the database with the resources' events and writes what it lacks as the project's next migrations: the jobs schema, then the `changes` schema, the function, and a trigger pair per resource with events. Apply it with the project's other migrations. A trigger changes when the resource's fields do, a field that became sensitive for instance, so run the command after changing the config. Once a resource has no events, the next migration drops its triggers; it never drops a table.
106
+
107
+ `protobase dev` and `protobase serve` do not start while a resource with events lacks its triggers, or has out-of-date ones, or the jobs schema is missing, and name the command to run. `dev` checks again whenever it reloads the config. Neither changes the schema itself.
108
+
109
+ ## The outbox
110
+
111
+ | Column | |
112
+ | --- | --- |
113
+ | `id` | Grows with every row, so a record's changes are in commit order. |
114
+ | `transaction` | The writing transaction's id. |
115
+ | `resource` | The resource whose table changed. |
116
+ | `op` | `INSERT`, `UPDATE` or `DELETE`. |
117
+ | `old`, `new` | The row before and after, by column name, without sensitive columns. 64-bit integers and decimals keep every digit when events are built from them. |
118
+ | `changed` | The columns an update changed, sensitive ones included. |
119
+ | `actor` | `{ "id": ..., "roles": [...] }` for a write through the API; `null` otherwise. |
120
+ | `database_role` | The role that wrote: the one `set role` chose, else the session's. |
121
+ | `dispatch_after`, `created_at` | When the row may be dispatched, and when its transaction started: an event's `timestamp`. |
@@ -0,0 +1,291 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/files.mdx: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Files
4
+
5
+ File fields, uploads with types detected from the content, downloads, derived fields, image variants and placeholders, external URLs, image referrers, and how stored files are deleted.
6
+
7
+ A file field is a `text` column that holds the file's URI. The bytes live with a **provider**, a named place for files: a folder on disk or an S3-compatible bucket. Protobase adds no table, trigger or foreign key to your database: a file field needs a text column and nothing else.
8
+
9
+ ```ts title="docs-examples/files/bikes.ts"
10
+ import { f, resource } from '@protobase/schema'
11
+ import { aspectRatio, fileSize, imageSize, processor } from '@protobase/server'
12
+
13
+ // A processor of your own reads the whole file when it needs to: here a SHA-256, to spot the same manual uploaded twice.
14
+ const sha256 = processor({
15
+ run: async (file) => {
16
+ const digest = await crypto.subtle.digest('SHA-256', await new Response(await file.read()).arrayBuffer())
17
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')
18
+ },
19
+ })
20
+
21
+ // A bike shop's bikes for sale: a photo with its size in two more columns, a manual, and a public picture for the
22
+ // shop's website, stored at most 2048 pixels wide as WebP, with a card-sized copy and a placeholder.
23
+ export const bikes = resource('bikes')
24
+ .table('shop.bikes')
25
+ .fields({
26
+ id: f.integer().readOnly().dbDefault(),
27
+ name: f.text(),
28
+ photo: f.file().accept(['image/*']).maxSize('10 MB').optional().derive({ photo_width: imageSize('width'), photo_ratio: aspectRatio() }),
29
+ photo_width: f.integer().readOnly().optional(),
30
+ photo_ratio: f.decimal({ precision: 8, scale: 4 }).readOnly().optional(),
31
+ manual: f.file().accept(['application/pdf']).optional().derive({ manual_bytes: fileSize(), manual_sha256: sha256 }),
32
+ manual_bytes: f.integer().readOnly().optional(),
33
+ manual_sha256: f.text().readOnly().optional(),
34
+ listing: f
35
+ .file()
36
+ .accept(['image/png', 'image/jpeg', 'image/webp'])
37
+ .maxSize('2 MB')
38
+ .public()
39
+ .optional()
40
+ .placeholder('listing_placeholder')
41
+ .variants({ card: { width: 640, height: 480, fit: 'cover', format: 'webp', quality: 75 } }, { original: { width: 2048, format: 'webp' } }),
42
+ listing_placeholder: f.text().readOnly().optional(),
43
+ })
44
+ .primaryKey((r) => r.id)
45
+ ```
46
+
47
+ | Option | |
48
+ | --- | --- |
49
+ | `.accept(['image/*', 'application/pdf'])` | Allowed types: exact types and `type/*` wildcards (`*/*` must be written out). They are checked against the type detected from the content (see [How the type is decided](#how-the-type-is-decided)). Without it any type is taken. |
50
+ | `.maxSize('10 MB')` | The largest upload, as bytes or text (`512 KiB`, `1.5 GB`); default 50 MB. |
51
+ | `.public()` | Stored with the `public` provider, whose files anyone with the link may open. |
52
+ | `.storage('archive')` | Stored with another provider; default `private`. |
53
+ | `.derive({ field: processor })` | Values computed from each upload and written to other fields of the row, see [Derived fields](#derived-fields). |
54
+ | `.placeholder('photo_placeholder')` | Each image's ThumbHash in that text field, drawn while the image loads, see [Image variants and placeholders](#image-variants-and-placeholders). |
55
+ | `.variants({ card: { … } }, { original? })` | Resized copies of each image stored beside it, see [Image variants and placeholders](#image-variants-and-placeholders). |
56
+ | `.externalUrls()` | Also takes an https URL of a file elsewhere instead of an upload, see [External URLs](#external-urls). |
57
+
58
+ A file field cannot be filterable, sortable, aliased, searched, sensitive, or the key, tenant, owner or soft delete field. [`protobase doctor`](cli.md#doctor)) checks that its column is a text type.
59
+
60
+ ## What the column holds
61
+
62
+ ```text
63
+ private:1/2992db9c-776e-4d4e-9e0f-59d485fefaf9.jpg?name=bike+red.png&size=48211
64
+ ```
65
+
66
+ - The **scheme is the provider's name**, so a provider can move from local disk to a bucket without touching any row. Name the role (`archive`), not the vendor: the name is part of every stored value.
67
+ - The **path** of an upload is `<tenant>/<random id>.<extension>`, with `_` for a resource without a tenant. Nothing in it comes from the row or from what the user typed, so renames and key changes need nothing.
68
+ - The **query** holds the uploader's file name and the size in bytes, and for an image with [variants](#image-variants-and-placeholders) their names and extensions: `&variants=card.webp,thumb.webp`. A plain `{provider}:{path}`, such as `public:images/test.jpg` written by an import, is valid too; its name is its last path segment.
69
+ - The **type is not stored**. It is the path's extension, looked up in one fixed table, which is also what downloads are served as.
70
+ - A field with `.externalUrls()` may hold an **https URL** instead, such as `https://images.example.com/listings/42.jpg`, see [External URLs](#external-urls).
71
+
72
+ Responses carry each file field as an object, and the stored value stays the URI:
73
+
74
+ ```json
75
+ { "uri": "private:1/2992db9c-….jpg?name=bike+red.png&size=48211", "name": "bike red.png", "type": "image/jpeg", "size": 48211,
76
+ "url": "/api/files/private/1/2992db9c-….jpg?r=bikes&k=42&f=photo&exp=1791673200&sig=…" }
77
+ ```
78
+
79
+ An image with variants also has `variants`, each `{ url, type, width, height }` by name, and one with a placeholder its `placeholder`. An external URL comes as `{ uri, name, type, url }` with the URL as both `uri` and `url`. A value that does not parse, or names a provider the config lacks, comes back as `{ uri, missing: true }`. The URL is made for each response and never changes the record's ETag.
80
+
81
+ ## Providers
82
+
83
+ ```ts title="protobase.config.ts"
84
+ import sharp from 'sharp'
85
+ import { defineConfig, localFiles } from '@protobase/server'
86
+ import * as config from './config'
87
+
88
+ export default defineConfig({
89
+ config,
90
+ files: {
91
+ providers: {
92
+ private: localFiles({ dir: './data/files/private' }),
93
+ public: localFiles({ dir: './data/files/public', public: true }),
94
+ archive: localFiles({ dir: '/mnt/archive', retention: '30 days' }),
95
+ },
96
+ retention: '1 day',
97
+ // Makes the image variants and placeholders
98
+ sharp,
99
+ },
100
+ })
101
+ ```
102
+
103
+ - `localFiles({ dir, public?, publicUrl?, retention? })` keeps files in a folder on local disk. Writes go to a temporary file first and are renamed into place, so nobody reads half a file. A full disk or quota answers `507`.
104
+ - `s3Files({ bucket, prefix?, endpoint?, region?, public?, publicUrl?, retention? })` keeps them in an S3-compatible bucket, see [S3-compatible buckets](#s3-compatible-buckets).
105
+ - Without config, `private` and `public` are the folders `data/files/private` and `data/files/public`, created when needed. Any other provider a field names must be configured.
106
+ - `PROTOBASE_FILES_<NAME>` configures a provider from the environment and wins over the config for that name: `PROTOBASE_FILES_PRIVATE=file:///data/files/private`, or `file:///data/files/public?public=1&public_url=https://cdn.example.com/app&retention=0`, or an `s3://` URL. `PROTOBASE_FILES_RETENTION` overrides `files.retention`.
107
+ - Uploads and download links are signed with `files.secret`, else `PROTOBASE_FILES_SECRET`, else `BETTER_AUTH_SECRET`. The server does not start with file fields and none of them set.
108
+
109
+ ### Limits
110
+
111
+ `maxBytes` (`'1 GB'`, as for `.maxSize()`) and `maxFiles` cap what one provider holds, for either kind; in a URL they are `max_bytes=1GB&max_files=20000`. An upload that would pass either is refused with `507`, and one that passes `maxBytes` while it streams stops there and leaves nothing. Scheduled deletes (`.cleanup/`) do not count, so a full provider can still be emptied.
112
+
113
+ A bucket has no quota of its own, so the provider counts what it holds with `list` on the first upload, and again once that count is five minutes old; in between it adds its own uploads. Several instances, or files added by hand, can therefore pass a limit by what they wrote since the last count.
114
+
115
+ ### Writing files from a seed
116
+
117
+ A seed, an import or another script that writes files outside a request uses `storeFile` from `@protobase/server`, so the same script fills the folder locally and the bucket where the app has one. It finds the provider as the server does, from `env` and the config's `files`, when that declares providers:
118
+
119
+ ```ts
120
+ import { storeFile } from '@protobase/server'
121
+
122
+ // A row then holds public:images/test.png
123
+ await storeFile({ provider: 'public', path: 'images/test.png', body: bytes, env: process.env })
124
+ ```
125
+
126
+ `body` is bytes or a stream. A relative folder, such as the default `data/files/public`, is taken from the working directory, so run the script where the server runs. A script that makes [variants](#image-variants-and-placeholders) stores each at `variantPath(path, name, extension)` the same way.
127
+
128
+ ### S3-compatible buckets
129
+
130
+ `s3Files` stores files in any bucket with the S3 API, such as Cloudflare R2, Scaleway Object Storage or AWS S3, under `prefix` when given, so one bucket can hold several providers or apps:
131
+
132
+ ```ts
133
+ // Cloudflare R2, in the EU jurisdiction
134
+ private: s3Files({ bucket: 'acme-files', prefix: 'private', endpoint: 'https://<account id>.eu.r2.cloudflarestorage.com', region: 'auto' }),
135
+ public: s3Files({ bucket: 'acme-files', prefix: 'public', endpoint: 'https://<account id>.eu.r2.cloudflarestorage.com', region: 'auto', publicUrl: 'https://files.acme.com' }),
136
+ // Scaleway, in Paris
137
+ archive: s3Files({ bucket: 'acme-archive', endpoint: 'https://s3.fr-par.scw.cloud', region: 'fr-par', retention: '30 days' }),
138
+ ```
139
+
140
+ Or from the environment, the same providers:
141
+
142
+ ```sh
143
+ PROTOBASE_FILES_PRIVATE=s3://acme-files/private?endpoint=https://<account id>.eu.r2.cloudflarestorage.com&region=auto
144
+ PROTOBASE_FILES_PUBLIC=s3://acme-files/public?endpoint=https://<account id>.eu.r2.cloudflarestorage.com&region=auto&public_url=https://files.acme.com
145
+ PROTOBASE_FILES_ARCHIVE=s3://acme-archive?endpoint=https://s3.fr-par.scw.cloud&region=fr-par&retention=30d
146
+ ```
147
+
148
+ - **Credentials** never go in the URL. A provider set from the environment reads `PROTOBASE_FILES_<NAME>_ACCESS_KEY_ID` and `PROTOBASE_FILES_<NAME>_SECRET_ACCESS_KEY`, else `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`, else `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`, and the server does not start without a pair. In the config, pass `accessKeyId` and `secretAccessKey`, or leave them out for the `S3_` or `AWS_` pair. The key needs to read, write, list and delete objects in the bucket.
149
+ - **Uploads** still go through Protobase's upload route, so types are checked and processors run; the body streams on to the bucket in parts, and an upload that fails stores nothing. Each object is stored with the type and disposition its path is served as. A bucket keeps the parts of an upload that never finished until they are aborted: R2 aborts them after 7 days, on Scaleway and AWS add a lifecycle rule that aborts incomplete multipart uploads after a day.
150
+ - **Private files** keep their signed `url`. A download checks the link and the row as above, then redirects with `302` to a presigned link to the bucket that lasts as long as the app's link, served with the same type and disposition. The bytes never pass through the app.
151
+ - **Public files** are linked at `publicUrl` followed by the prefix and the path, such as `https://files.acme.com/public/_/2992db9c-….png`: the bucket's own public address, an R2 custom domain or a Scaleway public bucket. Without `publicUrl`, `/api/files/<provider>/<path>` redirects to a presigned link instead.
152
+ - The bucket serves its files itself, so the `nosniff` and sandbox headers of the app's own downloads do not apply. The type always comes from the path's extension, never HTML, and the bucket is on another domain than the app. A page that `fetch`es file URLs, rather than showing them in `<img>` or linking them, needs CORS on the bucket.
153
+ - It runs on Bun, whose built-in S3 client it uses: `protobase-serve.js`, the `protobase` image, or the CLI started with Bun. On Node the first file operation fails.
154
+
155
+ ## Uploading
156
+
157
+ Uploads go through Protobase's own route, so the type is checked and processors run on the bytes:
158
+
159
+ 1. `POST /api/v1/{resource}:upload?field=photo&name=bike.png` with the file as the body. A `multipart/form-data` body with exactly one file part works too, using that part's name and type; it is read whole, so the raw body is better for large files. The caller needs `create` or `update` on the resource and write access to the field.
160
+ 2. The server reads the first bytes, decides the type and refuses a type the field does not allow with `415`, before anything is stored. A `Content-Length` over `maxSize` gets `413` before a byte is read, and a body that turns out larger stops there with `413`.
161
+ 3. The rest streams to the provider while it is counted. The answer is `201 { value, file: { name, type, size }, derived, corrected? }`.
162
+ 4. Send `value` as the field's value in a create, update or [batch write](api.md#batch-writes)) within 24 hours. It is a ticket, signed for that user, tenant, resource and field: the write stores the clean URI and the derived values in the same transaction.
163
+
164
+ A write takes only a ticket, `null` to clear the field, or the stored `uri` unchanged, and in a field with `.externalUrls()` an https URL. Anything else is refused with `400`, so a row can only point at a file its writer uploaded for that field, or at a URL elsewhere where the field allows one. From the client, `client.upload(resource, field, file, { onProgress })` does step 1; see [Client](client.md)).
165
+
166
+ ### How the type is decided
167
+
168
+ An upload carries three hints: what the **content** is (C, from its magic bytes), what the **name's extension** says (E), and what the **client declared** (H, the request's or the file part's `Content-Type`; `application/octet-stream` counts as none).
169
+
170
+ | Content | Type used | When the hints disagree |
171
+ | --- | --- | --- |
172
+ | Recognized: images, PDF, archives, Office files, audio, video, executables, ... | C | C wins and the answer reports `corrected: { from, to }`: a JPEG sent as `photo.png` is `image/jpeg`, and an executable named `invoice.pdf` is refused by `accept: ['application/pdf']`. |
173
+ | Not recognized, and text (UTF-8 without NUL bytes) | E when it is a text type (`csv`, `tsv`, `txt`, `md`, `json`); H when there is no extension; else `text/plain` | E wins over H: HTML named `.csv` is stored as `text/csv`. HTML and SVG are never taken as images. |
174
+ | Not recognized, and binary | E, only when `accept` lists that type exactly and H does not disagree; else `application/octet-stream` | Any disagreement gives `application/octet-stream`, which passes only an `accept` that names it. |
175
+
176
+ The decided type picks the stored extension, and downloads are served by that extension, so nothing posing as a PDF is ever served as something else, and nothing is served as HTML.
177
+
178
+ ## Downloads
179
+
180
+ `GET /api/files/<provider>/<path>` on the app's own host:
181
+
182
+ - **Private files** need the signed `url` from a response, made only for a caller who may read that row and field. It needs no token, so it works in an `<img src>`, and it is valid one to two hours (the same URL within the hour, so browsers cache it). Each download checks that the row still holds the file and that the file sits under that row's tenant: a replaced or cleared file stops downloading at once, and a URI copied into another tenant's row by SQL is never served.
183
+ - **Public files** are served to anyone at a permanent address, `/api/files/public/<path>`, cached for a year. `publicUrl` links them from elsewhere instead, such as a CDN in front of that route.
184
+ - Every download is `nosniff` with `Content-Security-Policy: sandbox; default-src 'none'`. Raster images, PDF, audio and video are `inline`; everything else, SVG included, is an attachment. A private file is named as its uploader named it, with the extension matched to the type (`photo.png` holding a JPEG downloads as `photo.jpg`); a public file by its stored path. `Range` requests work.
185
+ - A provider in a bucket answers with a redirect to the bucket instead, after the same checks, see [S3-compatible buckets](#s3-compatible-buckets).
186
+
187
+ ## Derived fields
188
+
189
+ `.derive({ field: processor })` computes values from each upload into other fields of the same resource. Those fields must be `readOnly()`, so only the upload sets them.
190
+
191
+ | Processor | Gives |
192
+ | --- | --- |
193
+ | `imageSize('width')`, `imageSize('height')` | an image's size in pixels as shown (EXIF rotation applied), for an integer field |
194
+ | `aspectRatio({ decimals? })` | width divided by height as decimal text, 4 places by default, for a decimal field |
195
+ | `fileSize()` | the size in bytes, for an integer field to sort or filter on |
196
+ | `fileType()` | the detected type, for a text field |
197
+ | `processor({ accepts?, run })` | your own: `run(file)` gets `{ name, type, size, head, read() }`, where `head` is the first 256 KB and `read()` streams the whole file |
198
+
199
+ Processors run once, on the upload route, after the file is stored. A processor whose `accepts` does not match the type leaves its field `null`, so a field that takes images and PDFs gets a width only for images. The values travel signed inside the ticket and are written with the file in the same transaction; replacing the file recomputes them and clearing it sets them to `null`. A value the field's own schema refuses is an error in the processor. Files stored before a processor was added keep their fields as they are.
200
+
201
+ ## Image variants and placeholders
202
+
203
+ `.placeholder()` and `.variants()` process each image as it is uploaded, with [sharp](https://sharp.pixelplumbing.com):
204
+
205
+ ```ts
206
+ photo: f.file().accept(['image/*']).public()
207
+ .placeholder('photo_placeholder')
208
+ .variants({
209
+ card: { width: 800, height: 600, fit: 'cover', format: 'webp', quality: 75 },
210
+ thumb: { width: 96, height: 96, fit: 'cover', format: 'webp' },
211
+ }),
212
+ photo_placeholder: f.text().readOnly().optional(),
213
+ ```
214
+
215
+ - **`.placeholder('photo_placeholder')`** computes the image's [ThumbHash](https://evanw.github.io/thumbhash/), about 30 characters of base64 that hold its shape and colours, into that read-only text field, written with the file like a [derived field](#derived-fields). The admin app draws it blurred wherever it shows the image, until the image has loaded.
216
+ - **`.variants({ name: variant })`** stores resized copies beside the file, each at most `width` by `height` pixels (either may be left out) and never enlarged. `fit: 'inside'`, the default, keeps the whole image in that box; `'cover'` fills the box and crops the rest, and needs both sides. `format` is `webp`, `avif`, `jpeg` or `png`, and `quality` 1 to 100, the format's default when left out. Names are snake_case. A variant is stored at the file's path followed by its name and extension (`…/2992db9c-….jpg.card.webp`) with the same provider, served and deleted with the file. The admin app shows tables, forms and cards with the smallest variant large enough for them.
217
+ - **`{ original: variant }`**, as `.variants()`' second argument, stores that image instead of the upload, so the upload is not kept: `{ original: { width: 2560, format: 'webp' } }` stores at most 2560 pixels wide as WebP.
218
+
219
+ Variants and placeholders turn the image upright first, following its EXIF orientation, and carry no metadata. JPEG, PNG, WebP, AVIF, GIF and TIFF images are processed; any other file, HEIC and SVG included, is stored as it is, without variants, and its placeholder is `null`. Files uploaded before a field declared them keep none.
220
+
221
+ sharp is a native package, so the config passes it in, and a [built bundle](cli.md#native-packages)) carries it with its add-on for linux:
222
+
223
+ ```ts
224
+ // protobase.config.ts
225
+ import sharp from 'sharp'
226
+
227
+ export default defineConfig({ config, files: { sharp } })
228
+ ```
229
+
230
+ The server does not start with a field that declares variants or a placeholder and no `files.sharp`. In code, `fileUrl(file, 'card')` from `@protobase/client` links a variant by name, or the file itself when it has none.
231
+
232
+ ## External URLs
233
+
234
+ `.externalUrls()` lets a file field hold the https URL of a file another site serves, instead of an upload: an import that links a supplier's product photos, say, rather than copying them into the app's storage.
235
+
236
+ ```ts
237
+ photo: f.file().accept(['image/*']).public().externalUrls()
238
+ .placeholder('photo_placeholder')
239
+ .variants({ card: { width: 800, height: 600, fit: 'cover', format: 'webp' } }),
240
+ ```
241
+
242
+ ```sh
243
+ curl -X PATCH https://app.example.com/api/v1/products/42 -H "authorization: Bearer $TOKEN" -H 'if-match: *' \
244
+ -H 'content-type: application/json' \
245
+ -d '{ "photo": "https://images.example.com/products/42/front.jpg" }'
246
+ ```
247
+
248
+ - **What is taken**: an absolute `https://` URL with a host, without a user name or password, written without spaces or other characters a URL escapes. `http:`, `data:` and anything else is refused with `400`, as in a field without the option.
249
+ - **The type** is the URL path's extension, from the same table as stored files, and must pass `.accept()`: an image field takes `…/front.jpg` and refuses `…/front` and `…/scan.pdf`. The name is the path's last segment.
250
+ - **Stored as given**: the column holds the URL itself, and Protobase never fetches, uploads or copies it. It has no size, and responses link it as it is, as `url`, for whoever may read the row.
251
+ - **No variants**: every place an image is drawn, cards, tables, thumbnails, forms and the record page, uses the URL itself, and `fileUrl(file, 'card')` gives it too. Size the image at its source when it should be small.
252
+ - **No ThumbHash**: a write through the API sets the field's derived fields and placeholder to `null`, since there are no bytes to compute them from; the image frame stays empty until the image loads. An import that writes the rows itself may write a placeholder beside the URL, and the admin app draws that one.
253
+ - **Nothing to delete**: replacing an upload with a URL schedules the upload's delete as any replacement does; a URL that is replaced or cleared schedules nothing.
254
+ - The other site sees each viewer's IP address when it serves the image, and decides when it changes or disappears. The admin app draws it without a referrer, see [Image referrers](#image-referrers).
255
+
256
+ ## Image referrers
257
+
258
+ The admin app draws every image of a file field with `referrerPolicy="no-referrer"`, so another site never learns which page showed its image, unless the image comes from a host it trusts:
259
+
260
+ - the page's own origin, which serves the app's downloads and the public files without `publicUrl`;
261
+ - the host of each provider's `publicUrl`, such as a bucket's custom domain on another domain than the app;
262
+ - the hosts of the app's [sources](remote-resources.md));
263
+ - the hosts `files.trustedHosts` adds, as lowercase host names without a scheme, port or path:
264
+
265
+ ```ts
266
+ export default defineConfig({
267
+ config,
268
+ files: { trustedHosts: ['images.example.com'] },
269
+ })
270
+ ```
271
+
272
+ A trusted host is matched exactly: `images.example.com` does not trust `cdn.images.example.com`. `/meta` names the trusted hosts besides the page's own as `files.trustedHosts`. Download links are opened with `rel="noreferrer"` wherever they point.
273
+
274
+ ## Deleting files
275
+
276
+ Files are deleted by schedule, never in the write itself, so a restore of the database to an earlier moment still finds its files:
277
+
278
+ - A write that **replaces or clears** a file, or **deletes a row** (not a soft delete), schedules the delete of each file it took out of its row, with its variants. It is due after the provider's retention: `files.retention`, 1 day by default, or 0 for a public provider.
279
+ - Every **upload** schedules one too, due an hour after its ticket expires, so a file nobody saved, or whose write rolled back, goes as well.
280
+ - Each scheduled delete is a small JSON object in the provider's own storage, in a `.cleanup/` folder, named after its due time and saying what to delete: `.cleanup/2026-10-12T03-00-00Z-<uuid>.json` holding `{ "provider": "private", "path": "1/2992db9c-….jpg", "due": "…" }`.
281
+ - A **cleanup run** handles the entries that are due. Right before deleting, it checks every file column of every resource for the file: one that a row holds again (a rolled-back write, a restore, a copied value) is kept, and its entry dropped. Two runs at once do no harm.
282
+
283
+ A run happens:
284
+
285
+ - in [`protobase serve`](cli.md#serve)), every 60 minutes (`PROTOBASE_FILES_CLEANUP_MINUTES`, 0 turns it off);
286
+ - with [`protobase files cleanup`](cli.md#files-cleanup)), from cron or a timer;
287
+ - with `POST /api/files:cleanup` and an admin's token, for a hosting platform. It answers `{ deleted, kept }`.
288
+
289
+ The scheduled deletes sit behind a small interface (`CleanupSchedule`: `add`, `due`, `done`), so a table in a schema of its own, added by a migration at update time, can replace the folder later.
290
+
291
+ What this does not cover: a write made with SQL outside the API schedules nothing, so a file whose row SQL changed or deleted stays in storage. The check before deleting looks only at the file fields the config declares; a column holding file URIs that no resource declares is not protected.