@protobase/cli 0.122.1 → 0.123.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/auth/migration-file.js +3 -1
  2. package/dist/auth/register.js +1 -0
  3. package/dist/auth/write-migration.js +27 -10
  4. package/dist/cli/package.js +1 -1
  5. package/dist/dev/dev-relay.js +1 -1
  6. package/dist/doctor/startup.js +1 -1
  7. package/dist/main.js +1 -1
  8. package/dist/migration/load-project.js +6 -7
  9. package/dist/migration/migrate-project.js +5 -3
  10. package/dist/migration/parts.js +5 -8
  11. package/dist/migration/plan-migrations.js +25 -0
  12. package/dist/migration/register.js +75 -11
  13. package/dist/migration/snapshot/auth-difference.js +37 -0
  14. package/dist/migration/snapshot/auth-target.js +13 -0
  15. package/dist/migration/snapshot/check.js +26 -0
  16. package/dist/migration/snapshot/consistency.js +29 -0
  17. package/dist/migration/snapshot/custom.js +39 -0
  18. package/dist/migration/snapshot/drop.js +64 -0
  19. package/dist/migration/snapshot/header.js +34 -0
  20. package/dist/migration/snapshot/lint-custom.js +23 -0
  21. package/dist/migration/snapshot/migration-files.js +30 -0
  22. package/dist/migration/snapshot/next-snapshot.js +40 -0
  23. package/dist/migration/snapshot/preconditions.js +25 -0
  24. package/dist/migration/snapshot/run-migration.js +50 -0
  25. package/dist/migration/snapshot/snapshot-file.js +33 -0
  26. package/dist/migration/snapshot/up.js +24 -0
  27. package/dist/migration/snapshot/write-file.js +24 -0
  28. package/dist/migration/summary.js +6 -6
  29. package/dist/supabase/dump-phase.js +3 -2
  30. package/dist/supabase/load-phase.js +5 -0
  31. package/dist/supabase/project-users.js +4 -3
  32. package/dist/supabase/storage-copy.js +1 -1
  33. package/dist/supabase/store-migrations.js +42 -4
  34. package/dist/users/password.js +1 -1
  35. package/package.json +9 -8
  36. package/skills/protobase/references/features/build-and-run.md +2 -1
  37. package/skills/protobase/references/features/data-model.md +1 -0
  38. package/skills/protobase/references/features/email-and-public-forms.md +1 -1
  39. package/skills/protobase/references/reference/api.md +1 -1
  40. package/skills/protobase/references/reference/auth.md +1 -1
  41. package/skills/protobase/references/reference/cli.md +25 -6
  42. package/skills/protobase/references/reference/config/api.md +9 -1
  43. package/skills/protobase/references/reference/data-config.md +36 -0
  44. package/skills/protobase/references/reference/email.md +4 -3
  45. package/dist/migration/write-migrations.js +0 -32
@@ -0,0 +1,40 @@
1
+ import { modelHash } from "./snapshot-file.js";
2
+ import { lastStepsOf } from "./auth-difference.js";
3
+ import { storeNamesList } from "@protobase/server/internal";
4
+ //#region src/migration/snapshot/next-snapshot.ts
5
+ /** The snapshot once the migration `endsAt` is applied: `auth`, the store's model then, and whether organizations are on now. */
6
+ const nextSnapshot = (previous, auth, organizationsOn, endsAt, protobaseVersion) => {
7
+ const model = auth ? { auth } : {};
8
+ return {
9
+ format: 1,
10
+ protobaseVersion,
11
+ endsAt,
12
+ modelHash: modelHash(model),
13
+ model,
14
+ decisions: {
15
+ modules: previous?.decisions.modules ?? {
16
+ kept: [],
17
+ archived: []
18
+ },
19
+ organizations: {
20
+ everOn: (previous?.decisions.organizations.everOn ?? false) || organizationsOn,
21
+ defaultOrganization: previous?.decisions.organizations.defaultOrganization ?? null
22
+ }
23
+ },
24
+ physical: auth ? { auth: storeNamesList(auth) } : {}
25
+ };
26
+ };
27
+ /** The header of the migration a snapshot ends at. */
28
+ const snapshotHeader = (snapshot, kind = {
29
+ custom: false,
30
+ additive: false
31
+ }) => ({
32
+ id: snapshot.endsAt.id,
33
+ version: snapshot.protobaseVersion,
34
+ steps: snapshot.model.auth ? lastStepsOf(snapshot.model.auth) : {},
35
+ model: snapshot.modelHash,
36
+ organizationsEverOn: snapshot.decisions.organizations.everOn,
37
+ ...kind
38
+ });
39
+ //#endregion
40
+ export { nextSnapshot, snapshotHeader };
@@ -0,0 +1,25 @@
1
+ import postgres from "postgres";
2
+ //#region src/migration/snapshot/preconditions.ts
3
+ const undefinedTable = "42P01";
4
+ /**
5
+ * Runs the steps' checks against the database at `url`, in a read-only transaction: a check refuses when the rows
6
+ * already there break what its step assumes, such as two accounts with one provider and account id.
7
+ */
8
+ const runPreconditions = async (url, checks) => {
9
+ const sql = postgres(url, {
10
+ max: 1,
11
+ onnotice: () => {}
12
+ });
13
+ try {
14
+ await sql.begin("read only", async (tx) => {
15
+ for (const check of checks) await tx.unsafe(check);
16
+ });
17
+ } catch (error) {
18
+ if (error.code !== undefinedTable) throw error;
19
+ throw new Error("The database lacks a table of the auth store that the snapshot has: apply the project's migrations to it first, or unset DATABASE_URL to write the migration without checking its rows");
20
+ } finally {
21
+ await sql.end();
22
+ }
23
+ };
24
+ //#endregion
25
+ export { runPreconditions };
@@ -0,0 +1,50 @@
1
+ import { readSnapshot, snapshotFile } from "./snapshot-file.js";
2
+ import { readMigrationFiles } from "./migration-files.js";
3
+ import { refuseInconsistent } from "./consistency.js";
4
+ import { authMigrationTitle } from "../../auth/migration-file.js";
5
+ import { authDifference } from "./auth-difference.js";
6
+ import { writeMigrationFile } from "./write-file.js";
7
+ import { runPreconditions } from "./preconditions.js";
8
+ //#region src/migration/snapshot/run-migration.ts
9
+ const section = (title, sql) => `-- ${title}.\n${sql}\n`;
10
+ /** The line `protobase migration`'s files open with, under their header. */
11
+ const intro = `-- Written by \`protobase migration\` from the config and ${snapshotFile}; applied with the project's other migrations.\n`;
12
+ /**
13
+ * `protobase migration`: writes what the config needs as the project's next migration, one file, and rewrites the
14
+ * snapshot to end at it. The auth store's steps come from the snapshot alone; with a database, their checks run against
15
+ * its rows, and the other parts are compared with it. Every part is compared before anything is written. Returns the
16
+ * file's path, `undefined` when nothing differs.
17
+ */
18
+ const runMigration = async ({ projectDir, dir, auth, database, protobaseVersion, newId }) => {
19
+ const snapshot = await readSnapshot(projectDir);
20
+ const files = await readMigrationFiles(dir);
21
+ refuseInconsistent(snapshot, files);
22
+ if (!snapshot && auth && files.some(({ text }) => text.includes("The auth schema changes this version of Protobase needs"))) throw new Error(`The project has auth migrations from before ${snapshotFile}: start it with \`protobase auth migration\`, run against the database with the project's migrations applied, then run \`protobase migration\` again`);
23
+ const difference = authDifference(snapshot, auth);
24
+ if (database && difference.migration && difference.migration.checks.length > 0) await runPreconditions(database.url, difference.migration.checks);
25
+ const compared = [];
26
+ for (const part of database?.parts ?? []) {
27
+ const sql = await part.sql();
28
+ if (sql !== void 0) compared.push({
29
+ name: part.name,
30
+ text: section(part.title, sql)
31
+ });
32
+ }
33
+ const sections = [...difference.migration ? [{
34
+ name: "auth",
35
+ text: section(authMigrationTitle, difference.migration.sql)
36
+ }] : [], ...compared];
37
+ if (sections.length === 0) return;
38
+ const content = {
39
+ name: sections.map(({ name }) => name).join("_"),
40
+ body: [intro, ...sections.map(({ text }) => text)].join("\n")
41
+ };
42
+ return writeMigrationFile(projectDir, dir, content, {
43
+ previous: snapshot,
44
+ auth: difference.model,
45
+ organizationsOn: auth?.organizationsOn ?? false,
46
+ protobaseVersion
47
+ }, newId());
48
+ };
49
+ //#endregion
50
+ export { intro, runMigration };
@@ -0,0 +1,33 @@
1
+ import { existsSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { readFile, rm, writeFile } from "node:fs/promises";
5
+ //#region src/migration/snapshot/snapshot-file.ts
6
+ const snapshotFile = "protobase.snapshot.json";
7
+ const modelHash = (model) => createHash("sha256").update(JSON.stringify(model)).digest("hex");
8
+ /** The file's text: two-space JSON and a final newline, so the same snapshot is the same bytes. */
9
+ const snapshotText = (snapshot) => `${JSON.stringify(snapshot, null, 2)}\n`;
10
+ /** The snapshot's JSON as it stands, of any format; `undefined` when the project has none. */
11
+ const readSnapshotJson = async (projectDir) => {
12
+ const file = path.join(projectDir, snapshotFile);
13
+ if (!existsSync(file)) return;
14
+ const text = await readFile(file, "utf8");
15
+ if (/^(<{7}|>{7}|={7})/m.test(text)) throw new Error(`${snapshotFile} has a merge conflict: delete this branch's newest migration, take the other branch's ${snapshotFile}, and run \`protobase migration\` again`);
16
+ return JSON.parse(text);
17
+ };
18
+ /** Refuses a format other than this version's: a newer one needs a newer Protobase, an older one `migration up`. */
19
+ const checkFormat = (format) => {
20
+ if (format > 1) throw new Error(`${snapshotFile} is format ${format}, which a newer Protobase wrote; this one reads format 1: upgrade Protobase`);
21
+ if (format < 1) throw new Error(`${snapshotFile} is format ${format}; this Protobase reads format 1: run \`protobase migration up\``);
22
+ };
23
+ /** The project's snapshot; `undefined` when it has none. */
24
+ const readSnapshot = async (projectDir) => {
25
+ const json = await readSnapshotJson(projectDir);
26
+ if (!json) return;
27
+ checkFormat(json.format);
28
+ return json;
29
+ };
30
+ const writeSnapshot = (projectDir, snapshot) => writeFile(path.join(projectDir, snapshotFile), snapshotText(snapshot));
31
+ const removeSnapshot = (projectDir) => rm(path.join(projectDir, snapshotFile));
32
+ //#endregion
33
+ export { checkFormat, modelHash, readSnapshot, readSnapshotJson, removeSnapshot, snapshotFile, snapshotText, writeSnapshot };
@@ -0,0 +1,24 @@
1
+ import { checkFormat, readSnapshotJson, snapshotFile, writeSnapshot } from "./snapshot-file.js";
2
+ //#region src/migration/snapshot/up.ts
3
+ const upgrades = {};
4
+ /**
5
+ * `protobase migration up`: rewrites the project's snapshot in this version's format. Refuses a newer format, which
6
+ * only a newer Protobase reads. Returns what it did.
7
+ */
8
+ const upgradeSnapshot = async (projectDir) => {
9
+ const found = await readSnapshotJson(projectDir);
10
+ if (!found) throw new Error(`The project has no ${snapshotFile}`);
11
+ let json = found;
12
+ if (json.format === 1) return `${snapshotFile} is format 1 already`;
13
+ if (json.format > 1) checkFormat(json.format);
14
+ const from = json.format;
15
+ while (json.format < 1) {
16
+ const upgrade = upgrades[json.format];
17
+ if (!upgrade) throw new Error(`${snapshotFile} is format ${json.format}, which no version of Protobase wrote`);
18
+ json = upgrade(json);
19
+ }
20
+ await writeSnapshot(projectDir, json);
21
+ return `upgraded ${snapshotFile} from format ${from} to 1`;
22
+ };
23
+ //#endregion
24
+ export { upgradeSnapshot };
@@ -0,0 +1,24 @@
1
+ import { writeSnapshot } from "./snapshot-file.js";
2
+ import { headerText } from "./header.js";
3
+ import { nextMigrationName } from "../../auth/migration-file.js";
4
+ import { nextSnapshot, snapshotHeader } from "./next-snapshot.js";
5
+ import path from "node:path";
6
+ import { mkdir, readdir, writeFile } from "node:fs/promises";
7
+ //#region src/migration/snapshot/write-file.ts
8
+ /**
9
+ * Writes `content` as the next numbered migration of `dir`, starting with its header and `id`, then rewrites the
10
+ * project's snapshot to end at it. Returns the file's path.
11
+ */
12
+ const writeMigrationFile = async (projectDir, dir, content, draft, id) => {
13
+ await mkdir(dir, { recursive: true });
14
+ const file = nextMigrationName(await readdir(dir), content.name);
15
+ const snapshot = nextSnapshot(draft.previous, draft.auth, draft.organizationsOn, {
16
+ file,
17
+ id
18
+ }, draft.protobaseVersion);
19
+ await writeFile(path.join(dir, file), `${headerText(snapshotHeader(snapshot, content.kind))}\n${content.body}`, { flag: "wx" });
20
+ await writeSnapshot(projectDir, snapshot);
21
+ return path.join(dir, file);
22
+ };
23
+ //#endregion
24
+ export { writeMigrationFile };
@@ -1,15 +1,15 @@
1
+ import { snapshotFile } from "./snapshot/snapshot-file.js";
1
2
  import path from "node:path";
2
3
  //#region src/migration/summary.ts
3
4
  /** Where to read how to add sign-in to a project that has none. */
4
5
  const signInGuide = "https://docs.protobase.net/guides/existing-database/";
5
6
  /**
6
- * What `protobase migration` prints: the files it wrote, relative to `cwd`, or that the database is current for what
7
- * the config enables. A config with sign-in off (`auth: false`) has none, so its database being current says nothing about it.
7
+ * What `protobase migration` prints: the file it wrote, relative to `cwd`, or that the migrations already make what
8
+ * the config needs. Without a database (`compared` false), the features besides the auth store were not compared. A
9
+ * config with sign-in off (`auth: false`) has no auth store, so the migrations being current says nothing about it.
8
10
  */
9
- const migrationSummary = (files, cwd, hasAuth) => {
10
- const written = files.length > 0 ? files.map((file) => `wrote ${path.relative(cwd, file)}\n`).join("") + "apply them with the project's migrations\n" : "the database is up to date; nothing to write\n";
11
- if (hasAuth) return written;
12
- return `${written}sign-in is off, so nothing was written for it: see ${signInGuide}\n`;
11
+ const migrationSummary = (file, cwd, { hasAuth, compared }) => {
12
+ return `${file ? `wrote ${path.relative(cwd, file)} and ${snapshotFile}\napply it with the project's migrations\n` : "the migrations make what the config needs; nothing to write\n"}${compared ? "" : "DATABASE_URL is not set, so only the auth store was compared: set it to compare the other features with the database\n"}${hasAuth ? "" : `sign-in is off, so nothing was written for it: see ${signInGuide}\n`}`;
13
13
  };
14
14
  //#endregion
15
15
  export { migrationSummary, signInGuide };
@@ -2,7 +2,7 @@ import { connect } from "../db/connect.js";
2
2
  import { databaseMarkers, missingMarkers } from "./platform-schemas.js";
3
3
  import { importedUsersConfig, planAuthConfig } from "./auth-config.js";
4
4
  import { writeMigration } from "./migration-files.js";
5
- import { authStoreMigrations } from "./store-migrations.js";
5
+ import { authStoreMigrations, refuseStoreRemoval, removeStoreMigrations } from "./store-migrations.js";
6
6
  import { checkoutMarkers } from "./checkout.js";
7
7
  import { cronPlan } from "./cron-plan.js";
8
8
  import { planFunctions } from "./functions/plan-functions.js";
@@ -133,6 +133,7 @@ const pattern = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
133
133
  const runDumpPhase = async (options, out) => {
134
134
  const authConfig = await planAuthConfig(options.projectDir, importedUsersConfig);
135
135
  const storeMigrations = await authStoreMigrations(options.migrationsDir);
136
+ await refuseStoreRemoval(options.migrationsDir, storeMigrations);
136
137
  const checkout = checkoutMarkers(options.projectDir);
137
138
  if (checkout.length > 0) out(`found the Supabase project's ${checkout.join(", ")}\n`);
138
139
  const functions = await planFunctions(options.projectDir);
@@ -179,7 +180,7 @@ const runDumpPhase = async (options, out) => {
179
180
  const usersFile = await writeMigration(options.migrationsDir, "supabase_users", usersColumnsMigration());
180
181
  const realtimeFile = await writeMigration(options.migrationsDir, "supabase_realtime", realtimeMigration(policies));
181
182
  await authConfig.write();
182
- for (const store of storeMigrations) await rm(path.join(options.migrationsDir, store));
183
+ await removeStoreMigrations(options.projectDir, options.migrationsDir, storeMigrations);
183
184
  const packages = await writeFunctions(options.projectDir, functions);
184
185
  await state.writeManifest({
185
186
  migration: file,
@@ -2,6 +2,9 @@ import { loadProjectAuth } from "../users/load-auth.js";
2
2
  import { connect } from "../db/connect.js";
3
3
  import { authStorageSchemas } from "./platform-schemas.js";
4
4
  import { runScaffold } from "../scaffold/run.js";
5
+ import { readSnapshot } from "../migration/snapshot/snapshot-file.js";
6
+ import { readMigrationFiles } from "../migration/snapshot/migration-files.js";
7
+ import { refuseInconsistent } from "../migration/snapshot/consistency.js";
5
8
  import { writeAuthMigration } from "../auth/write-migration.js";
6
9
  import { writeMigration } from "./migration-files.js";
7
10
  import { providerCounts } from "./identity-providers.js";
@@ -60,6 +63,7 @@ const runLoadPhase = async (options, out) => {
60
63
  const state = importState(options.projectDir);
61
64
  const manifest = await state.readManifest();
62
65
  if (!existsSync(path.join(options.migrationsDir, manifest.migration))) throw new Error(`The import's migration ${manifest.migration} is not in ${options.migrationsDir}; remove supabase-import/ and import again`);
66
+ refuseInconsistent(await readSnapshot(options.projectDir), await readMigrationFiles(options.migrationsDir));
63
67
  await checkReady(options.targetUrl, options.projectDir, manifest);
64
68
  const auth = await loadProjectAuth(options.projectDir);
65
69
  const replay = state.hasReplay() ? state.replay : void 0;
@@ -98,6 +102,7 @@ const runLoadPhase = async (options, out) => {
98
102
  if (cron.length > 0) out(`wrote ${cron.length} of pg_cron's jobs as recurring jobs in jobs/\n`);
99
103
  const authFile = await writeAuthMigration({
100
104
  auth,
105
+ projectDir: options.projectDir,
101
106
  dir: options.migrationsDir,
102
107
  name: "auth"
103
108
  });
@@ -3,9 +3,9 @@ import { writeAuthMigration } from "../auth/write-migration.js";
3
3
  import { planAuthConfig, sharedUsersConfig, sharedUsersSchema } from "./auth-config.js";
4
4
  import { writeMigration } from "./migration-files.js";
5
5
  import { sharedUsersMigration } from "./shared-users-migration.js";
6
- import { authStoreMigrations } from "./store-migrations.js";
6
+ import { authStoreMigrations, removeStoreMigrations } from "./store-migrations.js";
7
7
  import path from "node:path";
8
- import { mkdir, rm } from "node:fs/promises";
8
+ import { mkdir } from "node:fs/promises";
9
9
  //#region src/supabase/project-users.ts
10
10
  /**
11
11
  * Signs the project in `projectDir`, made on a Supabase database, in on Supabase's own users, changing nothing in
@@ -19,13 +19,14 @@ const useSupabaseUsers = async (projectDir, out) => {
19
19
  const authConfig = await planAuthConfig(projectDir, sharedUsersConfig);
20
20
  const storeMigrations = await authStoreMigrations(migrationsDir);
21
21
  const relative = (to) => path.relative(projectDir, to);
22
- for (const store of storeMigrations) await rm(path.join(migrationsDir, store));
22
+ await removeStoreMigrations(projectDir, migrationsDir, storeMigrations);
23
23
  await mkdir(migrationsDir, { recursive: true });
24
24
  await authConfig.write();
25
25
  if (storeMigrations.length > 0) out(`removed ${storeMigrations.length} migrations of Protobase's own user table: Supabase's users replace it\n`);
26
26
  out(`pointed ${relative(authConfig.file)} at ${sharedUsersSchema}.users, a view over auth.users\n`);
27
27
  const authFile = await writeAuthMigration({
28
28
  auth: await loadProjectAuth(projectDir),
29
+ projectDir,
29
30
  dir: migrationsDir,
30
31
  name: "auth",
31
32
  writer: "create protobase"
@@ -1,6 +1,6 @@
1
1
  import { copyFault } from "./storage-verify.js";
2
- import { HttpProblem, objectKey } from "@protobase/server";
3
2
  import { createHash } from "node:crypto";
3
+ import { HttpProblem, objectKey } from "@protobase/server";
4
4
  //#region src/supabase/storage-copy.ts
5
5
  const measured = () => {
6
6
  const hash = createHash("md5");
@@ -1,15 +1,53 @@
1
- import "../auth/migration-file.js";
1
+ import { removeSnapshot } from "../migration/snapshot/snapshot-file.js";
2
+ import { readMigrationFiles } from "../migration/snapshot/migration-files.js";
3
+ import { authMigrationTitle } from "../auth/migration-file.js";
4
+ import { intro } from "../migration/snapshot/run-migration.js";
2
5
  import { existsSync } from "node:fs";
3
6
  import path from "node:path";
4
- import { readFile, readdir } from "node:fs/promises";
7
+ import { readFile, readdir, rm } from "node:fs/promises";
5
8
  //#region src/supabase/store-migrations.ts
9
+ const headerLine = /^-- protobase:[a-z-]+(?: .*)?$/;
10
+ /**
11
+ * Whether `text` opens with the auth migration's title, after what Protobase starts a file with: the `-- protobase:`
12
+ * lines and `protobase migration`'s intro.
13
+ */
14
+ const isAuthMigration = (text) => {
15
+ const lines = text.replaceAll("\r\n", "\n").split("\n");
16
+ const body = lines.slice(lines.findIndex((row) => !headerLine.test(row))).join("\n");
17
+ return (body.startsWith(intro) ? body.slice(intro.length).trimStart() : body).startsWith(`-- ${authMigrationTitle}`);
18
+ };
6
19
  /** The migrations in `dir` that `protobase auth migration` or `protobase migration` wrote for the auth schema. */
7
20
  const authStoreMigrations = async (dir) => {
8
21
  if (!existsSync(dir)) return [];
9
22
  const files = (await readdir(dir)).filter((file) => file.endsWith(".sql")).sort();
10
23
  const found = [];
11
- for (const file of files) if ((await readFile(path.join(dir, file), "utf8")).startsWith(`-- The auth schema changes this version of Protobase needs, written by `)) found.push(file);
24
+ for (const file of files) if (isAuthMigration(await readFile(path.join(dir, file), "utf8"))) found.push(file);
12
25
  return found;
13
26
  };
27
+ const authOnly = /^\d+_auth\.sql$/;
28
+ /**
29
+ * Refuses when one of `files`, the auth store's migrations of `dir`, that Protobase wrote holds other features'
30
+ * statements too, or when Protobase wrote one of them and one of the migrations that stay, since removing the snapshot
31
+ * with the first leaves no snapshot ending at the second.
32
+ */
33
+ const refuseStoreRemoval = async (dir, files) => {
34
+ const migrations = await readMigrationFiles(dir);
35
+ const mixed = migrations.filter(({ file, header }) => header && files.includes(file) && !authOnly.test(file)).map(({ file }) => file);
36
+ if (mixed.length > 0) throw new Error(`${mixed.join(", ")} ${mixed.length === 1 ? "holds" : "hold"} other features' statements next to the auth migrations Supabase's users replace; move them to a migration of their own first, leaving the auth statements in a file named \`<number>_auth.sql\``);
37
+ const headed = migrations.some(({ file, header }) => header && files.includes(file));
38
+ const kept = migrations.filter(({ file, header }) => header && !files.includes(file)).map(({ file }) => file);
39
+ if (headed && kept.length > 0) throw new Error(`${kept.join(", ")} ${kept.length === 1 ? "was" : "were"} written by \`protobase migration\` after the auth migrations Supabase's users replace; drop ${kept.length === 1 ? "it" : "them"} with \`protobase migration drop\` first`);
40
+ };
41
+ /**
42
+ * Deletes `files`, the auth store's migrations of `dir`, and, when Protobase wrote one of them, the project's
43
+ * snapshot, which describes the store they made; the auth migration written next starts it again. Refuses first, as
44
+ * `refuseStoreRemoval` does, deleting nothing.
45
+ */
46
+ const removeStoreMigrations = async (projectDir, dir, files) => {
47
+ await refuseStoreRemoval(dir, files);
48
+ const headed = (await readMigrationFiles(dir)).some(({ file, header }) => header && files.includes(file));
49
+ for (const file of files) await rm(path.join(dir, file));
50
+ if (headed && existsSync(path.join(projectDir, "protobase.snapshot.json"))) await removeSnapshot(projectDir);
51
+ };
14
52
  //#endregion
15
- export { authStoreMigrations };
53
+ export { authStoreMigrations, refuseStoreRemoval, removeStoreMigrations };
@@ -1,5 +1,5 @@
1
- import { passwordLength } from "@protobase/server";
2
1
  import { randomBytes } from "node:crypto";
2
+ import { passwordLength } from "@protobase/server";
3
3
  //#region src/users/password.ts
4
4
  const rejectPasswordArgument = (value) => {
5
5
  if (value === void 0 || value === false) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.122.1",
3
+ "version": "0.123.0",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -43,13 +43,13 @@
43
43
  "dependencies": {
44
44
  "@better-auth/core": "^1.7.12",
45
45
  "@hono/node-server": "^2.1.3",
46
- "@protobase/config": "0.122.1",
47
- "@protobase/layout": "0.122.1",
48
- "@protobase/query": "0.122.1",
49
- "@protobase/schema": "0.122.1",
50
- "@protobase/server": "0.122.1",
51
- "@protobase/ui": "0.122.1",
52
- "@protobase/workflows": "0.122.1",
46
+ "@protobase/config": "0.123.0",
47
+ "@protobase/layout": "0.123.0",
48
+ "@protobase/query": "0.123.0",
49
+ "@protobase/schema": "0.123.0",
50
+ "@protobase/server": "0.123.0",
51
+ "@protobase/ui": "0.123.0",
52
+ "@protobase/workflows": "0.123.0",
53
53
  "@react-email/render": "^2.1.0",
54
54
  "@scalar/hono-api-reference": "^0.12.10",
55
55
  "@sentry/vite-plugin": "^11.10.0",
@@ -69,6 +69,7 @@
69
69
  "react": "^19.3.0",
70
70
  "rolldown": "~1.2.11",
71
71
  "semver": "^7.8.5",
72
+ "squawk-cli": "^2.73.0",
72
73
  "ts-morph": "^28.0.0",
73
74
  "vite": "^8.3.3",
74
75
  "ws": "^8.22.0",
@@ -10,8 +10,9 @@ Develop, build and run an app, on servers, in containers and on phones.
10
10
  - [UI-only dev server](../reference/cli.md#ui-only) (beta): `protobase dev --api <url>` serves the app's UI from the project with the API of an app already running, such as its staging deploy, with no database.
11
11
  - [Editor types](../reference/cli.md#types): `protobase types` gives the editor and `tsc` the types of the CLI that builds the app, with nothing installed.
12
12
  - [Project scripts](../reference/cli.md#run): `protobase run` runs a seed or a migration script on the CLI's packages.
13
- - [Migrate command](../reference/cli.md#migrate): `protobase migrate` applies the project's SQL migrations in one transaction, with nothing installed.
13
+ - [Migrate command](../reference/cli.md#migrate): `protobase migrate` applies the project's SQL migrations in one transaction, with nothing installed, and `--plan` prints the SQL it would apply.
14
14
  - [Migrations from config](../reference/cli.md#migration): Writes the SQL migrations for what the config turns on, as files of the project.
15
+ - [Schema snapshot](../reference/cli.md#migration) (beta): `protobase.snapshot.json` in the project describes the schema its migrations make, so each new migration is the next numbered file and the change shows in review. The sign-in tables are worked out from it without a database, `protobase migration check` fails CI when the config has a change the migrations lack, and `drop` takes the newest file back.
15
16
  - [User and organization commands](../reference/cli.md#users): Create users, set roles and manage organizations from the terminal.
16
17
  - [Encryption commands](../reference/cli.md#encryption-status): Report and fix plaintext or old-key values of encrypted fields.
17
18
  - [One bundle](../reference/cli.md#build): `protobase build` writes one folder with everything the app needs, without a database or secrets. It fails on a view that filters, sorts or searches by a field its resource does not allow.
@@ -17,6 +17,7 @@ Describe the tables of an existing Postgres database as resources, with their fi
17
17
  - [Checks the database makes](../reference/data-config.md#checks-the-database-makes): A database check or trigger that refuses a write is explained by a label you declare, translated and filled with the record's values, while the database's own message stays on the server.
18
18
  - [Opening an existing record](../reference/data-config.md#opening-an-existing-record): A create that repeats a record's unique values, such as a direct message with the same people, opens that record instead of failing, for whoever may read it; anyone else gets the usual conflict, which does not say the record exists.
19
19
  - [Record validation](../reference/data-config.md#resource): A rule over the whole record runs on every create and update and reports each problem on the field it concerns.
20
+ - [Preparing a record](../reference/data-config.md#preparing-a-record): Resources can prepare a record on the server before it is written: a hook fills in or rewrites values, such as a generated key or a normalised name, on every create and update path through the resources (REST, batch and MCP), inside the write's transaction; the PostgREST-compatible API writes tables without it.
20
21
  - [Rollups and formulas](../reference/data-config.md#rollups-and-formulas) (beta): Fields that hold counts, sums, averages, minimums or maximums of related records, or values calculated from the record's own numbers, kept current by the database.
21
22
  - [Lookups](../reference/data-config.md#lookups) (beta): A field can show a field of a linked record, such as an order's customer name, read with the record in the same query and only as far as the caller may read the linked record.
22
23
  - [Time rollups](../reference/data-config.md#time-rollups) (beta): A large events table gets an hourly or daily rollup that the app keeps up to date, so charts over months of millions of rows answer in milliseconds.
@@ -11,7 +11,7 @@ Mail the app sends, the PDF documents it makes, and forms for people without an
11
11
  - [Protobase's mail look](../reference/email.md#the-look-of-protobases-own-mail): Your emails use a layout, button, code and note with the look of Protobase's own mail.
12
12
  - [Header fields](../reference/email.md#templates): Your emails carry header fields of their own.
13
13
  - [One-click unsubscribe](../reference/email.md#unsubscribe) (beta): Mail you mark as bulk carries a one-click unsubscribe, and Protobase stops sending that kind of mail to whoever used it.
14
- - [Bounces and complaints](../reference/email.md#bounces-and-complaints) (beta): Bounces and spam complaints that Amazon SES or Resend report arrive as Mail feedback records with `bounced` and `complained` events, so a workflow, webhook or your own code can act on them.
14
+ - [Bounces and complaints](../reference/email.md#bounces-and-complaints) (beta): Bounces and spam complaints that Amazon SES or Resend report arrive as Mail feedback records with `bounced` and `complained` events, a complaint that hides who complained tied to the message it is about, so a workflow, webhook or your own code can act on them.
15
15
  - [Attachments](../reference/email.md#attachments): A message carries files, such as an invoice's PDF, through the app's mail or someone's own mailbox.
16
16
  - [PDF documents](../reference/pdf.md#documents): PDF files such as invoices and quotes are React components with typed data, rendered from jobs, hooks or functions and attached to mail as they are.
17
17
  - [Mail from your own mailbox](../reference/email.md#from-someones-own-mailbox) (beta): People link their Gmail on the account page, and the app's functions send mail from it; an action offers to connect the mailbox right there when the link is missing or expired.
@@ -216,7 +216,7 @@ Create, update and delete share one pipeline (`write-pipeline.ts`):
216
216
  1. the caller is authenticated and, for tenant-scoped resources, has a tenant (`403` otherwise);
217
217
  2. unknown fields, read-only fields and the tenant column in the body are refused, each value is validated by its field's zod schema (an empty string for a text field without `.optional()` counts as missing: `required`, or its default on a create), then the resource's `.validate()` rules run (`400` with `errors: [{ field, code, message }]`); what needs the network is checked before the transaction opens, such as the address of a [webhook subscription](webhooks.md)'s URL;
218
218
  3. one transaction with `SET LOCAL statement_timeout`; the row is locked with `FOR UPDATE`; another tenant's key, or a soft-deleted row, is a `404`;
219
- 4. the access rule runs, then `If-Match` is compared with the ETag (`428` when missing on PATCH, `412` when stale);
219
+ 4. on PATCH and DELETE, `If-Match` is compared with the ETag as soon as the row is locked (`428` when missing on PATCH, `412` when stale), so a PATCH answers it before the body's checks of step 2; then the resource's [`.prepare()`](data-config.md#preparing-a-record) hooks fill in or rewrite a create's or update's values (`422` with the field named when one refuses), then the access rule runs;
220
220
  5. the write, then `writeHooks` inside the same transaction (a hook that throws rolls the write back). Audit logging and the admin store plug in here. A hook does database work only, through the transaction it is given: while it waits on anything else, such as an HTTP call, the transaction stays open with the row locked, and on Protobase Cloud the database ends a transaction left idle for a second. Work that waits belongs in a [job](jobs.md) the hook enqueues;
221
221
  6. once it commits, the files it took out of its rows are scheduled for deletion (see [Deleting files](files.md#deleting-files)), so the transaction never waits on the storage.
222
222
 
@@ -34,7 +34,7 @@ bun run protobase auth migration # reads auth_migrations; writes the steps no
34
34
  bun run db:migrate # applies them
35
35
  ```
36
36
 
37
- Each step's statements come under a comment naming its module, number and name, such as `-- auth 2 account_keys: ...`, and the last step of a version is followed by its row in `auth_migrations`. The file only adds tables, nullable columns, columns with a default, and indexes, and the `pg_trgm` extension that the index of the users' names needs, never drops, retypes or tightens anything, so it is safe to apply unattended; Protobase's tests lint every step it ships for this. A step that assumes something of the rows already there starts with a check that refuses before it changes anything: `auth` step 2, which makes one account per provider and account id, stops when two accounts share both, naming them, so you keep one of each in a migration of your own written before it, then apply again. The file is plain SQL to review, edit or leave out where the project handles the auth schema itself. `--dir` and `--name` choose the folder and the name after the number. [`protobase migration`](cli.md#migration) writes the same file, along with what the config's other features need, such as [jobs](jobs.md).
37
+ Each step's statements come under a comment naming its module, number and name, such as `-- auth 2 account_keys: ...`, and the last step of a version is followed by its row in `auth_migrations`. The file only adds tables, nullable columns, columns with a default, and indexes, and the `pg_trgm` extension that the index of the users' names needs, never drops, retypes or tightens anything, so it is safe to apply unattended; Protobase's tests lint every step it ships for this. A step that assumes something of the rows already there starts with a check that refuses before it changes anything: `auth` step 2, which makes one account per provider and account id, stops when two accounts share both, naming them, so you keep one of each in a migration of your own written before it, then apply again. The file is plain SQL to review, edit or leave out where the project handles the auth schema itself. `--dir` and `--name` choose the folder and the name after the number. [`protobase migration`](cli.md#migration) writes the same steps from the project's `protobase.snapshot.json` instead of the database, so it needs no database, along with what the config's other features need, such as [jobs](jobs.md). The file `auth migration` writes starts with Protobase's lines and brings the store to every step of this version, so it also starts the project's snapshot, or moves it on, and `protobase migration` goes on from there.
38
38
 
39
39
  Every store has the tables of every module, whether the app turns the feature on or not: [passkeys](#passkeys), [two-factor authentication](#two-factor-authentication), [organizations](#organizations), the [OAuth provider for MCP](#oauth-for-mcp-clients) and [personal access tokens](personal-access-tokens.md). Turning a feature on or off needs no migration and drops nothing; the columns a feature adds to the user and session tables are empty until it is on. SAML providers and open sign-up keep nothing in the store. <gap>A store cannot leave out the tables of a feature the app does not use because recording the steps a store has, rather than versions, is not implemented.</gap>
40
40
 
@@ -625,22 +625,41 @@ For a project with [organizations](auth.md#organizations); `<organization>` is a
625
625
  ## `migrate`
626
626
 
627
627
  ```sh
628
- protobase migrate [connection string | --env VAR]
628
+ protobase migrate [connection string | --env VAR] [--plan]
629
629
  ```
630
630
 
631
- Applies the project's `db/migrations/*.sql` that the database has not applied yet, in file name order, as the runtime's [`migrate`](#build-serve) applies a bundle's: in one transaction behind the same lock, recorded in the same `migrations.applied` (see [Deploy](../guides/deploy.md#migrations)), so a database either one migrated is current for the other. It prints each file it applies, or that the database is up to date; a project without `db/migrations` applies nothing and says so. It runs none of the project's code, so a project with only `protobase.config.ts`, no `package.json` and nothing installed, migrates as well. The URL comes as for [`scaffold`](#scaffold), and is needed only when there are migrations. A project that still has a `db/migrate.ts` recording in `public.schema_migrations` first copies in the presets' current `db/migrate.ts` and `drop.ts`, so the two keep one record.
631
+ Applies the project's `db/migrations/*.sql` that the database has not applied yet, in file name order, as the runtime's [`migrate`](#build-serve) applies a bundle's: in one transaction behind the same lock, recorded in the same `migrations.applied` (see [Deploy](../guides/deploy.md#migrations)), so a database either one migrated is current for the other. It prints each file it applies, or that the database is up to date; a project without `db/migrations` applies nothing and says so. It runs none of the project's code, so a project with only `protobase.config.ts`, no `package.json` and nothing installed, migrates as well. The URL comes as for [`scaffold`](#scaffold), and is needed only when there are migrations. A project that still has a `db/migrate.ts` recording in `public.schema_migrations` first copies in the presets' current `db/migrate.ts` and `drop.ts`, so the two keep one record. `--plan` is a dry run: it prints each file not applied yet under its name, with its SQL, from a read-only transaction, and applies and records nothing.
632
632
 
633
633
  ## `migration`
634
634
 
635
+ :::caution[Beta]
636
+ A project with auth migrations written before the snapshot starts it with [`auth migration`](#auth-migration), against its database with those migrations applied; `migration` and `check` refuse such a project until then.
637
+ :::
638
+
635
639
  ```sh
636
640
  protobase migration [--dir db/migrations] [--extend <dir>]
641
+ protobase migration --custom <name> [--record-config]
642
+ protobase migration check
643
+ protobase migration drop
644
+ protobase migration up
637
645
  ```
638
646
 
639
- Writes what the database still needs for every feature the config enables, as the project's next migrations in `--dir`, one file per feature: the auth schema when sign-in is on (`NNN_auth.sql`, as [`auth migration`](#auth-migration) writes it), the [jobs schema](jobs.md#the-jobs-schema) when the config has jobs, `webhooks`, `workflows`, `notifications` or `mailFeedback`, or a resource has events, history, comments or an [AI field](ai.md) or is a [time rollup](data-config.md#keeping-it-up-to-date) (`NNN_jobs.sql`), the table of the bounces and complaints of [`mailFeedback`](email.md#bounces-and-complaints) (`NNN_mail_feedback.sql`), the [capture of events](events.md#migrations-and-startup) and the [history table](history.md#the-table) (`NNN_changes.sql`), the columns of [rollup and formula fields](data-config.md#rollups-and-formulas), the triggers that keep the rollups, and the tables, indexes and refresh functions of [time rollups](data-config.md#time-rollups) (`NNN_computed.sql`), the role the [assistant's read-only queries](assistant.md#the-built-in-backend) run as, when it finds the built-in assistant's key (`NNN_query.sql`), the [comments table](comments.md#the-table) (`NNN_comments.sql`), the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app) of `webhooks` (`NNN_webhooks.sql`), the [workflows, versions, runs and steps](workflows.md#turning-them-on) of `workflows` (`NNN_workflows.sql`), the [devices and history tables](notifications.md#table-names) of `notifications` (`NNN_notifications.sql`), the table of who unsubscribed from bulk mail of [`unsubscribe`](email.md#unsubscribe) (`NNN_unsubscribes.sql`), the `realtime_relay` schema of [`realtime: { processes: 'many' }`](supabase-realtime.md#several-processes) (`NNN_realtime_relay.sql`), the `channels` schema of [`realtime: { sqlSends: true }`](channels.md#from-sql) (`NNN_channel_sends.sql`), the trigger of [`realtime.relay`](realtime-relay.md#sessions) that ends a deleted session's sockets (`NNN_relay.sql`), and, with [`userTables`](user-tables.md#the-switch), the schemas of user tables (`NNN_user_tables.sql`) and the delete of the definitions of tables that resources in code [own now](user-tables.md#taking-a-table-over-as-code) (`NNN_owned_definitions.sql`). It compares the database, with the project's migrations applied, with the config (for the auth schema, it reads the store's record of the migrations it applied), merged with those of `--extend` as `dev` merges them, and writes nothing when the database is current. Apply the files with the project's other migrations. It reads the `.env` nearest the current directory and needs `DATABASE_URL`.
647
+ Writes what the config and this version of Protobase need beyond the project's `protobase.snapshot.json` as the project's next migration in `--dir`: one numbered file each run, named after what it holds, such as `004_auth.sql` or `005_changes_webhooks.sql`, after the folder's highest number, and rewrites the snapshot to end at it, so both show in the pull request. The file starts with lines Protobase reads back: `-- protobase:id`, a random id of its own, then the version that wrote it, each sign-in module's last step, and the hash of the snapshot's model once it is applied. It writes nothing, the snapshot included, when nothing differs. Apply the file with the project's other migrations.
648
+
649
+ The snapshot describes the schema the project's migrations make: the sign-in store as the runtime reads it, each module that is on with its tables, columns and indexes under the names the config gives them, its last step, and whether every table whose rows belong to an organization has the column that names it, with `modelHash`, the SHA-256 of exactly that; what the migrations decided, the file it ends at with its id, its `format` and the version of Protobase that wrote it, the modules kept or archived, whether organizations were ever on and the default organization; and `physical`, every schema, table, column and index name the store has. The sign-in store's part of the file comes from the snapshot alone, without a database: the [steps](auth.md#migrations) after each module's last one, those a newer Protobase ships included, each version followed by its row in `auth_migrations`, which the server's startup check reads. With `DATABASE_URL` set, the checks of those steps run first against the database's rows, in a read-only transaction, and refuse as the step would, such as on two accounts with one provider and account id. A name the store has that the config changes, such as a table renamed in [`auth.tables`](auth.md#table-and-column-names), is refused with what changed, since Protobase does not write renames: write it by hand with `--custom` and `--record-config`. <gap>`protobase migration` cannot write the sign-in store of a project with auth migrations from before `protobase.snapshot.json` because `protobase migration baseline`, which reads the database once to start the snapshot, is not implemented.</gap>
650
+
651
+ The rest of the file is what the other features the config enables still need of the database, compared with it, each under its own comment and named in the file name as in brackets: the [jobs schema](jobs.md#the-jobs-schema) when the config has jobs, `webhooks`, `workflows`, `notifications` or `mailFeedback`, or a resource has events, history, comments or an [AI field](ai.md) or is a [time rollup](data-config.md#keeping-it-up-to-date) (`jobs`), the table of the bounces and complaints of [`mailFeedback`](email.md#bounces-and-complaints) (`mail_feedback`), the [capture of events](events.md#migrations-and-startup) and the [history table](history.md#the-table) (`changes`), the columns of [rollup and formula fields](data-config.md#rollups-and-formulas), the triggers that keep the rollups, and the tables, indexes and refresh functions of [time rollups](data-config.md#time-rollups) (`computed`), the role the [assistant's read-only queries](assistant.md#the-built-in-backend) run as, when it finds the built-in assistant's key (`query`), the [comments table](comments.md#the-table) (`comments`), the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app) of `webhooks` (`webhooks`), the [workflows, versions, runs and steps](workflows.md#turning-them-on) of `workflows` (`workflows`), the [devices and history tables](notifications.md#table-names) of `notifications` (`notifications`), the table of who unsubscribed from bulk mail of [`unsubscribe`](email.md#unsubscribe) (`unsubscribes`), the `realtime_relay` schema of [`realtime: { processes: 'many' }`](supabase-realtime.md#several-processes) (`realtime_relay`), the `channels` schema of [`realtime: { sqlSends: true }`](channels.md#from-sql) (`channel_sends`), the trigger of [`realtime.relay`](realtime-relay.md#sessions) that ends a deleted session's sockets (`relay`), and, with [`userTables`](user-tables.md#the-switch), the schemas of user tables (`user_tables`) and the delete of the definitions of tables that resources in code [own now](user-tables.md#taking-a-table-over-as-code) (`owned_definitions`). Those are compared only with `DATABASE_URL` set, against the database with the project's migrations applied, and the command says so without it. <gap>`protobase migration` cannot write the jobs, change capture, rollup and other feature schemas from the snapshot because recording their models in it is not implemented.</gap> It reads the config merged with those of `--extend` as `dev` merges them, and the `.env` nearest the current directory.
652
+
653
+ - `--custom <name>` writes an empty numbered file, `NNN_<name>.sql`, with Protobase's lines and `-- protobase:custom`, for statements you write by hand, and makes the snapshot end at it. It counts as not additive; once it only adds, put `-- protobase:additive` among its `-- protobase:` lines and `check` lints it with the lint rules Protobase's own steps pass, such as no dropped table or column, no new required column and no unique constraint without a check of the rows. With `--record-config`, the snapshot takes the sign-in store's names as the config has them now, each module at the step it was: the file is where you make the store match, such as a rename.
654
+ - `check`, for CI, writes nothing and exits 1 with a line for each problem: a config or Protobase version that needs steps the migrations lack, a name the config changed, two files that share a number when Protobase wrote one of them, a snapshot that does not end at the newest file Protobase wrote or whose model does not match its `modelHash`, and a hand-written file marked additive that is not.
655
+ - `drop` deletes the newest file Protobase wrote and takes the snapshot back to the one before it, from that file's lines, or removes the snapshot with the first file. It refuses while two files share a number or the snapshot does not end at the newest file, so it never deletes another branch's file, and after a file that recorded a changed config, whose snapshot before it only version control has.
656
+ - `up` rewrites the snapshot in this version's format. Every other command refuses a snapshot of an older format, and one of a newer format, which only a newer Protobase reads.
657
+
658
+ When two branches each write a migration, both rewrite the snapshot, so merging the second reports a conflict in `protobase.snapshot.json`, and the commands refuse until it is resolved. On the second branch, delete its own new file, take the other branch's snapshot, and run `protobase migration` again: it writes the second branch's changes as one file after the other's.
640
659
 
641
660
  ```sh
642
- bun run db:migrate # the database at the project's current schema
643
- bun run protobase migration # writes db/migrations/NNN_auth.sql, NNN_jobs.sql, NNN_changes.sql, ... for what the config enables
661
+ bun run protobase migration # writes db/migrations/NNN_auth.sql and protobase.snapshot.json for what the config enables
662
+ bun run protobase migration check # in CI: exits 1 when the migrations lack a change of the config
644
663
  bun run db:migrate # applies them
645
664
  ```
646
665
 
@@ -667,7 +686,7 @@ Prints the app's entry for the apps file of the [realtime relay](realtime-relay.
667
686
  protobase auth migration [--dir db/migrations] [--name auth]
668
687
  ```
669
688
 
670
- Run inside a project, against its database with the project's migrations applied. It reads the versions the store applied from its `auth_migrations` table and writes the auth migrations of this Protobase it has not, each followed by its row there, as the next migration in `--dir`: `009_auth.sql` after `008_...`, with the store's schema, user table, columns and id type as the config's `auth` names them. Nothing is written when the store is current, nor with sign-in off, when it says so and exits 0. The file only adds, never drops; apply it with the project's other migrations. For a store made before 0.48, without `auth_migrations`, it writes the step that adopts it once, and refuses one that matches no version, naming what differs. See [migrations](auth.md#migrations).
689
+ Run inside a project, against its database with the project's migrations applied. It reads the versions the store applied from its `auth_migrations` table and writes the auth migrations of this Protobase it has not, each followed by its row there, as the next migration in `--dir`: `009_auth.sql` after `008_...`, with the store's schema, user table, columns and id type as the config's `auth` names them. Nothing is written when the store is current and the project has a snapshot, nor with sign-in off, when it says so and exits 0. The file only adds, never drops; apply it with the project's other migrations. It starts with Protobase's lines and starts the project's `protobase.snapshot.json`, or moves it on, with the store at every step, so [`migration`](#migration) goes on from it. A project without a snapshot whose store is current, such as one whose auth migrations an earlier Protobase wrote, gets a file without statements that starts it. For a store made before 0.48, without `auth_migrations`, it writes the step that adopts it once, and refuses one that matches no version, naming what differs. See [migrations](auth.md#migrations).
671
690
 
672
691
  ## `import supabase`
673
692
 
@@ -106,12 +106,20 @@ export default defineConfig(({ command }) => ({
106
106
  - **Type:** `string[]`
107
107
  - **Default:** none
108
108
 
109
- The write hooks by name, run in this order inside each create's, update's and delete's transaction, with that transaction. Each is the default export of `hooks/<name>.ts`, loaded on the first write; a name without its file stops the app at start with an error that names the file. A hook does database work only: while it waits on anything else, such as an HTTP call, the row stays locked, so it enqueues a job for such work. [Enqueueing](../jobs.md#enqueueing) shows a hook that does.
109
+ The write hooks by name, run in this order inside each create's, update's and delete's transaction, with that transaction. Each is the default export of `hooks/<name>.ts`, loaded on the first write; a name without its file stops the app at start with an error that names the file. A hook does database work only: while it waits on anything else, such as an HTTP call, the row stays locked, so it enqueues a job for such work. [Enqueueing](../jobs.md#enqueueing) shows a hook that does. A hook sees the row as written; values the server makes before the write, such as a generated key, come from a resource's [`.prepare()`](../data-config.md#preparing-a-record).
110
110
 
111
111
  ```ts
112
112
  export default defineConfig({ writeHooks: ['queue-sent-invoice'] })
113
113
  ```
114
114
 
115
+ A token made on create, by contrast, goes in the resource, so its `not null` column is written with the record:
116
+
117
+ ```ts
118
+ resource('api_tokens')
119
+ // ...
120
+ .prepare((values, { operation }) => (operation === 'create' ? { ...values, token: randomBytes(24).toString('base64url') } : values))
121
+ ```
122
+
115
123
  ## mcpEndpoint
116
124
 
117
125
  - **Type:** `{ sql?: boolean; writes?: boolean | { resources?: string[]; rolesWithoutApproval?: string[] }; instructions?: string } | false`