@protobase/cli 0.50.1 → 0.51.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/cli/package.js +1 -1
  2. package/dist/db/model.d.ts +43 -0
  3. package/dist/doctor/check.js +1 -1
  4. package/dist/doctor/run.js +1 -1
  5. package/dist/infer/defaults.d.ts +3 -0
  6. package/dist/infer/proposal.d.ts +24 -0
  7. package/dist/infer/proposal.js +3 -3
  8. package/dist/infer/type-map.d.ts +3 -0
  9. package/dist/project/project-types.js +6 -2
  10. package/dist/scaffold/drift.d.ts +9 -0
  11. package/dist/scaffold/drift.js +1 -1
  12. package/dist/scaffold/existing-config.d.ts +1 -0
  13. package/dist/scaffold/plan.d.ts +17 -0
  14. package/dist/scaffold/plan.js +1 -1
  15. package/dist/scaffold/prompt.d.ts +11 -0
  16. package/dist/scaffold/prompt.js +18 -17
  17. package/dist/scaffold/protobase-tables.d.ts +8 -0
  18. package/dist/scaffold/run.d.ts +17 -0
  19. package/dist/scaffold/run.js +4 -3
  20. package/dist/scaffold/tables.d.ts +17 -0
  21. package/dist/scaffold/tables.js +47 -0
  22. package/dist/scaffold/ui-file.d.ts +3 -0
  23. package/dist/scaffold-api.d.ts +4 -0
  24. package/dist/scaffold-api.js +4 -0
  25. package/dist/serve/host-modules.js +3 -3
  26. package/dist/supabase/load-phase.js +2 -2
  27. package/package.json +9 -8
  28. package/skills/protobase/references/features/start-a-project.md +1 -0
  29. package/skills/protobase/references/getting-started.md +29 -2
  30. package/skills/protobase/references/guides/existing-database.md +2 -0
  31. package/skills/protobase/references/reference/access.md +12 -0
  32. package/skills/protobase/references/reference/architecture.md +2 -2
  33. package/skills/protobase/references/reference/assistant.md +1 -1
  34. package/skills/protobase/references/reference/cli.md +3 -1
  35. package/skills/protobase/references/reference/data-config.md +1 -1
  36. package/skills/protobase/references/reference/languages.md +3 -1
  37. package/skills/protobase/references/reference/mcp.md +3 -3
  38. package/skills/protobase/references/reference/supabase-rest.md +1 -1
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.50.1";
2
+ var version = "0.51.1";
3
3
  //#endregion
4
4
  export { version };
@@ -0,0 +1,43 @@
1
+ //#region src/db/model.d.ts
2
+ export type DbColumn = {
3
+ name: string;
4
+ position: number;
5
+ typeName: string;
6
+ formatted: string;
7
+ isEnum: boolean;
8
+ enumValues: string[];
9
+ notNull: boolean;
10
+ identity: boolean;
11
+ identityAlways: boolean;
12
+ generated: boolean;
13
+ defaultExpr?: string;
14
+ };
15
+ export type DbForeignKey = {
16
+ columns: string[];
17
+ refSchema: string;
18
+ refTable: string;
19
+ refColumns: string[];
20
+ };
21
+ export type DbIndex = {
22
+ name: string;
23
+ columns: (string | null)[];
24
+ unique: boolean;
25
+ primary: boolean;
26
+ partial: boolean;
27
+ method: string;
28
+ opclasses: string[];
29
+ };
30
+ export type DbCheck = {
31
+ columns: string[];
32
+ definition: string;
33
+ };
34
+ export type DbTable = {
35
+ schema: string;
36
+ name: string;
37
+ kind: 'table' | 'view' | 'materialized view';
38
+ columns: DbColumn[];
39
+ foreignKeys: DbForeignKey[];
40
+ indexes: DbIndex[];
41
+ checks: DbCheck[];
42
+ };
43
+ //#endregion
@@ -1,9 +1,9 @@
1
1
  import { tableKey } from "../db/model.js";
2
2
  import { isUniqueSet, keyColumns } from "../db/keys.js";
3
3
  import { checkEnumValues } from "../infer/check-values.js";
4
- import { typesCompatible } from "../infer/compat.js";
5
4
  import { columnDefault } from "../infer/defaults.js";
6
5
  import { inferKind } from "../infer/type-map.js";
6
+ import { typesCompatible } from "../infer/compat.js";
7
7
  //#region src/doctor/check.ts
8
8
  const quoteIdent = (name) => /^[a-z_][a-z0-9_]*$/.test(name) ? name : `"${name.replaceAll("\"", "\"\"")}"`;
9
9
  const sameValues = (a = [], b = []) => a.length === b.length && a.every((v) => b.includes(v));
@@ -1,6 +1,6 @@
1
- import { loadDataConfig } from "../project/load-data-config.js";
2
1
  import { connect } from "../db/connect.js";
3
2
  import { introspect } from "../db/introspect.js";
3
+ import { loadDataConfig } from "../project/load-data-config.js";
4
4
  import { readOnlyDb } from "../db/read-only-db.js";
5
5
  import { checkResource } from "./check.js";
6
6
  import { indexIssues } from "./index-issues.js";
@@ -0,0 +1,3 @@
1
+ //#region src/infer/defaults.d.ts
2
+ export type DefaultValue = string | number | boolean;
3
+ //#endregion
@@ -0,0 +1,24 @@
1
+ import { BaseType } from "./type-map.js";
2
+ import { DefaultValue } from "./defaults.js";
3
+ //#region src/infer/proposal.d.ts
4
+ export type FieldType = BaseType | 'relation' | 'currency' | 'country';
5
+ export type Proposal = {
6
+ name: string;
7
+ column: string;
8
+ type: FieldType;
9
+ base: BaseType;
10
+ precision?: number;
11
+ scale?: number;
12
+ enumValues?: string[];
13
+ relation?: {
14
+ resource: string;
15
+ columns?: string[];
16
+ };
17
+ optional: boolean;
18
+ defaultValue?: DefaultValue;
19
+ readOnly: boolean;
20
+ dbDefault?: boolean;
21
+ filterable: boolean;
22
+ sortable: boolean;
23
+ };
24
+ //#endregion
@@ -1,10 +1,10 @@
1
1
  import { coverageIndexes } from "../db/keys.js";
2
- import { checkEnumValues } from "./check-values.js";
3
- import { columnDefault } from "./defaults.js";
4
- import { inferKind } from "./type-map.js";
5
2
  import { defaultColumn } from "./default-column.js";
6
3
  import { snakeName } from "./names.js";
7
4
  import { isTenantColumn } from "./tenant.js";
5
+ import { checkEnumValues } from "./check-values.js";
6
+ import { columnDefault } from "./defaults.js";
7
+ import { inferKind } from "./type-map.js";
8
8
  import { indexServes } from "@protobase/query";
9
9
  //#region src/infer/proposal.ts
10
10
  const columnIndexing = (table, column, type) => {
@@ -0,0 +1,3 @@
1
+ //#region src/infer/type-map.d.ts
2
+ export type BaseType = 'integer' | 'bigint' | 'decimal' | 'text' | 'boolean' | 'date' | 'timestamp' | 'uuid' | 'json' | 'enum';
3
+ //#endregion
@@ -52,7 +52,8 @@ const cliTypePaths = (ownDir = cliDir) => Object.fromEntries(typedPackages.flatM
52
52
  * Writes `.protobase/tsconfig.json` in `projectDir`, which the project's tsconfig.json extends: in a bundled project
53
53
  * its `paths` give the @protobase packages and those the serve runtime supplies the types of the CLI that builds the
54
54
  * app, with nothing installed; a locked project's installed packages type themselves, so it holds no paths. The
55
- * folder ignores itself in git, since the paths are this machine's.
55
+ * folder ignores itself in git, since the paths are this machine's. An unchanged file is left alone: Vite reloads every
56
+ * module on any write to a tsconfig.json, so another command rewriting it would rebuild a running dev server's API.
56
57
  */
57
58
  const writeProjectTypes = async (projectDir) => {
58
59
  const folder = path.join(projectDir, protobaseFolder);
@@ -60,7 +61,10 @@ const writeProjectTypes = async (projectDir) => {
60
61
  const ignore = path.join(folder, ".gitignore");
61
62
  if (!existsSync(ignore)) await writeFile(ignore, "*\n");
62
63
  const compilerOptions = projectPackages(projectDir).mode === "bundled" ? { paths: cliTypePaths() } : {};
63
- await writeFile(path.join(projectDir, typesFile), `${JSON.stringify({ compilerOptions }, null, 2)}\n`);
64
+ const file = path.join(projectDir, typesFile);
65
+ const content = `${JSON.stringify({ compilerOptions }, null, 2)}\n`;
66
+ if (existsSync(file) && readFileSync(file, "utf8") === content) return;
67
+ await writeFile(file, content);
64
68
  };
65
69
  //#endregion
66
70
  export { cliTypePaths, typesFile, writeProjectTypes };
@@ -0,0 +1,9 @@
1
+ import "./existing-config.js";
2
+ //#region src/scaffold/drift.d.ts
3
+ export type Drift = {
4
+ resource: string;
5
+ field: string;
6
+ problem: string;
7
+ suggestion: string;
8
+ };
9
+ //#endregion
@@ -1,6 +1,6 @@
1
- import { typesCompatible } from "../infer/compat.js";
2
1
  import { proposeField } from "../infer/proposal.js";
3
2
  import { renderField } from "../infer/render-field.js";
3
+ import { typesCompatible } from "../infer/compat.js";
4
4
  //#region src/scaffold/drift.ts
5
5
  const sameValues = (a = [], b = []) => a.length === b.length && a.every((v) => b.includes(v));
6
6
  const detectDrift = (existing, table, context) => existing.fields.filter((field) => !field.ignored).flatMap((field) => {
@@ -0,0 +1 @@
1
+ import "ts-morph";
@@ -0,0 +1,17 @@
1
+ import "./existing-config.js";
2
+ import { Drift } from "./drift.js";
3
+ import { ProtobaseSchema } from "./protobase-tables.js";
4
+ //#region src/scaffold/plan.d.ts
5
+ export type FileChange = {
6
+ path: string;
7
+ before?: string;
8
+ after: string;
9
+ };
10
+ export type ScaffoldPlan = {
11
+ changes: FileChange[];
12
+ drift: Drift[];
13
+ warnings: string[];
14
+ skipped: ProtobaseSchema[];
15
+ live: string[];
16
+ };
17
+ //#endregion
@@ -1,5 +1,6 @@
1
1
  import { tableKey } from "../db/model.js";
2
2
  import { keyColumns } from "../db/keys.js";
3
+ import { protobaseSchemas } from "./protobase-tables.js";
3
4
  import { camelCase } from "../infer/names.js";
4
5
  import { findField } from "./existing-config.js";
5
6
  import { proposeField } from "../infer/proposal.js";
@@ -8,7 +9,6 @@ import { detectDrift } from "./drift.js";
8
9
  import { ensureExports } from "./index-file.js";
9
10
  import { assignNames } from "./resource-names.js";
10
11
  import { planResource } from "./resource-plan.js";
11
- import { protobaseSchemas } from "./protobase-tables.js";
12
12
  import { dependencyOrder } from "./table-order.js";
13
13
  import { isExcluded, matchesTarget } from "./targets.js";
14
14
  import { uiFields } from "./ui-fields.js";
@@ -0,0 +1,11 @@
1
+ import { Proposal } from "../infer/proposal.js";
2
+ //#region src/scaffold/prompt.d.ts
3
+ export type DecideContext = {
4
+ table: string;
5
+ required: boolean;
6
+ };
7
+ export type Decide = (proposal: Proposal, context: DecideContext) => Promise<Proposal | null>;
8
+ type Ask = (question: string) => Promise<string>;
9
+ type Write = (text: string) => void;
10
+ export declare const asking: (ask: Ask, write: Write) => Decide;
11
+ //#endregion
@@ -17,12 +17,12 @@ const types = [
17
17
  "currency",
18
18
  "country"
19
19
  ];
20
- const retype = async (proposal, ask) => {
20
+ const retype = async (proposal, ask, write) => {
21
21
  const answer = (await ask(` type (${types.join(", ")}) [${proposal.type}]: `)).trim();
22
22
  if (!answer || answer === proposal.type) return proposal;
23
23
  const type = types.find((t) => t === answer);
24
24
  if (!type) {
25
- process.stdout.write(` unknown type "${answer}", keeping ${proposal.type}\n`);
25
+ write(` unknown type "${answer}", keeping ${proposal.type}\n`);
26
26
  return proposal;
27
27
  }
28
28
  const { enumValues, relation, precision, scale, defaultValue, ...rest } = proposal;
@@ -38,40 +38,41 @@ const retype = async (proposal, ask) => {
38
38
  }
39
39
  return next;
40
40
  };
41
- const edit = async (proposal, ask) => {
41
+ const edit = async (proposal, ask, write) => {
42
42
  const name = (await ask(` field name [${proposal.name}]: `)).trim() || proposal.name;
43
43
  return retype({
44
44
  ...proposal,
45
45
  name
46
- }, ask);
46
+ }, ask, write);
47
47
  };
48
- const interactive = (input = process.stdin, output = process.stdout) => {
49
- const rl = createInterface({
50
- input,
51
- output
52
- });
48
+ const asking = (ask, write) => {
53
49
  let acceptRest = false;
54
- const decide = async (initial, { table, required }) => {
50
+ return async (initial, { table, required }) => {
55
51
  if (acceptRest) return initial;
56
52
  let proposal = initial;
57
53
  for (;;) {
58
- output.write(`\n${table}.${proposal.column}\n ${proposal.name}: ${renderField(proposal)}\n`);
59
- const options = required ? "[a]ccept, accept a[l]l, [e]dit" : "[a]ccept, accept a[l]l, [e]dit, [i]gnore";
60
- const answer = (await rl.question(` ${options} (a): `)).trim().toLowerCase() || "a";
54
+ write(`\n${table}.${proposal.column}\n ${proposal.name}: ${renderField(proposal)}\n`);
55
+ const answer = (await ask(` ${required ? "[a]ccept, accept a[l]l, [e]dit" : "[a]ccept, accept a[l]l, [e]dit, [i]gnore"} (a): `)).trim().toLowerCase() || "a";
61
56
  if (answer === "a") return proposal;
62
57
  if (answer === "l") {
63
58
  acceptRest = true;
64
- output.write(" accepting this and every remaining proposal\n");
59
+ write(" accepting this and every remaining proposal\n");
65
60
  return proposal;
66
61
  }
67
- if (answer === "e") proposal = await edit(proposal, (q) => rl.question(q));
62
+ if (answer === "e") proposal = await edit(proposal, ask, write);
68
63
  if (answer === "i" && !required) return null;
69
64
  }
70
65
  };
66
+ };
67
+ const interactive = (input = process.stdin, output = process.stdout) => {
68
+ const rl = createInterface({
69
+ input,
70
+ output
71
+ });
71
72
  return {
72
- decide,
73
+ decide: asking((q) => rl.question(q), (text) => output.write(text)),
73
74
  close: () => rl.close()
74
75
  };
75
76
  };
76
77
  //#endregion
77
- export { acceptAll, interactive };
78
+ export { acceptAll, asking, interactive };
@@ -0,0 +1,8 @@
1
+ import { DbTable } from "../db/model.js";
2
+ //#region src/scaffold/protobase-tables.d.ts
3
+ export type ProtobaseSchema = {
4
+ schema: string;
5
+ what: 'auth store' | 'job queue';
6
+ tables: DbTable[];
7
+ };
8
+ //#endregion
@@ -0,0 +1,17 @@
1
+ import { Decide } from "./prompt.js";
2
+ import { UiSection } from "./ui-file.js";
3
+ import { ScaffoldPlan } from "./plan.js";
4
+ //#region src/scaffold/run.d.ts
5
+ export type ScaffoldOptions = {
6
+ url: string;
7
+ target?: string;
8
+ configDir: string;
9
+ yes: boolean;
10
+ dryRun: boolean;
11
+ ui: UiSection[];
12
+ excludes: string[];
13
+ live?: string[];
14
+ decide?: Decide;
15
+ };
16
+ export declare const runScaffold: (options: ScaffoldOptions, out: (text: string) => void) => Promise<ScaffoldPlan>;
17
+ //#endregion
@@ -18,9 +18,10 @@ const write = async ({ path: file, after }) => {
18
18
  await writeFile(file, after);
19
19
  };
20
20
  const runScaffold = async (options, out) => {
21
- if (!options.yes && !process.stdin.isTTY) throw new Error("Interactive scaffolding needs a terminal; pass --yes to accept all proposals");
21
+ const asks = !options.yes && !options.decide;
22
+ if (asks && !process.stdin.isTTY) throw new Error("Interactive scaffolding needs a terminal; pass --yes to accept all proposals");
22
23
  const sql = connect(options.url);
23
- const prompter = options.yes ? void 0 : interactive();
24
+ const prompter = asks ? interactive() : void 0;
24
25
  const plan = await (async () => {
25
26
  try {
26
27
  return await planScaffold({
@@ -30,7 +31,7 @@ const runScaffold = async (options, out) => {
30
31
  target: parseTarget(options.target),
31
32
  excludes: options.excludes,
32
33
  live: options.live,
33
- decide: prompter?.decide ?? acceptAll,
34
+ decide: options.decide ?? prompter?.decide ?? acceptAll,
34
35
  ui: options.ui,
35
36
  readText
36
37
  });
@@ -0,0 +1,17 @@
1
+ //#region src/scaffold/tables.d.ts
2
+ /**
3
+ * A table scaffold writes a resource over, with its number of columns and the tables among them its foreign keys point
4
+ * to, as schema.table, whose resources its relations name.
5
+ */
6
+ export type ScaffoldTable = {
7
+ schema: string;
8
+ name: string;
9
+ columns: number;
10
+ references: string[];
11
+ };
12
+ /** `scaffoldTables` of the database at `url`, read in one read-only session. */
13
+ export declare const listTables: (url: string) => Promise<{
14
+ tables: ScaffoldTable[];
15
+ skipped: string[];
16
+ }>;
17
+ //#endregion
@@ -0,0 +1,47 @@
1
+ import { connect } from "../db/connect.js";
2
+ import { tableKey } from "../db/model.js";
3
+ import { introspect } from "../db/introspect.js";
4
+ import { keyColumns } from "../db/keys.js";
5
+ import { protobaseSchemas } from "./protobase-tables.js";
6
+ //#region src/scaffold/tables.ts
7
+ /**
8
+ * The tables of a database without a config yet that scaffold, run on all of them, writes resources over, and what it
9
+ * leaves out, each with why: views, tables without a key, and Protobase's own tables, as one line per schema.
10
+ */
11
+ const scaffoldTables = (relations) => {
12
+ const tables = relations.filter((relation) => relation.kind === "table");
13
+ const protobase = protobaseSchemas(tables, {});
14
+ const isProtobase = (relation) => protobase.some(({ schema, tables }) => tables.includes(relation) || schema !== "public" && schema === relation.schema);
15
+ const own = relations.filter((relation) => !isProtobase(relation));
16
+ const skipped = [
17
+ ...own.filter((relation) => relation.kind !== "table").map((view) => `${tableKey(view)}: a ${view.kind}`),
18
+ ...own.filter((table) => table.kind === "table" && !keyColumns(table)).map((table) => `${tableKey(table)}: no primary key or unique NOT NULL index`),
19
+ ...protobase.map(({ schema, what }) => `schema ${schema}: Protobase's ${what}`)
20
+ ];
21
+ const importable = own.filter((table) => table.kind === "table" && keyColumns(table));
22
+ const keys = new Set(importable.map(tableKey));
23
+ const referencesOf = (table) => [...new Set(table.foreignKeys.map((key) => tableKey({
24
+ schema: key.refSchema,
25
+ name: key.refTable
26
+ })).filter((key) => keys.has(key)))];
27
+ return {
28
+ tables: importable.map((table) => ({
29
+ schema: table.schema,
30
+ name: table.name,
31
+ columns: table.columns.length,
32
+ references: referencesOf(table)
33
+ })).sort((a, b) => tableKey(a).localeCompare(tableKey(b))),
34
+ skipped
35
+ };
36
+ };
37
+ /** `scaffoldTables` of the database at `url`, read in one read-only session. */
38
+ const listTables = async (url) => {
39
+ const sql = connect(url);
40
+ try {
41
+ return scaffoldTables(await introspect(sql, { views: true }));
42
+ } finally {
43
+ await sql.end();
44
+ }
45
+ };
46
+ //#endregion
47
+ export { listTables, scaffoldTables };
@@ -0,0 +1,3 @@
1
+ //#region src/scaffold/ui-file.d.ts
2
+ export type UiSection = 'names' | 'list';
3
+ //#endregion
@@ -0,0 +1,4 @@
1
+ import { ScaffoldTable, listTables } from "./scaffold/tables.js";
2
+ import { asking } from "./scaffold/prompt.js";
3
+ import { ScaffoldOptions, runScaffold } from "./scaffold/run.js";
4
+ export { type ScaffoldOptions, type ScaffoldTable, asking, listTables, runScaffold };
@@ -0,0 +1,4 @@
1
+ import { listTables } from "./scaffold/tables.js";
2
+ import { asking } from "./scaffold/prompt.js";
3
+ import { runScaffold } from "./scaffold/run.js";
4
+ export { asking, listTables, runScaffold };
@@ -2,6 +2,9 @@ import * as pg$1 from "pg";
2
2
  import * as server from "@protobase/server";
3
3
  import * as layout from "@protobase/layout";
4
4
  import * as kysely from "kysely";
5
+ import * as postgres$1 from "postgres";
6
+ import * as schema from "@protobase/schema";
7
+ import * as query from "@protobase/query";
5
8
  import * as nodeServer from "@hono/node-server";
6
9
  import * as hono from "hono";
7
10
  import * as reactEmailRender from "@react-email/render";
@@ -13,13 +16,10 @@ import * as honoHttpException from "hono/http-exception";
13
16
  import * as honoValidator from "hono/validator";
14
17
  import * as jose from "jose";
15
18
  import * as kyselyPostgres from "kysely/helpers/postgres";
16
- import * as postgres$1 from "postgres";
17
19
  import * as react from "react";
18
20
  import * as reactJsxRuntime from "react/jsx-runtime";
19
21
  import * as zod from "zod";
20
22
  import * as protobaseConfig from "@protobase/config";
21
- import * as query from "@protobase/query";
22
- import * as schema from "@protobase/schema";
23
23
  //#region src/serve/host-modules.ts
24
24
  const hostModules = {
25
25
  "@protobase/config": protobaseConfig,
@@ -1,8 +1,8 @@
1
1
  import { loadProjectAuth } from "../users/load-auth.js";
2
- import { writeAuthMigration } from "../auth/write-migration.js";
3
2
  import { connect } from "../db/connect.js";
4
- import { runDoctor } from "../doctor/run.js";
5
3
  import { runScaffold } from "../scaffold/run.js";
4
+ import { writeAuthMigration } from "../auth/write-migration.js";
5
+ import { runDoctor } from "../doctor/run.js";
6
6
  import { convertedCronJobs } from "./cron-plan.js";
7
7
  import { importState } from "./import-state.js";
8
8
  import { writeMigration } from "./migration-files.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.50.1",
3
+ "version": "0.51.1",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -21,7 +21,8 @@
21
21
  },
22
22
  "exports": {
23
23
  "./auth": "./dist/project-auth.js",
24
- "./runner": "./dist/runner.js"
24
+ "./runner": "./dist/runner.js",
25
+ "./scaffold": "./dist/scaffold-api.js"
25
26
  },
26
27
  "bin": {
27
28
  "protobase": "./bin/protobase.mjs"
@@ -41,12 +42,12 @@
41
42
  "dependencies": {
42
43
  "@better-auth/core": "^1.7.12",
43
44
  "@hono/node-server": "^2.1.3",
44
- "@protobase/config": "0.50.1",
45
- "@protobase/layout": "0.50.1",
46
- "@protobase/query": "0.50.1",
47
- "@protobase/schema": "0.50.1",
48
- "@protobase/server": "0.50.1",
49
- "@protobase/ui": "0.50.1",
45
+ "@protobase/config": "0.51.1",
46
+ "@protobase/layout": "0.51.1",
47
+ "@protobase/query": "0.51.1",
48
+ "@protobase/schema": "0.51.1",
49
+ "@protobase/server": "0.51.1",
50
+ "@protobase/ui": "0.51.1",
50
51
  "@react-email/render": "^2.1.0",
51
52
  "@scalar/hono-api-reference": "^0.12.10",
52
53
  "@tailwindcss/vite": "^4.3.3",
@@ -5,6 +5,7 @@
5
5
  Start a new app, or an admin over an existing Postgres database, and keep the config in step with it.
6
6
 
7
7
  - [Project starter](../getting-started.md#start-an-app): `npm create protobase` (also `bun create` and `pnpm create`) starts a new app from the scratch, ERP or real estate preset, with its own Postgres in Docker for development, and prints the next steps. Each preset has an `AGENTS.md` with rules for coding agents.
8
+ - [Start on an existing database](../getting-started.md#on-an-existing-database): `npm create protobase <database-url>` makes a project on a Postgres database you already have and asks which of its tables become resources, only reading the database.
8
9
  - [Example apps](../getting-started.md#run-the-erp-example): Seeded example apps on Postgres: an ERP, real estate property management and a public property portal.
9
10
  - [One config](../reference/config.md): The whole app is one object of data in `protobase.config.ts`, typed with `defineConfig`, with a sensible default for every key.
10
11
  - [Code found by path](../reference/config.md#where-the-code-is): The config names jobs, hooks and providers, and Protobase finds their code by its path, such as `jobs/<name>.ts`.
@@ -2,7 +2,7 @@
2
2
 
3
3
  # Getting started
4
4
 
5
- Start an app with npm create protobase, install the repository, run the ERP, real estate and property portal examples and learn the development commands.
5
+ Start an app with npm create protobase, on a new database or one you have, install the repository, run the ERP, real estate and property portal examples and learn the development commands.
6
6
 
7
7
  Protobase is a config-driven admin panel framework for existing Postgres databases. Each resource's data config lives in `config/<resource>/data.ts` and its UI config in `ui.ts`, all exported from `config/index.ts`; the rest of the app, its sign-in, jobs, files and API settings, is one object of data in [`protobase.config.ts`](reference/config.md). A Hono server serves the API and a React app renders the admin. Coding agents get the guides and reference of the installed version with [`protobase skill install`](reference/cli.md#skill).
8
8
 
@@ -41,9 +41,36 @@ bun run protobase doctor
41
41
 
42
42
  `scaffold` writes `config/customers/data.ts` and `ui.ts` and exports them from `config/index.ts`, where Protobase finds every resource, view and page; `--exclude public.schema_migrations` leaves out the table the migrate script records its migrations in. `bun run dev` shows the new list at once. The [Data config](reference/data-config.md) and [UI config](reference/ui-config.md) say what else a resource can be.
43
43
 
44
+ ### On an existing database
45
+
46
+ Given the URL of a Postgres database you already have, `npm create protobase` makes the project on that database:
47
+
48
+ ```sh
49
+ npm create protobase 'postgres://user:password@localhost:5432/shop'
50
+ bun create protobase 'postgres://user:password@localhost:5432/shop'
51
+ pnpm create protobase 'postgres://user:password@localhost:5432/shop'
52
+ ```
53
+
54
+ It connects read-only and names the database and its Postgres version, then asks for the folder, the database's name by default (`npm create protobase my-app <url>` names it). It writes the scratch preset there, with the URL in `.env`, the URL without its password in `.env.example`, and no `docker-compose.yml`, and installs its packages with Bun, or with npm without Bun. It then lists the tables the project's [`scaffold`](reference/cli.md#scaffold) writes resources over, and what it leaves out, with why: views, tables without a primary key or a unique index on columns that are never null, and Protobase's own tables. It asks:
55
+
56
+ - which tables become resources: numbers, ranges such as `2-4` or names, separated by commas, all of them by default. The tables those point to through foreign keys come too, since a relation needs the resource of its table, and it names them;
57
+ - whether each gets a `ui.ts` with its names and list, yes by default;
58
+ - whether to review the field proposed for each column, as `scaffold` asks it, no by default.
59
+
60
+ Then it runs that `scaffold` in the project and prints the next steps. Without a terminal it asks nothing: the folder is the database's name, and every table gets a resource and a `ui.ts`. Quote the URL, as a shell reads `?` and `&` in it. `--preset` is refused with a URL: the project starts from scratch.
61
+
62
+ It never writes to the database. The first of the next steps does: `bun run db:migrate` adds the `auth` schema that sign-in keeps its users in, and `public.schema_migrations`, where the script records the migrations it applied.
63
+
64
+ ```sh
65
+ cd shop
66
+ bun run db:migrate # the first write to the database
67
+ bun run protobase users create you@example.com --generate-password
68
+ bun run dev # http://localhost:5173
69
+ ```
70
+
44
71
  ## Admin over an existing database
45
72
 
46
- For a Postgres database you already have, [Admin over an existing database](guides/existing-database.md) goes from an empty folder to signing in: install the packages, scaffold the config from the tables, check it with `doctor`, add sign-in and its tables, create the first admin and run `protobase dev`.
73
+ For a Postgres database you already have, `npm create protobase <database-url>` makes the project, as [above](#on-an-existing-database). [Admin over an existing database](guides/existing-database.md) does it by hand, in a folder of your own: install the packages, scaffold the config from the tables, check it with `doctor`, add sign-in and its tables, create the first admin and run `protobase dev`.
47
74
 
48
75
  ## Docs as Markdown
49
76
 
@@ -6,6 +6,8 @@ Put an admin on a Postgres database you already have, in six steps, from install
6
6
 
7
7
  You have a Postgres database and want an admin over its tables, without moving the data. This guide goes from an empty folder to signing in to that admin. It takes about fifteen minutes and needs Node 22.12 or later.
8
8
 
9
+ `npm create protobase <database-url>` does steps 1, 2 and 4 in one go, in a new project, and writes the migration of step 5 for its `bun run db:migrate` to apply: see [On an existing database](../getting-started.md#on-an-existing-database). This guide takes each step by hand, in a folder of your own.
10
+
9
11
  Protobase never changes your tables. Sign-in is the one thing it adds to the database: an `auth` schema with its own tables for users, sessions and signing keys. `protobase migration` writes them as a SQL file you apply yourself, like any other migration, and the app never changes the schema while it runs.
10
12
 
11
13
  ## 1. Install
@@ -190,6 +190,18 @@ export const apps = resource('apps')
190
190
  - **Rows of another organization are read-only in the list.** Their `permissions` say `update: false` and `delete: false`. The admin app opens one by switching the session to its organization first: a record page the session's organization does not have looks the record up across the lists, for a resource with a key of one filterable field, so the page and everything on it are read in the record's own organization.
191
191
  - **Where the memberships come from.** The authenticator of the app's sign-in (`auth`) reads them from the store, once per request that lists across organizations. An [authenticator](auth.md#tokens-and-roles) of your own gives them as the session's `memberships`, a function answering `[{ tenant, roles }]`, and must answer only organizations the person is a member of. Without it, as with `authenticate: { jwksUrl }` instead of `auth`, a list reads the session's organization alone.
192
192
 
193
+ ## Rules that read the record
194
+
195
+ A rule that reads its record, such as `read: (ctx, record) => record.owner_id === ctx.user.id`, is checked against the stored row wherever one record is read or written: a get, a reveal, history, comments, and every update and delete. The resolver calls each rule once without the record to learn whether it needs one; reading the record then, even as `record?.status` or through a default parameter, counts.
196
+
197
+ A list cannot run such a rule on each row without breaking its pages and counts, so a caller for whom the `read` or `list` rule reads the record may not list: a list, `:search`, `:seek`, their counts, aggregates, charts and map, exports, the labels of the records other lists point at, and the assistant's and MCP's list tool answer `403`, and a blocked delete does not name the resource. An explicit `list` rule beside such a `read` is refused too, since nothing proves it is as narrow. A caller whose verdict does not depend on the record, such as an admin under `ctx.user.roles.includes('admin') || record.owner_id === ctx.user.id`, lists as usual. To list, write the rule as a row filter, which a get and a list apply alike:
198
+
199
+ ```ts
200
+ .access({ read: (ctx) => where.eq('owner_id', ctx.user.id) })
201
+ ```
202
+
203
+ <gap>A resource whose read rule reads the record cannot be listed because declaring a row filter as the rule's list form is not implemented.</gap> <gap>A rollup of a readable record counts and adds up related records that their read rule or row filter hides because rollups are not computed per caller.</gap> These rules apply to `/api/v1` and what is built on it; `/api/sb/rest/v1` and its realtime use the tables' grants and RLS policies only.
204
+
193
205
  ## Restricted model and row filters
194
206
 
195
207
  [`resolveAccess`](https://docs.protobase.net/api/schema/functions/resolveaccess/) returns everything a request may do. Use [`restrictModel(model, access)`](https://docs.protobase.net/api/schema/functions/restrictmodel/) for everything user-facing (checking filters and sorts, queries, OpenAPI, `/meta`): hidden fields are gone, so they cannot be referenced, searched, sorted or leaked. Key columns always stay, because records are addressed by them.
@@ -17,9 +17,9 @@ A Bun workspace of npm packages under the `@protobase` scope, in `packages/<name
17
17
  | `@protobase/ui` | `packages/ui` | `@protobase/ui`, `@protobase/ui/theme.css`, `@protobase/ui/styles.css`; the admin app in `src/app` | browser | `schema`, `layout`, `client` |
18
18
  | `@protobase/server` | `packages/server` | `@protobase/server`, `@protobase/server/auth-store`, `@protobase/server/config-exports`, `@protobase/server/email`, `@protobase/server/vapid`; `@protobase/server/internal` for the other packages only | server | `schema`, `layout`, `query` |
19
19
  | `@protobase/config` | `packages/config` | `@protobase/config`, `@protobase/config/schema.json` | anywhere | types of `server` only: it runs nothing besides `defineConfig` |
20
- | `@protobase/cli` | `packages/cli` | the `protobase` command (`bin/protobase.mjs`), `@protobase/cli/auth`, `@protobase/cli/runner` | Node and Bun | `config`, `schema`, `layout`, `query`, `server`, `ui` |
20
+ | `@protobase/cli` | `packages/cli` | the `protobase` command (`bin/protobase.mjs`), `@protobase/cli/auth`, `@protobase/cli/runner`, `@protobase/cli/scaffold` | Node and Bun | `config`, `schema`, `layout`, `query`, `server`, `ui` |
21
21
  | `@protobase/mobile` | `packages/mobile` | none: the Capacitor packages and native plugins `protobase mobile` installs on first use | the app's iOS and Android projects | none |
22
- | `create-protobase` | `packages/create-protobase` | the `create-protobase` command, for `npm create protobase` | Node | none |
22
+ | `create-protobase` | `packages/create-protobase` | the `create-protobase` command, for `npm create protobase` | Node | no other `@protobase` package: `postgres` checks a database URL's connection, and `@protobase/cli/scaffold` is loaded from the project it installed |
23
23
  | `@protobase/presets` | `packages/presets` | none: private, `bun run presets:write` writes a project per preset | Bun | none; each preset depends on the `@protobase` packages of the major it is written at, locked at that version |
24
24
  | `tests/apps/*` | | none | any | `@protobase/*` entry points only |
25
25
 
@@ -68,7 +68,7 @@ Making the query role needs `CREATEROLE` once, for the role that applies the mig
68
68
 
69
69
  `assistant/tools.ts` adds tools of the app's own, which the built-in backend offers after its two: its default export is an array of tools, found by that path when the app starts. A tool is `defineTool({ name, description, parameters, run })` from `@protobase/server`: `parameters` is the JSON Schema of its arguments, and `run(args, context)` returns the text the model reads. A name must be 1 to 64 letters, digits, `_` or `-`, and a name taken twice stops the server at startup. A backend elsewhere has its own tools, so the file does nothing there, nor with `assistant: false`. A tool's `annotations` are MCP's tool hints (`readOnlyHint`, `destructiveHint`, ...), which the dock ignores; the same tools can be offered over the app's [MCP endpoint](mcp.md#building-on-it).
70
70
 
71
- `context` holds the user's `session`, `show(part)` to add a part to the answer, `approve(request)` for an approval card, `conversation` (the dock's, absent over MCP), `resources()` (the resources the user may read, restricted to their fields, with their views), and `records`: `list(resource, params)` with the REST API's list parameters, `get(resource, key)`, `create(resource, data)`, `update(resource, key, data, { etag? })` (without an ETag it updates any version), `delete(resource, key, { etag? })` (soft on a resource with `.softDelete()`) and `softDeleteField(resource)` (the field a delete sets, or `undefined` when a delete removes the record) on the app's resources **as the user**, through their access rules, tenant scope, validation and write hooks, as in the REST API. `get`, `create`, `update` and `delete` each answer `{ record, etag }`, and `list` a page of records. `batch(operations)` runs the operations of a REST [batch write](api.md#batch-writes) in one transaction and answers its `results`; a refusal or a missing record rejects with an `HttpProblem`, whose `detail` a tool can return to the model as text.
71
+ `context` holds the user's `session`, `locale` (the language they read, `'en'` or `'nl'`, for the texts a tool shows them such as its approvals; set over MCP, absent in the dock), `show(part)` to add a part to the answer, `approve(request)` for an approval card, `conversation` (the dock's, absent over MCP), `resources()` (the resources the user may read, restricted to their fields, with their views), and `records`: `list(resource, params)` with the REST API's list parameters, `get(resource, key)`, `create(resource, data)`, `update(resource, key, data, { etag? })` (without an ETag it updates any version), `delete(resource, key, { etag? })` (soft on a resource with `.softDelete()`) and `softDeleteField(resource)` (the field a delete sets, or `undefined` when a delete removes the record) on the app's resources **as the user**, through their access rules, tenant scope, validation and write hooks, as in the REST API. `get`, `create`, `update` and `delete` each answer `{ record, etag }`, and `list` a page of records. `batch(operations)` runs the operations of a REST [batch write](api.md#batch-writes) in one transaction and answers its `results`; a refusal or a missing record rejects with an `HttpProblem`, whose `detail` a tool can return to the model as text.
72
72
 
73
73
  A tool with a [widget](#widget-parts) creates or finds what it is about, shows a widget with its id, and returns the id and the state at that moment:
74
74
 
@@ -25,7 +25,7 @@ In this repository nothing needs a build: the packages' `exports` point at `src`
25
25
 
26
26
  ### In another process
27
27
 
28
- A process that runs many commands, such as a deploy, can run them without starting the CLI each time. `@protobase/cli/runner` exports one function for that; `@protobase/cli/auth` exports the other one a script may call, `loadProjectAuth`, which builds the project's sign-in as the `users` commands do (see [Auth](auth.md#first-run)). Nothing else of the CLI is exported:
28
+ A process that runs many commands, such as a deploy, can run them without starting the CLI each time. `@protobase/cli/runner` exports one function for that; `@protobase/cli/auth` exports the other one a script may call, `loadProjectAuth`, which builds the project's sign-in as the `users` commands do (see [Auth](auth.md#first-run)). `@protobase/cli/scaffold` is [`scaffold`](#scaffold) as functions, for `npm create protobase <database-url>`, which loads it from the project it installed: `listTables`, `runScaffold` and `asking`, its column prompt on a question function of the caller's. Nothing else of the CLI is exported:
29
29
 
30
30
  ```ts
31
31
  import { runCommand } from '@protobase/cli/runner'
@@ -63,6 +63,8 @@ Protobase's own tables are left out, since they hold password hashes, OAuth toke
63
63
  | `--ui-list`, `--ui-section <names\|list>` | write only those `ui.ts` sections |
64
64
  | `--exclude <schema[.table]>` | skip tables, repeatable |
65
65
 
66
+ `npm create protobase <database-url>` runs it in the project it makes, on the tables you pick there (see [On an existing database](../getting-started.md#on-an-existing-database)).
67
+
66
68
  Interactively, each new column shows its proposal: accept, accept all (this one and every one after it, without asking), edit (name, type) or ignore (writes `field: null`; key columns cannot be ignored).
67
69
 
68
70
  The list `--ui` writes shows five columns at most: the key unless it is a uuid, up to two relations, then the other fields but long text, json and audit timestamps. It sorts newest first by a sortable `created_at` (or `inserted_at`, `createdAt`, ...), else by another sortable date or timestamp, else not at all.
@@ -355,7 +355,7 @@ Every builder, option and type that `@protobase/schema` exports has a doc commen
355
355
 
356
356
  Without rules everyone who can sign in may do everything. Rules come in three kinds, and the [Access](access.md) reference explains the defaults:
357
357
 
358
- - **Per operation** (`list`, `read`, `create`, `update`, `delete`): `.access({ update: rule })`. A rule returns `true`, `false`, or an AIP-160 filter that limits the rows, like row-level security. A rule that reads the record (`record.status`) is checked against the stored row.
358
+ - **Per operation** (`list`, `read`, `create`, `update`, `delete`): `.access({ update: rule })`. A rule returns `true`, `false`, or an AIP-160 filter that limits the rows, like row-level security. A rule that reads the record (`record.status`) is checked against the stored row on a get and a write; a caller it reads the record for may not list, so a rule that should list is a filter. See [Rules that read the record](access.md#rules-that-read-the-record).
359
359
  - **Per row**: a filter from a rule, or a `.own` or `.team` capability with `.owner(...)`: `.own` gives the records whose owner is the user, `.team` those owned by the users that `defineRoles(roles, { teamOf: (user) => ids })` returns for them.
360
360
  - **Per field**: `.access({ read, create, update })` on the field. Field rules see only the user, never a record, so the fields a user can read are the same for every row.
361
361
 
@@ -26,4 +26,6 @@ Numbers, amounts and dates use the conventions of the language: English as writt
26
26
 
27
27
  Every built-in screen is translated: the shell with its sidebar, top bar, search, notification bell, profile menu and bottom bar; the list page with all its displays (table, cards, board, calendar, timeline and map), filters, search, sort, imports and exports; the record page with its actions, related lists, history, comments, gallery, saving, conflicts and deleting; the create page and composed pages; saved searches and favorites; the sign-in, sign-up and two-factor screens, the account and sign-in policy pages, and the organization, people and invitation pages; public forms; and the messages, toasts and confirmations around them. So are counts, relative times ("5 minutes ago"), yes, no and the other values the app writes itself, and the notices shown while the app loads.
28
28
 
29
- The texts a plugin or the server writes itself, such as an error message the API sends back or why a plugin could not be loaded, show as they are written.
29
+ The approvals an AI client asks for over [MCP](mcp.md#writes) are translated too, with their buttons and the refusal for a client that cannot ask: in the app's `locale`, or else in the language the client's request accepts.
30
+
31
+ The other texts a plugin or the server writes itself, such as an error message the API sends back or why a plugin could not be loaded, show as they are written.
@@ -70,7 +70,7 @@ export default defineConfig({ auth: { mcp: true }, mcpEndpoint: { writes: true }
70
70
 
71
71
  Each write goes through the REST API as the person: their role's access rules, `validate`, write hooks, events and webhooks apply, so the client can do only what the person may do in the app.
72
72
 
73
- Before each write the client asks the person to approve it, showing the resource and the data, or for a delete the resource, the key and whether the record can be restored, through MCP's form elicitation. For a resource without a soft delete, the approval says plainly that the delete cannot be undone. Nothing is written until they approve, and declining writes nothing. A client's own setting that always allows a tool is not this approval. An approval holds only for the call it was asked for, with the same arguments, by the same person in the same app, organization and client, and only once, within 10 minutes; any other call is asked again. A client that cannot ask, one without form elicitation or one on the 2025 protocol, gets each write refused with a message saying so.
73
+ Before each write the client asks the person to approve it, through MCP's form elicitation. The approval names the record as the record page's breadcrumb does, by the resource's label, its key and its title, such as `Update Task #42 "Fix the sign-in lockout"?`. An update lists each field it changes by its label, with its value before and after (`Status: In flight -> Done`); a create lists the new record's fields by their labels; a delete says whether the record can be restored, and for a resource without a soft delete says plainly that it cannot be undone. Enum values show by their labels, a [sensitive](data-config.md#sensitive-fields) field's value is hidden, and a value is cut at 200 characters. A record or field the person may not read is named by its key or its name in words, and an update or delete of a record changed since its `etag` is refused before asking. The approval, its button and the refusal for a client that cannot ask are in the person's [language](languages.md): the app's `locale`, or else the one the client's request accepts (`Accept-Language`). Nothing is written until they approve, and declining writes nothing. A client's own setting that always allows a tool is not this approval. An approval holds only for the call it was asked for, with the same arguments, by the same person in the same app, organization and client, and only once, within 10 minutes; any other call is asked again. A client that cannot ask, one without form elicitation or one on the 2025 protocol, gets each write refused with a message saying so.
74
74
 
75
75
  <gap>An approval cannot be answered on another server instance or after a restart because a shared approval store is not implemented.</gap> Behind a load balancer, send an MCP client's calls to the same instance.
76
76
 
@@ -125,8 +125,8 @@ The endpoint serves each request on its own, without an MCP session: a `GET` or
125
125
 
126
126
  `@protobase/server` exports the pieces the endpoint is made of, for an MCP server of your own with tools of your own:
127
127
 
128
- - `mcpHandler({ authenticate, resource, scope, server })`: the endpoint as a fetch handler. It checks the host, admits a valid token (`mcpGate`) and serves the request with the server that `server(session)` builds for its caller.
129
- - `mcpServer({ info, tools, context, report, rolesWithoutApproval, approvals })`: an MCP server offering [assistant tools](assistant.md#the-apps-own-tools), each with its JSON Schema and its `annotations`, MCP's tool hints. `context` is the tools' context without `approve`: each call gets its own, which asks the client's user, or approves at once when the session's user holds one of `rolesWithoutApproval`. `approvals` is `mcpApprovals()`, built once and passed to every server the endpoint builds: it keeps the approvals asked for until they are answered or expire.
128
+ - `mcpHandler({ authenticate, resource, scope, server })`: the endpoint as a fetch handler. It checks the host, admits a valid token (`mcpGate`) and serves the request with the server that `server(session, request)` builds for its caller; `request` is the HTTP request, such as for the language the person reads.
129
+ - `mcpServer({ info, tools, context, report, rolesWithoutApproval, approvals })`: an MCP server offering [assistant tools](assistant.md#the-apps-own-tools), each with its JSON Schema and its `annotations`, MCP's tool hints. `context` is the tools' context without `approve`, with the `locale` its approvals are asked in (English when absent): each call gets its own, which asks the client's user, or approves at once when the session's user holds one of `rolesWithoutApproval`. `approvals` is `mcpApprovals()`, built once and passed to every server the endpoint builds: it keeps the approvals asked for until they are answered or expire.
130
130
  - `mcpTools({ db, sql, writes })`: the default tools for a session; `writes` is `true`, `false` or `{ resources, rolesWithoutApproval }`.
131
131
  - `readRecordTools()`, or `listResourcesTool()`, `listRecordsTool()` and `getRecordTool()`: the read tools alone; `readOnlyQueryTool(db)` is `run_read_only_query`, and `readWriteQueryTool(db)` proposes one write statement that the user approves before it runs.
132
132
  - `writeRecordTools({ resources })`, or `createRecordTool(...)`, `updateRecordTool(...)` and `deleteRecordTool(...)`: the single write tools alone, on the listed resources or, without `resources`, on any; `batchWriteTool({ resources })` is `batch_write` alone.
@@ -23,7 +23,7 @@ The keys are `apiKeys` in `protobase.config.ts`, `{ publishable_key, secret_key
23
23
  | either key and a signed-in user's token | `authenticated` |
24
24
  | the secret key | the app's own role, which owns the tables |
25
25
 
26
- The transaction sets the role with `SET LOCAL ROLE` and the token's claims in `request.jwt.claims` and `request.jwt.claim.sub`, so Supabase's `auth.uid()`, `auth.role()` and `auth.jwt()` work, and the tables' RLS policies decide what the request may read and write. The `role` claim is the database role, as on Supabase. The database needs the `anon` and `authenticated` roles, and the app's role must be allowed to `SET ROLE` to them.
26
+ The transaction sets the role with `SET LOCAL ROLE` and the token's claims in `request.jwt.claims` and `request.jwt.claim.sub`, so Supabase's `auth.uid()`, `auth.role()` and `auth.jwt()` work, and the tables' RLS policies decide what the request may read and write. The resources' access rules (`.access(...)`) do not apply here: a table needs its own grants and policies, and one without a grant to `anon` or `authenticated` refuses them. The `role` claim is the database role, as on Supabase. The database needs the `anon` and `authenticated` roles, and the app's role must be allowed to `SET ROLE` to them.
27
27
 
28
28
  `/api/sb/rest/v1` serves the tables the app declares as resources, in the `public` schema, under their table names. Any other table is `404`.
29
29