@protobase/cli 0.121.9 → 0.121.11

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.
@@ -0,0 +1,33 @@
1
+ import { bucketsRefreshes } from "@protobase/server/internal";
2
+ import { sql } from "kysely";
3
+ //#region src/buckets/rebuild.ts
4
+ const timePattern = /^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)(Z|[+-]\d{2}:\d{2})?)?$/;
5
+ const isDate = (date) => (/* @__PURE__ */ new Date(`${date}T00:00Z`)).toISOString().slice(0, 10) === date;
6
+ const notATime = (value) => /* @__PURE__ */ new Error(`--from "${value}" is not a time: pass a date or a date and time, such as 2026-07-01 or 2026-07-01T10:00Z`);
7
+ /** The time `--from` names, as an ISO string in UTC; a value that is not a date or a date and time stops with an error naming it. */
8
+ const parseFrom = (value) => {
9
+ const match = timePattern.exec(value);
10
+ if (!match) throw notATime(value);
11
+ const [, date, clock = "00:00", zone = "Z"] = match;
12
+ const time = /* @__PURE__ */ new Date(`${date}T${clock}${zone}`);
13
+ if (Number.isNaN(time.getTime()) || !isDate(date)) throw notATime(value);
14
+ return time.toISOString();
15
+ };
16
+ /** The refresh function of the time rollup `resource`; any other resource stops with an error naming it. */
17
+ const rebuildFunction = (models, resource) => {
18
+ const model = models.find((candidate) => candidate.name === resource);
19
+ if (!model) throw new Error(`The project has no resource "${resource}"`);
20
+ const [refresh] = bucketsRefreshes([model]);
21
+ if (!refresh) throw new Error(`"${resource}" is not a time rollup: only a resource declared with .bucketsOf() can be rebuilt`);
22
+ return refresh.fn;
23
+ };
24
+ /**
25
+ * Recounts the time rollup `resource` from the bucket `from` falls in, or every bucket without it, through its refresh
26
+ * function: one statement that writes only the rollup's table.
27
+ */
28
+ const rebuildBuckets = async (db, models, resource, from) => {
29
+ const fn = rebuildFunction(models, resource);
30
+ await sql`select ${sql.raw(fn)}(${from ?? "-infinity"}::timestamptz)`.execute(db);
31
+ };
32
+ //#endregion
33
+ export { parseFrom, rebuildBuckets, rebuildFunction };
@@ -0,0 +1,17 @@
1
+ //#region src/buckets/register.ts
2
+ const out = (text) => void process.stdout.write(text);
3
+ const registerBuckets = (program) => {
4
+ program.command("buckets").description("Recount the time rollups the app keeps").command("rebuild").description("Recount a time rollup's buckets from a time, or all of them, such as after importing records older than its late").argument("<resource>", "the time rollup, by its resource name").option("--from <time>", "recount from the bucket this date or date and time (UTC unless it names a zone) falls in; default: every bucket").action(async (resource, opts) => {
5
+ const [{ parseFrom, rebuildBuckets }, { loadBundleProject }] = await Promise.all([import("./rebuild.js"), import("../project/load-bundle-project.js")]);
6
+ const from = opts.from === void 0 ? void 0 : parseFrom(opts.from);
7
+ const project = await loadBundleProject(void 0, process.cwd());
8
+ try {
9
+ await rebuildBuckets(project.db, project.resources.map((source) => source.toModel()), resource, from);
10
+ } finally {
11
+ await project.close();
12
+ }
13
+ out(`Recounted ${resource} ${from ? `from ${from}` : "from its first record"}\n`);
14
+ });
15
+ };
16
+ //#endregion
17
+ export { registerBuckets };
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.121.9";
2
+ var version = "0.121.11";
3
3
  //#endregion
4
4
  export { version };
package/dist/main.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { registerAuth } from "./auth/register.js";
2
+ import { registerBuckets } from "./buckets/register.js";
2
3
  import { defaultConnectionEnv, isConnectionString, resolveConnectionUrl } from "./db/connection-url.js";
3
4
  import { parseHosts } from "./dev/hosts.js";
4
5
  import { loadNearestEnvFile } from "./dev/env.js";
@@ -196,6 +197,7 @@ registerOrganizations(program);
196
197
  registerToken(program);
197
198
  registerAuth(program);
198
199
  registerMigration(program);
200
+ registerBuckets(program);
199
201
  registerEject(program);
200
202
  registerFiles(program);
201
203
  registerEncryption(program);
@@ -1,10 +1,23 @@
1
+ import { relayPresencePath } from "@protobase/server";
1
2
  //#region src/relay/app-entry.ts
2
- /** The app's entry in the relay's apps file: its id, its keys and the browser origin of its URL. */
3
- const relayAppEntry = (relay, appUrl) => ({
3
+ /** How long a person who closed their last socket still counts as present, so a phone that reconnects never goes offline. */
4
+ const presenceGraceSeconds = 30;
5
+ const systemPath = (apiPath = "/api/v1") => apiPath.slice(0, apiPath.lastIndexOf("/"));
6
+ const presenceEntry = (presence, appUrl, apiPath) => {
7
+ if (!appUrl) throw new Error("realtime.relay.presence needs the app's url (url or PROTOBASE_URL), where the relay posts its presence reports");
8
+ return {
9
+ url: new URL(relayPresencePath(systemPath(apiPath)), appUrl).href,
10
+ key: presence.key,
11
+ grace_seconds: presenceGraceSeconds
12
+ };
13
+ };
14
+ /** The app's entry in the relay's apps file: its id, its keys, the browser origin of its URL and, with presence, where its reports go. */
15
+ const relayAppEntry = (relay, appUrl, apiPath) => ({
4
16
  id: relay.app,
5
17
  api_keys: [relay.apiKey],
6
18
  ticket_keys: [relay.ticketKey],
7
- origins: appUrl ? [new URL(appUrl).origin] : []
19
+ origins: appUrl ? [new URL(appUrl).origin] : [],
20
+ ...relay.presence && { presence: presenceEntry(relay.presence, appUrl, apiPath) }
8
21
  });
9
22
  //#endregion
10
23
  export { relayAppEntry };
@@ -11,7 +11,7 @@ const registerRelay = (program) => {
11
11
  const config = await loadSourceConfig(process.cwd(), { command: "tool" });
12
12
  if (!config.realtime?.relay) throw new Error("The config has no realtime.relay");
13
13
  const url = config.url ?? process.env.PROTOBASE_URL;
14
- process.stdout.write(`${JSON.stringify(relayAppEntry(checkRelayOptions(config.realtime.relay), url), null, 2)}\n`);
14
+ process.stdout.write(`${JSON.stringify(relayAppEntry(checkRelayOptions(config.realtime.relay), url, config.apiPath), null, 2)}\n`);
15
15
  });
16
16
  };
17
17
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.121.9",
3
+ "version": "0.121.11",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -43,13 +43,13 @@
43
43
  "dependencies": {
44
44
  "@better-auth/core": "^1.7.12",
45
45
  "@hono/node-server": "^2.1.3",
46
- "@protobase/config": "0.121.9",
47
- "@protobase/layout": "0.121.9",
48
- "@protobase/query": "0.121.9",
49
- "@protobase/schema": "0.121.9",
50
- "@protobase/server": "0.121.9",
51
- "@protobase/ui": "0.121.9",
52
- "@protobase/workflows": "0.121.9",
46
+ "@protobase/config": "0.121.11",
47
+ "@protobase/layout": "0.121.11",
48
+ "@protobase/query": "0.121.11",
49
+ "@protobase/schema": "0.121.11",
50
+ "@protobase/server": "0.121.11",
51
+ "@protobase/ui": "0.121.11",
52
+ "@protobase/workflows": "0.121.11",
53
53
  "@react-email/render": "^2.1.0",
54
54
  "@scalar/hono-api-reference": "^0.12.10",
55
55
  "@sentry/vite-plugin": "^11.10.0",
@@ -14,11 +14,13 @@ Describe the tables of an existing Postgres database as resources, with their fi
14
14
  - [Record authors](../reference/data-config.md#resource): A record can keep who created it. The server sets it to the signed-in user on every create, and no request can set or change it.
15
15
  - [Record search](../reference/data-config.md#resource): You choose which fields text search and the global search look in. Partial words match, and phone numbers match by their last digits.
16
16
  - [Manual order](../reference/data-config.md#resource): Records can be kept in an order set by hand, also per parent record, such as the lines of an invoice.
17
+ - [Checks the database makes](../reference/data-config.md#checks-the-database-makes): A database check or trigger that refuses a write is explained by a label you declare, translated and filled with the record's values, while the database's own message stays on the server.
17
18
  - [Opening an existing record](../reference/data-config.md#opening-an-existing-record): A create that repeats a record's unique values, such as a direct message with the same people, opens that record instead of failing, for whoever may read it; anyone else gets the usual conflict, which does not say the record exists.
18
19
  - [Record validation](../reference/data-config.md#resource): A rule over the whole record runs on every create and update and reports each problem on the field it concerns.
19
20
  - [Rollups and formulas](../reference/data-config.md#rollups-and-formulas) (beta): Fields that hold counts, sums, averages, minimums or maximums of related records, or values calculated from the record's own numbers, kept current by the database.
20
21
  - [Lookups](../reference/data-config.md#lookups) (beta): A field can show a field of a linked record, such as an order's customer name, read with the record in the same query and only as far as the caller may read the linked record.
21
22
  - [Time rollups](../reference/data-config.md#time-rollups) (beta): A large events table gets an hourly or daily rollup that the app keeps up to date, so charts over months of millions of rows answer in milliseconds.
23
+ - [Time rollup rebuild](../reference/cli.md#buckets-rebuild) (beta): `protobase buckets rebuild` recounts a time rollup from an earlier time, such as after importing older records.
22
24
  - [Sensitive fields](../reference/data-config.md#sensitive-fields): Values such as bank account numbers are left out of every response and shown masked. A permitted user reveals one value at a time, and each reveal is audited.
23
25
  - [Recent strong sign-in](../reference/data-config.md#recent-strong-sign-in): A sensitive field can ask for a passkey or a second step in the last minutes before it is revealed, or an emailed code for an account with neither. The record page asks the person to confirm it's them, then shows it.
24
26
  - [Computed reveals](../reference/data-config.md#computed-reveals) (beta): A secret kept elsewhere, or built from several values, is revealed like a sensitive field, with the same access, audit and recent sign-in check, but made when it is asked for.
@@ -18,6 +18,6 @@ The changes of each record, comments on it, and pages that refresh as records ch
18
18
  - [Polling, then a socket](../reference/live.md#polling-then-a-socket): Apps and Node scripts poll for changes first and switch to a WebSocket after 30 seconds, or at once, falling back to polling while the socket is down.
19
19
  - [Presence](../reference/channels.md#presence) (beta): Apps see who else has a record open and what each of them tracks, such as online or away, for whoever may read the record.
20
20
  - [Realtime relay](../reference/realtime-relay.md) (in development): Apps hand their realtime connections to a relay, so they and their database can sleep while people stay connected: the app issues connect tickets for signed-in people and visitors, keeps the relay's channel members in step with its members records, tells each channel's members of every change, and closes a session's sockets when it signs out or expires. `protobase dev` runs a relay for the app by itself.
21
- - Relay presence (coming soon): The relay reports who comes online, goes away and goes offline, and the app records it, raises its events and tells the right people.
21
+ - [Relay presence](../reference/realtime-relay.md#presence) (in development): The relay reports who comes online, goes away and goes offline; the app keeps it in a resource of its own, raises that resource's events, so workflows can act when someone goes offline, and tells the people who share a conversation with them.
22
22
  - Relay client events (coming soon): Clients send each other events such as typing through the relay, as each channel resource declares them, with a schema, a size and a rate.
23
23
  - [Broadcasts](../reference/channels.md#broadcasts) (beta): Apps on a record send each other short-lived events, such as typing, which are never stored, as JSON or as bytes, such as a chunk of audio or a drawing stroke; the app's own code sends them too, from an API function, over HTTP or [from SQL](../reference/channels.md#from-sql) with `channels.send()`.
@@ -16,3 +16,4 @@ Show a list as cards, a map, a board, a calendar or a timeline, and reorder reco
16
16
  - [Drop rules](../reference/ui-config.md#drop-rules): Rules for where a dragged record may land, such as never above a task it waits for.
17
17
  - [Ranked after dependencies](../reference/ui-config.md#ranked-after-what-they-depend-on): Ranked records stay below the records they depend on while those are pending.
18
18
  - [Board drops](../reference/ui-config.md#board-drops): Dropping a card on a board column can run your own write, such as creating an approval.
19
+ - [Moving cards by another field](../reference/ui-config.md#moving-cards-by-another-field): A board by a status the database computes can still take cards in the columns you name, saving another field the status follows, with a declared check's label when the database refuses.
@@ -11,7 +11,7 @@ The page of one record, with its sections, related records, galleries, charts an
11
11
  - [Record pages that open another](../reference/ui-config.md#a-record-page-that-opens-another): A record's page opens another address built from its fields in its place, such as a workflow run opening its workflow's page with the run shown.
12
12
  - [Record page opens elsewhere](../reference/ui-config.md#open-elsewhere) (beta): A view can send its record's address to another page its fields name, such as a message opening in its conversation, so search results and links land where the record is read.
13
13
  - [Full-area record pages](../reference/ui-config.md#full-area-record-pages) (beta): A view draws its record pages with a component of its own that fills the area beside the sidebar and under the top bar, such as a chat channel, and links to the standard page.
14
- - [Conversation pages](../reference/ui-config.md#conversation-pages) (beta): A record's page is its conversation, configured with no component of your own: a header with its title, topic and details, its messages grouped by day and author with mentions and edits shown, and a box that sends one, opening on a New messages line at the reader's place, on the web and at mobile width. People react to its messages, edit and delete them and reply in threads beside the conversation, by pointer or touch, and start or join the record's call from its header, shown beside the messages, or above them at mobile width.
14
+ - [Conversation pages](../reference/ui-config.md#conversation-pages) (beta): A record's page is its conversation, configured with no component of your own: a header with its title, topic and details, its messages grouped by day and author with mentions and edits shown, and a box that sends one, opening on a New messages line at the reader's place, on the web and at mobile width. People react to its messages, edit and delete them, reply in threads beside the conversation and share files that show under their message, by pointer or touch, and start or join the record's call from its header, shown beside the messages, or above them at mobile width.
15
15
  - [Read view and edit](../reference/ui-config.md#read-view-and-edit): A record opens as a read-only fact sheet or a form, and Edit opens the form at its own address.
16
16
  - [Unsaved edits](../reference/ui-config.md#editing-a-record): Unsaved changes to a record stay in the browser and can be resumed, and leaving a form, a dialog or a comment with changes asks first.
17
17
  - [Record forms](../reference/ui-config.md#editing-a-record): Relations are picked from a list that narrows as you type, numbers are read as the browser's language writes them, and a refused save says under each field what is wrong.
@@ -278,7 +278,7 @@ The API sends no CORS headers until it has something to allow: other websites in
278
278
 
279
279
  ## Errors
280
280
 
281
- Every error is `application/problem+json` (RFC 9457) with `type` (`urn:protobase:problem:<slug>`), `title`, `status`, `detail`, `instance`. Filter and `order_by` errors add `parameter` and `errors: [{ code, message, hint, span: { start, end } }]`; invalid parameters add `errors: [{ parameter, message }]`. A create or update whose body fails the checks is `invalid-record` with `errors: [{ field, code, message, params }]`, `code` one of `required`, `invalid-value`, `read-only`, `unknown-field` and `invalid-record` (a `.validate()` rule); `params` is the limit an invalid value broke, such as `{ min }`, `{ max }` or a decimal's `{ precision, scale }`. Database constraint failures map to `409` or `400` without the raw message. A create or update that writes the position of a resource with `after` so a record ranks at or above one it depends on is a `409` `ranks-above-dependency`, as in a [`reorder`](#batch-writes). A create that repeats the values of a resource's [`.openExisting()`](data-config.md#opening-an-existing-record) unique key is a `409` `conflict` with `existing: { key }`, the key of the record holding them as its address writes it, only when the caller may read that record; otherwise it is the plain `409`, as any unique conflict is. A delete that other records still point at is a `409` `conflict` with `blockedBy: { resource, field? }`: their resource, when the caller may list it, and its relation field pointing at the record, when they may filter by it, so a client can open those records; the admin app's toast names them, such as "Orders still point at this company.", with a link to that list. Postgres names one table of them only, so `blockedBy` holds one resource. A write that Postgres rolls back because it locked the same records as another write in the opposite order (a deadlock) is a `409` `conflict` too: nothing was written, so send it again. Anything unexpected is a `500` with a fixed detail, reported to the app's error hook (`hooks/error.ts`, `createAdmin`'s `options.onUnhandledError`) and, when it is set, the [error tracker](#error-reporting).
281
+ Every error is `application/problem+json` (RFC 9457) with `type` (`urn:protobase:problem:<slug>`), `title`, `status`, `detail`, `instance`. Filter and `order_by` errors add `parameter` and `errors: [{ code, message, hint, span: { start, end } }]`; invalid parameters add `errors: [{ parameter, message }]`. A create or update whose body fails the checks is `invalid-record` with `errors: [{ field, code, message, params }]`, `code` one of `required`, `invalid-value`, `read-only`, `unknown-field` and `invalid-record` (a `.validate()` rule); `params` is the limit an invalid value broke, such as `{ min }`, `{ max }` or a decimal's `{ precision, scale }`. Database constraint failures map to `409` or `400` without the raw message. A check violation naming a check the resource declares with [`.checks()`](data-config.md#checks-the-database-makes) is a `400` `invalid-record` with `errors: [{ field: '_record', code, message }]`, `code` the check's name and `message` its label from the config, never the database's text; any other check violation is the generic `400`, and the server logs a warning with the constraint's name. A create or update that writes the position of a resource with `after` so a record ranks at or above one it depends on is a `409` `ranks-above-dependency`, as in a [`reorder`](#batch-writes). A create that repeats the values of a resource's [`.openExisting()`](data-config.md#opening-an-existing-record) unique key is a `409` `conflict` with `existing: { key }`, the key of the record holding them as its address writes it, only when the caller may read that record; otherwise it is the plain `409`, as any unique conflict is. A delete that other records still point at is a `409` `conflict` with `blockedBy: { resource, field? }`: their resource, when the caller may list it, and its relation field pointing at the record, when they may filter by it, so a client can open those records; the admin app's toast names them, such as "Orders still point at this company.", with a link to that list. Postgres names one table of them only, so `blockedBy` holds one resource. A write that Postgres rolls back because it locked the same records as another write in the opposite order (a deadlock) is a `409` `conflict` too: nothing was written, so send it again. Anything unexpected is a `500` with a fixed detail, reported to the app's error hook (`hooks/error.ts`, `createAdmin`'s `options.onUnhandledError`) and, when it is set, the [error tracker](#error-reporting).
282
282
 
283
283
  | Status | Slugs |
284
284
  | --- | --- |
@@ -643,13 +643,22 @@ bun run protobase migration # writes db/migrations/NNN_auth.sql, NNN_jobs.
643
643
  bun run db:migrate # applies them
644
644
  ```
645
645
 
646
+ ## `buckets rebuild`
647
+
648
+ ```sh
649
+ protobase buckets rebuild <resource> # every bucket
650
+ protobase buckets rebuild <resource> --from 2026-07-01 # from the bucket of that day's first hour on
651
+ ```
652
+
653
+ Recounts a [time rollup](data-config.md#keeping-it-up-to-date)'s buckets from the one `--from` falls in, or all of them without it, in one statement through the rollup's refresh function, such as after importing records older than its `late`. `--from` takes a date or a date and time, such as `2026-07-01T10:00`, in UTC unless it names a zone (`2026-07-01T10:00+02:00`); anything else stops with an error naming it. It writes only the rollup's table, and refuses a resource that is not a time rollup. It reads the `.env` nearest the current directory and needs `DATABASE_URL`.
654
+
646
655
  ## `relay app`
647
656
 
648
657
  ```sh
649
658
  protobase relay app
650
659
  ```
651
660
 
652
- Prints the app's entry for the apps file of the [realtime relay](realtime-relay.md), as JSON: its `id`, `api_keys` and `ticket_keys` from `realtime.relay`, and in `origins` the origin of the app's `url` (or `PROTOBASE_URL`). Add the relay's limits and options to it there. It reads `protobase.config.ts` with `command: 'tool'` and the `.env` nearest the current directory.
661
+ Prints the app's entry for the apps file of the [realtime relay](realtime-relay.md), as JSON: its `id`, `api_keys` and `ticket_keys` from `realtime.relay`, and in `origins` the origin of the app's `url` (or `PROTOBASE_URL`); with [presence](realtime-relay.md#presence), `presence` with the app's presence endpoint at that `url`, the presence key and a `grace_seconds` of 30. Add the relay's limits and options to it there. It reads `protobase.config.ts` with `command: 'tool'` and the `.env` nearest the current directory.
653
662
 
654
663
  ## `auth migration`
655
664
 
@@ -151,7 +151,7 @@ export default defineConfig({ runtimeUpdates: false })
151
151
 
152
152
  ## realtime
153
153
 
154
- - **Type:** `{ processes?: 'one' | 'many', sqlSends?: boolean, relay?: { url, app, apiKey, ticketKey, channels } }`
154
+ - **Type:** `{ processes?: 'one' | 'many', sqlSends?: boolean, relay?: { url, app, apiKey, ticketKey, channels, presence? } }`
155
155
  - **Default:** `{ processes: 'one', sqlSends: false }`
156
156
 
157
157
  How [channels](../channels.md) and [Supabase Realtime](../supabase-realtime.md) are served. With `'one'`, one process serves the app, and broadcasts and presence go between its channels in memory. Set `'many'` when several processes serve the app behind one address: broadcasts and presence then go between the processes through the `realtime_relay` schema of the app's database, which [`protobase migration`](../cli.md#migration) writes and the server checks at start. See [Several processes](../channels.md#several-processes). Set `sqlSends: true` to let SQL in the app's database broadcast to channels with `channels.send()`, from the `channels` schema that `protobase migration` writes and the server checks at start. See [From SQL](../channels.md#from-sql). With `relay`, the app also hands its realtime connections to a relay, so it can sleep while people stay connected; see [Realtime relay](../realtime-relay.md).
@@ -66,6 +66,7 @@ export const repairs = resource('repairs')
66
66
  | `.position((r) => r.position, { within?, after? })` | The integer field holding the records' order by hand, 1 the first, which a list's **Reorder** button changes by dragging; with `within: (r) => r.invoice_id`, a filterable relation, each parent's records have an order of their own, sorted in its related section; with `after`, a record never ranks above the records it depends on. The field must be sortable. See [Reordering by hand](ui-config.md#reordering-by-hand) and [Ranked after what they depend on](ui-config.md#ranked-after-what-they-depend-on). |
67
67
  | `.parent((r) => r.vm_id, 'update')` | The relation whose record each record belongs to, and the access on it (`'read'` or `'update'`) that creating, changing, deleting and undeleting a record needs, checked with the caller's own rules on that resource. With `'read'`, every read of its records also keeps to those whose parent the caller reads. The relation is one column, to a resource with a key of one field. See [Records that belong to another](access.md#records-that-belong-to-another). |
68
68
  | `.links((r) => [r.objective_id, r.task_id])` | Its records link records of two resources, so each side lists the other, and what points at it, at [`/{parent}/{key}/{resource}`](api.md#lists-under-a-record). Two different filterable relations of one column. [`protobase doctor`](cli.md#doctor) asks for the indexes reading either side needs. |
69
+ | `.checks({ tasks_parked_by_hand: { label: '{title} waits for a day.' } })` | The database checks whose refusal the API names, each by its constraint name, with the label the app shows. See [Checks the database makes](#checks-the-database-makes). |
69
70
  | `.openExisting((r) => [r.organization_id, r.member_key])` | A unique key of the table whose conflict on create opens the record already holding those values, such as a direct message with the same members. See [Opening an existing record](#opening-an-existing-record). |
70
71
  | `.validate((record) => issues)` | A rule over the whole record, run after the field checks on every create and update. It returns `[{ field, message }]` or `undefined`; issues answer `400` with the field named. |
71
72
  | `.access({ ... })` | Rules per operation. See [Access](#access). |
@@ -280,7 +281,6 @@ export const orders = resource('orders')
280
281
  :::caution[Beta]
281
282
  Not yet:
282
283
 
283
- - <gap>A time rollup cannot recount records that arrive later than `late` by itself because a rebuild command for older ranges is not implemented.</gap>
284
284
  - <gap>A time rollup cannot average an optional field because a count of its records with a value is not implemented.</gap>
285
285
  :::
286
286
 
@@ -348,7 +348,7 @@ Only the database writes a rollup's rows: creates, updates and deletes are refus
348
348
 
349
349
  The app's [jobs](jobs.md) keep every time rollup up to date: a built-in [recurring job](jobs.md#recurring-jobs), `buckets.refresh`, runs every minute and calls each rollup's refresh function from `late` before now, one query per rollup, such as `select rollups.readings_hourly_refresh(now() - interval '2 hours')` for the example. So the buckets from that time on take in the records added, changed and deleted since, and a dashboard on the rollup is at most a minute behind, while one run only reads the source's records of the last `late`. A failed run is not retried, as the next minute's run recomputes the same buckets; it is listed on the [Failed jobs page](jobs.md#failed-jobs-page). A time rollup turns jobs on, so [`protobase migration`](cli.md#migration) writes the [jobs schema](jobs.md#the-jobs-schema) too, and the rollup is refreshed wherever the app runs its jobs, such as `protobase serve` or a [`protobase worker`](cli.md#worker).
350
350
 
351
- A record that arrives, or changes, later than `late` after its time is counted only by a refresh from before it: call the rollup's function yourself with an earlier time, such as `select rollups.readings_hourly_refresh('2026-07-01')`, which recomputes every bucket from that day's first hour in one statement. <gap>A time rollup cannot recount records that arrive later than `late` by itself because a rebuild command for older ranges is not implemented.</gap>
351
+ A record that arrives, or changes, later than `late` after its time, such as one imported from an older history, is counted only by a refresh from before it: [`protobase buckets rebuild`](cli.md#buckets-rebuild) recounts a rollup from an earlier time, such as `protobase buckets rebuild readings_hourly --from 2026-07-01`, which recomputes every bucket from that day's first hour in one statement, or every bucket without `--from`.
352
352
 
353
353
  The server does not start while a rollup's table or function is missing or out of date, with a message that names the rollup; the migration fixes that. It stops with an error, without writing anything, when the table already exists as the project's own.
354
354
 
@@ -534,6 +534,35 @@ resource('direct_messages')
534
534
  - The [create form](ui-config.md#opening-the-existing-record) then opens that record instead of saying it could not save.
535
535
  - An encrypted or file field cannot be part of the key: the API stores those as values that never match another record's.
536
536
 
537
+ ## Checks the database makes
538
+
539
+ A rule the database keeps, such as a task that waits for a day staying parked, refuses a write with a check violation. The API leaves the database's own message out, since it can name values the caller may not see, so by default the refusal says only that a check constraint rejected the record. `.checks()` names the checks whose refusal the app can explain, each by its constraint name, with a label:
540
+
541
+ ```ts
542
+ resource('tasks')
543
+ .table('tasks')
544
+ .fields({ id: f.integer().readOnly().dbDefault(), title: f.text(), lane: f.enum(['parked', 'queued']), waits_until: f.timestamp().optional() })
545
+ .primaryKey((r) => r.id)
546
+ .checks({ tasks_parked_by_hand: { label: '{title} waits for a day, so it stays parked.' } })
547
+ ```
548
+
549
+ The name is a `CHECK` constraint's, or one a trigger gives with Postgres's own fields: `using errcode = 'check_violation', constraint = '<name>'`. Its message is for the database's logs and never leaves the server:
550
+
551
+ ```sql
552
+ create function tasks_lane_check() returns trigger language plpgsql as $$
553
+ begin
554
+ if new.lane = 'queued' and new.waits_until > now() then
555
+ raise exception 'Task % waits until %', new.id, new.waits_until using errcode = 'check_violation', constraint = 'tasks_parked_by_hand';
556
+ end if;
557
+ return new;
558
+ end $$;
559
+ ```
560
+
561
+ - A write the check refuses is a [`400` `invalid-record`](api.md#errors) whose one error is `{ field: '_record', code: '<name>', message: '<label>' }`, built from the config alone: nothing of the database's message, detail or hint. A batch names the operation, as for any refusal.
562
+ - The label is an ICU message whose `{field}` values the admin app fills from the record it shows, such as the card dropped on a board, never from the database. Each value must be a field of the resource, or the server does not start. It is translated as `resources.<resource>.checks.<name>.label` in the app's [texts](languages.md#your-own-texts).
563
+ - A name is declared once across the app, since the error names only the check: a second resource declaring it stops the server at startup. A name cannot be one of the API's own error codes, such as `required`, and is at most 63 bytes, the most of a name Postgres keeps.
564
+ - A check violation naming a check no resource declares keeps the generic refusal, and the server logs a warning with its name only. A plain `raise exception` without these fields is an unexpected error, a `500`, reported to the app's error hook.
565
+
537
566
  ## Keys and relations
538
567
 
539
568
  A key of several columns is a list, and a record's address joins its parts with a comma (`/stock/CHAIN-11,L`). A relation to such a resource names its columns, in the order of that key:
@@ -50,7 +50,7 @@ export const texts = translations({ en, nl })
50
50
  }
51
51
  ```
52
52
 
53
- A layout shows a message with [`<Trans i18nKey="today.open" values={{ count: 2 }} />`](layouts.md#texts-in-the-readers-language), and a page whose `title` is one is named by it in the sidebar too. A view's labels take their key from where they sit, under `resources.<resource>`: `names.singular` and `names.plural`, `help`, `fields.<field>.label`, `.help` and `.values.<value>`, `layout.<index>.title`, `.help` and `.empty` (a tab's items under `layout.<index>.items.<index>`), and `actions.<action>.label` and `.confirm`. A label the translations leave out shows as the view writes it.
53
+ A layout shows a message with [`<Trans i18nKey="today.open" values={{ count: 2 }} />`](layouts.md#texts-in-the-readers-language), and a page whose `title` is one is named by it in the sidebar too. A view's labels take their key from where they sit, under `resources.<resource>`: `names.singular` and `names.plural`, `help`, `fields.<field>.label`, `.help` and `.values.<value>`, `layout.<index>.title`, `.help` and `.empty` (a tab's items under `layout.<index>.items.<index>`), and `actions.<action>.label` and `.confirm`; a resource's [checks](data-config.md#checks-the-database-makes) take `checks.<name>.label`, whose values the app fills from the record. A label the translations leave out shows as the view writes it.
54
54
 
55
55
  Each reader gets the app's own `locale` when it sets one the translations have, else the first of their browser's languages the translations have, by its tag or its language (`nl-BE` reads `nl`), else English, else the first language. A language is any BCP 47 tag, such as `de` or `pt-BR`, while the built-in screens stay in English or Dutch. `/meta` serves the reader's language and only the messages their pages name, as `texts: { locale, messages }`, with the page titles and labels already in it.
56
56
 
@@ -7,7 +7,7 @@ Hand the app's realtime connections to a relay, so the app and its database can
7
7
  The app can hand its realtime connections to a relay, the open source [protobase-realtime](https://github.com/PrototeamHQ/protobase-realtime) server: the relay holds everyone's WebSocket, and the app talks to it only when something changes, so a quiet app and its database sleep while people stay connected. The relay keeps no data and never reads the app's database: the app tells it who is in which channel, what changed and for whom, and which sign-in sessions ended. It works beside the app's own [channels](channels.md) and [live updates](live.md), which stay as they are.
8
8
 
9
9
  :::caution[In development]
10
- The app's side is built: tickets, membership, change notices and session ends. <gap>Pages cannot connect to the relay from `@protobase/client` because its relay client is not implemented.</gap> <gap>The relay cannot report presence to the app because the app's presence endpoint is not implemented.</gap> <gap>Clients cannot send each other events such as typing through the relay because declaring client events per channel resource is not implemented.</gap>
10
+ The app's side is built: tickets, membership, change notices, session ends and presence. <gap>Pages cannot connect to the relay from `@protobase/client` because its relay client is not implemented.</gap> <gap>Clients cannot send each other events such as typing through the relay because declaring client events per channel resource is not implemented.</gap>
11
11
  :::
12
12
 
13
13
  ## Config
@@ -27,6 +27,7 @@ export default defineConfig(({ env }) => ({
27
27
  },
28
28
  rooms: {},
29
29
  },
30
+ presence: { resource: 'presences', user: 'user_id', status: 'status', at: 'since', key: env.RELAY_PRESENCE_KEY! },
30
31
  },
31
32
  },
32
33
  }))
@@ -40,6 +41,7 @@ export default defineConfig(({ env }) => ({
40
41
  | `channels` | The channel resources, by name. Each record of one is a channel, `<resource>/<key>`, named as its [record channel](channels.md) is; the resource needs a key of one field. |
41
42
  | `channels.<resource>.members` | Where the channel's members come from: a resource whose records each put one person in one channel, with its relation field to the channel resource (`channel`) and its field of the person's user id (`user`). Index both columns: tickets read by the user, notices by the channel. Without `members`, the channel is open: a channel of a public record, which tickets list when asked (see [Tickets](#tickets)). |
42
43
  | `channels.<resource>.mentions` | A field of the records noticed on the channel that lists the user ids they mention, an array or one id, which [notices](#notices) carry. |
44
+ | `presence` | Turns on [presence](#presence): the app's own resource it is kept in, its fields of the person's user id (`user`), the status (`status`) and when it began (`at`), and the bearer token of the relay's reports (`key`), at least 32 characters. |
43
45
 
44
46
  The relay needs the app's own [sign-in](auth.md), whose sessions its tickets name, with its store in the app's own database, as the `auth` config puts it: an auth store in another database is refused. A members resource's changes must be captured, so declare [`.live()`](live.md) on it; the relay hears of the changes of every resource whose changes are captured, such as a live one, that is a channel resource or has a relation field to one. [`protobase migration`](cli.md#migration) writes the trigger that ends a deleted session's sockets, in the `relay` schema, and the server checks it at start.
45
47
 
@@ -61,7 +63,7 @@ It starts the relay on the first load of a config with `realtime.relay`, an edit
61
63
 
62
64
  A client connects to the relay with a ticket from `POST /api/relay/ticket`, with `{ "channels": [...] }`, optional, as JSON. The answer is `{ ticket, url, expiresAt }`: the relay's socket address and a ticket that connects once, within a minute. Every connection, a reconnect too, takes a new ticket.
63
65
 
64
- - **Signed in:** the ticket names the person and the sign-in session they called with, so a device that connects makes no new session, and lists every channel they are a member of, as the members resources hold it. A caller without a session of the app, such as an API key or an outside app acting for the user, is refused with `403`; a session that ended with `401`.
66
+ - **Signed in:** the ticket names the person and the sign-in session they called with, so a device that connects makes no new session, and lists every channel they are a member of, as the members resources hold it, and `people`, which every signed-in person has and [presence](#presence) is published on. A caller without a session of the app, such as an API key or an outside app acting for the user, is refused with `403`; a session that ended with `401`.
65
67
  - **Visitors:** with an `anonymous` role, a caller without a token gets a ticket of an anonymous session of its own, which receives and never sends.
66
68
  - **Open channels:** both list the channels they ask for in `channels` of resources without `members` whose records are public: the `anonymous` role may read them, as `GET /api/v1/<resource>/<key>` decides it for a visitor. Someone's own access to a record never makes its channel open, so no one's access to one can end while their socket stays open. A channel there is none of, one whose record is not public and one of a resource with members are refused alike with `404`; a record only some people may read takes `members`. A ticket lists at most 200 channels (`400`, or `422` when the memberships are more).
67
69
 
@@ -82,3 +84,31 @@ Once an open channel's record stops being public, its notices stop, and a new ti
82
84
  ## Sessions
83
85
 
84
86
  When a sign-in session ends, its sockets close: a trigger on the sessions table queues a `relay.close-sessions` job in the deleting transaction, for a sign-out, a revoke, a ban, a newer sign-in in the same browser or a delete in SQL alike, and the job tells the relay to close them. A ticket also queues a `relay.session-expiry` job for its session's expiry, once for each session: it closes the session's sockets once the session expired, and waits for the new expiry of one that was extended meanwhile. The person's other sessions stay connected. The relay itself keeps no timers.
87
+
88
+ ## Presence
89
+
90
+ With `presence`, the relay reports who comes online, goes away and goes offline, combined over their devices, and the app keeps it in a resource of its own, one record per person:
91
+
92
+ ```ts
93
+ export const presences = resource('presences')
94
+ .fields({ user_id: f.text(), status: f.enum(['online', 'away', 'offline']), since: f.timestamp() })
95
+ .primaryKey((r) => r.user_id)
96
+ .live()
97
+ .events((e) => [e.updated('wentOffline', { when: 'status = "offline"' })])
98
+ ```
99
+
100
+ The resource is keyed by its user field, its status field is text or an enum of `online`, `away` and `offline`, and its `at` field a timestamp; its changes must be captured, such as with [`.live()`](live.md). The server refuses to start otherwise. Protobase adds no table of its own.
101
+
102
+ Only the relay writes the records, so give no role `presences.create`, `presences.update` or `presences.delete`: whoever may write one can set anyone's presence and raise its events. A role that reads the resource reads the presence of everyone its rows allow, which can reach further than `people` does, so grant `presences.read` no wider than that.
103
+
104
+ The relay posts its reports to `POST /api/relay/presence` with the presence key as its bearer token, never a sign-in; the [apps file entry](cli.md#relay-app) names the address. A report holds at most 500 changes, each a person's status and when it began. The app writes them in one statement, which replaces a record's status only with one that began later, and answers `204`: a report the relay sends again, or one that arrives late, changes nothing. A report with a missing or wrong key is refused with `401` before its body is read. To change the key, change it in the config and in the apps file; the relay sends a refused report again, waiting up to a minute between tries, until the app takes it, so no change is lost. When the relay restarted, which a report says with its start time, everyone it has not reported since and who is not offline yet is set offline as of that start, once in each server process for each start; the relay sends no report until someone's status changes, so this waits for the first one.
105
+
106
+ Each write goes through the resource's table, so its changes raise the resource's [events](events.md), [webhooks](webhooks.md) and [workflows](workflows.md) as any other record's do, such as a workflow on `presences.wentOffline`. An offline report raises its event once.
107
+
108
+ Each change of a person's presence is also published on `people` as a `presence_changed` event, the same bytes to everyone who shares a channel with members with them, themselves included, as the members tables hold it at dispatch, read for the whole batch in one query:
109
+
110
+ ```json
111
+ { "user": "u1", "status": "offline", "at": "2026-11-21T10:00:00.000Z" }
112
+ ```
113
+
114
+ A person who shares no channel is published to no one. <gap>A page cannot show who of the others is online because reading presence in the pages is not implemented.</gap>
@@ -287,6 +287,7 @@ Nothing in a list moves by dragging unless its `.list(...)` says so with `drag`,
287
287
  | --- | --- |
288
288
  | `rank: true` | The records of a resource with a [`.position(...)`](#reordering-by-hand) and no `within`, at any time: the table's rows by their handles while the list shows every record in the position's order, ascending, without a filter or search, instead of after **Reorder**; and a [board's](#boards) cards to their place in a column. |
289
289
  | `board: true` | A board's card to another column, which saves the record with that column's value. |
290
+ | `board: { set?, columns? }` | A board's card between the `columns` it names, by value, or every column, which saves the column's value in the field `set`, or in `by` when it names none. See [Moving cards by another field](#moving-cards-by-another-field). |
290
291
  | `board: 'name'` | A board's card between the columns the board drop of that name in the UI config's `boardDrops` lists, each running its own write. See [Board drops](#board-drops). |
291
292
  | `rule: 'name'` | Where the table's rows may land when re-ranked, by **Reorder** or `rank`: the drop rule of that name in the UI config's `dropRules`. See [Drop rules](#drop-rules). |
292
293
 
@@ -351,6 +352,22 @@ export default defineUi({
351
352
 
352
353
  The list names it with `drag: { board: 'decide' }`, which works when `by` is read-only. A card moves only from and to the columns the board drop lists: one in another column stays in it, as does a card dropped on another column, or on the column of records without a value. After the write the record is read again, and the card lands in the column its value now puts it in, which may not be the one it was dropped on; the toast says which, with **Undo** when the write gave an undo. A refused write puts the card back with the reason. Moving a card still takes the right to update the resource and the record, and on a ranked board a card dropped in another column lands where its rank puts it. A list naming a board drop the UI config does not register says so in place of its board.
353
354
 
355
+ #### Moving cards by another field
356
+
357
+ Some boards are by a field the database computes, such as a task's status, from a field people do write, such as the lane a task waits in. `drag: { board: { set, columns } }` saves the column's value in that field instead, and only in the columns it names:
358
+
359
+ ```ts
360
+ .list((r, d) => ({ columns: [r.title, r.status], displays: [d.board({ by: r.status })], drag: { board: { set: 'lane', columns: ['parked', 'queued'] } } }))
361
+ ```
362
+
363
+ A card moves only from and to the columns `columns` names, every column when it is left out: a card in another column stays in it, as does one dropped on another column. A drop is one update of the record, `set` set to the column's value with the ETag the card was listed with, which the resource's access rules, `validate` and the database's triggers decide. After the update the record is read again, and the card lands in the column its `by` value now puts it in, which may not be the one it was dropped on; the toast says which, with **Undo**, which puts back the value `set` had with the ETag of the record as read again, so a trigger that wrote the record again after the update does not make it stale. On a ranked board a card dropped in another column lands where its rank puts it. `set` must be a field the API writes, and every column a value it takes, or the view is refused; without `set` the drop saves `by`, which must be writable.
364
+
365
+ A trigger refuses a drop by naming a check the resource declares with [`.checks()`](data-config.md#checks-the-database-makes), so the card goes back with that check's label, filled with the card's values; a check it does not declare says only that the database refused the change:
366
+
367
+ ```sql
368
+ raise exception 'Task % waits until %', new.id, new.waits_until using errcode = 'check_violation', constraint = 'tasks_parked_by_hand';
369
+ ```
370
+
354
371
  ## A filter the list opens with
355
372
 
356
373
  ```ts
@@ -775,7 +792,7 @@ The standard record page, with the layout's sections, the related records, Edit
775
792
  ### Conversation pages
776
793
 
777
794
  :::caution[Beta]
778
- A conversation page shows each message's text with its mentions and keeps line breaks, without markdown; it has no files yet, and a deleted message leaves no trace in its place.
795
+ A conversation page shows each message's text with its mentions and keeps line breaks, without markdown, and a deleted message leaves no trace in its place.
779
796
  :::
780
797
 
781
798
  `.record({ conversation })` makes the record page the record's conversation, for a record that holds one, such as a chat channel, a direct message or a support case, with no component of the app's own. It fills the content area as a [full-area record page](#full-area-record-pages) does, on the web and at mobile width: a header row, the messages that point at the record, and a box that sends one, which stays in view while the messages scroll above it.
@@ -803,6 +820,7 @@ view<typeof channels>('channels').record({
803
820
  labels: { thumbs_up: { symbol: '👍', name: 'Thumbs up' }, heart: { symbol: '❤️', name: 'Heart' } },
804
821
  },
805
822
  thread: { field: 'thread_id', count: 'reply_count', last: 'last_reply_at' },
823
+ attachments: { resource: 'attachments', field: 'message_id', file: 'file', width: 'width', height: 'height' },
806
824
  call: 'call',
807
825
  },
808
826
  })
@@ -826,6 +844,7 @@ view<typeof channels>('channels').record({
826
844
  | `delete` | `true`: anyone the message resource's delete access allows deletes a message, after confirming; or `{ unless }`, a condition on the message's own fields that keeps it, such as `reply_count > 0`. |
827
845
  | `reactions` | Emoji reactions under each message: `{ resource, field, user, emoji, labels }`. |
828
846
  | `thread` | Replies in a thread under a message, in a panel beside the conversation: `{ field, count, last }`. |
847
+ | `attachments` | [Files](#files-in-messages) a message carries, kept in a resource of their own: `{ resource, field, file, width, height }`. |
829
848
  | `call` | The record's [call](calls.md), by the name of the [API function](../guides/api-functions.md) that admits people to it. |
830
849
 
831
850
  The header shows the record's title, which the top bar repeats at mobile width and so shows there only with `members`, the subtitle, the call with `call`, and *Details*, a link to the record's standard page at `?standard=true`, with its sections, Edit and Delete. The latest 50 messages show oldest first, with *Load earlier messages* at the top for more. A day divider opens each day, and one person's messages sent within five minutes of each other show under their name once. A message resource with [`.live()`](live.md) shows new, changed and deleted messages as they happen. Every read goes through the reader's own access: a message they may not read never shows, and a reader who may not read the messages, a field each one needs or the fields of `thread` gets the standard page. The box shows for a reader who may create messages.
@@ -841,6 +860,17 @@ With `reactions`, `edit`, `delete` or `thread`, people act on the messages where
841
860
  - **Delete**: *Delete* asks before the message goes for everyone. A reader who may not read the fields `unless` reads gets no *Delete*.
842
861
  - **Threads**: `field` is the filterable relation of the messages to themselves that holds a reply's first message, empty for a message of the conversation itself, `count` an integer field holding a first message's number of replies and `last` a date or timestamp field holding when its last reply came, both kept by the database, such as by a trigger. The conversation shows only messages outside threads; under a message with replies, a link names how many and when the last came. It and *Reply in thread* open the thread at `?thread=<key>`, so a link can open it too: in a panel beside the conversation, covering the screen at mobile width, with the first message, its replies and a box of its own that replies in the thread. An address naming a message of another conversation opens no thread there. A reply gets its first message's conversation from the box, so keep the two the same in the database, such as by a check in the trigger that counts the replies, as an API create can set them apart.
843
862
 
863
+ #### Files in messages
864
+
865
+ With `attachments`, people share files in a message and see them under it. A button left of the box opens the file picker, and files pasted into the box or dropped on it join the message too. Each file uploads as soon as it is picked and shows above the box with its size, how far its upload is, or why it was refused, with a button that takes it off: a file larger than the file field's [`maxSize`](files.md) is refused before it uploads, and one the server refuses shows the server's reason. The message waits for the uploads still on their way, and once a file is uploaded it may go without text. The message and its files are written in one [batch](api.md#batch-writes), so the message never shows without them.
866
+
867
+ Under a message, an image shows as a preview at most 240 pixels high that opens it in a new tab, and any other file as a link with its name and size that downloads it. The files of a page of messages are read together with it, through the reader's own access, and their links are those the API signs for the reader. *Delete* deletes a message's files first, in the same batch.
868
+
869
+ - `resource` keeps one record per file: `field` is its filterable relation to the message and `file` its file field, whose value gives the file's name, type and size.
870
+ - `width` and `height` are integer fields of an image's size in pixels, such as those a `.derive({ width: imageSize('width'), height: imageSize('height') })` on the file fills, so an image takes its place before it loads. Both are optional.
871
+
872
+ A message of files alone has no text, so the message resource's text field is optional. A reader who may not read `field` or `file` sees no files, and the box offers none.
873
+
844
874
  #### Calls
845
875
 
846
876
  :::caution[Beta]