@protobase/cli 0.129.0 → 0.130.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 (96) 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 +50 -0
  16. package/dist/migration/baseline/write-baseline.js +80 -0
  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 +56 -15
  27. package/dist/migration/release/release-record.js +9 -7
  28. package/dist/migration/release/release-steps.js +15 -3
  29. package/dist/migration/snapshot/auth-difference.js +111 -12
  30. package/dist/migration/snapshot/auth-target.js +9 -3
  31. package/dist/migration/snapshot/check.js +26 -9
  32. package/dist/migration/snapshot/custom.js +6 -3
  33. package/dist/migration/snapshot/drop.js +5 -1
  34. package/dist/migration/snapshot/header.js +11 -4
  35. package/dist/migration/snapshot/module-changes.js +22 -0
  36. package/dist/migration/snapshot/module-prompts.js +28 -0
  37. package/dist/migration/snapshot/module-sections.js +38 -0
  38. package/dist/migration/snapshot/next-snapshot.js +24 -8
  39. package/dist/migration/snapshot/off-choice.js +11 -0
  40. package/dist/migration/snapshot/organizations-off-facts.js +49 -0
  41. package/dist/migration/snapshot/revival-rows.js +34 -0
  42. package/dist/migration/snapshot/run-migration.js +82 -16
  43. package/dist/migration/snapshot/snapshot-file.js +7 -0
  44. package/dist/migration/snapshot/terminal-prompts.js +21 -0
  45. package/dist/migration/snapshot/write-file.js +1 -1
  46. package/dist/migration/summary.js +3 -2
  47. package/dist/organizations/api.js +4 -2
  48. package/dist/organizations/commands.js +27 -10
  49. package/dist/organizations/pin-source.js +20 -0
  50. package/dist/organizations/pin.js +40 -0
  51. package/dist/organizations/register.js +20 -12
  52. package/dist/scaffold/protobase-tables.js +2 -2
  53. package/dist/serve/create-admin.js +6 -3
  54. package/dist/serve/lifecycle.js +2 -2
  55. package/dist/serve/migrate-release.js +1 -1
  56. package/dist/serve/relay-check.js +7 -8
  57. package/dist/serve/startup-checks.js +12 -22
  58. package/dist/supabase/load-phase.js +3 -1
  59. package/dist/supabase/project-users.js +4 -1
  60. package/dist/users/commands.js +44 -6
  61. package/dist/users/load-auth.js +9 -3
  62. package/dist/users/manage.js +16 -1
  63. package/dist/users/register.js +28 -25
  64. package/dist/users/set-disabled.js +3 -2
  65. package/dist/users/users-api.js +9 -3
  66. package/dist/worker/start-worker.js +7 -4
  67. package/package.json +8 -8
  68. package/skills/protobase/references/features/api-functions.md +1 -0
  69. package/skills/protobase/references/features/build-and-run.md +3 -2
  70. package/skills/protobase/references/features/sign-in-and-accounts.md +2 -1
  71. package/skills/protobase/references/guides/api-functions.md +27 -2
  72. package/skills/protobase/references/guides/deploy.md +2 -2
  73. package/skills/protobase/references/reference/assistant.md +1 -1
  74. package/skills/protobase/references/reference/auth.md +52 -17
  75. package/skills/protobase/references/reference/calls.md +1 -1
  76. package/skills/protobase/references/reference/cli.md +41 -27
  77. package/skills/protobase/references/reference/comments.md +1 -1
  78. package/skills/protobase/references/reference/config/api.md +1 -1
  79. package/skills/protobase/references/reference/config/jobs-and-events.md +1 -1
  80. package/skills/protobase/references/reference/config/sign-in.md +22 -4
  81. package/skills/protobase/references/reference/config.md +1 -1
  82. package/skills/protobase/references/reference/data-config.md +9 -9
  83. package/skills/protobase/references/reference/derived.md +1 -1
  84. package/skills/protobase/references/reference/email.md +2 -2
  85. package/skills/protobase/references/reference/events.md +2 -2
  86. package/skills/protobase/references/reference/history.md +1 -1
  87. package/skills/protobase/references/reference/jobs.md +5 -5
  88. package/skills/protobase/references/reference/live.md +2 -2
  89. package/skills/protobase/references/reference/notifications.md +4 -4
  90. package/skills/protobase/references/reference/personal-access-tokens.md +2 -2
  91. package/skills/protobase/references/reference/realtime-relay.md +1 -1
  92. package/skills/protobase/references/reference/status.md +2 -2
  93. package/skills/protobase/references/reference/supabase-rest.md +1 -1
  94. package/skills/protobase/references/reference/user-tables.md +1 -1
  95. package/skills/protobase/references/reference/webhooks.md +1 -1
  96. package/dist/migration/snapshot/lint-custom.js +0 -23
@@ -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,
@@ -1,37 +1,136 @@
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 { keepSql, latestSteps, nameChanges, offlineStepsMigration, resolveNames, revivalCheckSql, 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}`);
45
+ };
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) => {
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) => {
78
+ const user = target.names.names.table("user");
79
+ const userName = target.names.schema === void 0 ? user.name : `${target.names.schema}.${user.name}`;
80
+ return snapshot?.decisions.external?.includes(userName) ?? false;
15
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));
16
84
  /** How to write what the steps cannot, once refused. */
17
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`";
18
88
  /**
19
- * The difference between the snapshot's auth store and the config's, from the snapshot alone: the steps after each
20
- * module's last one (`migration`, undefined when there are none), and the store's model once they are applied.
89
+ * The difference between the snapshot's auth store and the config's, from the snapshot alone: `migration`, what keeps
90
+ * each module turned off (`off`, the choice made for them), the check that refuses to turn a kept one on again while
91
+ * its tables hold rows, and the steps after each module's last one, undefined when there is none of these; the
92
+ * store's model once it is applied; and the modules kept then.
21
93
  */
22
- const authDifference = (snapshot, target) => {
94
+ const authDifference = (snapshot, target, off) => {
23
95
  const refusals = authRefusals(snapshot, target);
24
96
  if (refusals.length > 0) throw new Error(`${refusals.join("; ")}. ${customHint}`);
97
+ const unset = target ? organizationRefusals(snapshot, target) : [];
98
+ if (unset.length > 0) throw new Error(unset.join("; "));
99
+ const changes = moduleChanges(snapshot, target);
100
+ const kept = keptAfter(snapshot?.decisions.modules.kept ?? [], changes);
25
101
  if (!target) return {
26
102
  model: void 0,
27
- migration: void 0
103
+ migration: void 0,
104
+ changes,
105
+ kept
28
106
  };
107
+ 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}.`);
108
+ if (changes.off.length > 0 && off !== "keep") throw new Error(`--off ${off} is not available yet: a module turned off keeps its tables and rows (--off keep)`);
29
109
  const before = snapshot?.model.auth;
30
- const migration = offlineStepsMigration(target.names, before && lastStepsOf(before));
110
+ const steps = stepsAfter(snapshot, target);
111
+ const existing = Object.keys(before?.modules ?? {});
112
+ const external = externalUser(snapshot, target) || target.names.users.keyTable !== void 0;
113
+ const parts = [
114
+ ...changes.off.map(({ module }) => keepSql(target.names, module, existing, external)),
115
+ ...changes.revived.flatMap(({ module, step }) => [revivalCheckSql(target.names, module, step), ...[unwatchSql(target.names, module, existing, external)].filter((text) => text !== void 0)]),
116
+ ...steps ? [steps.sql] : []
117
+ ];
118
+ const model = storeModel(target.names, steps || !before ? latestSteps(target.names.names.modules) : snapshotStore(snapshot).lastSteps);
119
+ if (parts.length === 0 && redescribed(before, model)) parts.push(redescribedSql);
31
120
  return {
32
- migration,
33
- model: storeModel(target.names, migration || !before ? latestSteps(target.names.names.modules) : lastStepsOf(before))
121
+ migration: parts.length === 0 ? void 0 : {
122
+ sql: parts.join("\n\n"),
123
+ checks: steps?.checks ?? [],
124
+ ...steps?.after && { after: steps.after }
125
+ },
126
+ model,
127
+ changes,
128
+ kept
34
129
  };
35
130
  };
131
+ /** Whether this version of Protobase describes the snapshot's store otherwise than the snapshot does, with no step to apply. */
132
+ const redescribed = (before, model) => before !== void 0 && modelHash$1({ auth: before }) !== modelHash$1({ auth: model });
133
+ /** The migration that records the store as this version describes it, changing nothing in the database. */
134
+ 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.";
36
135
  //#endregion
37
- export { authDifference, authRefusals, customHint, lastStepsOf };
136
+ 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,26 +1,43 @@
1
+ import { moduleChanges } from "./module-changes.js";
1
2
  import { readSnapshot, snapshotFile } from "./snapshot-file.js";
2
- import { authRefusals, lastStepsOf } 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 { offlineStepsMigration } from "@protobase/server/internal";
7
+ import { moduleSections } from "./module-sections.js";
8
+ import { lintFiles } from "../older-code/lint-files.js";
9
+ import { schemaModules, storeModel } from "@protobase/server/internal";
8
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
+ };
9
15
  /**
10
16
  * `protobase migration check`, for CI: what keeps the migrations from matching the config, one line each, from the
11
17
  * files and the snapshot alone, writing nothing. The snapshot disagreeing with the files, a config change the
12
- * 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.
13
20
  */
14
- const checkMigrations = async (projectDir, dir, auth) => {
21
+ const checkMigrations = async (projectDir, dir, auth, modules) => {
15
22
  const snapshot = await readSnapshot(projectDir);
16
23
  const files = await readMigrationFiles(dir);
17
24
  const found = inconsistencies(snapshot, files);
18
- const before = snapshot?.model.auth;
19
25
  const refusals = authRefusals(snapshot, auth);
20
- 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 auth migration\`, against the database with the project's migrations applied`);
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`);
21
27
  else if (refusals.length > 0) found.push(...refusals);
22
- else if (auth && offlineStepsMigration(auth.names, before && lastStepsOf(before))) found.push("the config and this version of Protobase need auth store steps the migrations lack: run `protobase migration`");
23
- return [...found, ...lintCustomFiles(files)];
28
+ else if (auth && organizationRefusals(snapshot, auth).length > 0) found.push(...organizationRefusals(snapshot, auth));
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`");
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)];
24
41
  };
25
42
  //#endregion
26
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 }
@@ -41,7 +41,11 @@ const dropMigration = async (projectDir, dir) => {
41
41
  return newest.file;
42
42
  }
43
43
  const auth = atSteps(snapshot.model.auth, previous.header.steps);
44
- const model = auth ? { auth } : {};
44
+ const modules = previous.header.modules;
45
+ const model = {
46
+ ...auth && { auth },
47
+ ...modules && { modules }
48
+ };
45
49
  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
50
  const rebuilt = {
47
51
  ...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,28 @@
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?\n keep: they stay as they are, and turning it on again goes on from them. Archive and delete are coming soon.${modules.map(({ module }) => rowsNote(module) + darkNote(module, facts)).join("")}\n [k]eep (k): `;
7
+ /** Asks what becomes of the tables of the modules turned off: keep, the default and for now the only choice. */
8
+ const chooseOff = (ask) => async (modules, facts) => {
9
+ const answer = (await ask(offQuestion(modules, facts))).trim().toLowerCase();
10
+ if (answer === "" || answer === "k" || answer === "keep") return "keep";
11
+ throw new Error(`"${answer}" is not a choice: keep is the only one for now`);
12
+ };
13
+ /** The refusal of a module turned on again while its kept tables hold rows, with the way through. */
14
+ 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\``;
15
+ /** Asks whether to bring back the rows of a module turned on again. */
16
+ const confirmRevival = (ask) => async (rows) => {
17
+ 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();
18
+ return answer === "y" || answer === "yes";
19
+ };
20
+ /** The way on once the store's only organization is chosen as the default: the config's entry for it, then a new run. */
21
+ 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.`;
22
+ /** Asks whether the store's only organization, which is not the default one, becomes the default. */
23
+ const offerDefault = (ask) => async (organization) => {
24
+ 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();
25
+ return answer === "y" || answer === "yes";
26
+ };
27
+ //#endregion
28
+ export { chooseOff, confirmRevival, defaultChosen, offQuestion, offerDefault, revivalRefused };
@@ -0,0 +1,38 @@
1
+ import { moduleDifference, retiredDifference, schemaModules, targetIds } from "@protobase/server/internal";
2
+ //#region src/migration/snapshot/module-sections.ts
3
+ /**
4
+ * What the schema modules of `targets` lack of the snapshot's model, from the snapshot alone: each module's
5
+ * statements, by module, with what of them the code before does not run on and what they leave for once the
6
+ * transaction commits (`after`); and the modules' model once they are applied. A module the config no longer needs stays as the migrations left it, but for each resource's objects, which
7
+ * go, breaking older code (`retiredDifference`). `model` is undefined without any module.
8
+ */
9
+ const moduleSections = (snapshot, targets) => {
10
+ const before = snapshot?.model.modules;
11
+ const written = targetIds(targets).map((id) => ({
12
+ id,
13
+ ...moduleDifference(schemaModules[id], targets[id], before?.[id])
14
+ }));
15
+ const retired = Object.keys(schemaModules).flatMap((id) => {
16
+ const had = before?.[id];
17
+ return had && !targets[id] ? [{
18
+ id,
19
+ ...retiredDifference(schemaModules[id], had)
20
+ }] : [];
21
+ });
22
+ const changed = [...written, ...retired];
23
+ return {
24
+ sections: changed.flatMap(({ id, sql, after, breaks }) => sql === void 0 ? [] : [{
25
+ name: id,
26
+ title: schemaModules[id].title,
27
+ sql,
28
+ breaks,
29
+ ...after !== void 0 && { after }
30
+ }]),
31
+ model: changed.length > 0 ? {
32
+ ...before,
33
+ ...Object.fromEntries(changed.map(({ id, model }) => [id, model]))
34
+ } : before
35
+ };
36
+ };
37
+ //#endregion
38
+ export { moduleSections };
@@ -2,9 +2,22 @@ import { modelHash as modelHash$1 } from "./snapshot-file.js";
2
2
  import { lastStepsOf } from "./auth-difference.js";
3
3
  import { storeNamesList } from "@protobase/server/internal";
4
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 } : {};
5
+ const externalUser = (auth) => {
6
+ const user = auth?.modules.auth?.tables.user;
7
+ if (!auth?.userKeyTable || !user) return [];
8
+ return [auth.schema === null ? user.name : `${auth.schema}.${user.name}`];
9
+ };
10
+ /**
11
+ * The snapshot once the migration `endsAt` is applied: `auth`, the store's model then, `modules`, the schema modules'
12
+ * then, and what the config says of organizations now. It goes on from `before`, the decisions of the snapshot before it, which a baseline reads from
13
+ * the database.
14
+ */
15
+ const nextSnapshot = (before, auth, modules, organizations, endsAt, protobaseVersion) => {
16
+ const model = {
17
+ ...auth && { auth },
18
+ ...modules && { modules }
19
+ };
20
+ const external = [.../* @__PURE__ */ new Set([...before?.external ?? [], ...externalUser(auth)])].sort();
8
21
  return {
9
22
  format: 1,
10
23
  protobaseVersion,
@@ -12,14 +25,15 @@ const nextSnapshot = (previous, auth, organizationsOn, endsAt, protobaseVersion)
12
25
  modelHash: modelHash$1(model),
13
26
  model,
14
27
  decisions: {
15
- modules: previous?.decisions.modules ?? {
28
+ modules: before?.modules ?? {
16
29
  kept: [],
17
30
  archived: []
18
31
  },
19
32
  organizations: {
20
- everOn: (previous?.decisions.organizations.everOn ?? false) || organizationsOn,
21
- defaultOrganization: previous?.decisions.organizations.defaultOrganization ?? null
22
- }
33
+ everOn: (before?.organizations.everOn ?? false) || organizations.on,
34
+ defaultOrganization: organizations.default ?? before?.organizations.defaultOrganization ?? null
35
+ },
36
+ ...external.length > 0 && { external }
23
37
  },
24
38
  physical: auth ? { auth: storeNamesList(auth) } : {}
25
39
  };
@@ -27,11 +41,13 @@ const nextSnapshot = (previous, auth, organizationsOn, endsAt, protobaseVersion)
27
41
  /** The header of the migration a snapshot ends at. */
28
42
  const snapshotHeader = (snapshot, kind = {
29
43
  custom: false,
30
- additive: false
44
+ additive: false,
45
+ breaksOlderCode: false
31
46
  }) => ({
32
47
  id: snapshot.endsAt.id,
33
48
  version: snapshot.protobaseVersion,
34
49
  steps: snapshot.model.auth ? lastStepsOf(snapshot.model.auth) : {},
50
+ ...snapshot.model.modules && { modules: snapshot.model.modules },
35
51
  model: snapshot.modelHash,
36
52
  organizationsEverOn: snapshot.decisions.organizations.everOn,
37
53
  ...kind
@@ -0,0 +1,11 @@
1
+ import { offChoices } from "@protobase/server/internal";
2
+ //#region src/migration/snapshot/off-choice.ts
3
+ /** The `--off` choice, checked: one of `offChoices`, or `undefined` when not given. */
4
+ const offChoice = (value) => {
5
+ if (value === void 0) return;
6
+ const choice = offChoices.find((known) => known === value);
7
+ if (!choice) throw new Error(`--off takes ${offChoices.join(", ")}, not "${value}"`);
8
+ return choice;
9
+ };
10
+ //#endregion
11
+ export { offChoice };
@@ -0,0 +1,49 @@
1
+ import { keptNames, resolveNames } from "@protobase/server/internal";
2
+ import postgres from "postgres";
3
+ //#region src/migration/snapshot/organizations-off-facts.ts
4
+ const tokensOutside = async (tx, token, organizationId, defaultId) => {
5
+ const [found] = await tx.unsafe(`select to_regclass($1) is not null as table, exists (select from pg_catalog.pg_attribute where attrelid = to_regclass($1) and attname = $2 and not attisdropped) as column`, [String(token), organizationId.name]);
6
+ if (!found.table) return 0;
7
+ const where = found.column ? ` where ${organizationId} is distinct from $1` : "";
8
+ const [tokens] = await tx.unsafe(`select count(*)::int as count from ${token}${where}`, found.column ? [defaultId] : []);
9
+ return tokens.count;
10
+ };
11
+ /** The facts of turning organizations off, read from the database at `url` in a read-only transaction, the tables named as organizations on name them. */
12
+ const organizationsOffFacts = async (url, names, defaultId) => {
13
+ const kept = keptNames(names.names);
14
+ const user = kept.table("user");
15
+ const member = kept.table("member");
16
+ const organization = kept.table("organization");
17
+ const { organization_id: memberOrganization, user_id: memberUser } = member.columns;
18
+ const { name, slug } = organization.columns;
19
+ const { schema, tables } = names.names.input;
20
+ const token = resolveNames({
21
+ schema,
22
+ tables
23
+ }).table("personal_access_token");
24
+ const sql = postgres(url, {
25
+ max: 1,
26
+ onnotice: () => {}
27
+ });
28
+ try {
29
+ return await sql.begin("read only", async (tx) => {
30
+ const [people] = await tx.unsafe(`select count(*)::int as count from ${user} as people where not exists (select from ${member} where ${memberOrganization} = $1 and ${memberUser} = people.id)`, [defaultId]);
31
+ const otherTokens = await tokensOutside(tx, token, token.columns.organization_id, defaultId);
32
+ const organizations = await tx.unsafe(`select id::text as id, ${name} as name, ${slug} as slug from ${organization} order by id limit 2`);
33
+ const only = organizations.length === 1 && organizations[0].id !== defaultId ? organizations[0] : void 0;
34
+ return {
35
+ outside: people.count,
36
+ otherTokens,
37
+ ...only && { only: {
38
+ id: only.id,
39
+ name: only.name,
40
+ slug: only.slug
41
+ } }
42
+ };
43
+ });
44
+ } finally {
45
+ await sql.end();
46
+ }
47
+ };
48
+ //#endregion
49
+ export { organizationsOffFacts };
@@ -0,0 +1,34 @@
1
+ import { keptTables } from "@protobase/server/internal";
2
+ import postgres from "postgres";
3
+ //#region src/migration/snapshot/revival-rows.ts
4
+ /**
5
+ * The rows the tables of each module of `revived` kept while off still hold, in the database at `url`, read in a
6
+ * read-only transaction: one count per table. Modules whose tables are empty are left out.
7
+ */
8
+ const revivedRows = async (url, names, revived) => {
9
+ const sql = postgres(url, {
10
+ max: 1,
11
+ onnotice: () => {}
12
+ });
13
+ try {
14
+ return await sql.begin("read only", async (tx) => {
15
+ const found = [];
16
+ for (const { module, step } of revived) {
17
+ const counts = [];
18
+ for (const table of keptTables(names, module, step)) {
19
+ const [row] = await tx.unsafe(`select count(*)::int as rows from ${String(table)}`);
20
+ if (row.rows > 0) counts.push(`${table.name} ${row.rows}`);
21
+ }
22
+ if (counts.length > 0) found.push({
23
+ module,
24
+ found: counts.sort().join(", ")
25
+ });
26
+ }
27
+ return found;
28
+ });
29
+ } finally {
30
+ await sql.end();
31
+ }
32
+ };
33
+ //#endregion
34
+ export { revivedRows };