@protobase/cli 0.23.5 → 0.23.7
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.
- package/dist/build/service-worker-code.js +52 -0
- package/dist/build/shell.js +10 -3
- package/dist/dev/entry.js +2 -1
- package/dist/migration/parts.js +6 -1
- package/dist/package.js +1 -1
- package/dist/project/service-worker.js +46 -0
- package/dist/serve/lifecycle.js +2 -1
- package/package.json +6 -6
- package/skills/protobase/SKILL.md +2 -1
- package/skills/protobase/references/reference/auth.md +1 -1
- package/skills/protobase/references/reference/cli.md +8 -7
- package/skills/protobase/references/reference/data-config.md +54 -0
- package/skills/protobase/references/reference/installable-app.md +36 -0
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { faviconFile } from "./favicon.js";
|
|
2
|
+
import { themeFile } from "./theme.js";
|
|
3
|
+
//#region src/build/service-worker-code.ts
|
|
4
|
+
/** The service worker's file in the shell, at the root so it may answer the whole origin. */
|
|
5
|
+
const serviceWorkerFile = "protobase.sw.js";
|
|
6
|
+
/**
|
|
7
|
+
* The shell's service worker, which makes the admin app open without a network and then say the API is unreachable;
|
|
8
|
+
* data is never cached. A build of the shell names its own `version`, so a new shell's worker replaces the old one and
|
|
9
|
+
* drops its cache. `precache` is what the page loads first: the page itself and the assets it links.
|
|
10
|
+
*
|
|
11
|
+
* - A navigation goes to the network, and only when that fails gets the cached page, so an online app is always the
|
|
12
|
+
* server's.
|
|
13
|
+
* - The content-hashed assets under /assets come from the cache, filled as the app loads them.
|
|
14
|
+
* - The project's theme and favicon go to the network, the cached copy standing in when it fails.
|
|
15
|
+
* - Everything else, the API above all, never reaches the worker's cache.
|
|
16
|
+
*/
|
|
17
|
+
const serviceWorkerCode = ({ version, precache }) => `const cacheName = ${JSON.stringify(`protobase-shell-${version}`)}
|
|
18
|
+
const precache = ${JSON.stringify(precache)}
|
|
19
|
+
const revalidated = ${JSON.stringify([`/${themeFile}`, `/${faviconFile}`])}
|
|
20
|
+
|
|
21
|
+
const fromCache = (request) =>
|
|
22
|
+
caches.match(request).then((cached) => cached || fetch(request).then((response) => {
|
|
23
|
+
if (response.ok) caches.open(cacheName).then((cache) => cache.put(request, response.clone()))
|
|
24
|
+
return response
|
|
25
|
+
}))
|
|
26
|
+
|
|
27
|
+
const fromNetwork = (request, fallback) =>
|
|
28
|
+
fetch(request).then((response) => {
|
|
29
|
+
if (response.ok && fallback === request) caches.open(cacheName).then((cache) => cache.put(request, response.clone()))
|
|
30
|
+
return response
|
|
31
|
+
}, (error) => caches.match(fallback).then((cached) => cached || Promise.reject(error)))
|
|
32
|
+
|
|
33
|
+
self.addEventListener('install', (event) => {
|
|
34
|
+
event.waitUntil(caches.open(cacheName).then((cache) => cache.addAll(precache.map((url) => new Request(url, { cache: 'reload' })))).then(() => self.skipWaiting()))
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
self.addEventListener('activate', (event) => {
|
|
38
|
+
const old = (key) => key.startsWith('protobase-shell-') && key !== cacheName
|
|
39
|
+
event.waitUntil(caches.keys().then((keys) => Promise.all(keys.filter(old).map((key) => caches.delete(key)))).then(() => self.clients.claim()))
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
self.addEventListener('fetch', (event) => {
|
|
43
|
+
const request = event.request
|
|
44
|
+
const url = new URL(request.url)
|
|
45
|
+
if (request.method !== 'GET' || url.origin !== self.location.origin) return
|
|
46
|
+
if (request.mode === 'navigate') event.respondWith(fromNetwork(request, '/index.html'))
|
|
47
|
+
else if (url.pathname.startsWith('/assets/')) event.respondWith(fromCache(request))
|
|
48
|
+
else if (revalidated.includes(url.pathname)) event.respondWith(fromNetwork(request, request))
|
|
49
|
+
})
|
|
50
|
+
`;
|
|
51
|
+
//#endregion
|
|
52
|
+
export { serviceWorkerCode, serviceWorkerFile };
|
package/dist/build/shell.js
CHANGED
|
@@ -4,6 +4,8 @@ import { adminAppDir, uiEntry, uiPackageDir } from "../project/admin-app.js";
|
|
|
4
4
|
import { sharedModulesPlugin } from "../project/shared-modules.js";
|
|
5
5
|
import { faviconLink } from "../project/favicon-link.js";
|
|
6
6
|
import { themeLink } from "../project/theme-link.js";
|
|
7
|
+
import { serviceWorkerFile } from "./service-worker-code.js";
|
|
8
|
+
import { serviceWorker } from "../project/service-worker.js";
|
|
7
9
|
import { existsSync } from "node:fs";
|
|
8
10
|
import path from "node:path";
|
|
9
11
|
import { build } from "vite";
|
|
@@ -14,8 +16,12 @@ import { tmpdir } from "node:os";
|
|
|
14
16
|
//#region src/build/shell.ts
|
|
15
17
|
/** What a shell folder holds beside its files: the `BundleShell` a bundle's manifest copies. */
|
|
16
18
|
const shellManifestFile = "protobase.shell.json";
|
|
17
|
-
/** The shell's files, as URL paths: its page
|
|
18
|
-
const shellPaths = [
|
|
19
|
+
/** The shell's files, as URL paths: its page, its content-hashed assets and its service worker. */
|
|
20
|
+
const shellPaths = [
|
|
21
|
+
"/index.html",
|
|
22
|
+
"/assets",
|
|
23
|
+
`/${serviceWorkerFile}`
|
|
24
|
+
];
|
|
19
25
|
/** Where @protobase/ui's package ships its prebuilt shell, which `protobase build` copies and `protobase serve` serves. */
|
|
20
26
|
const prebuiltShellDir = path.join(uiPackageDir, "dist", "shell");
|
|
21
27
|
const shellIdentity = async () => {
|
|
@@ -31,7 +37,7 @@ const shellIdentity = async () => {
|
|
|
31
37
|
* The admin app as a production build, the same for every project: index.html and content-hashed files under assets/,
|
|
32
38
|
* with protobase.shell.json saying which version it is. Asset URLs are absolute, so index.html works as the answer to
|
|
33
39
|
* any deep link. It calls /api on its own origin and loads the project's UI, like every plugin, from what `/meta`
|
|
34
|
-
* names, and links the project's theme at /protobase.theme.css and its favicon at /protobase.favicon.svg. The modules plugins share with it have entries of
|
|
40
|
+
* names, and links the project's theme at /protobase.theme.css and its favicon at /protobase.favicon.svg, and registers its service worker. The modules plugins share with it have entries of
|
|
35
41
|
* their own, which index.html's import map names.
|
|
36
42
|
*/
|
|
37
43
|
const buildShell = async (outDir) => {
|
|
@@ -49,6 +55,7 @@ const buildShell = async (outDir) => {
|
|
|
49
55
|
projectUiPlugin(void 0),
|
|
50
56
|
themeLink(),
|
|
51
57
|
faviconLink(),
|
|
58
|
+
serviceWorker(),
|
|
52
59
|
react(),
|
|
53
60
|
tailwindcss()
|
|
54
61
|
],
|
package/dist/dev/entry.js
CHANGED
|
@@ -2,7 +2,7 @@ import { devJobs } from "./dev-jobs.js";
|
|
|
2
2
|
import { projectErrorReporter } from "../project/error-reporter.js";
|
|
3
3
|
import { projectAdmin } from "../project/project-admin.js";
|
|
4
4
|
import { loadProject, projectDb } from "./project.js";
|
|
5
|
-
import { checkAi, checkAuthSchema, checkChanges, checkComments, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
|
|
5
|
+
import { checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
|
|
6
6
|
import { Hono } from "hono";
|
|
7
7
|
//#region src/dev/entry.ts
|
|
8
8
|
const projectDir = process.env.PROTOBASE_PROJECT;
|
|
@@ -17,6 +17,7 @@ if (project.auth && !store.__protobaseAuthSchemaChecked) {
|
|
|
17
17
|
}
|
|
18
18
|
await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
|
|
19
19
|
await checkComments(db, resources.map((resource) => resource.toModel()));
|
|
20
|
+
await checkComputed(db, resources.map((resource) => resource.toModel()));
|
|
20
21
|
checkAi({
|
|
21
22
|
models: resources.map((resource) => resource.toModel()),
|
|
22
23
|
views: views.map((source) => source.toModel()),
|
package/dist/migration/parts.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { authSchemaMigration, changesMigration, commentsMigration, isCaptured, jobsSchemaMigration, webhooksMigration } from "@protobase/server";
|
|
1
|
+
import { authSchemaMigration, changesMigration, commentsMigration, computedMigration, isCaptured, jobsSchemaMigration, webhooksMigration } from "@protobase/server";
|
|
2
2
|
//#region src/migration/parts.ts
|
|
3
3
|
/** Every feature the project's config enables, in the order their files are written. */
|
|
4
4
|
const migrationParts = (project) => {
|
|
@@ -20,6 +20,11 @@ const migrationParts = (project) => {
|
|
|
20
20
|
title: "The change capture the resources' events and history need",
|
|
21
21
|
sql: () => changesMigration(project.db, project.models, project.events)
|
|
22
22
|
},
|
|
23
|
+
{
|
|
24
|
+
name: "computed",
|
|
25
|
+
title: "The columns of the resources' rollup and formula fields, and the triggers that keep the rollups",
|
|
26
|
+
sql: () => computedMigration(project.db, project.models)
|
|
27
|
+
},
|
|
23
28
|
...comments ? [{
|
|
24
29
|
name: "comments",
|
|
25
30
|
title: "The comments table of the resources with comments",
|
package/dist/package.js
CHANGED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { faviconFile } from "../build/favicon.js";
|
|
2
|
+
import { themeFile } from "../build/theme.js";
|
|
3
|
+
import { serviceWorkerCode, serviceWorkerFile } from "../build/service-worker-code.js";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
//#region src/project/service-worker.ts
|
|
6
|
+
const linkedAssets = (html) => [...new Set([...html.matchAll(/["'](\/assets\/[^"']+)["']/g)].map((match) => match[1]))];
|
|
7
|
+
/**
|
|
8
|
+
* Gives a production build of the app its service worker (see `serviceWorkerCode`) at `/protobase.sw.js`, which the
|
|
9
|
+
* page registers. The worker's version hashes the build's file names, which hash their contents.
|
|
10
|
+
*/
|
|
11
|
+
const serviceWorker = () => ({
|
|
12
|
+
name: "protobase-service-worker",
|
|
13
|
+
apply: "build",
|
|
14
|
+
transformIndexHtml: {
|
|
15
|
+
order: "post",
|
|
16
|
+
handler: () => [{
|
|
17
|
+
tag: "script",
|
|
18
|
+
children: `if ('serviceWorker' in navigator) navigator.serviceWorker.register('/${serviceWorkerFile}')`,
|
|
19
|
+
injectTo: "body"
|
|
20
|
+
}]
|
|
21
|
+
},
|
|
22
|
+
generateBundle: {
|
|
23
|
+
order: "post",
|
|
24
|
+
handler(_options, bundle) {
|
|
25
|
+
const page = bundle["index.html"];
|
|
26
|
+
if (page?.type !== "asset") throw new Error("The app build has no index.html to give a service worker");
|
|
27
|
+
const version = createHash("sha256").update(Object.keys(bundle).sort().join("\n")).digest("hex").slice(0, 16);
|
|
28
|
+
const precache = [
|
|
29
|
+
"/index.html",
|
|
30
|
+
...linkedAssets(String(page.source)),
|
|
31
|
+
`/${themeFile}`,
|
|
32
|
+
`/${faviconFile}`
|
|
33
|
+
];
|
|
34
|
+
this.emitFile({
|
|
35
|
+
type: "asset",
|
|
36
|
+
fileName: serviceWorkerFile,
|
|
37
|
+
source: serviceWorkerCode({
|
|
38
|
+
version,
|
|
39
|
+
precache
|
|
40
|
+
})
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
//#endregion
|
|
46
|
+
export { serviceWorker };
|
package/dist/serve/lifecycle.js
CHANGED
|
@@ -2,7 +2,7 @@ import { projectAdmin } from "../project/project-admin.js";
|
|
|
2
2
|
import { createPgDb } from "../project/pg-db.js";
|
|
3
3
|
import { createServeApp } from "./app.js";
|
|
4
4
|
import { startCleanupTimer } from "./cleanup-timer.js";
|
|
5
|
-
import { checkAi, checkAuthSchema, checkChanges, checkComments, checkJobsSchema, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
|
|
5
|
+
import { checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
|
|
6
6
|
import pg from "pg";
|
|
7
7
|
import { createAdaptorServer } from "@hono/node-server";
|
|
8
8
|
//#region src/serve/lifecycle.ts
|
|
@@ -23,6 +23,7 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
|
|
|
23
23
|
const startJobsAndListen = async () => {
|
|
24
24
|
if (env.startupChecks) await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
|
|
25
25
|
if (env.startupChecks) await checkComments(db, resources.map((resource) => resource.toModel()));
|
|
26
|
+
if (env.startupChecks) await checkComputed(db, resources.map((resource) => resource.toModel()));
|
|
26
27
|
if (env.startupChecks) checkAi({
|
|
27
28
|
models: resources.map((resource) => resource.toModel()),
|
|
28
29
|
views: views.map((source) => source.toModel()),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.23.
|
|
3
|
+
"version": "0.23.7",
|
|
4
4
|
"description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -35,11 +35,11 @@
|
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"@hono/node-server": "^2.1.3",
|
|
37
37
|
"@hono/vite-dev-server": "^0.26.1",
|
|
38
|
-
"@protobase/layout": "0.23.
|
|
39
|
-
"@protobase/query": "0.23.
|
|
40
|
-
"@protobase/schema": "0.23.
|
|
41
|
-
"@protobase/server": "0.23.
|
|
42
|
-
"@protobase/ui": "0.23.
|
|
38
|
+
"@protobase/layout": "0.23.7",
|
|
39
|
+
"@protobase/query": "0.23.7",
|
|
40
|
+
"@protobase/schema": "0.23.7",
|
|
41
|
+
"@protobase/server": "0.23.7",
|
|
42
|
+
"@protobase/ui": "0.23.7",
|
|
43
43
|
"@react-email/render": "^2.1.0",
|
|
44
44
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
45
45
|
"@tailwindcss/vite": "^4.3.3",
|
|
@@ -56,7 +56,7 @@ Guides:
|
|
|
56
56
|
|
|
57
57
|
Reference:
|
|
58
58
|
|
|
59
|
-
- When defining resources, fields, keys, relations and validation → read [Data config](references/reference/data-config.md)
|
|
59
|
+
- When defining resources, fields, keys, relations, rollups, formulas and validation → read [Data config](references/reference/data-config.md)
|
|
60
60
|
- When defining views, columns, filters, charts, related records and actions → read [UI config](references/reference/ui-config.md)
|
|
61
61
|
- When asking how the packages fit together → read [Architecture](references/reference/architecture.md)
|
|
62
62
|
- When calling or changing the REST API, its filters, writes and errors → read [REST API](references/reference/api.md)
|
|
@@ -80,6 +80,7 @@ Reference:
|
|
|
80
80
|
- When using resources another Protobase API serves → read [Remote resources](references/reference/remote-resources.md)
|
|
81
81
|
- When setting the app's tokens, colors and fonts → read [Theme](references/reference/theme.md)
|
|
82
82
|
- When showing the app's screens in Dutch → read [Languages](references/reference/languages.md)
|
|
83
|
+
- When installing the app on a phone or computer, or asking what it does offline → read [Installable app](references/reference/installable-app.md)
|
|
83
84
|
- When grouping sidebar entries or listing recent records → read [Sidebar](references/reference/sidebar.md)
|
|
84
85
|
- When changing the user menu → read [User menu](references/reference/user-menu.md)
|
|
85
86
|
- When adding tabs along the bottom of a phone → read [Bottom bar](references/reference/bottom-bar.md)
|
|
@@ -63,7 +63,7 @@ Upgrading from 0.5 or earlier, where `auth:migrate` created the tables, goes thr
|
|
|
63
63
|
- Cookies are `SameSite=Lax`, and `Secure` when `BETTER_AUTH_URL` is https.
|
|
64
64
|
- Sign-in is rate limited (5 password attempts per minute and client by default, `signInPerMinute`, which also limits [sign-up](#open-sign-up) requests; 3 per minute for emailed codes); the limiter keys on `x-forwarded-for`, so run behind a proxy that sets it.
|
|
65
65
|
- Passwords need at least 12 characters.
|
|
66
|
-
- `appName` is the app's name: authenticator apps and passkey prompts show it, the admin app's sidebar shows it at the top beside Protobase's mark (Protobase's wordmark when it is `Protobase`), every browser tab of the admin app ends its title with it, the [auth emails](email.md#protobases-own-mail)) name the app with it, and the platform's mailer sends them as it (the sender's display name). Default `PROTOBASE_APP_NAME`, when set, and `Protobase` otherwise, then without a display name.
|
|
66
|
+
- `appName` is the app's name: authenticator apps and passkey prompts show it, the admin app's sidebar shows it at the top beside Protobase's mark (Protobase's wordmark when it is `Protobase`), every browser tab of the admin app ends its title with it, the [installed app](installable-app.md)) is called by it, the [auth emails](email.md#protobases-own-mail)) name the app with it, and the platform's mailer sends them as it (the sender's display name). Default `PROTOBASE_APP_NAME`, when set, and `Protobase` otherwise, then without a display name.
|
|
67
67
|
|
|
68
68
|
## First run
|
|
69
69
|
|
|
@@ -105,7 +105,7 @@ One process, one port: Vite serves the admin app from `@protobase/ui`'s `src/app
|
|
|
105
105
|
|
|
106
106
|
- **Database:** the URL comes from the variable named by `--env`, read from the environment or the nearest `.env` at or above the project. The connection is checked before anything starts; if it fails, the command names host, port and reason (and points to its `db:up` script when it has one). The project needs `pg` installed, because the API connects with Kysely over the project's own `pg`.
|
|
107
107
|
- **Cache:** Vite's dependency cache is `node_modules/.vite`; two dev servers sharing it can disturb each other's optimisation, so pass `--cache-dir` for a second one (the integration test does).
|
|
108
|
-
- **Login:** real sign-in only, with the `authenticate` and `auth` exported by `protobase.config.ts` (see [Login with Better Auth](auth.md))). A project without an authenticator fails at startup with a message pointing there, one whose auth schema is behind with the tables and columns it lacks (see [`auth migration`](#auth-migration)), and one with a resource whose [events](events.md)) or [history](history.md)) lack their triggers, or whose [comments](comments.md)) lack their table, 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. Create the first admin with `protobase users create`.
|
|
108
|
+
- **Login:** real sign-in only, with the `authenticate` and `auth` exported by `protobase.config.ts` (see [Login with Better Auth](auth.md))). A project without an authenticator fails at startup with a message pointing there, one whose auth schema is behind with the tables and columns it lacks (see [`auth migration`](#auth-migration)), 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. Create the first admin with `protobase users create`.
|
|
109
109
|
- **Jobs:** with [jobs](jobs.md)) in the config it runs them in its process, once the jobs schema checks out (see [`migration`](#migration)); an edited job runs its new code from the next job on.
|
|
110
110
|
- **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). 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.
|
|
111
111
|
- **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>`. A `protobase.config.ts` in the project root replaces the convention; its default export may contain any of:
|
|
@@ -178,6 +178,7 @@ dist/
|
|
|
178
178
|
node_modules/ the packages it loads from disk, only when it imports native add-ons
|
|
179
179
|
public/
|
|
180
180
|
index.html, assets/ the admin app: the shell, the same for every project
|
|
181
|
+
protobase.sw.js the shell's service worker (see Installable app)
|
|
181
182
|
plugins/app/ the project's protobase.ui.tsx, built as a plugin
|
|
182
183
|
plugins/<extension>/ each --extend folder's protobase.ui.tsx, built as a plugin
|
|
183
184
|
protobase.theme.css the project's theme, checked and minified; empty without one
|
|
@@ -215,7 +216,7 @@ By default the bundle runs on Node and on Bun. `--bun` makes it a bundle for Bun
|
|
|
215
216
|
"plugins": [
|
|
216
217
|
{ "name": "app", "path": "plugins/app/plugin.json", "api": 1, "protobase": ">=0.12.0", "fields": { "steps": ["enum"] } }
|
|
217
218
|
],
|
|
218
|
-
"shell": { "protobase": "0.12.0", "pluginApi": 1, "paths": ["/index.html", "/assets"] },
|
|
219
|
+
"shell": { "protobase": "0.12.0", "pluginApi": 1, "paths": ["/index.html", "/assets", "/protobase.sw.js"] },
|
|
219
220
|
"nodeModules": "node_modules"
|
|
220
221
|
}
|
|
221
222
|
```
|
|
@@ -235,7 +236,7 @@ By default the bundle runs on Node and on Bun. `--bun` makes it a bundle for Bun
|
|
|
235
236
|
|
|
236
237
|
`public/` holds two parts that are built apart.
|
|
237
238
|
|
|
238
|
-
- **The shell**, `index.html` and `
|
|
239
|
+
- **The shell**, `index.html`, `assets/` and `protobase.sw.js`: the admin app, a production build of `@protobase/ui`'s `src/app` with no project code in it, the same for every project on a release. `@protobase/ui`'s package ships it prebuilt in `dist/shell/` and the [protobase image](../guides/deploy.md#images)) at `/opt/protobase/shell/`; the build copies it. It calls the API on its own origin under `/api`, so the same bundle works under any hostname, and reads everything else at runtime: the resources, views, pages and roles from `/api/meta`, sign-in from `/api/auth`, the project's UI from its plugins and its look from `/protobase.theme.css`, which it links after its own stylesheets, its tab icon from `/protobase.favicon.svg`, and its [web app manifest](installable-app.md)) from `/api/manifest.webmanifest`.
|
|
239
240
|
- **The plugins**, `plugins/<name>/`: the project's `protobase.ui.tsx` as the plugin `app`, and each [extension](#extensions)'s, each built as [`build-plugin`](#build-plugin) builds one, against the `@protobase/ui` installed in the project. `/api/meta` names them, and the shell loads them as it loads any [plugin](plugins.md)). A component or field type the config declares but no `protobase.ui.tsx` exports fails the build (see [Components](custom-components.md#components))).
|
|
240
241
|
|
|
241
242
|
The modules the app shares with plugins, `react`, `react/jsx-runtime`, `react-dom` and `@protobase/ui`, are entries of their own, `/assets/shared-<name>-<hash>.js`, each exporting every name of its module. `index.html` maps the four names to them with an import map, ahead of every script, so a plugin's imports of them run on the app's copies.
|
|
@@ -359,7 +360,7 @@ Serves the API of a bundle from `protobase build` and owns the process around it
|
|
|
359
360
|
| `REQUEST_LOG` | `true` logs every request; default `false` |
|
|
360
361
|
| `PROTOBASE_SMTP_URL` | the SMTP server for password-reset mail, emailed sign-in and two-factor codes and the app's own [email](email.md)), credential included: `smtp://user:password@host:587` (STARTTLS when offered) or `smtps://...:465`; without it they are off ([Password reset](auth.md#password-reset)), [Emailed sign-in codes](auth.md#emailed-sign-in-codes))) |
|
|
361
362
|
| `PROTOBASE_MAIL_FROM` | the sender of that mail, a plain address such as `noreply@admin.example.com`; set with `PROTOBASE_SMTP_URL` or not at all |
|
|
362
|
-
| `PROTOBASE_APP_NAME` | the app's name, such as `Property Finder`: what its auth emails, its sidebar
|
|
363
|
+
| `PROTOBASE_APP_NAME` | the app's name, such as `Property Finder`: what its auth emails, its sidebar, its browser tabs and the [installed app](installable-app.md)) call it, and the sender's display name of its mail ([`appName`](auth.md#configuration))) |
|
|
363
364
|
| `PROTOBASE_SIGN_IN_ISSUER`, `PROTOBASE_SIGN_IN_CLIENT_ID`, `PROTOBASE_SIGN_IN_CLIENT_SECRET` | an OpenID Connect provider people who have an account can sign in with; all three or none. `PROTOBASE_SIGN_IN_PROVIDER` and `PROTOBASE_SIGN_IN_NAME` are optional ([Platform sign-in provider](auth.md#platform-sign-in-provider))) |
|
|
364
365
|
| `PROTOBASE_OPERATOR_ISSUER`, `PROTOBASE_OPERATOR_CLIENT_ID`, `PROTOBASE_OPERATOR_CLIENT_SECRET` | the OpenID Connect provider of the operator's staff, for [staff sign-in](auth.md#staff-sign-in)) as people of the app; all three or none. `PROTOBASE_OPERATOR_NAME` and `PROTOBASE_OPERATOR_GROUP` are optional ([Operator provider](auth.md#operator-provider))) |
|
|
365
366
|
| `PROTOBASE_ORIGINS`, `PROTOBASE_PASSKEY_DOMAIN` | the other origins the app is served on, comma separated, and the host new passkeys are made for ([Several origins](auth.md#several-origins))) |
|
|
@@ -372,7 +373,7 @@ Serves the API of a bundle from `protobase build` and owns the process around it
|
|
|
372
373
|
| `PROTOBASE_FILES_<NAME>`, `PROTOBASE_FILES_RETENTION`, `PROTOBASE_FILES_SECRET` | [file providers](files.md#providers)) and their settings, over `files` in the config; a bucket's credentials in `PROTOBASE_FILES_<NAME>_ACCESS_KEY_ID` and `_SECRET_ACCESS_KEY` |
|
|
373
374
|
| `PROTOBASE_FILES_CLEANUP_MINUTES` | minutes between runs of the [scheduled file deletes](files.md#deleting-files)), default 60; 0 leaves them to `protobase files cleanup` or the platform |
|
|
374
375
|
| `PROTOBASE_JOBS` | `false` runs none of the app's [jobs](jobs.md)) in this process, which still enqueues them; default `true` |
|
|
375
|
-
| `PROTOBASE_STARTUP_CHECKS` | `false` skips the startup reads of the auth, changes, webhooks and jobs schemas, which make a start slower; default `true`. Set it only to restart a bundle that already started on this database, such as when a platform wakes a sleeping app, never for a new bundle or after its migrations ran |
|
|
376
|
+
| `PROTOBASE_STARTUP_CHECKS` | `false` skips the startup reads of the auth, changes, computed columns, webhooks and jobs schemas, which make a start slower; default `true`. Set it only to restart a bundle that already started on this database, such as when a platform wakes a sleeping app, never for a new bundle or after its migrations ran |
|
|
376
377
|
| `PROTOBASE_SHELL` | `protobase serve <bundle>` only: a shell folder, such as the `/opt/protobase/shell` of a protobase image or `@protobase/ui`'s `dist/shell`, to serve the bundle's app from (see [its own shell](#serve)) |
|
|
377
378
|
| `PROTOBASE_JOBS_DRAIN_TOKEN` | the operator's bearer token for `POST /api/jobs/drain`, which [runs the due jobs](jobs.md#hosts-that-sleep)) of a host that lets the app sleep; without it there is no such endpoint |
|
|
378
379
|
|
|
@@ -381,7 +382,7 @@ Better Auth and other settings are the project's own variables (`BETTER_AUTH_SEC
|
|
|
381
382
|
- **Routes:** `createAdmin` (`/api/v1`, `/api/meta`, `/api/functions/*`, `/api/auth/*`, ...) and `GET /health`, which answers `{"status":"ok"}` without a token and without touching the database. The runtime never serves the UI; `protobase serve <bundle>` serves `public/` for every path outside the manifest's `api` and `/.well-known/webauthn`, after `/health`.
|
|
382
383
|
- **Plugins:** the runtime reads the manifest's `plugins`: `/api/meta` names them, and a view that shows a field with one of their [field types](plugins.md#field-types)) that does not show the field's storage type stops startup, naming the view, the field and what the field type shows.
|
|
383
384
|
- **Version:** before loading the config module, the runtime reads `protobase.bundle.json` beside it and refuses a bundle built by a Protobase version it does not serve, or one without a version, with an error naming both versions (see [Versioning](versioning.md#bundles-and-runtimes))). A config module needs its manifest beside it.
|
|
384
|
-
- **Startup:** a bundle without a default export, `config` or `authenticate`, or with an `options.basePath` other than `/api/v1`, stops startup with a one-line error and exit code 1, as does a missing `DATABASE_URL`, an auth schema that lacks a table or column (see [`auth migration`](#auth-migration)), a resource whose [events](events.md)) or [history](history.md)) lack their triggers or have out-of-date ones, or a missing history or [comments](comments.md#the-table)) table, a jobs schema that is missing or behind for a config with [jobs](jobs.md#the-jobs-schema)) (see [`migration`](#migration)), an [AI field or action](ai.md#the-model)) without a model key, or a taken port; `PROTOBASE_STARTUP_CHECKS=false` skips the checks of those schemas and the key. `protobase serve listening on port <port>` means it is ready.
|
|
385
|
+
- **Startup:** a bundle without a default export, `config` or `authenticate`, or with an `options.basePath` other than `/api/v1`, stops startup with a one-line error and exit code 1, as does a missing `DATABASE_URL`, an auth schema that lacks a table or column (see [`auth migration`](#auth-migration)), a resource whose [events](events.md)) or [history](history.md)) lack their triggers or have out-of-date ones, or a missing history or [comments](comments.md#the-table)) table, a [rollup or formula field](data-config.md#rollups-and-formulas)) whose column or trigger is missing or out of date, a jobs schema that is missing or behind for a config with [jobs](jobs.md#the-jobs-schema)) (see [`migration`](#migration)), an [AI field or action](ai.md#the-model)) without a model key, or a taken port; `PROTOBASE_STARTUP_CHECKS=false` skips the checks of those schemas and the key. `protobase serve listening on port <port>` means it is ready.
|
|
385
386
|
- **Jobs:** with [jobs](jobs.md)) in the config it runs them beside the API, unless `PROTOBASE_JOBS=false`, and with `PROTOBASE_JOBS_DRAIN_TOKEN` it answers `POST /api/jobs/drain` for the operator.
|
|
386
387
|
- **Shutdown:** the first SIGTERM or SIGINT stops accepting connections, waits for open requests, gives running jobs 30 seconds to finish, drains the pool `serve` created (a `db` the config exports is the project's to close) and exits with 0.
|
|
387
388
|
- **Host modules:** under Bun, the runtime registers [the modules it supplies](#the-config-module) as virtual modules, so the bundle needs no `node_modules` for them. `protobase serve`, on Node or Bun, resolves them from the `node_modules` next to the bundle, so keep the bundle inside the project. Native packages load from the bundle's own `node_modules/` under both.
|
|
@@ -443,7 +444,7 @@ For a project with [organizations](auth.md#organizations)); `<organization>` is
|
|
|
443
444
|
protobase migration [--dir db/migrations] [--extend <dir>]
|
|
444
445
|
```
|
|
445
446
|
|
|
446
|
-
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 `protobase.config.ts` exports `auth` (`NNN_auth.sql`, as [`auth migration`](#auth-migration) writes it), the [jobs schema](jobs.md#the-jobs-schema)) when the config has jobs or a resource has events, history, comments or an [AI field](ai.md)) (`NNN_jobs.sql`), the [capture of events](events.md#migrations-and-startup)) and the [history table](history.md#the-table)) (`NNN_changes.sql`), the [comments table](comments.md#the-table)) (`NNN_comments.sql`), and the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app)) of `webhooks()` (`NNN_webhooks.sql`). It compares the database, with the project's migrations applied, with the config, merged with the configs it extends and 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` unless the config exports `db`.
|
|
447
|
+
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 `protobase.config.ts` exports `auth` (`NNN_auth.sql`, as [`auth migration`](#auth-migration) writes it), the [jobs schema](jobs.md#the-jobs-schema)) when the config has jobs or a resource has events, history, comments or an [AI field](ai.md)) (`NNN_jobs.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)) and the triggers that keep the rollups (`NNN_computed.sql`), the [comments table](comments.md#the-table)) (`NNN_comments.sql`), and the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app)) of `webhooks()` (`NNN_webhooks.sql`). It compares the database, with the project's migrations applied, with the config, merged with the configs it extends and 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` unless the config exports `db`.
|
|
447
448
|
|
|
448
449
|
```sh
|
|
449
450
|
bun run db:migrate # the database at the project's current schema
|
|
@@ -109,6 +109,8 @@ Every option returns a new [field](https://docs.protobase.net/api/schema/interfa
|
|
|
109
109
|
| `.access({ read, create, update })` | Role rules for this column. See [Access](#access). |
|
|
110
110
|
| `.sensitive()` | Hidden like a password: no response carries it, and a caller who may read it reveals one record's value at a time. See [Sensitive fields](#sensitive-fields). |
|
|
111
111
|
| `.ai({ prompt })` | A job fills the field from `prompt`, `{field}` replaced by the record's values, after a create and after an update of a field the prompt reads, as the user who wrote. Text or enum, optional. See [AI fields and actions](ai.md)). |
|
|
112
|
+
| `.rollup({ from, via, fn, field })` | The database keeps the field from the records of another resource: their count, sum, average, least or greatest value. Read-only. See [Rollups and formulas](#rollups-and-formulas). |
|
|
113
|
+
| `.formula(expression)` | The database computes the field from the record's other number fields, as a generated column. Read-only. See [Rollups and formulas](#rollups-and-formulas). |
|
|
112
114
|
|
|
113
115
|
The ERP's products show most of them, together with soft delete and a tenant:
|
|
114
116
|
|
|
@@ -140,6 +142,58 @@ export const products = resource('products')
|
|
|
140
142
|
.access(erpAccess('products'))
|
|
141
143
|
```
|
|
142
144
|
|
|
145
|
+
## Rollups and formulas
|
|
146
|
+
|
|
147
|
+
A **rollup** is a value of the other records that point at a record, such as an order's total of its lines. A **formula** is a value computed from the record's own fields, such as a line's amount. Neither needs SQL: you declare the field, and [`protobase migration`](cli.md#migration)) writes its column into the project's next migration (`NNN_computed.sql`). Both are real columns, kept by the database in the transaction that writes, so they are right for writes from psql or other services too, and they filter and sort like any column once they have an index.
|
|
148
|
+
|
|
149
|
+
```ts title="docs-examples/reference/rollups.ts"
|
|
150
|
+
import { f, resource } from '@protobase/schema'
|
|
151
|
+
|
|
152
|
+
// An order's total and line count kept from its lines, and each line's amount computed from its own fields.
|
|
153
|
+
|
|
154
|
+
/** shop.orders: one row per order. */
|
|
155
|
+
export const orders = resource('orders')
|
|
156
|
+
.table('shop.orders')
|
|
157
|
+
.fields({
|
|
158
|
+
id: f.integer().readOnly().filterable().sortable().dbDefault(),
|
|
159
|
+
customer: f.text(),
|
|
160
|
+
// The sum of its lines' amounts; 0 for an order without lines.
|
|
161
|
+
total: f.decimal({ precision: 12, scale: 2 }).rollup({ from: 'order_lines', via: 'order_id', fn: 'sum', field: 'amount' }).filterable().sortable(),
|
|
162
|
+
line_count: f.integer().rollup({ from: 'order_lines', via: 'order_id', fn: 'count' }),
|
|
163
|
+
// The largest line; empty for an order without lines.
|
|
164
|
+
largest_line: f.decimal({ precision: 12, scale: 2 }).optional().rollup({ from: 'order_lines', via: 'order_id', fn: 'max', field: 'amount' }),
|
|
165
|
+
})
|
|
166
|
+
.primaryKey((r) => r.id)
|
|
167
|
+
|
|
168
|
+
/** shop.order_lines: what each order is for. */
|
|
169
|
+
export const orderLines = resource('order_lines')
|
|
170
|
+
.table('shop.order_lines')
|
|
171
|
+
.fields({
|
|
172
|
+
id: f.integer().readOnly().filterable().dbDefault(),
|
|
173
|
+
order_id: f.relation('orders').filterable(),
|
|
174
|
+
quantity: f.integer().min(1),
|
|
175
|
+
unit_price: f.decimal({ precision: 10, scale: 2 }),
|
|
176
|
+
discount: f.decimal({ precision: 10, scale: 2 }).optional(),
|
|
177
|
+
amount: f.decimal({ precision: 12, scale: 2 }).formula('round(quantity * unit_price - coalesce(discount, 0), 2)'),
|
|
178
|
+
})
|
|
179
|
+
.primaryKey((r) => r.id)
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
`.rollup({ from, via, fn, field })` reads the records of resource `from` whose relation field `via` points at the record. They are the records that are not soft deleted, when `from` has soft delete.
|
|
183
|
+
|
|
184
|
+
| `fn` | Value | Field |
|
|
185
|
+
| --- | --- | --- |
|
|
186
|
+
| `count` | How many records there are; with `field`, how many have a value for it. 0 without records. | `f.integer()` or `f.bigint()` |
|
|
187
|
+
| `sum` | The sum of `field`. 0 without records. | a number field |
|
|
188
|
+
| `avg` | The average of `field`. Empty without records. | `f.decimal()`, `.optional()` |
|
|
189
|
+
| `min`, `max` | The least or greatest value of `field`. Empty without records. | a number field, `.optional()` |
|
|
190
|
+
|
|
191
|
+
Empty values of `field` are left out, as in SQL. The migration adds the column, a function in the `rollups` schema and a trigger on `from`'s table that sets the value after every insert, delete and update of the columns it reads, and then sets every record's value once. A rollup over its own table, a resource with a key of several columns, or a relation of several columns is not supported yet.
|
|
192
|
+
|
|
193
|
+
`.formula(expression)` is a Postgres generated column. The expression reads the record's number fields, and takes numbers, `+ - * /`, parentheses, `coalesce(a, b, ...)` and `round(x)` or `round(x, digits)`. It is computed exactly as decimals, so `7 / 2` is 3.5, and is stored as the field's type, so an integer field rounds the result. A formula that reads an optional field is `.optional()` too, unless `coalesce()` gives that field a value. A formula cannot read another formula. When the expression changes, the migration drops the column and adds it again, so an index on it must be created again in the same migration.
|
|
194
|
+
|
|
195
|
+
Neither field can be written through the API, have a default, or be sensitive. The server does not start while a declared column, function or trigger is missing or out of date, with a message that names the fields; the migration fixes that. It stops with an error, without writing anything, when the column already exists as the project's own: a plain column where a formula is declared, a generated column it did not write, or a rollup column of another type.
|
|
196
|
+
|
|
143
197
|
## Sensitive fields
|
|
144
198
|
|
|
145
199
|
A sensitive field, such as a bank account number, is written like any other field but never read with the record: lists, gets, `:search`, `:seek`, create and update responses and batch results leave it out, and it cannot be filtered, sorted, searched, counted or picked with `fields`. The record page shows it masked, with an eye button. Showing it asks the server for that one value with `POST /{resource}/{key}:reveal` (see [REST API](api.md#sensitive-fields-and-audit))), which needs the same access as reading the record and the field, inside the caller's tenant, and publishes an audit event before it answers.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
<!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/installable-app.md: run `bun run docs:skill`, do not edit. -->
|
|
2
|
+
|
|
3
|
+
# Installable app
|
|
4
|
+
|
|
5
|
+
The admin app installs as an app of its own on phones and computers, named for the app, and opens without a network to say the server is out of reach.
|
|
6
|
+
|
|
7
|
+
Every app built with `protobase build` can be installed from the browser, as a Progressive Web App: Chrome and Edge offer **Install** in the address bar, Android's browsers **Add to home screen**, and Safari on iPhone and iPad **Share > Add to Home Screen**. The installed app opens in a window of its own, without the browser's toolbars, at the app's home page.
|
|
8
|
+
|
|
9
|
+
There is nothing to set up. The app installs under its name, `appName` or `PROTOBASE_APP_NAME` (see [auth configuration](auth.md#configuration))), with its favicon, `protobase.favicon.svg` (see [Logo and favicon](theme.md#logo-and-favicon))), as its icon. Safari takes no SVG icon and shows a picture of the page on the home screen instead.
|
|
10
|
+
|
|
11
|
+
## The manifest
|
|
12
|
+
|
|
13
|
+
The app's page links its web app manifest at `/api/manifest.webmanifest`, which the server answers to anyone, without a token:
|
|
14
|
+
|
|
15
|
+
```json
|
|
16
|
+
{
|
|
17
|
+
"name": "Property Finder",
|
|
18
|
+
"short_name": "Property Finder",
|
|
19
|
+
"id": "/",
|
|
20
|
+
"start_url": "/",
|
|
21
|
+
"scope": "/",
|
|
22
|
+
"display": "standalone",
|
|
23
|
+
"icons": [{ "src": "/protobase.favicon.svg", "sizes": "any", "type": "image/svg+xml" }]
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Without a network
|
|
28
|
+
|
|
29
|
+
The data stays online: the installed app reads and writes through the API as the browser tab does, and nothing works offline. The page registers a service worker, `/protobase.sw.js` in the bundle's `public/`, which keeps only the app itself, so the app still opens without a network and says it cannot reach the server.
|
|
30
|
+
|
|
31
|
+
- A page always comes from the server while it answers, and from the cache only when the network fails.
|
|
32
|
+
- The files under `/assets`, named by their content, come from the cache once loaded. The page and what it loads first are cached when the worker installs.
|
|
33
|
+
- The theme and the favicon come from the server, with the cached copy used when the network fails.
|
|
34
|
+
- Nothing else is cached: the API, the plugins and other sites go to the network as without the worker.
|
|
35
|
+
|
|
36
|
+
Each build of the app has its own worker, which replaces the previous one and drops its cache on the next visit. `protobase dev` registers no worker, so the dev server's changes always show.
|