@protobase/cli 0.129.1 → 0.130.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 (99) hide show
  1. package/dist/auth/config-organizations.js +15 -0
  2. package/dist/auth/register.js +8 -2
  3. package/dist/auth/write-migration.js +34 -12
  4. package/dist/cli/package.js +1 -1
  5. package/dist/config/build-project.js +1 -0
  6. package/dist/config/project-modules.js +64 -0
  7. package/dist/config/read-only-queries.js +9 -0
  8. package/dist/config/user-tables-config.js +1 -1
  9. package/dist/dev/dev-jobs.js +12 -6
  10. package/dist/dev/entry.js +12 -19
  11. package/dist/doctor/capture-files.js +3 -3
  12. package/dist/doctor/startup.js +2 -4
  13. package/dist/migration/apply-migrations.js +9 -6
  14. package/dist/migration/baseline/read-live-modules.js +31 -0
  15. package/dist/migration/baseline/read-live-store.js +18 -4
  16. package/dist/migration/baseline/write-baseline.js +50 -17
  17. package/dist/migration/migrate-project.js +3 -3
  18. package/dist/migration/migration-project.js +29 -15
  19. package/dist/migration/older-code/catalog.js +34 -0
  20. package/dist/migration/older-code/contractions.js +86 -0
  21. package/dist/migration/older-code/lint-files.js +55 -0
  22. package/dist/migration/older-code/refusal.js +9 -0
  23. package/dist/migration/older-code/trial.js +58 -0
  24. package/dist/migration/parts.js +8 -104
  25. package/dist/migration/record/after-file.js +20 -2
  26. package/dist/migration/register.js +67 -19
  27. package/dist/migration/release/release-record.js +9 -7
  28. package/dist/migration/release/release-steps.js +15 -3
  29. package/dist/migration/sign-off/contract.js +65 -0
  30. package/dist/migration/sign-off/delete.js +50 -0
  31. package/dist/migration/sign-off/signed-off-file.js +19 -0
  32. package/dist/migration/snapshot/auth-difference.js +135 -15
  33. package/dist/migration/snapshot/auth-target.js +9 -3
  34. package/dist/migration/snapshot/check.js +24 -5
  35. package/dist/migration/snapshot/custom.js +6 -3
  36. package/dist/migration/snapshot/drop.js +7 -2
  37. package/dist/migration/snapshot/header.js +11 -4
  38. package/dist/migration/snapshot/module-changes.js +22 -0
  39. package/dist/migration/snapshot/module-prompts.js +42 -0
  40. package/dist/migration/snapshot/module-sections.js +38 -0
  41. package/dist/migration/snapshot/next-snapshot.js +13 -7
  42. package/dist/migration/snapshot/off-choice.js +11 -0
  43. package/dist/migration/snapshot/organizations-off-facts.js +49 -0
  44. package/dist/migration/snapshot/revival-rows.js +34 -0
  45. package/dist/migration/snapshot/run-migration.js +82 -15
  46. package/dist/migration/snapshot/snapshot-file.js +7 -0
  47. package/dist/migration/snapshot/terminal-prompts.js +21 -0
  48. package/dist/migration/snapshot/write-file.js +1 -1
  49. package/dist/migration/summary.js +3 -2
  50. package/dist/organizations/api.js +4 -2
  51. package/dist/organizations/commands.js +27 -10
  52. package/dist/organizations/pin-source.js +20 -0
  53. package/dist/organizations/pin.js +40 -0
  54. package/dist/organizations/register.js +20 -12
  55. package/dist/scaffold/protobase-tables.js +2 -2
  56. package/dist/serve/create-admin.js +6 -3
  57. package/dist/serve/lifecycle.js +2 -2
  58. package/dist/serve/migrate-release.js +1 -1
  59. package/dist/serve/relay-check.js +7 -8
  60. package/dist/serve/startup-checks.js +12 -22
  61. package/dist/supabase/load-phase.js +3 -1
  62. package/dist/supabase/project-users.js +4 -1
  63. package/dist/users/commands.js +44 -6
  64. package/dist/users/load-auth.js +9 -3
  65. package/dist/users/manage.js +16 -1
  66. package/dist/users/register.js +28 -25
  67. package/dist/users/set-disabled.js +3 -2
  68. package/dist/users/users-api.js +9 -3
  69. package/dist/worker/start-worker.js +7 -4
  70. package/package.json +8 -8
  71. package/skills/protobase/references/features/api-functions.md +1 -0
  72. package/skills/protobase/references/features/build-and-run.md +4 -2
  73. package/skills/protobase/references/features/sign-in-and-accounts.md +2 -1
  74. package/skills/protobase/references/guides/api-functions.md +27 -2
  75. package/skills/protobase/references/guides/deploy.md +2 -2
  76. package/skills/protobase/references/reference/assistant.md +1 -1
  77. package/skills/protobase/references/reference/auth.md +52 -17
  78. package/skills/protobase/references/reference/calls.md +1 -1
  79. package/skills/protobase/references/reference/cli.md +48 -28
  80. package/skills/protobase/references/reference/comments.md +1 -1
  81. package/skills/protobase/references/reference/config/api.md +1 -1
  82. package/skills/protobase/references/reference/config/jobs-and-events.md +1 -1
  83. package/skills/protobase/references/reference/config/sign-in.md +22 -4
  84. package/skills/protobase/references/reference/config.md +1 -1
  85. package/skills/protobase/references/reference/data-config.md +9 -9
  86. package/skills/protobase/references/reference/derived.md +1 -1
  87. package/skills/protobase/references/reference/email.md +2 -2
  88. package/skills/protobase/references/reference/events.md +2 -2
  89. package/skills/protobase/references/reference/history.md +1 -1
  90. package/skills/protobase/references/reference/jobs.md +5 -5
  91. package/skills/protobase/references/reference/live.md +2 -2
  92. package/skills/protobase/references/reference/notifications.md +4 -4
  93. package/skills/protobase/references/reference/personal-access-tokens.md +2 -2
  94. package/skills/protobase/references/reference/realtime-relay.md +1 -1
  95. package/skills/protobase/references/reference/status.md +2 -2
  96. package/skills/protobase/references/reference/supabase-rest.md +1 -1
  97. package/skills/protobase/references/reference/user-tables.md +1 -1
  98. package/skills/protobase/references/reference/webhooks.md +1 -1
  99. package/dist/migration/snapshot/lint-custom.js +0 -23
@@ -3,12 +3,14 @@ import { modelHash, recordsRuntimeModel, runtimeModel, storeNamesList } from "@p
3
3
  //#region src/migration/release/release-record.ts
4
4
  /**
5
5
  * The row that records a release in the record of migrations once its steps are applied, as a file's record block
6
- * does: the model this release reads with `auth`, additive when only the auth store's steps, which only add, apply.
7
- * `undefined` when the record has the model already and no step applies.
6
+ * does: the model this release reads with the project's auth and schema modules, additive when only the auth store's
7
+ * steps, which only add, and schema modules' statements the code before runs on apply. `undefined` when the release
8
+ * reads nothing of the record, or the record holds its model already and no step applies.
8
9
  */
9
- const releaseRecord = async (auth, steps, protobaseVersion, id) => {
10
- if (steps.length === 0 && await recordsRuntimeModel(auth)) return;
11
- const model = runtimeModel(auth);
10
+ const releaseRecord = async (project, steps, protobaseVersion, id) => {
11
+ const model = runtimeModel(project.auth, project.modules);
12
+ if (!model.auth && !model.modules) return;
13
+ if (steps.length === 0 && await recordsRuntimeModel(project.db, model)) return;
12
14
  const row = {
13
15
  id,
14
16
  number: null,
@@ -16,8 +18,8 @@ const releaseRecord = async (auth, steps, protobaseVersion, id) => {
16
18
  protobaseVersion,
17
19
  model,
18
20
  modelHash: modelHash(model),
19
- physical: { auth: storeNamesList(model.auth) },
20
- additive: steps.every(({ name }) => name === "auth"),
21
+ physical: model.auth ? { auth: storeNamesList(model.auth) } : {},
22
+ additive: steps.every(({ name, breaks }) => name === "auth" || breaks !== void 0 && breaks.length === 0),
21
23
  completed: true
22
24
  };
23
25
  return {
@@ -1,11 +1,13 @@
1
1
  import { authMigrationTitle } from "../../auth/migration-file.js";
2
2
  import { migrationParts } from "../parts.js";
3
3
  import { authSchemaMigration } from "@protobase/server";
4
+ import { moduleDifference, schemaModules, targetIds } from "@protobase/server/internal";
4
5
  //#region src/migration/release/release-steps.ts
5
6
  /**
6
7
  * What this release of Protobase still needs of the project's database for every feature its config turns on, compared
7
- * with the database itself: the auth store by its `auth_migrations` record, the other parts by their schemas, as
8
- * `protobase migration` compares them. In the order they apply; none when the database is current.
8
+ * with the database itself: the auth store by the steps its `auth_steps` table records, each schema module by what its
9
+ * catalogue shows (`SchemaModule.read`), the other parts by their schemas, as `protobase migration` compares them. In
10
+ * the order they apply; none when the database is current.
9
11
  */
10
12
  const releaseSteps = async (project) => {
11
13
  const auth = project.auth && await authSchemaMigration(project.auth);
@@ -14,8 +16,18 @@ const releaseSteps = async (project) => {
14
16
  title: authMigrationTitle,
15
17
  sql: auth
16
18
  }] : [];
19
+ for (const id of targetIds(project.modules)) {
20
+ const input = project.modules[id];
21
+ const { sql, after, breaks } = moduleDifference(schemaModules[id], input, await schemaModules[id].read(project.db, input));
22
+ if (sql !== void 0) steps.push({
23
+ name: id,
24
+ title: schemaModules[id].title,
25
+ sql: after === void 0 ? sql : `${sql}\n\n${after}`,
26
+ breaks
27
+ });
28
+ }
17
29
  for (const part of migrationParts(project)) {
18
- const sql = await part.sql({ authWritten: Boolean(auth) });
30
+ const sql = await part.sql();
19
31
  if (sql !== void 0) steps.push({
20
32
  name: part.name,
21
33
  title: part.title,
@@ -0,0 +1,65 @@
1
+ import { readSnapshot, snapshotFile } from "../snapshot/snapshot-file.js";
2
+ import { readMigrationFiles } from "../snapshot/migration-files.js";
3
+ import { refuseInconsistent } from "../snapshot/consistency.js";
4
+ import { nextMigrationName } from "../../auth/migration-file.js";
5
+ import { writeMigrationFile } from "../snapshot/write-file.js";
6
+ import { signedOffFile } from "./signed-off-file.js";
7
+ import { readdir } from "node:fs/promises";
8
+ import { archiveSchema, archiveStatements, archivedModule, markedSql, revokeStatements, signOffGate } from "@protobase/server/internal";
9
+ //#region src/migration/sign-off/contract.ts
10
+ /** The line `protobase migration contract`'s files open with, under their header. */
11
+ const contractIntro = "-- Written by `protobase migration contract`: it signs off the update of each migration it names, and archives what that update retired.\n";
12
+ /**
13
+ * `protobase migration contract`: writes the next migration, which archives each sign-in module turned off with
14
+ * `--off archive` or `--off delete`, behind a check that refuses until the file that turned it off was applied `hours`
15
+ * ago and another after it; every statement names that file with `-- protobase:contract`. The snapshot moves the
16
+ * modules from `kept` to `archived`. Returns the file's path.
17
+ */
18
+ const writeContract = async ({ projectDir, dir, hours, protobaseVersion, newId }) => {
19
+ const snapshot = await readSnapshot(projectDir);
20
+ const files = await readMigrationFiles(dir);
21
+ refuseInconsistent(snapshot, files);
22
+ const deferred = (snapshot?.decisions.modules.kept ?? []).filter((kept) => kept.off !== void 0);
23
+ if (!snapshot?.model.auth || deferred.length === 0) throw new Error(`Nothing awaits a sign-off: ${snapshotFile} has no sign-in module turned off with \`--off archive\` or \`--off delete\``);
24
+ const store = snapshot.model.auth.schema;
25
+ const schema = archiveSchema(Number(nextMigrationName(await readdir(dir), "contract").split("_")[0]));
26
+ const signedOff = [...new Set(deferred.map(({ off }) => off.file))].map((id) => signedOffFile(files, id));
27
+ const id = newId();
28
+ const body = [
29
+ contractIntro,
30
+ ...signedOff.map((file) => `-- The sign-off of ${file.name}: it applies once that file was applied ${hours} hours ago, and a migration after it.\n${markedSql(file.id, [signOffGate(file, hours, "The sign-off", true)])}\n`),
31
+ ...deferred.map(({ off, ...kept }) => `-- ${kept.module} archived to ${schema}: its tables, with no foreign key to the tables still on, and each column it retired as <column>_archive, all still watched in retired.writes.\n${markedSql(off.file, archiveStatements(store, schema, {
32
+ ...kept,
33
+ off
34
+ }))}\n`),
35
+ `-- Nothing but a superuser uses ${schema}: the app's roles and the one applying this file are refused.\n${markedSql(deferred[0].off.file, revokeStatements(schema))}\n`
36
+ ].join("\n");
37
+ const decisions = {
38
+ ...snapshot.decisions,
39
+ modules: {
40
+ kept: snapshot.decisions.modules.kept.filter((kept) => kept.off === void 0),
41
+ archived: [...snapshot.decisions.modules.archived, ...deferred.map((kept) => archivedModule(store, schema, kept, id))]
42
+ }
43
+ };
44
+ const content = {
45
+ name: "contract",
46
+ body,
47
+ additive: false,
48
+ kind: {
49
+ custom: false,
50
+ additive: false,
51
+ breaksOlderCode: true
52
+ }
53
+ };
54
+ const draft = {
55
+ previous: snapshot,
56
+ auth: snapshot.model.auth,
57
+ modules: snapshot.model.modules,
58
+ organizations: { on: false },
59
+ protobaseVersion,
60
+ decisions
61
+ };
62
+ return writeMigrationFile(projectDir, dir, content, draft, id);
63
+ };
64
+ //#endregion
65
+ export { contractIntro, writeContract };
@@ -0,0 +1,50 @@
1
+ import { readSnapshot, snapshotFile } from "../snapshot/snapshot-file.js";
2
+ import { readMigrationFiles } from "../snapshot/migration-files.js";
3
+ import { refuseInconsistent } from "../snapshot/consistency.js";
4
+ import { writeMigrationFile } from "../snapshot/write-file.js";
5
+ import { signedOffFile } from "./signed-off-file.js";
6
+ import { deleteStatements, markedSql, signOffGate, stepRecordOf } from "@protobase/server/internal";
7
+ //#region src/migration/sign-off/delete.ts
8
+ /**
9
+ * `protobase migration delete <module>`: writes the next migration, which drops what the sign-off archived of
10
+ * `module`, its tables and its column archives, and while it is off its rows in `auth_steps`, behind checks that
11
+ * refuse until the archive was applied `hours` ago and while `retired.writes` counts a write of it within them, or does
12
+ * not watch it. The snapshot no longer lists it as archived. Returns the file's path.
13
+ */
14
+ const writeDelete = async ({ projectDir, dir, hours, protobaseVersion, newId, module }) => {
15
+ const snapshot = await readSnapshot(projectDir);
16
+ const files = await readMigrationFiles(dir);
17
+ refuseInconsistent(snapshot, files);
18
+ const archived = snapshot?.decisions.modules.archived ?? [];
19
+ const entry = archived.find((found) => found.module === module);
20
+ if (!snapshot?.model.auth || !entry) {
21
+ const listed = archived.length === 0 ? "none is" : `${archived.map((found) => found.module).join(", ")} ${archived.length === 1 ? "is" : "are"}`;
22
+ throw new Error(`${module} has no archive to delete: ${listed} archived in ${snapshotFile}. A module turned off is archived by \`protobase migration contract\` once turned off with \`--off archive\` or \`--off delete\``);
23
+ }
24
+ const archive = signedOffFile(files, entry.file);
25
+ const steps = snapshot.model.auth.modules[entry.module] !== void 0 || snapshot.decisions.modules.kept.some((kept) => kept.module === entry.module) ? void 0 : stepRecordOf(snapshot.model.auth);
26
+ const body = [`-- Written by \`protobase migration delete ${module}\`: it drops for good what ${archive.name} archived of ${module}.\n`, `-- It applies once ${archive.name} was applied ${hours} hours ago, and while retired.writes counts no write of what it drops within them.\n${markedSql(archive.id, [signOffGate(archive, hours, `Deleting ${module}`, false), ...deleteStatements(entry, hours, steps)])}\n`].join("\n");
27
+ const decisions = {
28
+ ...snapshot.decisions,
29
+ modules: {
30
+ ...snapshot.decisions.modules,
31
+ archived: archived.filter((found) => found !== entry)
32
+ }
33
+ };
34
+ const content = {
35
+ name: `delete_${module}`,
36
+ body,
37
+ additive: false
38
+ };
39
+ const draft = {
40
+ previous: snapshot,
41
+ auth: snapshot.model.auth,
42
+ modules: snapshot.model.modules,
43
+ organizations: { on: false },
44
+ protobaseVersion,
45
+ decisions
46
+ };
47
+ return writeMigrationFile(projectDir, dir, content, draft, newId());
48
+ };
49
+ //#endregion
50
+ export { writeDelete };
@@ -0,0 +1,19 @@
1
+ import { snapshotFile } from "../snapshot/snapshot-file.js";
2
+ //#region src/migration/sign-off/signed-off-file.ts
3
+ /** The migration with id `id` among `files`, by its id and its name as `migrations.history` records it. */
4
+ const signedOffFile = (files, id) => {
5
+ const found = files.find(({ header }) => header?.id === id);
6
+ if (!found) throw new Error(`The migration ${id} is not among the project's migrations: take back the file that has it, or ${snapshotFile} from before it`);
7
+ return {
8
+ id,
9
+ name: found.file.replace(/\.sql$/, "")
10
+ };
11
+ };
12
+ /** The hours a sign-off waits, from `--hours`: a whole number, at least 1. */
13
+ const signOffHours = (value) => {
14
+ const hours = Number(value);
15
+ if (!Number.isInteger(hours) || hours < 1) throw new Error(`--hours takes a whole number of hours, at least 1, not "${value}"`);
16
+ return hours;
17
+ };
18
+ //#endregion
19
+ export { signOffHours, signedOffFile };
@@ -1,44 +1,164 @@
1
- import { snapshotFile } from "./snapshot-file.js";
2
- import { latestSteps, nameChanges, offlineStepsMigration, storeModel } from "@protobase/server/internal";
1
+ import { keptAfter, moduleChanges } from "./module-changes.js";
2
+ import { modelHash as modelHash$1, snapshotFile } from "./snapshot-file.js";
3
+ import { forgetStepsSql, keepSql, latestSteps, nameChanges, offlineStepsMigration, resolveNames, restoredKeysSql, retiredNames, revivalCheckSql, stepRecordOf, storeModel, unwatchSql } from "@protobase/server/internal";
3
4
  //#region src/migration/snapshot/auth-difference.ts
4
5
  /** Each module's last step in a model. */
5
6
  const lastStepsOf = (model) => Object.fromEntries(Object.entries(model.modules).map(([module, entry]) => [module, entry.lastStep]));
7
+ const stillOn = (model, target) => ({
8
+ ...model,
9
+ modules: Object.fromEntries(Object.entries(model.modules).filter(([module]) => target.names.names.modules.includes(module)))
10
+ });
11
+ const withRevived = (snapshot, before, target) => {
12
+ const revived = snapshot.decisions.modules.kept.filter(({ module }) => target.names.names.modules.includes(module));
13
+ return {
14
+ ...before,
15
+ modules: {
16
+ ...before.modules,
17
+ ...Object.fromEntries(revived.map(({ module, step, tables }) => [module, {
18
+ lastStep: step,
19
+ tables
20
+ }]))
21
+ }
22
+ };
23
+ };
24
+ const widerModel = (snapshot, before, target) => {
25
+ const modules = [.../* @__PURE__ */ new Set([...Object.keys(before.modules), ...target.names.names.modules])];
26
+ const names = resolveNames({
27
+ ...target.names.names.input,
28
+ modules
29
+ });
30
+ return stillOn(storeModel({
31
+ ...target.names,
32
+ names
33
+ }, snapshotStore(snapshot).lastSteps), target);
34
+ };
6
35
  /**
7
36
  * What the config asks of the auth store that Protobase's steps cannot write, one line each: sign-in turned off while
8
- * the snapshot has the store, or a name or type the store has changed. None when the steps can bring it there.
37
+ * the snapshot has the store, or a name or type the store has changed of a module that stays on or of a kept one
38
+ * turned on again. None when the steps can bring it there.
9
39
  */
10
40
  const authRefusals = (snapshot, target) => {
11
41
  const before = snapshot?.model.auth;
12
42
  if (!before) return [];
13
43
  if (!target) return [`sign-in is off while ${snapshotFile} has the auth store, and turning it off is not supported yet`];
14
- return nameChanges(before, storeModel(target.names, lastStepsOf(before))).map((change) => `the auth store's ${change}`);
44
+ return nameChanges(stillOn(withRevived(snapshot, before, target), target), widerModel(snapshot, before, target)).map((change) => `the auth store's ${change}`);
15
45
  };
16
- /** The steps the store lacks after the snapshot's, which leave alone a user table the snapshot records as external. */
17
- const stepsAfter = (snapshot, target) => {
46
+ /**
47
+ * What the config lacks of organizations, one line each: the default organization, once they are on or were ever on,
48
+ * which stands in for every one while they are off; and the role of the users there already, as they turn on for the
49
+ * first time over a store that may hold users, which each becomes a member of the default organization with.
50
+ */
51
+ const organizationRefusals = (snapshot, target) => {
52
+ const everOn = snapshot?.decisions.organizations.everOn ?? false;
53
+ if (!target.organizationsOn && !everOn) return [];
54
+ if (!target.organizations) return [`organizations.default is not set, and organizations ${target.organizationsOn ? "are on" : "were on"}: give the config the organization that stands in while they are off, such as default: { id: 'main', name: 'Main', slug: 'main' }`];
55
+ const store = snapshotStore(snapshot);
56
+ const firstOn = target.organizationsOn && store?.lastSteps.organizations === void 0;
57
+ const usersThere = store !== void 0 || target.names.users.keyTable !== void 0 || externalUser(snapshot, target);
58
+ if (firstOn && usersThere && target.organizations.existingUsersRole === void 0) return ["organizations.existingUsersRole is not set, and organizations turn on: name the app role every user there already holds in the default organization"];
59
+ return [];
60
+ };
61
+ /**
62
+ * The store as the snapshot has it, for the steps after its own: each module's last step, a kept one's included, so a
63
+ * module turned on again goes on from it; `undefined` when it has none.
64
+ */
65
+ const snapshotStore = (snapshot) => {
18
66
  const before = snapshot?.model.auth;
67
+ if (!before) return;
68
+ return {
69
+ lastSteps: {
70
+ ...Object.fromEntries(snapshot.decisions.modules.kept.map(({ module, step }) => [module, step])),
71
+ ...lastStepsOf(before)
72
+ },
73
+ on: Object.keys(before.modules),
74
+ stepRecord: before.modules.auth?.tables.auth_steps !== void 0
75
+ };
76
+ };
77
+ const externalUser = (snapshot, target) => {
19
78
  const user = target.names.names.table("user");
20
79
  const userName = target.names.schema === void 0 ? user.name : `${target.names.schema}.${user.name}`;
21
- return offlineStepsMigration(target.names, before && lastStepsOf(before), snapshot?.decisions.external?.includes(userName) ?? false);
80
+ return snapshot?.decisions.external?.includes(userName) ?? false;
22
81
  };
82
+ /** The steps the store lacks after the snapshot's, which leave alone a user table the snapshot records as external. */
83
+ const stepsAfter = (snapshot, target) => offlineStepsMigration(target.names, snapshotStore(snapshot), target.organizations, externalUser(snapshot, target));
23
84
  /** How to write what the steps cannot, once refused. */
24
85
  const customHint = "Write the change by hand with `protobase migration --custom <name> --record-config`.";
86
+ /** The way through when a module turned off has no choice made for its tables. */
87
+ const offHint = "Run `protobase migration` in a terminal to choose what becomes of its tables, or pass `--off keep`, `--off archive` or `--off delete`";
88
+ const refuseArchivedAgain = (snapshot, off, choice) => {
89
+ if (choice === "keep") return;
90
+ const again = off.filter(({ module }) => snapshot?.decisions.modules.archived.some((archived) => archived.module === module));
91
+ if (again.length === 0) return;
92
+ throw new Error(`${again.map(({ module }) => module).join(", ")} has an archive from an earlier time it was off: delete it first with \`protobase migration delete <module>\`, or pass \`--off keep\``);
93
+ };
94
+ const freshAfterArchive = (snapshot, before, target) => (snapshot?.decisions.modules.archived ?? []).filter(({ module }) => target.names.names.modules.includes(module) && !before?.modules[module] && !snapshot.decisions.modules.kept.some((kept) => kept.module === module));
95
+ const turnedOn = (snapshot, before, target) => before ? target.names.names.modules.filter((module) => !before.modules[module] && !snapshot.decisions.modules.kept.some((kept) => kept.module === module)) : [];
96
+ const forgetArchived = (fresh, before) => {
97
+ const steps = before && stepRecordOf(before);
98
+ if (!steps) return [];
99
+ return fresh.map(({ module }) => `-- ${module} on again after its archive: it starts again from its first step, and the archive stays as it is until \`protobase migration delete ${module}\`.\n${forgetStepsSql(steps, module)}`);
100
+ };
25
101
  /**
26
- * The difference between the snapshot's auth store and the config's, from the snapshot alone: the steps after each
27
- * module's last one (`migration`, undefined when there are none), and the store's model once they are applied.
102
+ * The difference between the snapshot's auth store and the config's, from the snapshot alone: `migration`, what keeps
103
+ * each module turned off (`off`, the choice made for them), the check that refuses to turn a kept one on again while
104
+ * its tables hold rows, and the steps after each module's last one, undefined when there is none of these; the
105
+ * store's model once it is applied; and the modules kept then, those turned off with archive or delete awaiting the
106
+ * sign-off that archives them, with the migration `file` that turns them off.
28
107
  */
29
- const authDifference = (snapshot, target) => {
108
+ const authDifference = (snapshot, target, off, file = "") => {
30
109
  const refusals = authRefusals(snapshot, target);
31
110
  if (refusals.length > 0) throw new Error(`${refusals.join("; ")}. ${customHint}`);
111
+ const unset = target ? organizationRefusals(snapshot, target) : [];
112
+ if (unset.length > 0) throw new Error(unset.join("; "));
113
+ const changes = moduleChanges(snapshot, target);
32
114
  if (!target) return {
33
115
  model: void 0,
34
- migration: void 0
116
+ migration: void 0,
117
+ changes,
118
+ kept: keptAfter(snapshot?.decisions.modules.kept ?? [], changes)
35
119
  };
120
+ if (changes.off.length > 0 && off === void 0) throw new Error(`${changes.off.map(({ module }) => module).join(", ")} is off in the config while ${snapshotFile} has its tables. ${offHint}.`);
121
+ refuseArchivedAgain(snapshot, changes.off, off);
36
122
  const before = snapshot?.model.auth;
37
- const migration = stepsAfter(snapshot, target);
123
+ const steps = stepsAfter(snapshot, target);
124
+ const existing = Object.keys(before?.modules ?? {});
125
+ const external = externalUser(snapshot, target) || target.names.users.keyTable !== void 0;
126
+ const deferred = off === "archive" || off === "delete" ? changes.off.map((module) => ({
127
+ ...module,
128
+ off: {
129
+ choice: off,
130
+ file,
131
+ columns: retiredNames(target.names, module.module, existing, external)
132
+ }
133
+ })) : changes.off;
134
+ const kept = keptAfter(snapshot?.decisions.modules.kept ?? [], {
135
+ ...changes,
136
+ off: deferred
137
+ });
138
+ const fresh = freshAfterArchive(snapshot, before, target);
139
+ const parts = [
140
+ ...forgetArchived(fresh, before),
141
+ ...changes.off.map(({ module }) => keepSql(target.names, module, existing, external)),
142
+ ...changes.revived.flatMap(({ module, step }) => [revivalCheckSql(target.names, module, step), ...[unwatchSql(target.names, module, existing, external)].filter((text) => text !== void 0)]),
143
+ ...steps ? [steps.sql] : [],
144
+ ...turnedOn(snapshot, before, target).flatMap((module) => [restoredKeysSql(target.names, module, existing)].filter((text) => text !== void 0))
145
+ ];
146
+ const model = storeModel(target.names, steps || !before ? latestSteps(target.names.names.modules) : snapshotStore(snapshot).lastSteps);
147
+ if (parts.length === 0 && redescribed(before, model)) parts.push(redescribedSql);
38
148
  return {
39
- migration,
40
- model: storeModel(target.names, migration || !before ? latestSteps(target.names.names.modules) : lastStepsOf(before))
149
+ migration: parts.length === 0 ? void 0 : {
150
+ sql: parts.join("\n\n"),
151
+ checks: steps?.checks ?? [],
152
+ ...steps?.after && { after: steps.after }
153
+ },
154
+ model,
155
+ changes,
156
+ kept
41
157
  };
42
158
  };
159
+ /** Whether this version of Protobase describes the snapshot's store otherwise than the snapshot does, with no step to apply. */
160
+ const redescribed = (before, model) => before !== void 0 && modelHash$1({ auth: before }) !== modelHash$1({ auth: model });
161
+ /** The migration that records the store as this version describes it, changing nothing in the database. */
162
+ const redescribedSql = "-- The auth store as this version of Protobase describes it, such as which tables hold the rows of an organization; nothing in the database changes.";
43
163
  //#endregion
44
- export { authDifference, authRefusals, customHint, lastStepsOf, stepsAfter };
164
+ export { authDifference, authRefusals, customHint, lastStepsOf, offHint, organizationRefusals, redescribed, redescribedSql, snapshotStore, stepsAfter };
@@ -1,13 +1,19 @@
1
- import { settingsStoreNames } from "@protobase/server/internal";
1
+ import { organizationsEnabled, organizationsInput, settingsStoreNames } from "@protobase/server/internal";
2
2
  //#region src/migration/snapshot/auth-target.ts
3
+ /** What the config says of organizations, as the snapshot records it; off without sign-in. */
4
+ const organizationsNow = (target) => ({
5
+ on: target?.organizationsOn ?? false,
6
+ ...target?.organizations && { default: target.organizations.default }
7
+ });
3
8
  /** The config's auth store, from its `auth` and whether auth/hooks.ts gives users their ids; `undefined` with sign-in off. */
4
9
  const authTarget = async (config) => {
5
10
  if (!config.auth) return;
6
11
  const hooks = await config.authFiles?.module("auth/hooks.ts")?.();
7
12
  return {
8
13
  names: settingsStoreNames(config.auth, typeof hooks?.generateUserId === "function"),
9
- organizationsOn: Boolean(config.auth.organizations)
14
+ organizationsOn: organizationsEnabled(config.auth.organizations),
15
+ organizations: organizationsInput(config.auth.organizations)
10
16
  };
11
17
  };
12
18
  //#endregion
13
- export { authTarget };
19
+ export { authTarget, organizationsNow };
@@ -1,24 +1,43 @@
1
+ import { moduleChanges } from "./module-changes.js";
1
2
  import { readSnapshot, snapshotFile } from "./snapshot-file.js";
2
- import { authRefusals, stepsAfter } from "./auth-difference.js";
3
+ import { authRefusals, organizationRefusals, redescribed, snapshotStore, stepsAfter } from "./auth-difference.js";
3
4
  import { readMigrationFiles } from "./migration-files.js";
4
5
  import { inconsistencies } from "./consistency.js";
5
6
  import "../../auth/migration-file.js";
6
- import { lintCustomFiles } from "./lint-custom.js";
7
+ import { moduleSections } from "./module-sections.js";
8
+ import { lintFiles } from "../older-code/lint-files.js";
9
+ import { schemaModules, storeModel } from "@protobase/server/internal";
7
10
  //#region src/migration/snapshot/check.ts
11
+ const unswitched = (snapshot, auth) => {
12
+ const { off, revived } = moduleChanges(snapshot, auth);
13
+ return off.length === 0 && revived.length === 0;
14
+ };
8
15
  /**
9
16
  * `protobase migration check`, for CI: what keeps the migrations from matching the config, one line each, from the
10
17
  * files and the snapshot alone, writing nothing. The snapshot disagreeing with the files, a config change the
11
- * migrations lack, and a hand-written migration marked additive that is not. None when they match.
18
+ * migrations lack, a schema module of `modules` they lack or have older, and a file that does not say, or says wrongly,
19
+ * how it treats older code (`lintFiles`). None when they match.
12
20
  */
13
- const checkMigrations = async (projectDir, dir, auth) => {
21
+ const checkMigrations = async (projectDir, dir, auth, modules) => {
14
22
  const snapshot = await readSnapshot(projectDir);
15
23
  const files = await readMigrationFiles(dir);
16
24
  const found = inconsistencies(snapshot, files);
17
25
  const refusals = authRefusals(snapshot, auth);
18
26
  if (!snapshot && auth && files.some(({ text }) => text.includes("The auth schema changes this version of Protobase needs"))) found.push(`the project has auth migrations from before ${snapshotFile}: start it with \`protobase migration baseline\`, against the database with the project's migrations applied`);
19
27
  else if (refusals.length > 0) found.push(...refusals);
28
+ else if (auth && organizationRefusals(snapshot, auth).length > 0) found.push(...organizationRefusals(snapshot, auth));
20
29
  else if (auth && stepsAfter(snapshot, auth)) found.push("the config and this version of Protobase need auth store steps the migrations lack: run `protobase migration`");
21
- return [...found, ...lintCustomFiles(files)];
30
+ else if (auth && snapshot?.model.auth && unswitched(snapshot, auth) && redescribed(snapshot.model.auth, storeModel(auth.names, snapshotStore(snapshot).lastSteps))) found.push("this version of Protobase describes the auth store otherwise than the migrations record it: run `protobase migration`");
31
+ const changes = moduleChanges(snapshot, auth);
32
+ const switched = [...changes.off.map(({ module }) => `${module} off`), ...changes.revived.map(({ module }) => `${module} on again`)];
33
+ if (refusals.length === 0 && switched.length > 0) found.push(`the config turns ${switched.join(", ")}, which the migrations lack: run \`protobase migration\``);
34
+ const sections = moduleSections(snapshot, modules).sections;
35
+ const label = ({ name }) => schemaModules[name].label;
36
+ const unrecorded = sections.filter(({ name }) => !snapshot?.model.modules?.[name]).map(label);
37
+ const behind = sections.filter(({ name }) => snapshot?.model.modules?.[name]).map(label);
38
+ if (unrecorded.length > 0) found.push(`the migrations do not record ${unrecorded.join(" and ")}: run \`protobase migration\`, or \`protobase migration baseline\` against the database where a migration of an earlier version made it`);
39
+ if (behind.length > 0) found.push(`the migrations lack what this version of Protobase writes of ${behind.join(" and ")}: run \`protobase migration\``);
40
+ return [...found, ...await lintFiles(files)];
22
41
  };
23
42
  //#endregion
24
43
  export { checkMigrations };
@@ -1,3 +1,4 @@
1
+ import { organizationsNow } from "./auth-target.js";
1
2
  import { readSnapshot, snapshotFile } from "./snapshot-file.js";
2
3
  import { lastStepsOf } from "./auth-difference.js";
3
4
  import { readMigrationFiles } from "./migration-files.js";
@@ -7,7 +8,7 @@ import { storeModel } from "@protobase/server/internal";
7
8
  //#region src/migration/snapshot/custom.ts
8
9
  const body = (recordConfig) => [
9
10
  `-- Written by hand; \`protobase migration --custom\` numbered it and made ${snapshotFile} end at it.`,
10
- "-- It counts as not additive. Once it only adds, put a line `-- protobase:additive` among the lines above, and `protobase migration check` lints it.",
11
+ ...recordConfig ? ["-- It breaks older code, as a rename does: once it is applied, the version before refuses to start on the database, and rolling back to it is blocked."] : ["-- Say what it is among the lines above: `-- protobase:additive` once it only adds, which `protobase migration check` lints, or `-- protobase:breaks-older-code` when it takes from older code what it reads, such as a rename or a dropped column; the version before then refuses to start on the database, and rolling back to it is blocked."],
11
12
  "-- Write its statements here, above the row that records it, which stays the last statement.",
12
13
  ...recordConfig ? [`-- ${snapshotFile} records the auth store as the config names it now: make the store match it here, such as renaming what the config renamed.`] : [],
13
14
  ""
@@ -30,7 +31,8 @@ const writeCustomMigration = async ({ projectDir, dir, name, recordConfig, after
30
31
  const draft = {
31
32
  previous: snapshot,
32
33
  auth: recordConfig ? before && auth && storeModel(auth.names, lastStepsOf(before)) : before,
33
- organizationsOn: auth?.organizationsOn ?? false,
34
+ modules: snapshot?.model.modules,
35
+ organizations: organizationsNow(auth),
34
36
  protobaseVersion
35
37
  };
36
38
  const content = {
@@ -38,7 +40,8 @@ const writeCustomMigration = async ({ projectDir, dir, name, recordConfig, after
38
40
  body: body(recordConfig),
39
41
  kind: {
40
42
  custom: true,
41
- additive: false
43
+ additive: false,
44
+ breaksOlderCode: recordConfig
42
45
  },
43
46
  additive: false,
44
47
  ...after && { after: afterBody }
@@ -4,7 +4,7 @@ import { protobaseFiles, readMigrationFiles } from "./migration-files.js";
4
4
  import { refuseInconsistent } from "./consistency.js";
5
5
  import path from "node:path";
6
6
  import { rm } from "node:fs/promises";
7
- import { storeNamesList } from "@protobase/server/internal";
7
+ import { contractMark, storeNamesList } from "@protobase/server/internal";
8
8
  //#region src/migration/snapshot/drop.ts
9
9
  const atSteps = (model, steps) => {
10
10
  if (!model || Object.keys(steps).length === 0) return;
@@ -31,6 +31,7 @@ const dropMigration = async (projectDir, dir) => {
31
31
  const written = protobaseFiles(files);
32
32
  const newest = written.at(-1);
33
33
  const previous = written.at(-2);
34
+ if (newest.text.includes(contractMark(""))) throw new Error(`${newest.file} signs off or deletes what an earlier migration retired, which changes ${snapshotFile}'s decisions: delete it by hand and take ${snapshotFile} from before it from version control`);
34
35
  const remove = async () => {
35
36
  await rm(path.join(dir, newest.file));
36
37
  await rm(path.join(dir, afterFileOf(newest.file)), { force: true });
@@ -41,7 +42,11 @@ const dropMigration = async (projectDir, dir) => {
41
42
  return newest.file;
42
43
  }
43
44
  const auth = atSteps(snapshot.model.auth, previous.header.steps);
44
- const model = auth ? { auth } : {};
45
+ const modules = previous.header.modules;
46
+ const model = {
47
+ ...auth && { auth },
48
+ ...modules && { modules }
49
+ };
45
50
  if (modelHash$1(model) !== previous.header.model) throw new Error(`${newest.file} changed more than the steps, so the snapshot before it cannot be rebuilt: delete it by hand and take ${snapshotFile} from before it from version control`);
46
51
  const rebuilt = {
47
52
  ...snapshot,
@@ -1,13 +1,17 @@
1
1
  //#region src/migration/snapshot/header.ts
2
+ /** The line that marks a hand-written file as breaking older code, after `-- `. */
3
+ const breaksOlderCodeLine = "protobase:breaks-older-code";
2
4
  const line = /^-- protobase:([a-z-]+)(?: (.*))?$/;
3
- const headerText = ({ id, version, steps, model, organizationsEverOn, custom, additive }) => [
5
+ const headerText = ({ id, version, steps, modules, model, organizationsEverOn, custom, additive, breaksOlderCode }) => [
4
6
  `-- protobase:id ${id}`,
5
7
  `-- protobase:version ${version}`,
6
8
  `-- protobase:steps ${Object.entries(steps).map(([module, step]) => `${module}=${step}`).join(" ")}`.trimEnd(),
9
+ ...modules ? [`-- protobase:modules ${JSON.stringify(modules)}`] : [],
7
10
  `-- protobase:model ${model}`,
8
11
  ...organizationsEverOn ? ["-- protobase:organizations ever-on"] : [],
9
12
  ...custom ? ["-- protobase:custom"] : [],
10
- ...additive ? ["-- protobase:additive"] : []
13
+ ...additive ? ["-- protobase:additive"] : [],
14
+ ...breaksOlderCode ? [`-- ${breaksOlderCodeLine}`] : []
11
15
  ].join("\n");
12
16
  /** The header of a migration's text; `undefined` when it does not start with Protobase's id. */
13
17
  const parseHeader = (text) => {
@@ -20,15 +24,18 @@ const parseHeader = (text) => {
20
24
  const id = values.get("id");
21
25
  if (!id) return;
22
26
  const steps = (values.get("steps") ?? "").split(" ").filter(Boolean).map((pair) => pair.split("="));
27
+ const modules = values.get("modules");
23
28
  return {
24
29
  id,
25
30
  version: values.get("version") ?? "",
26
31
  steps: Object.fromEntries(steps.map(([module, step]) => [module, Number(step)])),
32
+ ...modules && { modules: JSON.parse(modules) },
27
33
  model: values.get("model") ?? "",
28
34
  organizationsEverOn: values.get("organizations") === "ever-on",
29
35
  custom: values.has("custom"),
30
- additive: values.has("additive")
36
+ additive: values.has("additive"),
37
+ breaksOlderCode: values.has("breaks-older-code")
31
38
  };
32
39
  };
33
40
  //#endregion
34
- export { headerText, parseHeader };
41
+ export { breaksOlderCodeLine, headerText, parseHeader };
@@ -0,0 +1,22 @@
1
+ //#region src/migration/snapshot/module-changes.ts
2
+ /** What the config turns off or on again of the snapshot's modules; none without a store in either. */
3
+ const moduleChanges = (snapshot, target) => {
4
+ const before = snapshot?.model.auth;
5
+ if (!before || !target) return {
6
+ off: [],
7
+ revived: []
8
+ };
9
+ const on = target.names.names.modules;
10
+ return {
11
+ off: Object.entries(before.modules).filter(([module]) => !on.includes(module)).map(([module, entry]) => ({
12
+ module,
13
+ step: entry.lastStep,
14
+ tables: entry.tables
15
+ })),
16
+ revived: snapshot.decisions.modules.kept.filter(({ module }) => on.includes(module))
17
+ };
18
+ };
19
+ /** The modules kept once `changes` apply: those turned off join, those turned on again leave, by module. */
20
+ const keptAfter = (kept, changes) => [...kept.filter(({ module }) => !changes.revived.some((revived) => revived.module === module)), ...changes.off].sort((a, b) => a.module.localeCompare(b.module));
21
+ //#endregion
22
+ export { keptAfter, moduleChanges };
@@ -0,0 +1,42 @@
1
+ //#region src/migration/snapshot/module-prompts.ts
2
+ const rowsNote = (module) => module === "personal_access_tokens" ? "\n Its tokens stay valid unless deleted: once it is on again, each acts again for its user, refused while the user is banned, the token expired or the user no longer holds the token's role." : "";
3
+ const plural = (count, one, many) => `${count} ${count === 1 ? one : many}`;
4
+ const darkNote = (module, facts) => module === "organizations" && facts ? `\n While organizations are off, the default organization stands in for all of them, and only its members can sign in. That locks out ${plural(facts.outside, "person", "people")} and stops ${plural(facts.otherTokens, "personal access token", "personal access tokens")} created outside it from working.` : "";
5
+ /** The question that chooses what becomes of the tables of the modules turned off, saying what goes dark with organizations (`facts`). */
6
+ const offQuestion = (modules, facts) => `${modules.map(({ module }) => module).join(", ")} is off in the config. What becomes of its tables and rows?
7
+ keep: they stay as they are, and turning it on again goes on from them.
8
+ archive: they stay as they are until \`protobase migration contract\` signs the update off, which moves them to an archive the app cannot use.
9
+ delete: as archive, and once it is archived, \`protobase migration delete\` removes it for good.${modules.map(({ module }) => rowsNote(module) + darkNote(module, facts)).join("")}
10
+ [k]eep, [a]rchive or [d]elete (k): `;
11
+ const answers = {
12
+ keep: [
13
+ "",
14
+ "k",
15
+ "keep"
16
+ ],
17
+ archive: ["a", "archive"],
18
+ delete: ["d", "delete"]
19
+ };
20
+ /** Asks what becomes of the tables of the modules turned off: keep, the default, archive or delete. */
21
+ const chooseOff = (ask) => async (modules, facts) => {
22
+ const answer = (await ask(offQuestion(modules, facts))).trim().toLowerCase();
23
+ const choice = Object.keys(answers).find((known) => answers[known].includes(answer));
24
+ if (!choice) throw new Error(`"${answer}" is not a choice: answer keep, archive or delete`);
25
+ return choice;
26
+ };
27
+ /** The refusal of a module turned on again while its kept tables hold rows, with the way through. */
28
+ const revivalRefused = ({ module, found }) => `${module} is on again while its kept tables hold rows: ${found}. Delete them in a migration of the project's own first, or bring them back: pass --force to write the migration, and apply it with \`protobase migrate --force\``;
29
+ /** Asks whether to bring back the rows of a module turned on again. */
30
+ const confirmRevival = (ask) => async (rows) => {
31
+ const answer = (await ask(`${rows.module} is on again, and its kept tables hold rows: ${rows.found}. Bring them back into use?${rowsNote(rows.module)}\n The migration then applies with \`protobase migrate --force\`. [y/N] `)).trim().toLowerCase();
32
+ return answer === "y" || answer === "yes";
33
+ };
34
+ /** The way on once the store's only organization is chosen as the default: the config's entry for it, then a new run. */
35
+ const defaultChosen = ({ id, name, slug }) => `Nothing was written. Add \`default: { id: ${JSON.stringify(id)}, name: ${JSON.stringify(name)}, slug: ${JSON.stringify(slug)} }\` to \`auth.organizations\` in your config, and set \`authenticate.tenant\` to ${JSON.stringify(id)}. Then run \`protobase migration\` again.`;
36
+ /** Asks whether the store's only organization, which is not the default one, becomes the default. */
37
+ const offerDefault = (ask) => async (organization) => {
38
+ const answer = (await ask(`The store's only organization, ${organization.name} (${organization.slug}), is not the default organization, so nobody could sign in while organizations are off. Make ${organization.name} the default organization? [y/N] `)).trim().toLowerCase();
39
+ return answer === "y" || answer === "yes";
40
+ };
41
+ //#endregion
42
+ export { chooseOff, confirmRevival, defaultChosen, offQuestion, offerDefault, revivalRefused };