@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
@@ -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 };
@@ -8,11 +8,15 @@ const externalUser = (auth) => {
8
8
  return [auth.schema === null ? user.name : `${auth.schema}.${user.name}`];
9
9
  };
10
10
  /**
11
- * The snapshot once the migration `endsAt` is applied: `auth`, the store's model then, and whether organizations are
12
- * on now. It goes on from `before`, the decisions of the snapshot before it, which a baseline reads from the database.
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.
13
14
  */
14
- const nextSnapshot = (before, auth, organizationsOn, endsAt, protobaseVersion) => {
15
- const model = auth ? { auth } : {};
15
+ const nextSnapshot = (before, auth, modules, organizations, endsAt, protobaseVersion) => {
16
+ const model = {
17
+ ...auth && { auth },
18
+ ...modules && { modules }
19
+ };
16
20
  const external = [.../* @__PURE__ */ new Set([...before?.external ?? [], ...externalUser(auth)])].sort();
17
21
  return {
18
22
  format: 1,
@@ -26,8 +30,8 @@ const nextSnapshot = (before, auth, organizationsOn, endsAt, protobaseVersion) =
26
30
  archived: []
27
31
  },
28
32
  organizations: {
29
- everOn: (before?.organizations.everOn ?? false) || organizationsOn,
30
- defaultOrganization: before?.organizations.defaultOrganization ?? null
33
+ everOn: (before?.organizations.everOn ?? false) || organizations.on,
34
+ defaultOrganization: organizations.default ?? before?.organizations.defaultOrganization ?? null
31
35
  },
32
36
  ...external.length > 0 && { external }
33
37
  },
@@ -37,11 +41,13 @@ const nextSnapshot = (before, auth, organizationsOn, endsAt, protobaseVersion) =
37
41
  /** The header of the migration a snapshot ends at. */
38
42
  const snapshotHeader = (snapshot, kind = {
39
43
  custom: false,
40
- additive: false
44
+ additive: false,
45
+ breaksOlderCode: false
41
46
  }) => ({
42
47
  id: snapshot.endsAt.id,
43
48
  version: snapshot.protobaseVersion,
44
49
  steps: snapshot.model.auth ? lastStepsOf(snapshot.model.auth) : {},
50
+ ...snapshot.model.modules && { modules: snapshot.model.modules },
45
51
  model: snapshot.modelHash,
46
52
  organizationsEverOn: snapshot.decisions.organizations.everOn,
47
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 };
@@ -1,51 +1,118 @@
1
+ import { organizationsNow } from "./auth-target.js";
2
+ import { moduleChanges } from "./module-changes.js";
1
3
  import { readSnapshot, snapshotFile } from "./snapshot-file.js";
2
4
  import { authDifference } from "./auth-difference.js";
3
5
  import { readMigrationFiles } from "./migration-files.js";
4
6
  import { refuseInconsistent } from "./consistency.js";
5
7
  import { authMigrationTitle } from "../../auth/migration-file.js";
6
8
  import { writeMigrationFile } from "./write-file.js";
9
+ import { defaultChosen, revivalRefused } from "./module-prompts.js";
10
+ import { organizationsOffFacts } from "./organizations-off-facts.js";
11
+ import { revivedRows } from "./revival-rows.js";
12
+ import { breaksOlderCodeNote, olderCodeRefusal } from "../older-code/refusal.js";
13
+ import { moduleSections } from "./module-sections.js";
7
14
  import { runPreconditions } from "./preconditions.js";
15
+ import { schemaModules } from "@protobase/server/internal";
8
16
  //#region src/migration/snapshot/run-migration.ts
17
+ const checkRevivals = async (url, run, revived) => {
18
+ if (revived.length === 0 || run.force) return;
19
+ for (const rows of await revivedRows(url, run.auth.names, revived)) if (!(run.confirmRevival && await run.confirmRevival(rows))) throw new Error(revivalRefused(rows));
20
+ };
21
+ const refuseUnrecorded = async (read, snapshot, sections, targets) => {
22
+ for (const { name } of sections) {
23
+ if (snapshot?.model.modules?.[name] || !await read(name, targets[name])) continue;
24
+ throw new Error(`The database has ${schemaModules[name].label}, which ${snapshotFile} does not record: describe it with \`protobase migration baseline\`, run against the database with the project's migrations applied, then run \`protobase migration\` again`);
25
+ }
26
+ };
27
+ const offFacts = async (run, turnedOff) => {
28
+ const defaultId = run.auth?.organizations?.default.id;
29
+ if (!run.database || defaultId === void 0 || !turnedOff.some(({ module }) => module === "organizations")) return;
30
+ const facts = await organizationsOffFacts(run.database.url, run.auth.names, defaultId);
31
+ if (facts.only && run.offerDefault && await run.offerDefault(facts.only)) throw new Error(defaultChosen(facts.only));
32
+ return facts;
33
+ };
9
34
  const section = (title, sql) => `-- ${title}.\n${sql}\n`;
10
35
  /** The line `protobase migration`'s files open with, under their header. */
11
36
  const intro = `-- Written by \`protobase migration\` from the config and ${snapshotFile}; applied with the project's other migrations.\n`;
12
37
  /**
13
38
  * `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
39
+ * snapshot to end at it. The auth store's steps and the schema modules' come from the snapshot alone; with a database,
40
+ * the steps' checks run against its rows, and the other parts are compared with it. Every part is compared before anything is written. Returns the
16
41
  * file's path, `undefined` when nothing differs.
17
42
  */
18
- const runMigration = async ({ projectDir, dir, auth, database, protobaseVersion, newId }) => {
43
+ const runMigration = async (run) => {
44
+ const { projectDir, dir, auth, modules, database, protobaseVersion, newId } = run;
19
45
  const snapshot = await readSnapshot(projectDir);
20
46
  const files = await readMigrationFiles(dir);
21
47
  refuseInconsistent(snapshot, files);
22
48
  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 migration baseline\`, run against the database with the project's migrations applied, then run \`protobase migration\` again`);
23
- const difference = authDifference(snapshot, auth);
49
+ const { off: turnedOff } = moduleChanges(snapshot, auth);
50
+ const off = run.off ?? (turnedOff.length > 0 && run.chooseOff ? await run.chooseOff(turnedOff, await offFacts(run, turnedOff)) : void 0);
51
+ const id = newId();
52
+ const difference = authDifference(snapshot, auth, off, id);
53
+ if (database) await checkRevivals(database.url, run, difference.changes.revived);
24
54
  if (database && difference.migration && difference.migration.checks.length > 0) await runPreconditions(database.url, difference.migration.checks);
55
+ const written = moduleSections(snapshot, modules);
56
+ if (database) await refuseUnrecorded(database.readModule, snapshot, written.sections, modules);
25
57
  const compared = [];
26
58
  for (const part of database?.parts ?? []) {
27
- const sql = await part.sql({ authWritten: Boolean(difference.migration) });
59
+ const sql = await part.sql();
28
60
  if (sql !== void 0) compared.push({
29
61
  name: part.name,
30
62
  text: section(part.title, sql)
31
63
  });
32
64
  }
33
- const sections = [...difference.migration ? [{
34
- name: "auth",
35
- text: section(authMigrationTitle, difference.migration.sql)
36
- }] : [], ...compared];
65
+ const sections = [
66
+ ...difference.migration ? [{
67
+ name: "auth",
68
+ text: section(authMigrationTitle, difference.migration.sql)
69
+ }] : [],
70
+ ...written.sections.map(({ name, title, sql }) => ({
71
+ name,
72
+ text: section(title, sql)
73
+ })),
74
+ ...compared
75
+ ];
37
76
  if (sections.length === 0) return;
77
+ const own = /* @__PURE__ */ new Set(["auth", ...written.sections.map(({ name }) => name)]);
78
+ const found = database ? await database.contractions(sections) : [];
79
+ const refused = found.filter(({ name }) => !own.has(name));
80
+ if (refused.length > 0) throw new Error(olderCodeRefusal(refused));
81
+ const label = (name) => name === "auth" ? "The sign-in modules' steps" : schemaModules[name].title;
82
+ const breaking = [...found.flatMap(({ name, found: lines }) => lines.map((line) => `${label(name)}: ${line}`)), ...written.sections.flatMap(({ title, breaks }) => breaks.map((line) => `${title}: ${line}`))];
83
+ const afterParts = [...difference.migration?.after ? [difference.migration.after.trimEnd()] : [], ...written.sections.flatMap(({ title, after }) => after === void 0 ? [] : [section(title, after).trimEnd()])];
84
+ const after = afterParts.length > 0 ? `${afterParts.join("\n\n")}\n` : void 0;
38
85
  const content = {
39
86
  name: sections.map(({ name }) => name).join("_"),
40
- body: [intro, ...sections.map(({ text }) => text)].join("\n"),
41
- additive: sections.every(({ name }) => name === "auth")
87
+ body: [
88
+ intro,
89
+ ...breaking.length > 0 ? [breaksOlderCodeNote(breaking)] : [],
90
+ ...sections.map(({ text }) => text)
91
+ ].join("\n"),
92
+ additive: breaking.length === 0,
93
+ ...breaking.length > 0 && { kind: {
94
+ custom: false,
95
+ additive: false,
96
+ breaksOlderCode: true
97
+ } },
98
+ ...after && { after }
99
+ };
100
+ const decisions = snapshot && {
101
+ ...snapshot.decisions,
102
+ modules: {
103
+ ...snapshot.decisions.modules,
104
+ kept: difference.kept
105
+ }
42
106
  };
43
- return writeMigrationFile(projectDir, dir, content, {
107
+ const draft = {
44
108
  previous: snapshot,
45
109
  auth: difference.model,
46
- organizationsOn: auth?.organizationsOn ?? false,
47
- protobaseVersion
48
- }, newId());
110
+ modules: written.model,
111
+ organizations: organizationsNow(auth),
112
+ protobaseVersion,
113
+ ...decisions && { decisions }
114
+ };
115
+ return writeMigrationFile(projectDir, dir, content, draft, id);
49
116
  };
50
117
  //#endregion
51
118
  export { intro, runMigration };
@@ -21,11 +21,18 @@ const checkFormat = (format) => {
21
21
  if (format > 1) throw new Error(`${snapshotFile} is format ${format}, which a newer Protobase wrote; this one reads format 1: upgrade Protobase`);
22
22
  if (format < 1) throw new Error(`${snapshotFile} is format ${format}; this Protobase reads format 1: run \`protobase migration up\``);
23
23
  };
24
+ /** Refuses kept modules recorded without their step and tables, which `protobase migration baseline` writes again. */
25
+ const checkKept = (snapshot) => {
26
+ const named = snapshot.decisions.modules.kept.filter((kept) => typeof kept !== "object" || kept === null || typeof kept.step !== "number" || typeof kept.tables !== "object");
27
+ if (named.length === 0) return;
28
+ throw new Error(`${snapshotFile} keeps ${named.map(String).join(", ")} without the step and tables it had: start the snapshot again with \`protobase migration baseline\``);
29
+ };
24
30
  /** The project's snapshot; `undefined` when it has none. */
25
31
  const readSnapshot = async (projectDir) => {
26
32
  const json = await readSnapshotJson(projectDir);
27
33
  if (!json) return;
28
34
  checkFormat(json.format);
35
+ checkKept(json);
29
36
  return json;
30
37
  };
31
38
  const writeSnapshot = (projectDir, snapshot) => writeFile(path.join(projectDir, snapshotFile), snapshotText(snapshot));
@@ -0,0 +1,21 @@
1
+ import { chooseOff, confirmRevival, offerDefault } from "./module-prompts.js";
2
+ import { createInterface } from "node:readline/promises";
3
+ //#region src/migration/snapshot/terminal-prompts.ts
4
+ /** The questions of `protobase migration` asked on the terminal, and what closes it once answered. */
5
+ const terminalPrompts = () => {
6
+ const rl = createInterface({
7
+ input: process.stdin,
8
+ output: process.stdout
9
+ });
10
+ const ask = (question) => rl.question(question);
11
+ return {
12
+ prompts: {
13
+ chooseOff: chooseOff(ask),
14
+ confirmRevival: confirmRevival(ask),
15
+ offerDefault: offerDefault(ask)
16
+ },
17
+ close: () => rl.close()
18
+ };
19
+ };
20
+ //#endregion
21
+ export { terminalPrompts };
@@ -14,7 +14,7 @@ import { mkdir, readdir, writeFile } from "node:fs/promises";
14
14
  const writeMigrationFile = async (projectDir, dir, content, draft, id) => {
15
15
  await mkdir(dir, { recursive: true });
16
16
  const file = nextMigrationName(await readdir(dir), content.name);
17
- const snapshot = nextSnapshot(draft.decisions ?? draft.previous?.decisions, draft.auth, draft.organizationsOn, {
17
+ const snapshot = nextSnapshot(draft.decisions ?? draft.previous?.decisions, draft.auth, draft.modules, draft.organizations, {
18
18
  file,
19
19
  id
20
20
  }, draft.protobaseVersion);
@@ -5,11 +5,12 @@ import path from "node:path";
5
5
  const signInGuide = "https://docs.protobase.net/guides/existing-database/";
6
6
  /**
7
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
8
+ * the config needs. Without a database (`compared` false), the features besides the auth store and the schema modules,
9
+ * which the snapshot holds, were not compared. A
9
10
  * config with sign-in off (`auth: false`) has no auth store, so the migrations being current says nothing about it.
10
11
  */
11
12
  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
+ 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 and the jobs schema were compared, with the snapshot: 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
14
  };
14
15
  //#endregion
15
16
  export { migrationSummary, signInGuide };
@@ -1,12 +1,14 @@
1
+ import { pinSource } from "./pin-source.js";
1
2
  import { addAppRoleToOwners, addEveryUser, addMember, createOrganization, listOrganizations, removeMember, setMemberRoles } from "@protobase/server";
2
3
  //#region src/organizations/api.ts
3
4
  const organizationsApi = (auth) => ({
4
- listOrganizations: (after) => listOrganizations(auth, after && { after }),
5
+ ...pinSource(auth),
6
+ listOrganizations: (scope, after) => listOrganizations(auth, scope, after && { after }),
5
7
  createOrganization: (input) => createOrganization(auth, input),
6
8
  addMember: (input) => addMember(auth, input),
7
9
  setMemberRoles: (input) => setMemberRoles(auth, input),
8
10
  removeMember: (input) => removeMember(auth, input),
9
- addAppRoleToOwners: (appRole) => addAppRoleToOwners(auth, appRole),
11
+ addAppRoleToOwners: (scope, appRole) => addAppRoleToOwners(auth, scope, appRole),
10
12
  addEveryUser: (organization) => addEveryUser(auth, organization)
11
13
  });
12
14
  //#endregion
@@ -1,10 +1,14 @@
1
+ import { pinLine, resolvePin, scopeOf } from "./pin.js";
2
+ import { everyOrganization } from "@protobase/query";
1
3
  //#region src/organizations/commands.ts
2
4
  /** A slug from a name: lowercase ASCII words joined by dashes; diacritics are dropped, so Müller becomes muller. */
3
5
  const slugOf = (name) => name.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 63);
4
6
  /** `a,b` as a list of roles; an empty text is none. */
5
7
  const parseRoleList = (text) => text === void 0 ? void 0 : text.split(",").map((name) => name.trim()).filter(Boolean);
6
- const listOrganizationsCommand = async (api, out) => {
7
- let page = await api.listOrganizations();
8
+ const listOrganizationsCommand = async (api, options, out) => {
9
+ const pin = await resolvePin(api, options, "organizations list", () => everyOrganization("protobase organizations list: --all-organizations"));
10
+ out(pinLine(pin));
11
+ let page = await api.listOrganizations(scopeOf(pin));
8
12
  if (page.organizations.length === 0) {
9
13
  out("No organizations yet. Create one with: protobase organizations create \"Acme\" --owner you@example.com\n");
10
14
  return;
@@ -15,7 +19,7 @@ const listOrganizationsCommand = async (api, out) => {
15
19
  for (const member of organization.members) out(` ${member.email} ${member.role}${member.appRoles.length > 0 ? ` ${member.appRoles.join(",")}` : ""}\n`);
16
20
  }
17
21
  if (!page.next) return;
18
- page = await api.listOrganizations(page.next);
22
+ page = await api.listOrganizations(scopeOf(pin), page.next);
19
23
  }
20
24
  };
21
25
  /**
@@ -37,34 +41,47 @@ const createOrganizationCommand = async (api, options, out) => {
37
41
  for (const user of await api.addEveryUser(organization.id)) if (user.role === "owner") out(` ${user.email}: owner, with every app role\n`);
38
42
  else out(` ${user.email}: member${user.appRoles.length > 0 ? `, with ${user.appRoles.join(",")}` : ""}\n`);
39
43
  };
44
+ const memberPin = async (api, options, command) => {
45
+ const pin = await resolvePin(api, options, command);
46
+ if ("every" in pin) throw new Error(`protobase ${command} acts on one organization`);
47
+ return pin.organization;
48
+ };
40
49
  const addMemberCommand = async (api, options, out) => {
41
50
  const appRoles = parseRoleList(options.appRoles);
51
+ const organization = await memberPin(api, options, "organizations add-member");
42
52
  await api.addMember({
43
- organization: options.organization,
53
+ organization: organization.id,
44
54
  email: options.email,
45
55
  ...options.orgRole && { role: options.orgRole },
46
56
  ...appRoles && { appRoles }
47
57
  });
48
- out(`Added ${options.email} to ${options.organization}\n`);
58
+ out(`Added ${options.email} to ${organization.slug}\n`);
49
59
  };
50
60
  const setMemberRolesCommand = async (api, options, out) => {
51
61
  const appRoles = parseRoleList(options.appRoles);
52
62
  if (options.orgRole === void 0 && appRoles === void 0) throw new Error("Pass --org-role, --app-roles or both");
63
+ const organization = await memberPin(api, options, "organizations set-roles");
53
64
  await api.setMemberRoles({
54
- organization: options.organization,
65
+ organization: organization.id,
55
66
  email: options.email,
56
67
  ...options.orgRole && { role: options.orgRole },
57
68
  ...appRoles && { appRoles }
58
69
  });
59
- out(`Changed the roles of ${options.email} in ${options.organization}\n`);
70
+ out(`Changed the roles of ${options.email} in ${organization.slug}\n`);
60
71
  };
61
72
  const removeMemberCommand = async (api, options, out) => {
62
- await api.removeMember(options);
63
- out(`Removed ${options.email} from ${options.organization}\n`);
73
+ const organization = await memberPin(api, options, "organizations remove-member");
74
+ await api.removeMember({
75
+ organization: organization.id,
76
+ email: options.email
77
+ });
78
+ out(`Removed ${options.email} from ${organization.slug}\n`);
64
79
  };
65
80
  const addAppRoleCommand = async (api, options, out) => {
66
81
  if (options.to !== "owners") throw new Error(`--to takes "owners", not "${options.to}"`);
67
- const changed = await api.addAppRoleToOwners(options.role);
82
+ const pin = await resolvePin(api, options, "organizations add-app-role", () => everyOrganization("protobase organizations add-app-role: --all-organizations"));
83
+ out(pinLine(pin));
84
+ const changed = await api.addAppRoleToOwners(scopeOf(pin), options.role);
68
85
  out(`Gave ${options.role} to ${changed} owner${changed === 1 ? "" : "s"}\n`);
69
86
  };
70
87
  //#endregion
@@ -0,0 +1,20 @@
1
+ import { isMemberByEmail, organizationByKey } from "@protobase/server";
2
+ //#region src/organizations/pin-source.ts
3
+ const pinSource = (auth) => {
4
+ const pinned = auth.organizations?.options.default;
5
+ return {
6
+ organizationsOn: auth.organizations !== void 0,
7
+ ...pinned && { defaultOrganization: pinned },
8
+ organizationByKey: async (key) => {
9
+ const found = await organizationByKey(auth, key);
10
+ return found && {
11
+ id: found.id,
12
+ slug: found.slug,
13
+ name: found.name
14
+ };
15
+ },
16
+ isMember: (organizationId, email) => isMemberByEmail(auth, organizationId, email)
17
+ };
18
+ };
19
+ //#endregion
20
+ export { pinSource };
@@ -0,0 +1,40 @@
1
+ //#region src/organizations/pin.ts
2
+ /**
3
+ * The pin of a command named `command` with organizations on. `wide` is the command's reviewed way out, as
4
+ * `everyOrganization('<command>: --all-organizations')`; a command without one refuses `--all-organizations`.
5
+ */
6
+ const resolvePin = async (source, options, command, wide) => {
7
+ if (!source.organizationsOn) throw new Error(`protobase ${command} needs organizations: turn on auth.organizations in the config`);
8
+ if (options.allOrganizations && options.organization !== void 0) throw new Error("Pass --organization or --all-organizations, not both");
9
+ if (options.allOrganizations) {
10
+ if (!wide) throw new Error(`protobase ${command} acts on one organization: pass --organization <slug> instead of --all-organizations`);
11
+ return { every: wide() };
12
+ }
13
+ if (options.organization !== void 0) {
14
+ const found = await source.organizationByKey(options.organization);
15
+ if (!found) throw new Error(`No organization "${options.organization}"`);
16
+ return { organization: found };
17
+ }
18
+ const pinned = source.defaultOrganization;
19
+ if (!pinned) throw new Error("No organization is pinned: set auth.organizations.default in the config, or pass --organization <slug> or --all-organizations");
20
+ const found = await source.organizationByKey(pinned.id);
21
+ if (!found) throw new Error(`The config's auth.organizations.default names organization "${pinned.slug}" (${pinned.id}), which the database does not have: pass --organization <slug> or --all-organizations`);
22
+ return { organization: found };
23
+ };
24
+ /** The pin of a command that works without organizations too: none while they are off, which refuses the pin's flags. */
25
+ const resolveOptionalPin = async (source, options, command, wide) => {
26
+ if (source.organizationsOn) return resolvePin(source, options, command, wide);
27
+ if (options.organization !== void 0 || options.allOrganizations) throw new Error("--organization and --all-organizations need organizations: turn on auth.organizations in the config");
28
+ };
29
+ /** What the scope of `@protobase/server`'s host functions takes: the organization's id, or every organization. */
30
+ const scopeOf = (pin) => "every" in pin ? pin.every : pin.organization.id;
31
+ /** The line a command prints first, naming what it acts on. */
32
+ const pinLine = (pin) => "every" in pin ? "Every organization\n" : `Organization: ${pin.organization.slug} (${pin.organization.name})\n`;
33
+ /** Refuses a user outside the pinned organization, for a command that changes their whole account. */
34
+ const checkPinnedUser = async (source, pin, email) => {
35
+ if ("every" in pin) return;
36
+ if (await source.isMember(pin.organization.id, email)) return;
37
+ throw new Error(`${email} is not a member of ${pin.organization.slug}: pass --organization <slug> for theirs, or --all-organizations to reach any user`);
38
+ };
39
+ //#endregion
40
+ export { checkPinnedUser, pinLine, resolveOptionalPin, resolvePin, scopeOf };
@@ -5,12 +5,18 @@ const projectApi = async () => {
5
5
  return organizationsApi(await loadProjectAuth(process.cwd()));
6
6
  };
7
7
  const finish = (code) => process.exit(code);
8
- const memberOptions = (command) => command.argument("<organization>", "its slug or id").argument("<email>").option("--org-role <role>", "owner, admin or member: who manages the organization").option("--app-roles <roles>", "app roles in this organization, comma separated (see `users roles`)");
8
+ const organizationOption = (command) => command.option("--organization <organization>", "its slug or id (default: auth.organizations.default of the config)");
9
+ /** `--organization`, and `--all-organizations` for a command that can reach every organization. */
10
+ const pinOptions = (command) => organizationOption(command).option("--all-organizations", "act on every organization", false);
11
+ const memberOptions = (command) => organizationOption(command).argument("<email>").option("--org-role <role>", "owner, admin or member: who manages the organization").option("--app-roles <roles>", "app roles in this organization, comma separated (see `users roles`)");
9
12
  const registerOrganizations = (program) => {
10
13
  const organizations = program.command("organizations").description("Manage the organizations of the project in the current directory (with `auth.organizations` in protobase.config.ts)");
11
- organizations.command("list").description("List organizations with their members and roles").action(async () => {
14
+ pinOptions(organizations.command("list").description("List the organization with its members and roles")).action(async (opts) => {
12
15
  const { listOrganizationsCommand } = await import("./commands.js");
13
- await listOrganizationsCommand(await projectApi(), out);
16
+ await listOrganizationsCommand(await projectApi(), {
17
+ organization: opts.organization,
18
+ allOrganizations: opts.allOrganizations
19
+ }, out);
14
20
  finish(0);
15
21
  });
16
22
  organizations.command("create").description("Create an organization; its owner holds every app role").argument("<name>").requiredOption("--owner <email>", "the user who owns it").option("--slug <slug>", "default: from the name").option("--id <id>", "keep an existing tenant value, for an app that ran as one organization").option("--members <all>", "\"all\": every other user joins; their global roles move here, superusers become owners").action(async (name, opts) => {
@@ -24,42 +30,44 @@ const registerOrganizations = (program) => {
24
30
  }, out);
25
31
  finish(0);
26
32
  });
27
- memberOptions(organizations.command("add-member").description("Add a user to an organization (organization role member unless given)")).action(async (organization, email, opts) => {
33
+ memberOptions(organizations.command("add-member").description("Add a user to the organization (organization role member unless given)")).action(async (email, opts) => {
28
34
  const { addMemberCommand } = await import("./commands.js");
29
35
  await addMemberCommand(await projectApi(), {
30
- organization,
36
+ organization: opts.organization,
31
37
  email,
32
38
  orgRole: opts.orgRole,
33
39
  appRoles: opts.appRoles
34
40
  }, out);
35
41
  finish(0);
36
42
  });
37
- memberOptions(organizations.command("set-roles").description("Change a member's organization role, app roles, or both")).action(async (organization, email, opts) => {
43
+ memberOptions(organizations.command("set-roles").description("Change a member's organization role, app roles, or both")).action(async (email, opts) => {
38
44
  const { setMemberRolesCommand } = await import("./commands.js");
39
45
  await setMemberRolesCommand(await projectApi(), {
40
- organization,
46
+ organization: opts.organization,
41
47
  email,
42
48
  orgRole: opts.orgRole,
43
49
  appRoles: opts.appRoles
44
50
  }, out);
45
51
  finish(0);
46
52
  });
47
- organizations.command("remove-member").description("Remove a member (refuses the last owner)").argument("<organization>", "its slug or id").argument("<email>").action(async (organization, email) => {
53
+ organizationOption(organizations.command("remove-member").description("Remove a member (refuses the last owner)")).argument("<email>").action(async (email, opts) => {
48
54
  const { removeMemberCommand } = await import("./commands.js");
49
55
  await removeMemberCommand(await projectApi(), {
50
- organization,
56
+ organization: opts.organization,
51
57
  email
52
58
  }, out);
53
59
  finish(0);
54
60
  });
55
- organizations.command("add-app-role").description("Give an app role to every owner of every organization, for a role added after they were made").argument("<role>").requiredOption("--to <owners>", "\"owners\"").action(async (role, opts) => {
61
+ pinOptions(organizations.command("add-app-role").description("Give an app role to the organization's owners, for a role added after they were made")).argument("<role>").requiredOption("--to <owners>", "\"owners\"").action(async (role, opts) => {
56
62
  const { addAppRoleCommand } = await import("./commands.js");
57
63
  await addAppRoleCommand(await projectApi(), {
58
64
  role,
59
- to: opts.to
65
+ to: opts.to,
66
+ organization: opts.organization,
67
+ allOrganizations: opts.allOrganizations
60
68
  }, out);
61
69
  finish(0);
62
70
  });
63
71
  };
64
72
  //#endregion
65
- export { registerOrganizations };
73
+ export { pinOptions, registerOrganizations };
@@ -1,5 +1,5 @@
1
1
  import { tableKey } from "../db/model.js";
2
- import { migrationsTableName, storeTableNames } from "@protobase/server/auth-store";
2
+ import { storeRecordNames, storeTableNames } from "@protobase/server/auth-store";
3
3
  import { definitionsSchema, userTablesSchema } from "@protobase/server/config-exports";
4
4
  //#region src/scaffold/protobase-tables.ts
5
5
  const storeCore = [
@@ -17,7 +17,7 @@ const authStore = (schema, tables) => {
17
17
  if (schema === "auth") return tables;
18
18
  const has = (name) => tables.some((table) => table.name === name);
19
19
  const user = userTableOf(schema, tables);
20
- if (!has(migrationsTableName) && !(storeCore.every(has) && user !== void 0)) return [];
20
+ if (!storeRecordNames.some(has) && !(storeCore.every(has) && user !== void 0)) return [];
21
21
  if (schema !== "public") return tables;
22
22
  return tables.filter((table) => storeTableNames.includes(table.name) || table.name === user);
23
23
  };