@protobase/cli 0.121.7 → 0.121.8

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.
@@ -13,10 +13,10 @@ import { shellCodeSplitting } from "./shell-chunks.js";
13
13
  import { existsSync } from "node:fs";
14
14
  import path from "node:path";
15
15
  import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
16
+ import { tmpdir } from "node:os";
16
17
  import { build } from "vite";
17
18
  import tailwindcss from "@tailwindcss/vite";
18
19
  import react from "@vitejs/plugin-react";
19
- import { tmpdir } from "node:os";
20
20
  //#region src/build/shell.ts
21
21
  /** What a shell folder holds beside its files: the `ShellManifest`. */
22
22
  const shellManifestFile = "protobase.shell.json";
@@ -1,8 +1,8 @@
1
1
  import { bunBuild } from "./bun-build.js";
2
2
  import path from "node:path";
3
3
  import { mkdtemp, rm } from "node:fs/promises";
4
- import { build } from "vite";
5
4
  import { tmpdir } from "node:os";
5
+ import { build } from "vite";
6
6
  //#region src/build/vite-bundle.ts
7
7
  const viteBuild = async ({ root, entry, outFile, plugins, logLevel = "warn" }) => {
8
8
  await build({
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.121.7";
2
+ var version = "0.121.8";
3
3
  //#endregion
4
4
  export { version };
@@ -1,8 +1,8 @@
1
1
  import { errorMessage } from "../error-message.js";
2
2
  import { serverPackage } from "./server-package.js";
3
+ import { devHost } from "./loopback.js";
3
4
  import { moduleFile } from "../module-file.js";
4
5
  import { createApiVite } from "./api-vite.js";
5
- import { devHost } from "./loopback.js";
6
6
  import { isProjectFile } from "./project-files.js";
7
7
  import { startupLogger } from "./startup-logger.js";
8
8
  import { createAdaptorServer } from "@hono/node-server";
@@ -43,12 +43,15 @@ const listen = (server) => new Promise((resolve, reject) => {
43
43
  resolve(server.address().port);
44
44
  });
45
45
  });
46
- const stop = async () => {
46
+ let stopping;
47
+ const stop = () => stopping ??= stopOnce();
48
+ const stopOnce = async () => {
47
49
  server?.close();
48
50
  server?.closeAllConnections();
49
51
  const devSupport = await vite.ssrLoadModule(support);
50
52
  await devSupport.stopDevJobs();
51
53
  await devSupport.stopDevRealtimePrune();
54
+ await devSupport.stopDevRelay();
52
55
  await vite.close();
53
56
  process.exit(process.exitCode ?? 0);
54
57
  };
@@ -1,4 +1,5 @@
1
1
  import { apiWebSocketServer } from "../project/api-websocket-server.js";
2
2
  import { stopDevJobs } from "./dev-jobs.js";
3
3
  import { stopDevRealtimePrune } from "./dev-prune.js";
4
- export { apiWebSocketServer, stopDevJobs, stopDevRealtimePrune };
4
+ import { stopDevRelay } from "./dev-relay.js";
5
+ export { apiWebSocketServer, stopDevJobs, stopDevRealtimePrune, stopDevRelay };
@@ -1,4 +1,5 @@
1
1
  import { stopDevJobs } from "./dev-jobs.js";
2
+ import { stopDevRelay } from "./dev-relay.js";
2
3
  import { stopDevRealtimePrune } from "./dev-prune.js";
3
4
  import { apiWebSocketServer } from "../project/api-websocket-server.js";
4
- export { apiWebSocketServer, stopDevJobs, stopDevRealtimePrune };
5
+ export { apiWebSocketServer, stopDevJobs, stopDevRealtimePrune, stopDevRelay };
@@ -1,8 +1,8 @@
1
1
  import { projectPackages } from "../version/project-packages.js";
2
2
  import { uiPackageDir } from "../project/admin-app.js";
3
+ import { devHost } from "./loopback.js";
3
4
  import { layoutCheck } from "../build/layout-check.js";
4
5
  import { extensionImports, projectStyles } from "../project/extensions.js";
5
- import { devHost } from "./loopback.js";
6
6
  import { frameHeaders } from "../serve/static-site.js";
7
7
  import { projectUiPlugin } from "../project/project-ui.js";
8
8
  import { bundledImports, bundledPackageDirs } from "../project/bundled-imports.js";
@@ -0,0 +1,5 @@
1
+ import "@protobase/config";
2
+ //#region src/dev/dev-relay.d.ts
3
+ /** Ends the relay protobase dev started, when the dev server closes. */
4
+ export declare const stopDevRelay: () => Promise<void>;
5
+ //#endregion
@@ -0,0 +1,74 @@
1
+ import { relayAppEntry } from "../relay/app-entry.js";
2
+ import { relayBinary } from "./relay-binary.js";
3
+ import { freePort, relayUrl, startRelay } from "./relay-process.js";
4
+ import { checkRelayOptions } from "@protobase/server";
5
+ import { randomBytes } from "node:crypto";
6
+ //#region src/dev/dev-relay.ts
7
+ const store = globalThis;
8
+ const devLimits = {
9
+ connections: 1e3,
10
+ channels_per_ticket: 200,
11
+ request_bytes: 1048576
12
+ };
13
+ const devKeys = () => store.__protobaseDevRelayKeys ??= {
14
+ apiKey: randomBytes(32).toString("base64url"),
15
+ ticketKey: randomBytes(32).toString("base64url")
16
+ };
17
+ const relayEnded = (code) => {
18
+ delete store.__protobaseDevRelay;
19
+ process.stderr.write(`error: the relay of protobase dev ended (exit code ${code}); save a file of the project to start it again\n`);
20
+ };
21
+ /**
22
+ * The config with a relay of its own when `realtime.relay` names none: without a `url`, protobase dev runs the relay
23
+ * from its npm package for the app at `devUrl`, with keys it makes unless the config sets them, and gives the app its
24
+ * address and keys. It starts on the first load whose config has `realtime.relay`, and again when an edit changes the
25
+ * app's entry in its apps file; a config without `realtime.relay`, or one with a `url`, stops it.
26
+ */
27
+ const withDevRelay = async (config, projectDir, devUrl) => {
28
+ const relay = config.realtime?.relay;
29
+ if (!relay || relay.url) {
30
+ await stopDevRelay();
31
+ return config;
32
+ }
33
+ const keys = devKeys();
34
+ const options = {
35
+ ...relay,
36
+ apiKey: relay.apiKey || keys.apiKey,
37
+ ticketKey: relay.ticketKey || keys.ticketKey
38
+ };
39
+ const entry = JSON.stringify({
40
+ ...relayAppEntry(options, devUrl),
41
+ limits: devLimits
42
+ });
43
+ if (store.__protobaseDevRelay?.entry !== entry) {
44
+ await stopDevRelay();
45
+ const port = await freePort();
46
+ checkRelayOptions({
47
+ ...options,
48
+ url: relayUrl(port)
49
+ });
50
+ store.__protobaseDevRelay = {
51
+ entry,
52
+ url: relayUrl(port),
53
+ relay: await startRelay(await relayBinary(projectDir), port, JSON.parse(entry), relayEnded)
54
+ };
55
+ }
56
+ return {
57
+ ...config,
58
+ realtime: {
59
+ ...config.realtime,
60
+ relay: {
61
+ ...options,
62
+ url: store.__protobaseDevRelay.url
63
+ }
64
+ }
65
+ };
66
+ };
67
+ /** Ends the relay protobase dev started, when the dev server closes. */
68
+ const stopDevRelay = async () => {
69
+ const running = store.__protobaseDevRelay;
70
+ delete store.__protobaseDevRelay;
71
+ await running?.relay.stop();
72
+ };
73
+ //#endregion
74
+ export { stopDevRelay, withDevRelay };
package/dist/dev/entry.js CHANGED
@@ -3,6 +3,7 @@ import { projectIcons } from "../build/app-icons.js";
3
3
  import { projectErrorReporter } from "../project/error-reporter.js";
4
4
  import { servedAdmin } from "../project/served-admin.js";
5
5
  import { devJobs } from "./dev-jobs.js";
6
+ import { withDevRelay } from "./dev-relay.js";
6
7
  import { devRealtimePrune } from "./dev-prune.js";
7
8
  import { devDatabase, loadDevConfig } from "./project.js";
8
9
  import { withDevServiceWorker } from "./service-worker-route.js";
@@ -12,7 +13,7 @@ import { upgradeWebSocket } from "@hono/node-server";
12
13
  import { Hono } from "hono";
13
14
  //#region src/dev/entry.ts
14
15
  const projectDir = process.env.PROTOBASE_PROJECT;
15
- const config = await loadDevConfig(projectDir, JSON.parse(process.env.PROTOBASE_EXTENSIONS ?? "[]"));
16
+ const config = await withDevRelay(await loadDevConfig(projectDir, JSON.parse(process.env.PROTOBASE_EXTENSIONS ?? "[]")), projectDir, process.env.PROTOBASE_DEV_URL);
16
17
  const database = devDatabase(projectDir);
17
18
  const { db } = database;
18
19
  const project = await buildProject(config, database);
@@ -0,0 +1,30 @@
1
+ import { createRequire } from "node:module";
2
+ import path from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ //#region src/dev/relay-binary.ts
5
+ const relayPackage = "@protobase/realtime";
6
+ const cliDir = fileURLToPath(new URL("../..", import.meta.url));
7
+ const resolveFrom = (dir) => {
8
+ try {
9
+ return createRequire(path.join(dir, "package.json")).resolve(relayPackage);
10
+ } catch (error) {
11
+ if (error.code === "MODULE_NOT_FOUND") return;
12
+ throw error;
13
+ }
14
+ };
15
+ /** The entry of the relay's npm package: the project's own install first, then the CLI's. */
16
+ const relayPackageEntry = (projectDir, ownDir = cliDir) => {
17
+ const entry = resolveFrom(projectDir) ?? resolveFrom(ownDir);
18
+ if (!entry) throw new Error(`realtime.relay has no url, so protobase dev runs a relay of its own from ${relayPackage}, which is not installed: add it to the project's devDependencies, or set realtime.relay.url to a running relay`);
19
+ return entry;
20
+ };
21
+ /** The path of the relay binary for this machine, as the package's `binaryPath()` finds it. */
22
+ const relayBinary = async (projectDir, ownDir = cliDir) => {
23
+ const { binaryPath } = await import(
24
+ /* @vite-ignore */
25
+ pathToFileURL(relayPackageEntry(projectDir, ownDir)).href
26
+ );
27
+ return binaryPath();
28
+ };
29
+ //#endregion
30
+ export { relayBinary, relayPackage, relayPackageEntry };
@@ -0,0 +1,71 @@
1
+ import { devHost } from "./loopback.js";
2
+ import path from "node:path";
3
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
4
+ import { spawn } from "node:child_process";
5
+ import { once } from "node:events";
6
+ import { createServer } from "node:net";
7
+ import { tmpdir } from "node:os";
8
+ //#region src/dev/relay-process.ts
9
+ /** The address of a relay on the loopback's `port`. */
10
+ const relayUrl = (port) => `http://${devHost}:${port}`;
11
+ /** A port free on the loopback now, which the relay listens on next: the relay cannot report a port of its own choosing. */
12
+ const freePort = async () => {
13
+ const server = createServer();
14
+ server.listen(0, devHost);
15
+ await once(server, "listening");
16
+ const { port } = server.address();
17
+ server.close();
18
+ await once(server, "close");
19
+ return port;
20
+ };
21
+ /**
22
+ * Starts the relay `binary` on the loopback's `port`, serving the one app of `entry` from an apps file in a folder of
23
+ * its own. Its output goes to the terminal; `onExit` hears of a relay that ends other than through `stop`. The relay
24
+ * gets no other environment than its two variables, and is killed when this process exits.
25
+ */
26
+ const startRelay = async (binary, port, entry, onExit) => {
27
+ const dir = await mkdtemp(path.join(tmpdir(), "protobase-relay-"));
28
+ const appsFile = path.join(dir, "apps.json");
29
+ await writeFile(appsFile, JSON.stringify({ apps: [entry] }), { mode: 384 });
30
+ const child = spawn(binary, [], {
31
+ env: {
32
+ RELAY_APPS_FILE: appsFile,
33
+ RELAY_ADDR: `${devHost}:${port}`
34
+ },
35
+ stdio: [
36
+ "ignore",
37
+ "inherit",
38
+ "inherit"
39
+ ],
40
+ detached: true,
41
+ windowsHide: true
42
+ });
43
+ const kill = () => child.kill();
44
+ process.once("exit", kill);
45
+ const removeDir = () => rm(dir, {
46
+ recursive: true,
47
+ force: true
48
+ });
49
+ let stopping = false;
50
+ child.once("exit", (code) => {
51
+ process.off("exit", kill);
52
+ if (!stopping) removeDir().then(() => onExit(code));
53
+ });
54
+ await once(child, "spawn").catch(async (error) => {
55
+ process.off("exit", kill);
56
+ await removeDir();
57
+ throw error;
58
+ });
59
+ const stop = async () => {
60
+ stopping = true;
61
+ if (child.exitCode === null && child.signalCode === null) {
62
+ const exited = once(child, "exit");
63
+ child.kill("SIGTERM");
64
+ await exited;
65
+ }
66
+ await removeDir();
67
+ };
68
+ return { stop };
69
+ };
70
+ //#endregion
71
+ export { freePort, relayUrl, startRelay };
@@ -1,5 +1,5 @@
1
1
  import { authMigrationTitle } from "../auth/migration-file.js";
2
- import { authSchemaMigration, callsMigration, capturedBy, changesMigration, channelSendsMigration, commentsMigration, computedMigration, derivedMigration, jobsSchemaMigration, mailFeedbackMigration, mailFeedbackResource, notificationsMigration, ownedDefinitionsMigration, queryRunnerMigration, realtimeRelayMigration, relayMigration, relayed, sqlSends, statusMigration, unsubscribesMigration, userTablesMigration, webhooksMigration, workflowsMigration } from "@protobase/server";
2
+ import { authSchemaMigration, callsMigration, capturedBy, changesMigration, channelSendsMigration, commentsMigration, computedMigration, derivedMigration, hasBuckets, jobsSchemaMigration, mailFeedbackMigration, mailFeedbackResource, notificationsMigration, ownedDefinitionsMigration, queryRunnerMigration, realtimeRelayMigration, relayMigration, relayed, sqlSends, statusMigration, unsubscribesMigration, userTablesMigration, webhooksMigration, workflowsMigration } from "@protobase/server";
3
3
  //#region src/migration/parts.ts
4
4
  /** Every feature the project's config enables, in the order their files are written. */
5
5
  const migrationParts = (project) => {
@@ -13,7 +13,7 @@ const migrationParts = (project) => {
13
13
  title: authMigrationTitle,
14
14
  sql: () => authSchemaMigration(project.auth)
15
15
  }] : [],
16
- ...project.jobs.length > 0 || captured.some(capturedBy(captured)) || comments || aiFields || project.webhooks || project.workflows || project.notifications || project.realtime?.relay ? [{
16
+ ...project.jobs.length > 0 || captured.some(capturedBy(captured)) || comments || aiFields || project.models.some(hasBuckets) || project.webhooks || project.workflows || project.notifications || project.realtime?.relay ? [{
17
17
  name: "jobs",
18
18
  title: "The jobs schema this version of Protobase needs",
19
19
  sql: () => jobsSchemaMigration(project.db)
@@ -7,7 +7,7 @@ import { loadBundle } from "../serve/load-bundle.js";
7
7
  import { statSync } from "node:fs";
8
8
  import path from "node:path";
9
9
  import pg from "pg";
10
- import { checkJobsSchema, configExports, isCaptured, startJobs } from "@protobase/server";
10
+ import { checkJobsSchema, configExports, hasBuckets, isCaptured, startJobs } from "@protobase/server";
11
11
  //#region src/worker/start-worker.ts
12
12
  const bundleConfigFile = async (bundle) => {
13
13
  if (!statSync(bundle).isDirectory()) return bundle;
@@ -26,9 +26,9 @@ const startWorker = async ({ config, databaseUrl, openDb = (url) => openAppDatab
26
26
  const project = await buildProject(config, database);
27
27
  const builtIn = configExports(project.config).resources.some((resource) => {
28
28
  const model = resource.toModel();
29
- return isCaptured(model) || model.live || model.comments || Object.values(model.fields).some((field) => field.ai);
29
+ return isCaptured(model) || model.live || model.comments || Object.values(model.fields).some((field) => field.ai) || hasBuckets(model);
30
30
  });
31
- if (project.jobs.length === 0 && !builtIn) throw new Error("The bundle has no jobs: name their module in protobase.config.ts as `jobs`, or give a resource events, history, comments or an AI field");
31
+ if (project.jobs.length === 0 && !builtIn) throw new Error("The bundle has no jobs: name their module in protobase.config.ts as `jobs`, or give a resource events, history, comments or an AI field, or declare a time rollup");
32
32
  const { admin, jobs: definitions } = projectAdmin(project, db);
33
33
  await checkJobsSchema(db);
34
34
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.121.7",
3
+ "version": "0.121.8",
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.7",
47
- "@protobase/layout": "0.121.7",
48
- "@protobase/query": "0.121.7",
49
- "@protobase/schema": "0.121.7",
50
- "@protobase/server": "0.121.7",
51
- "@protobase/ui": "0.121.7",
52
- "@protobase/workflows": "0.121.7",
46
+ "@protobase/config": "0.121.8",
47
+ "@protobase/layout": "0.121.8",
48
+ "@protobase/query": "0.121.8",
49
+ "@protobase/schema": "0.121.8",
50
+ "@protobase/server": "0.121.8",
51
+ "@protobase/ui": "0.121.8",
52
+ "@protobase/workflows": "0.121.8",
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",
@@ -18,7 +18,7 @@ Describe the tables of an existing Postgres database as resources, with their fi
18
18
  - [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
19
  - [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
20
  - [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
- - [Time rollups](../reference/data-config.md#time-rollups) (in development): A large events table gets an hourly or daily rollup table that the app's migrations create, so charts over months of millions of rows can read a few thousand rows instead.
21
+ - [Time rollups](../reference/data-config.md#time-rollups) (in development): A large events table gets an hourly or daily rollup table that the app's migrations create and the app keeps up to date, at most a minute behind, so charts over months of millions of rows can read a few thousand rows instead.
22
22
  - [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
23
  - [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
24
  - [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.
@@ -17,7 +17,7 @@ The changes of each record, comments on it, and pages that refresh as records ch
17
17
  - [Change stream](../reference/live.md#the-stream): Apps follow record changes over a stream that catches up after a reconnect.
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
- - [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.
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
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.
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()`.
@@ -12,6 +12,7 @@ React components, field types, pages and handlers of your own, loaded as plugins
12
12
  - [Custom field types](../reference/plugins.md#field-types): Register how a kind of value is shown and edited, and pick it per field in a view.
13
13
  - [Custom create pages](../reference/custom-components.md#create-pages): Replace a resource's create form with your own page, such as a booking flow.
14
14
  - [Form parts](../reference/custom-components.md#form-parts): Build your own forms from the app's fields, pickers, switches, buttons and dialogs.
15
+ - [Menus and toasts](../reference/custom-components.md#form-parts): Build your own menus that open beside their button on a desktop and as a sheet on a phone, with rows like the app's menus, and confirm an action with a toast.
15
16
  - [Markdown](../reference/custom-components.md#components): Show markdown in your own components, such as a chat message, as the app's markdown fields draw it.
16
17
  - [Polling lists](../reference/custom-components.md#record-sections): A list your own component reads can refetch on an interval you set, to stay current.
17
18
  - [Image carousel](../reference/custom-components.md#image-carousel): Step through screenshots or a record's files in your own components by swiping or with arrows, as cards step through photos.
@@ -288,7 +288,7 @@ Every error is `application/problem+json` (RFC 9457) with `type` (`urn:protobase
288
288
  | 404 | `not-found` |
289
289
  | 409 | `conflict`: a unique key, a record other records point at, or a deadlock with another write, which may be sent again |
290
290
  | 412 / 428 | `precondition-failed` / `precondition-required` |
291
- | 503 | `read-only`: the database refuses writes, as during a deploy's write freeze; send the write again after `Retry-After`. `database-restarting`: the database or its connection pooler is shutting down or starting up; send the request again after `Retry-After`. `connections-busy`: every database connection stayed busy for 2 seconds (see [Safety](#safety)) |
291
+ | 503 | `read-only`: the database refuses writes, as during a deploy's write freeze; send the write again after `Retry-After`. `database-restarting`: the database or its connection pooler is shutting down, starting up or recovering from a crash; send the request again after `Retry-After`. `connections-busy`: every database connection stayed busy for 2 seconds (see [Safety](#safety)) |
292
292
  | 504 | `statement-timeout`: a query ran past its limit (see [Safety](#safety)) |
293
293
 
294
294
  ### Error reporting
@@ -202,6 +202,7 @@ One port, two processes: Vite serves the admin app from `@protobase/ui`'s `src/a
202
202
  - **Login:** real sign-in only, with the config's `auth`, on by default, or its `authenticate` for tokens of an auth server elsewhere (see [protobase.config.ts](config.md) and [Login with Better Auth](auth.md)). A project with sign-in off and no authenticator fails at startup with a message pointing there, as does one with sign-in on and no `PROTOBASE_SECRET`, one whose auth store has not applied every migration of this version, naming them (see [`auth migration`](#auth-migration)), one with a resource over a table of the auth store, and one with a resource whose [events](events.md) or [history](history.md) lack their triggers, or whose [comments](comments.md) lack their table, or whose [rollup and formula fields](data-config.md#rollups-and-formulas) lack their columns or triggers, which it checks again on every reload (see [`migration`](#migration)), and one with an [AI field or action](ai.md#the-model) and no model key; there is no development login. The `login` line of the startup message says how to sign in: while the auth store has no users, it prints the exact command that creates the first admin, such as `bun run protobase users create you@example.com --generate-password` (the package manager that started `dev`, `npx` otherwise). Against a database that has users already, such as an app's hosted one, sign in as one of them or add one with a new email; its own password is set there. A `warning` line follows for each way the auth store's tables differ from what the app's sign-in needs, such as a column dropped by hand: the one place Protobase compares them, since `serve` reads the store's record of [migrations](auth.md#migrations) alone.
203
203
  - **Mobile releases:** see [below](#mobile-releases).
204
204
  - **Jobs:** with [jobs](jobs.md) in the config it runs them in the API's process, once the jobs schema checks out (see [`migration`](#migration)); an edited job runs its new code from the next job on. `--no-jobs` runs none of them and delivers none of the app's [events](events.md), webhooks or pushes, for a dev server on the database of a hosted app that already runs them; jobs are still enqueued, for that app to run, and the startup message says `jobs off`.
205
+ - **Realtime relay:** with [`realtime.relay`](realtime-relay.md) and no `url`, it runs the relay from `@protobase/realtime`, the project's install or else the CLI's, for the app, gives the app its address and keys, and stops it with the dev server (see [Local development](realtime-relay.md#local-development)).
205
206
  - **Tunnels and other hosts:** Vite only answers `localhost` by default. `--allowed-hosts .trycloudflare.com,app.example.com` adds Host headers (a leading dot matches all subdomains). The API's WebSockets, such as an [API function](../guides/api-functions.md#websockets)'s, pass the same check: an upgrade with another Host header is refused with `403`. Hot reload needs no extra setting: the Vite client takes protocol, host and port from the page, so behind an HTTPS tunnel it connects over `wss` on 443 as long as the tunnel forwards WebSockets.
206
207
  - **Project discovery**, by convention: `config/index.ts` exports the resources (and views), and every `config/*/ui.ts` export that is not already exported by the index is added as a view. Each `functions/<name>.ts` (or `functions/<name>/index.ts`) is an [API function](../guides/api-functions.md) at `/api/functions/<name>`. `protobase.config.ts` (or `protobase.config.json`) in the project root describes the rest as data, and the jobs, hooks and other code it names are found by their paths; see [protobase.config.ts](config.md). Without it, the app runs on the defaults.
207
208
  - **Project UI:** the app imports `protobase.ui.tsx` from the project root, with hot reload, when it exists (see [Custom components](custom-components.md)): the same contract as the plugin `protobase build` makes of it, built into the dev page instead. Layout files are checked as they load, as `protobase build` checks them.
@@ -545,7 +546,7 @@ A host that serves bundles without running their config, such as a router in fro
545
546
  protobase worker <bundle> # a bundle from `protobase build`: its folder or its protobase.config.js
546
547
  ```
547
548
 
548
- Runs the bundle's [jobs](jobs.md), and the delivery of its [events](webhooks.md#delivery-and-retries), and nothing else, until SIGTERM or SIGINT, which let running jobs finish for 30 seconds as `serve` does. It checks the bundle's version and the jobs schema at start like `serve`, reads the `.env` nearest the current directory and needs `DATABASE_URL`. Run it beside a `serve` with `PROTOBASE_JOBS=false`, from the same bundle. It refuses a bundle with nothing to run: no jobs, and no resource with events, history, comments or an AI field, whose jobs are Protobase's own. Like `serve`, it reports a crash to the app's [error tracker](api.md#error-reporting). `protobase worker running <n> jobs` means it is ready.
549
+ Runs the bundle's [jobs](jobs.md), and the delivery of its [events](webhooks.md#delivery-and-retries), and nothing else, until SIGTERM or SIGINT, which let running jobs finish for 30 seconds as `serve` does. It checks the bundle's version and the jobs schema at start like `serve`, reads the `.env` nearest the current directory and needs `DATABASE_URL`. Run it beside a `serve` with `PROTOBASE_JOBS=false`, from the same bundle. It refuses a bundle with nothing to run: no jobs, no resource with events, history, comments or an AI field, and no [time rollup](data-config.md#keeping-it-up-to-date), whose jobs are Protobase's own. Like `serve`, it reports a crash to the app's [error tracker](api.md#error-reporting). `protobase worker running <n> jobs` means it is ready.
549
550
 
550
551
  ## `files cleanup`
551
552
 
@@ -634,7 +635,7 @@ Applies the project's `db/migrations/*.sql` that the database has not applied ye
634
635
  protobase migration [--dir db/migrations] [--extend <dir>]
635
636
  ```
636
637
 
637
- Writes what the database still needs for every feature the config enables, as the project's next migrations in `--dir`, one file per feature: the auth schema when sign-in is on (`NNN_auth.sql`, as [`auth migration`](#auth-migration) writes it), the [jobs schema](jobs.md#the-jobs-schema) when the config has jobs, `webhooks`, `workflows`, `notifications` or `mailFeedback`, or a resource has events, history, comments or an [AI field](ai.md) (`NNN_jobs.sql`), the table of the bounces and complaints of [`mailFeedback`](email.md#bounces-and-complaints) (`NNN_mail_feedback.sql`), the [capture of events](events.md#migrations-and-startup) and the [history table](history.md#the-table) (`NNN_changes.sql`), the columns of [rollup and formula fields](data-config.md#rollups-and-formulas), the triggers that keep the rollups, and the tables, indexes and refresh functions of [time rollups](data-config.md#time-rollups) (`NNN_computed.sql`), the role the [assistant's read-only queries](assistant.md#the-built-in-backend) run as, when it finds the built-in assistant's key (`NNN_query.sql`), the [comments table](comments.md#the-table) (`NNN_comments.sql`), the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app) of `webhooks` (`NNN_webhooks.sql`), the [workflows, versions, runs and steps](workflows.md#turning-them-on) of `workflows` (`NNN_workflows.sql`), the [devices and history tables](notifications.md#table-names) of `notifications` (`NNN_notifications.sql`), the table of who unsubscribed from bulk mail of [`unsubscribe`](email.md#unsubscribe) (`NNN_unsubscribes.sql`), the `realtime_relay` schema of [`realtime: { processes: 'many' }`](supabase-realtime.md#several-processes) (`NNN_realtime_relay.sql`), the `channels` schema of [`realtime: { sqlSends: true }`](channels.md#from-sql) (`NNN_channel_sends.sql`), the trigger of [`realtime.relay`](realtime-relay.md#sessions) that ends a deleted session's sockets (`NNN_relay.sql`), and, with [`userTables`](user-tables.md#the-switch), the schemas of user tables (`NNN_user_tables.sql`) and the delete of the definitions of tables that resources in code [own now](user-tables.md#taking-a-table-over-as-code) (`NNN_owned_definitions.sql`). It compares the database, with the project's migrations applied, with the config (for the auth schema, it reads the store's record of the migrations it applied), merged with those of `--extend` as `dev` merges them, and writes nothing when the database is current. Apply the files with the project's other migrations. It reads the `.env` nearest the current directory and needs `DATABASE_URL`.
638
+ Writes what the database still needs for every feature the config enables, as the project's next migrations in `--dir`, one file per feature: the auth schema when sign-in is on (`NNN_auth.sql`, as [`auth migration`](#auth-migration) writes it), the [jobs schema](jobs.md#the-jobs-schema) when the config has jobs, `webhooks`, `workflows`, `notifications` or `mailFeedback`, or a resource has events, history, comments or an [AI field](ai.md) or is a [time rollup](data-config.md#keeping-it-up-to-date) (`NNN_jobs.sql`), the table of the bounces and complaints of [`mailFeedback`](email.md#bounces-and-complaints) (`NNN_mail_feedback.sql`), the [capture of events](events.md#migrations-and-startup) and the [history table](history.md#the-table) (`NNN_changes.sql`), the columns of [rollup and formula fields](data-config.md#rollups-and-formulas), the triggers that keep the rollups, and the tables, indexes and refresh functions of [time rollups](data-config.md#time-rollups) (`NNN_computed.sql`), the role the [assistant's read-only queries](assistant.md#the-built-in-backend) run as, when it finds the built-in assistant's key (`NNN_query.sql`), the [comments table](comments.md#the-table) (`NNN_comments.sql`), the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app) of `webhooks` (`NNN_webhooks.sql`), the [workflows, versions, runs and steps](workflows.md#turning-them-on) of `workflows` (`NNN_workflows.sql`), the [devices and history tables](notifications.md#table-names) of `notifications` (`NNN_notifications.sql`), the table of who unsubscribed from bulk mail of [`unsubscribe`](email.md#unsubscribe) (`NNN_unsubscribes.sql`), the `realtime_relay` schema of [`realtime: { processes: 'many' }`](supabase-realtime.md#several-processes) (`NNN_realtime_relay.sql`), the `channels` schema of [`realtime: { sqlSends: true }`](channels.md#from-sql) (`NNN_channel_sends.sql`), the trigger of [`realtime.relay`](realtime-relay.md#sessions) that ends a deleted session's sockets (`NNN_relay.sql`), and, with [`userTables`](user-tables.md#the-switch), the schemas of user tables (`NNN_user_tables.sql`) and the delete of the definitions of tables that resources in code [own now](user-tables.md#taking-a-table-over-as-code) (`NNN_owned_definitions.sql`). It compares the database, with the project's migrations applied, with the config (for the auth schema, it reads the store's record of the migrations it applied), merged with those of `--extend` as `dev` merges them, and writes nothing when the database is current. Apply the files with the project's other migrations. It reads the `.env` nearest the current directory and needs `DATABASE_URL`.
638
639
 
639
640
  ```sh
640
641
  bun run db:migrate # the database at the project's current schema
@@ -361,6 +361,8 @@ A component that asks for input looks like the app's own forms when it is built
361
361
  | `RecordPicker` | Records of another resource, picked as the create form picks a relation: type to narrow them by their search fields or title, scroll for more, or use the keyboard. `resource` names the resource, whose model it reads from the app; `value` is the chosen record's key as text and `onChange` gets the new one. With `multiple`, `value` and `onChange` hold several keys, such as the objectives a task serves through a join resource: each shows as a token that can be taken off. |
362
362
  | `Segmented`, `MenuSelect` | A switch between a few short options in a row (`size`, `iconOnly`), and the same options in a menu. |
363
363
  | `Button`, `buttonClass` | A button (`variant` `primary`, `secondary`, `ghost` or `danger`, `size` `sm`, `md` or `icon`, a square for an icon alone, `loading`, and `busyLabel`, what it says while loading, as a status a screen reader announces), and its classes for a link that looks like one. |
364
+ | `MenuSurface`, `usePopoverMenu`, `menuItemClass` | A menu of your own that looks and behaves like the app's: `usePopoverMenu()` gives `open`, `setOpen`, the `button` and `menu` refs and `place`, the menu's fixed `top`, `right` and `maxWidth` beside its button (undefined for its first, hidden frame), and closes it on a click outside, Escape, a scroll or a resize; `MenuSurface` draws the `menu` beside its button on a desktop and in a sheet from the bottom of a phone; `menuItemClass` styles each row as the app's menu items. |
365
+ | `useToast` | Brief notices at the bottom of the page, such as "Text copied": `show({ state, title, description, action })` returns an id for `update` and `dismiss`; `state` is `success`, `info`, `warning`, `error` or `loading`, which stays until updated. |
364
366
  | `Dialog`, `ResponsiveDialog` | A modal with a `title`, `description`, `actions` and a body, which Escape and a click outside close with `onClose`; the responsive one becomes a sheet from the bottom of a phone, which follows a finger dragging it down by its header, or by its content once that is scrolled to its top, and closes when flung or let go past a third of its height. |
365
367
 
366
368
  ```tsx
@@ -280,11 +280,10 @@ export const orders = resource('orders')
280
280
  :::caution[In development]
281
281
  Coming soon:
282
282
 
283
- - <gap>A time rollup cannot keep itself up to date because the recurring job that refreshes its latest buckets is not implemented.</gap> Until then the migration fills it once, and calling its refresh function brings it up to date.
284
283
  - <gap>Charts and `:aggregate` and `:series` cannot read a time rollup's counts, sums and averages correctly because mapping them onto its stored columns is not implemented.</gap>
285
284
  :::
286
285
 
287
- A large events table, such as millions of meter readings, gets a **time rollup**: a table with one row per hour or day and per group, holding how many records fell in it and the sums and greatest values of their numbers. A chart over months then reads a few thousand rows instead of millions. You declare the rollup as a resource over the events resource, and [`protobase migration`](cli.md#migration) writes its table, indexes and refresh function into the project's next migration (`NNN_computed.sql`), with the rollup filled once. It is plain Postgres: no extension.
286
+ A large events table, such as millions of meter readings, gets a **time rollup**: a table with one row per hour or day and per group, holding how many records fell in it and the sums and greatest values of their numbers. A chart over months then reads a few thousand rows instead of millions. You declare the rollup as a resource over the events resource, and [`protobase migration`](cli.md#migration) writes its table, indexes and refresh function into the project's next migration (`NNN_computed.sql`), with the rollup filled once. From then on the app keeps it up to date by itself, at most a minute behind. It is plain Postgres: no extension.
288
287
 
289
288
  ```ts title="docs-examples/reference/time-rollups.ts"
290
289
  import { f, resource } from '@protobase/schema'
@@ -340,10 +339,16 @@ The rollup's records have these fields, all read-only:
340
339
  | `<field>_sum` | The sum of the field: a bigint for an integer, a decimal of ten more digits for a bigint or a decimal. Empty when every value was. |
341
340
  | `<field>_max` | The greatest value of the field, of its type. Empty when every value was. |
342
341
 
343
- Records the source soft deleted are left out. The migration creates the table in the rollup's schema, with a unique index on `(bucket, by...)` and an index on `(group, bucket)` per group, so a list filtered on the bucket, on a group or on both passes the [scan guard](api.md#safety). It writes `rollups.<table>_refresh(from timestamptz)`, which recomputes every bucket from the one `from` falls in, in one statement: it upserts their counts and sums and deletes those left without records. `select rollups.readings_hourly_refresh(now() - interval '2 hours')` brings the example up to date. When the rollup's declaration changes, the migration drops its table and creates and fills it again. The table and function of a rollup the config no longer has stay; a migration of your own drops them, in a deploy after the one that stops reading them.
342
+ Records the source soft deleted are left out. The migration creates the table in the rollup's schema, with a unique index on `(bucket, by...)` and an index on `(group, bucket)` per group, so a list filtered on the bucket, on a group or on both passes the [scan guard](api.md#safety). It writes `rollups.<table>_refresh(from timestamptz)`, which recomputes every bucket from the one `from` falls in, in one statement: it upserts their counts and sums and deletes those left without records. When the rollup's declaration changes, the migration drops its table and creates and fills it again. The table and function of a rollup the config no longer has stay; a migration of your own drops them, in a deploy after the one that stops reading them.
344
343
 
345
344
  Only the database writes a rollup's rows: creates, updates and deletes are refused whatever its rules say, and it cannot have soft delete, a manual order, an author, a parent or `.openExisting()`. Its access is its own `.access()`: the source's rules do not reach it, so give it rules that let read only those who may see every record of a group. Its tenant is the source's, which is why `by` includes it. A field that is sensitive or has its own read rule, such as `.access({ read: roles.can('costs.read') })`, cannot be grouped by or measured, and one with its own read rule cannot be the rollup's `time`, since a bucket would show it to anyone who reads the rollup. The server does not start while the source has its own `read` or `list` rule in `.access()`, whatever the rule returns, or while a role reads only some of the source's records that a bucket mixes with others: `.own` or `.team` while `by` does not include the source's owner field, or a role's filter on fields outside `by`. <gap>A time rollup cannot group by an optional field because a bucket key with empty parts is not implemented.</gap> <gap>A time rollup cannot roll up a resource whose reads follow a parent because applying the parent's access to buckets is not implemented.</gap> <gap>A time rollup cannot roll up a resource with its own `read` or `list` access rule because declaring the fields such a rule filters on is not implemented.</gap>
346
345
 
346
+ ### Keeping it up to date
347
+
348
+ 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).
349
+
350
+ 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
+
347
352
  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.
348
353
 
349
354
  ## Sensitive fields
@@ -45,6 +45,18 @@ The relay needs the app's own [sign-in](auth.md), whose sessions its tickets nam
45
45
 
46
46
  [`protobase relay app`](cli.md#relay-app) prints the app's entry for the relay's apps file, from this config and the app's `url`.
47
47
 
48
+ ## Local development
49
+
50
+ [`protobase dev`](cli.md#dev) runs a relay of its own when `realtime.relay` has no `url`, such as with `RELAY_URL` unset in `.env`, so local realtime needs no second command. Add the relay's npm package to the project once:
51
+
52
+ ```sh
53
+ npm install --save-dev @protobase/realtime
54
+ ```
55
+
56
+ <gap>`protobase dev` cannot run the relay without the project installing `@protobase/realtime` because the CLI does not depend on it until the package is published.</gap>
57
+
58
+ It starts the relay on the first load of a config with `realtime.relay`, an edit that adds it included, on a free port of `127.0.0.1`, serving this one app with the dev server's origin, and gives the app its address. The keys are the config's when it sets them, and otherwise made anew for each `protobase dev`. An edit that changes the app's id or keys starts it again, one that removes `realtime.relay` or sets a `url` stops it, and it stops with `dev`. Its own messages, such as an apps file it refuses, show in the terminal. With a `url`, the app uses that relay and `dev` starts none.
59
+
48
60
  ## Tickets
49
61
 
50
62
  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.
@@ -830,7 +830,7 @@ view<typeof channels>('channels').record({
830
830
 
831
831
  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.
832
832
 
833
- With `readPosition`, the conversation opens on a *New messages* line above the first message someone else wrote since the reader's position, and moves the position to the newest message whenever they read to the end. The read position resource keeps one record per reader and record: its `.author()` is the reader, `field` is a relation to the record and `message` an integer field holding the key of the newest message read, so the message resource's key is one integer column that grows as messages arrive. The page reads and writes only the reader's own position. Without `readPosition`, there is no line and nothing is written.
833
+ With `readPosition`, the conversation opens on a *New messages* line above the first message someone else wrote since the reader's position, and moves the position to the highest message key shown whenever they read to the end; it never moves back, even when another tab of the same reader moved it further. The read position resource keeps one record per reader and record: its `.author()` is the reader, a filterable field, `field` is a filterable relation to the record and `message` an integer field holding the key of the newest message read, both writable, so the message resource's key is one integer column that grows as messages arrive. The page reads and writes only the reader's own position. <gap>A move cannot be kept when yet another tab moves the position between this tab's reread and its write, which then shows an error, because a second retry of the conditional write is not implemented.</gap> Without `readPosition`, there is no line and nothing is written.
834
834
 
835
835
  #### Reactions, edits, deletes and threads
836
836