@protobase/cli 0.46.11 → 0.46.13

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 (74) hide show
  1. package/dist/auth/register.js +1 -2
  2. package/dist/auth/write-migration.js +1 -1
  3. package/dist/build/app-icons.js +1 -1
  4. package/dist/build/config-bundle.js +1 -1
  5. package/dist/build/deploy-bundle.js +2 -2
  6. package/dist/build/entry-code.js +1 -1
  7. package/dist/build/plugin-build.js +3 -3
  8. package/dist/build/plugin-fields.js +1 -1
  9. package/dist/build/service-worker-code.js +1 -1
  10. package/dist/build/shell.js +2 -2
  11. package/dist/build/ui-check.js +2 -2
  12. package/dist/build/vite-bundle.js +1 -1
  13. package/dist/bundle/manifest.js +1 -1
  14. package/dist/cli/package.js +1 -1
  15. package/dist/db/connect.js +1 -9
  16. package/dist/db/connection-url.js +14 -0
  17. package/dist/dev/entry.js +3 -3
  18. package/dist/dev/project.js +2 -2
  19. package/dist/dev/run.js +8 -4
  20. package/dist/dev/startup-logger.js +24 -0
  21. package/dist/doctor/run.js +3 -0
  22. package/dist/encryption/register.js +1 -2
  23. package/dist/error-message.js +15 -0
  24. package/dist/exit-signal.js +10 -0
  25. package/dist/files/register.js +1 -2
  26. package/dist/infer/proposal.js +1 -1
  27. package/dist/main.js +39 -26
  28. package/dist/migration/load-project.js +1 -1
  29. package/dist/migration/register.js +7 -4
  30. package/dist/migration/summary.js +15 -0
  31. package/dist/mobile/local-spec.js +1 -1
  32. package/dist/mobile/run.js +1 -1
  33. package/dist/mobile/web-part.js +2 -2
  34. package/dist/mobile/workspace.js +1 -1
  35. package/dist/notifications/register.js +1 -2
  36. package/dist/organizations/api.js +15 -0
  37. package/dist/organizations/register.js +5 -15
  38. package/dist/project/favicon-link.js +1 -1
  39. package/dist/project/import-project-file.js +21 -11
  40. package/dist/project/load-bundle-project.js +2 -2
  41. package/dist/project/load-data-config.js +4 -11
  42. package/dist/project/placeholder-secret.js +9 -0
  43. package/dist/runner.d.ts +20 -0
  44. package/dist/runner.js +94 -0
  45. package/dist/scaffold/existing-config.js +4 -1
  46. package/dist/scaffold/plan.js +11 -7
  47. package/dist/scaffold/project.js +2 -1
  48. package/dist/scaffold/prompt.js +12 -5
  49. package/dist/scaffold/run.js +1 -1
  50. package/dist/scaffold/ui-fields.js +3 -0
  51. package/dist/scaffold/ui-file.js +26 -4
  52. package/dist/serve/app.js +1 -1
  53. package/dist/serve/bundle-version.js +1 -1
  54. package/dist/serve/create-admin.js +3 -3
  55. package/dist/serve/host-modules.js +6 -6
  56. package/dist/serve/lifecycle.js +3 -3
  57. package/dist/serve/mobile-release.js +1 -1
  58. package/dist/serve/serve-bundle-path.js +1 -1
  59. package/dist/serve/serve-bundle.js +3 -3
  60. package/dist/serve/serve-dir.js +2 -2
  61. package/dist/supabase/dump-phase.js +1 -1
  62. package/dist/supabase/load-phase.js +1 -1
  63. package/dist/supabase/register.js +1 -1
  64. package/dist/supabase/storage-phase.js +1 -1
  65. package/dist/users/commands.js +7 -1
  66. package/dist/users/register.js +17 -11
  67. package/dist/users/users-api.js +2 -1
  68. package/dist/worker/start-worker.js +2 -2
  69. package/package.json +9 -6
  70. package/skills/protobase/SKILL.md +1 -0
  71. package/skills/protobase/references/features/start-a-project.md +1 -1
  72. package/skills/protobase/references/getting-started.md +16 -1
  73. package/skills/protobase/references/guides/existing-database.md +112 -0
  74. package/skills/protobase/references/reference/cli.md +29 -8
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
- import { homedir } from "node:os";
3
2
  import { pathToFileURL } from "node:url";
3
+ import { homedir } from "node:os";
4
4
  //#region src/mobile/local-spec.ts
5
5
  const localSpec = /^(?:file:|[.]|~[/\\]|[/\\]|[a-z]:)/i;
6
6
  /** Whether npm installs the dependency spec `spec` from this machine, copying it, rather than fetching it. */
@@ -1,5 +1,5 @@
1
- import { checkInstalledPlugins, checkPinnedNative, pinnedNative } from "./pinned-packages.js";
2
1
  import { nativeFingerprint } from "./fingerprint.js";
2
+ import { checkInstalledPlugins, checkPinnedNative, pinnedNative } from "./pinned-packages.js";
3
3
  import { withoutAndroidSigning } from "./android-signing.js";
4
4
  import { runChild } from "./child-process.js";
5
5
  import { apiUrl, checkReleaseUrl, httpAllowances } from "./api-origin.js";
@@ -1,10 +1,10 @@
1
1
  import { bundleLayout } from "../bundle/manifest.js";
2
- import { buildDeployBundle } from "../build/deploy-bundle.js";
3
2
  import { withApiOrigin } from "./api-origin-page.js";
4
3
  import { siteFiles } from "../serve/site-files.js";
4
+ import { buildDeployBundle } from "../build/deploy-bundle.js";
5
5
  import path from "node:path";
6
- import { releaseManifest } from "@protobase/server";
7
6
  import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
7
+ import { releaseManifest } from "@protobase/server";
8
8
  import { releaseManifestFile } from "@protobase/schema/internal";
9
9
  const writeReleaseManifest = async (web) => {
10
10
  const files = await Promise.all((await siteFiles({
@@ -6,8 +6,8 @@ import { isLocalSpec } from "./local-spec.js";
6
6
  import { checkLocalPins, isUnmet, localPins } from "./local-pins.js";
7
7
  import { existsSync } from "node:fs";
8
8
  import path from "node:path";
9
- import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
10
9
  import { fileURLToPath } from "node:url";
10
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
11
11
  //#region src/mobile/workspace.ts
12
12
  /** Where the mobile build lives in a project: npm's install of @protobase/mobile, the app's files and native projects. */
13
13
  const workspaceDir = (projectDir) => path.join(projectDir, protobaseFolder, "mobile");
@@ -1,7 +1,6 @@
1
- import { printVapidKeys } from "./print-vapid-keys.js";
2
1
  //#region src/notifications/register.ts
3
2
  const registerNotifications = (program) => {
4
- program.command("notifications").description("Set up the delivery of notifications").command("vapid-keys").description("Print a fresh VAPID key pair for Web Push, as PROTOBASE_VAPID_PUBLIC_KEY and PROTOBASE_VAPID_PRIVATE_KEY").action(() => printVapidKeys((text) => void process.stdout.write(text), (text) => void process.stderr.write(text)));
3
+ program.command("notifications").description("Set up the delivery of notifications").command("vapid-keys").description("Print a fresh VAPID key pair for Web Push, as PROTOBASE_VAPID_PUBLIC_KEY and PROTOBASE_VAPID_PRIVATE_KEY").action(async () => (await import("./print-vapid-keys.js")).printVapidKeys((text) => void process.stdout.write(text), (text) => void process.stderr.write(text)));
5
4
  };
6
5
  //#endregion
7
6
  export { registerNotifications };
@@ -0,0 +1,15 @@
1
+ import { addAppRoleToOwners, addMember, createOrganization, listOrganizations, listUsers, removeMember, setMemberRoles, setUserRole } from "@protobase/server";
2
+ //#region src/organizations/api.ts
3
+ const organizationsApi = (auth) => ({
4
+ listOrganizations: () => listOrganizations(auth),
5
+ createOrganization: (input) => createOrganization(auth, input),
6
+ addMember: (input) => addMember(auth, input),
7
+ setMemberRoles: (input) => setMemberRoles(auth, input),
8
+ removeMember: (input) => removeMember(auth, input),
9
+ addAppRoleToOwners: (appRole) => addAppRoleToOwners(auth, appRole),
10
+ listUsers: () => listUsers(auth),
11
+ setUserRole: (input) => setUserRole(auth, input),
12
+ membershipRoles: () => auth.roleDefinitions.names.filter((name) => name !== "admin" && name !== "user")
13
+ });
14
+ //#endregion
15
+ export { organizationsApi };
@@ -1,20 +1,10 @@
1
- import { loadProjectAuth } from "../users/load-auth.js";
2
1
  import { addAppRoleCommand, addMemberCommand, createOrganizationCommand, listOrganizationsCommand, removeMemberCommand, setMemberRolesCommand } from "./commands.js";
3
- import { addAppRoleToOwners, addMember, createOrganization, listOrganizations, listUsers, removeMember, setMemberRoles, setUserRole } from "@protobase/server";
4
2
  //#region src/organizations/register.ts
5
3
  const out = (text) => process.stdout.write(text);
6
- const organizationsApi = (auth) => ({
7
- listOrganizations: () => listOrganizations(auth),
8
- createOrganization: (input) => createOrganization(auth, input),
9
- addMember: (input) => addMember(auth, input),
10
- setMemberRoles: (input) => setMemberRoles(auth, input),
11
- removeMember: (input) => removeMember(auth, input),
12
- addAppRoleToOwners: (appRole) => addAppRoleToOwners(auth, appRole),
13
- listUsers: () => listUsers(auth),
14
- setUserRole: (input) => setUserRole(auth, input),
15
- membershipRoles: () => auth.roleDefinitions.names.filter((name) => name !== "admin" && name !== "user")
16
- });
17
- const projectApi = async () => organizationsApi(await loadProjectAuth(process.cwd()));
4
+ const projectApi = async () => {
5
+ const [{ organizationsApi }, { loadProjectAuth }] = await Promise.all([import("./api.js"), import("../users/load-auth.js")]);
6
+ return organizationsApi(await loadProjectAuth(process.cwd()));
7
+ };
18
8
  const finish = (code) => process.exit(code);
19
9
  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`)");
20
10
  const registerOrganizations = (program) => {
@@ -67,4 +57,4 @@ const registerOrganizations = (program) => {
67
57
  });
68
58
  };
69
59
  //#endregion
70
- export { organizationsApi, registerOrganizations };
60
+ export { registerOrganizations };
@@ -1,8 +1,8 @@
1
1
  import { faviconFile, projectFavicon } from "../build/favicon.js";
2
2
  import { existsSync } from "node:fs";
3
3
  import path from "node:path";
4
- import { pngIcons } from "@protobase/server";
5
4
  import { readFile } from "node:fs/promises";
5
+ import { pngIcons } from "@protobase/server";
6
6
  //#region src/project/favicon-link.ts
7
7
  /**
8
8
  * Links the project's favicon at `/protobase.favicon.svg` in the app's page, and its Apple touch icon at
@@ -1,21 +1,31 @@
1
- import { runnerImport } from "vite";
1
+ import path from "node:path";
2
2
  //#region src/project/import-project-file.ts
3
- const importProjectFile = async (file, plugins = []) => {
4
- const { module } = await runnerImport(file, {
3
+ const runnerImport = async (file, plugins = []) => {
4
+ const { module } = await (await import("vite")).runnerImport(file, {
5
5
  configFile: false,
6
6
  logLevel: "error",
7
7
  plugins
8
8
  });
9
9
  return module;
10
10
  };
11
+ const importProjectFile = async (file) => process.versions.bun ? import(file) : runnerImport(file);
11
12
  /**
12
- * Imports `code` as if it were the project's file `file`, which need not exist: its imports resolve from there, and
13
- * the modules it imports are loaded once, however many of them import each other.
13
+ * Imports several of the project's files in order, so that the modules they share are loaded once. Bun's module cache
14
+ * does that itself; Vite's runner gets them as the imports of one module, which need not exist, beside the first file.
14
15
  */
15
- const importProjectCode = (file, code) => importProjectFile(file, [{
16
- name: "protobase-project-code",
17
- resolveId: (id) => id === file ? `\0${file}` : void 0,
18
- load: (id) => id === `\0${file}` ? code : void 0
19
- }]);
16
+ const importProjectFiles = async (files) => {
17
+ if (process.versions.bun) {
18
+ const modules = [];
19
+ for (const file of files) modules.push(await importProjectFile(file));
20
+ return modules;
21
+ }
22
+ const id = path.join(path.dirname(files[0]), "protobase-project-files.js");
23
+ const code = [...files.map((file, i) => `import * as m${i} from ${JSON.stringify(file)}`), `export const modules = [${files.map((_, i) => `m${i}`).join(", ")}]`].join("\n");
24
+ return (await runnerImport(id, [{
25
+ name: "protobase-project-files",
26
+ resolveId: (source) => source === id ? `\0${id}` : void 0,
27
+ load: (source) => source === `\0${id}` ? code : void 0
28
+ }])).modules;
29
+ };
20
30
  //#endregion
21
- export { importProjectCode, importProjectFile };
31
+ export { importProjectFile, importProjectFiles };
@@ -1,8 +1,8 @@
1
1
  import { loadNearestEnvFile } from "../dev/env.js";
2
- import { importProjectFile } from "./import-project-file.js";
3
- import { readManifest } from "../bundle/manifest.js";
4
2
  import { createPgDb } from "./pg-db.js";
3
+ import { readManifest } from "../bundle/manifest.js";
5
4
  import { loadBundle } from "../serve/load-bundle.js";
5
+ import { importProjectFile } from "./import-project-file.js";
6
6
  import { existsSync, statSync } from "node:fs";
7
7
  import path from "node:path";
8
8
  import { configExports } from "@protobase/server";
@@ -1,6 +1,6 @@
1
- import { importProjectCode } from "./import-project-file.js";
2
- import { uiDirs } from "./convention-files.js";
3
1
  import { conventionConfig } from "./convention.js";
2
+ import { uiDirs } from "./convention-files.js";
3
+ import { importProjectFiles } from "./import-project-file.js";
4
4
  import path from "node:path";
5
5
  import { configExports } from "@protobase/server";
6
6
  //#region src/project/load-data-config.ts
@@ -10,15 +10,8 @@ import { configExports } from "@protobase/server";
10
10
  */
11
11
  const loadDataConfig = async (configDir) => {
12
12
  const dirs = uiDirs(configDir);
13
- const code = [
14
- `import * as index from ${JSON.stringify(path.join(configDir, "index.ts"))}`,
15
- ...dirs.map((dir, i) => `import * as ui${i} from ${JSON.stringify(path.join(configDir, dir, "ui.ts"))}`),
16
- "export { index }",
17
- `export const ui = [${dirs.map((dir, i) => `[${JSON.stringify(dir)}, ui${i}]`).join(", ")}]`,
18
- ""
19
- ].join("\n");
20
- const loaded = await importProjectCode(path.join(configDir, "protobase-data-config.js"), code);
21
- const config = conventionConfig(loaded.index, loaded.ui);
13
+ const [index, ...ui] = await importProjectFiles([path.join(configDir, "index.ts"), ...dirs.map((dir) => path.join(configDir, dir, "ui.ts"))]);
14
+ const config = conventionConfig(index, dirs.map((dir, i) => [dir, ui[i]]));
22
15
  const { resources, views, pages } = configExports(config);
23
16
  return {
24
17
  models: resources.map((resource) => resource.toModel()),
@@ -0,0 +1,9 @@
1
+ //#region src/project/placeholder-secret.ts
2
+ const placeholder = /^change-?me/i;
3
+ /**
4
+ * A warning when BETTER_AUTH_SECRET is still the placeholder of .env.example: whoever knows it can sign session
5
+ * cookies for the app. Undefined otherwise.
6
+ */
7
+ const placeholderSecretWarning = (env) => env.BETTER_AUTH_SECRET && placeholder.test(env.BETTER_AUTH_SECRET) ? "BETTER_AUTH_SECRET is still the placeholder from .env.example, which signs session cookies anyone can forge; set it to the output of `openssl rand -base64 32`" : void 0;
8
+ //#endregion
9
+ export { placeholderSecretWarning };
@@ -0,0 +1,20 @@
1
+ //#region src/runner.d.ts
2
+ export type CommandOptions = {
3
+ /** The folder the command runs in; default: the current one. */
4
+ cwd?: string;
5
+ /** The command's whole environment, as a child process gets it; default: a copy of the current one. */
6
+ env?: Record<string, string | undefined>;
7
+ /** What the command reads from stdin; default: nothing. */
8
+ stdin?: string;
9
+ };
10
+ export type CommandResult = {
11
+ exitCode: number;
12
+ stdout: string;
13
+ stderr: string;
14
+ };
15
+ /**
16
+ * Runs one protobase command in this process, as `protobase <args>` would run in a process of its own, and returns its
17
+ * exit code and output. The CLI stays loaded between commands, so only the first pays for starting it.
18
+ */
19
+ export declare const runCommand: (args: string[], options?: CommandOptions) => Promise<CommandResult>;
20
+ //#endregion
package/dist/runner.js ADDED
@@ -0,0 +1,94 @@
1
+ import { ExitSignal } from "./exit-signal.js";
2
+ import { run } from "./main.js";
3
+ import { createRequire } from "node:module";
4
+ import { realpathSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { Readable } from "node:stream";
7
+ //#region src/runner.ts
8
+ const longRunning = /* @__PURE__ */ new Set([
9
+ "dev",
10
+ "serve",
11
+ "worker",
12
+ "mobile"
13
+ ]);
14
+ const enter = (options, output) => {
15
+ const cwd = process.cwd();
16
+ const env = { ...process.env };
17
+ const exitCode = process.exitCode;
18
+ const { exit } = process;
19
+ const stdin = Object.getOwnPropertyDescriptor(process, "stdin");
20
+ const writeOut = process.stdout.write;
21
+ const writeErr = process.stderr.write;
22
+ const replaceEnv = (next) => {
23
+ for (const name of Object.keys(process.env)) delete process.env[name];
24
+ for (const [name, value] of Object.entries(next)) if (value !== void 0) process.env[name] = value;
25
+ };
26
+ const capture = (stream) => ((chunk) => {
27
+ output[stream] += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
28
+ return true;
29
+ });
30
+ if (options.cwd) process.chdir(options.cwd);
31
+ replaceEnv(options.env ?? env);
32
+ process.exitCode = void 0;
33
+ process.exit = ((code) => {
34
+ throw new ExitSignal(Number(code ?? process.exitCode ?? 0));
35
+ });
36
+ Object.defineProperty(process, "stdin", {
37
+ value: Object.assign(Readable.from(options.stdin ? [options.stdin] : []), { isTTY: false }),
38
+ configurable: true
39
+ });
40
+ process.stdout.write = capture("stdout");
41
+ process.stderr.write = capture("stderr");
42
+ return () => {
43
+ process.stdout.write = writeOut;
44
+ process.stderr.write = writeErr;
45
+ if (stdin) Object.defineProperty(process, "stdin", stdin);
46
+ process.exit = exit;
47
+ process.exitCode = exitCode ?? 0;
48
+ replaceEnv(env);
49
+ process.chdir(cwd);
50
+ };
51
+ };
52
+ const modules = createRequire(import.meta.url).cache;
53
+ const forgetProjectFiles = (projectDir, loadedBefore) => {
54
+ const prefix = realpathSync(projectDir) + path.sep;
55
+ for (const file of Object.keys(modules)) {
56
+ if (loadedBefore.has(file) || !file.startsWith(prefix) || file.includes(`${path.sep}node_modules${path.sep}`)) continue;
57
+ delete modules[file];
58
+ }
59
+ };
60
+ const runOne = async (args, options) => {
61
+ if (longRunning.has(args[0] ?? "")) throw new Error(`protobase ${args[0]} runs until a signal; start it as a process`);
62
+ const output = {
63
+ stdout: "",
64
+ stderr: ""
65
+ };
66
+ const loadedBefore = new Set(Object.keys(modules));
67
+ const leave = enter(options, output);
68
+ try {
69
+ await run([
70
+ "protobase",
71
+ "protobase",
72
+ ...args
73
+ ]);
74
+ return {
75
+ exitCode: Number(process.exitCode ?? 0),
76
+ ...output
77
+ };
78
+ } finally {
79
+ forgetProjectFiles(process.cwd(), loadedBefore);
80
+ leave();
81
+ }
82
+ };
83
+ let queue = Promise.resolve();
84
+ /**
85
+ * Runs one protobase command in this process, as `protobase <args>` would run in a process of its own, and returns its
86
+ * exit code and output. The CLI stays loaded between commands, so only the first pays for starting it.
87
+ */
88
+ const runCommand = (args, options = {}) => {
89
+ const result = queue.then(() => runOne(args, options));
90
+ queue = result.then(() => void 0, () => void 0);
91
+ return result;
92
+ };
93
+ //#endregion
94
+ export { runCommand };
@@ -23,11 +23,13 @@ const describeField = (name, initializer) => {
23
23
  let column;
24
24
  let type;
25
25
  let enumValues;
26
+ let sortable = false;
26
27
  let node = initializer;
27
28
  while (Node.isCallExpression(node)) {
28
29
  const expression = node.getExpression();
29
30
  if (!Node.isPropertyAccessExpression(expression)) break;
30
31
  if (expression.getName() === "column") column ??= stringArg(node);
32
+ if (expression.getName() === "sortable") sortable = true;
31
33
  if (expression.getExpression().getText() === "f") {
32
34
  type = expression.getName();
33
35
  const arg = node.getArguments()[0];
@@ -41,7 +43,8 @@ const describeField = (name, initializer) => {
41
43
  column: column ?? defaultColumn(name),
42
44
  ignored: false,
43
45
  ...type && { type },
44
- ...enumValues && { enumValues }
46
+ ...enumValues && { enumValues },
47
+ ...sortable && { sortable }
45
48
  };
46
49
  };
47
50
  const fieldsObject = (root) => {
@@ -41,18 +41,22 @@ const change = (file, before, after) => before === after ? [] : [{
41
41
  }];
42
42
  const planScaffold = async (input) => {
43
43
  const { configDir, existing, ui } = input;
44
- const skipped = protobaseSchemas(input.tables.filter((table) => matchesTarget(input.target, table)), input.target);
45
- const isProtobase = (table) => skipped.some((schema) => schema.tables.includes(table));
46
- const names = assignNames(input.tables.filter((table) => !isProtobase(table)), existing);
47
44
  const byTable = new Map(existing.map((resource) => [resource.table, resource]));
45
+ const wanted = (table) => matchesTarget(input.target, table) && !isExcluded(input.excludes, table);
46
+ const tables = input.tables.filter((table) => table.kind === "table");
47
+ const skipped = protobaseSchemas(tables.filter((table) => matchesTarget(input.target, table)), input.target);
48
+ const isProtobase = (table) => skipped.some((schema) => schema.tables.includes(table));
49
+ const inProtobaseSchema = (view) => skipped.some(({ schema }) => schema === view.schema && schema !== "public");
50
+ const skippedViews = input.tables.filter((table) => table.kind !== "table" && wanted(table) && !byTable.has(tableKey(table)) && !inProtobaseSchema(table));
51
+ const names = assignNames(tables.filter((table) => !isProtobase(table)), existing);
48
52
  const context = (table) => ({
49
53
  table,
50
54
  resourceNameOf: (schema, name) => names.get(`${schema}.${name}`) ?? name
51
55
  });
52
- const targets = dependencyOrder(input.tables.filter((table) => matchesTarget(input.target, table) && !isExcluded(input.excludes, table) && !isProtobase(table)));
56
+ const targets = dependencyOrder(tables.filter((table) => wanted(table) && !isProtobase(table)));
53
57
  const changes = [];
54
58
  const drift = [];
55
- const warnings = [];
59
+ const warnings = skippedViews.map((view) => `${tableKey(view)}: a ${view.kind}, skipped; scaffold writes resources over tables, declare one over a view by hand`);
56
60
  const registrations = [];
57
61
  const live = [];
58
62
  const isLive = (key) => input.live?.includes(key) ?? false;
@@ -117,8 +121,8 @@ const planScaffold = async (input) => {
117
121
  }
118
122
  const indexFile = path.join(configDir, "index.ts");
119
123
  const indexBefore = await input.readText(indexFile);
120
- const wanted = [...indexBefore === void 0 ? await registerExisting(input, registrations) : [], ...registrations];
121
- if (wanted.length > 0 || indexBefore === void 0) changes.push(...change(indexFile, indexBefore, ensureExports(indexBefore ?? "", wanted)));
124
+ const exports = [...indexBefore === void 0 ? await registerExisting(input, registrations) : [], ...registrations];
125
+ if (exports.length > 0 || indexBefore === void 0) changes.push(...change(indexFile, indexBefore, ensureExports(indexBefore ?? "", exports)));
122
126
  return {
123
127
  changes,
124
128
  drift,
@@ -5,7 +5,8 @@ const project = new Project({
5
5
  skipAddingFilesFromTsConfig: true,
6
6
  manipulationSettings: {
7
7
  indentationText: IndentationText.TwoSpaces,
8
- quoteKind: QuoteKind.Single
8
+ quoteKind: QuoteKind.Single,
9
+ useTrailingCommas: true
9
10
  }
10
11
  });
11
12
  const parseSource = (text, name = "source.ts") => project.createSourceFile(name, text, { overwrite: true });
@@ -45,18 +45,25 @@ const edit = async (proposal, ask) => {
45
45
  name
46
46
  }, ask);
47
47
  };
48
- const interactive = () => {
48
+ const interactive = (input = process.stdin, output = process.stdout) => {
49
49
  const rl = createInterface({
50
- input: process.stdin,
51
- output: process.stdout
50
+ input,
51
+ output
52
52
  });
53
+ let acceptRest = false;
53
54
  const decide = async (initial, { table, required }) => {
55
+ if (acceptRest) return initial;
54
56
  let proposal = initial;
55
57
  for (;;) {
56
- process.stdout.write(`\n${table}.${proposal.column}\n ${proposal.name}: ${renderField(proposal)}\n`);
57
- const options = required ? "[a]ccept, [e]dit" : "[a]ccept, [e]dit, [i]gnore";
58
+ output.write(`\n${table}.${proposal.column}\n ${proposal.name}: ${renderField(proposal)}\n`);
59
+ const options = required ? "[a]ccept, accept a[l]l, [e]dit" : "[a]ccept, accept a[l]l, [e]dit, [i]gnore";
58
60
  const answer = (await rl.question(` ${options} (a): `)).trim().toLowerCase() || "a";
59
61
  if (answer === "a") return proposal;
62
+ if (answer === "l") {
63
+ acceptRest = true;
64
+ output.write(" accepting this and every remaining proposal\n");
65
+ return proposal;
66
+ }
60
67
  if (answer === "e") proposal = await edit(proposal, (q) => rl.question(q));
61
68
  if (answer === "i" && !required) return null;
62
69
  }
@@ -24,7 +24,7 @@ const runScaffold = async (options, out) => {
24
24
  const plan = await (async () => {
25
25
  try {
26
26
  return await planScaffold({
27
- tables: await introspect(sql),
27
+ tables: await introspect(sql, { views: true }),
28
28
  existing: await readExistingResources(options.configDir),
29
29
  configDir: options.configDir,
30
30
  target: parseTarget(options.target),
@@ -11,10 +11,12 @@ const uiFields = (table, existing, decisions) => {
11
11
  const resolved = declared ? {
12
12
  name: declared.name,
13
13
  type: declared.type ?? "text",
14
+ sortable: declared.sortable ?? false,
14
15
  ignored: declared.ignored
15
16
  } : decided && {
16
17
  name: decided.proposal.name,
17
18
  type: decided.proposal.type,
19
+ sortable: decided.proposal.sortable,
18
20
  ignored: decided.ignored
19
21
  };
20
22
  if (!resolved || resolved.ignored) return [];
@@ -22,6 +24,7 @@ const uiFields = (table, existing, decisions) => {
22
24
  return [{
23
25
  name: resolved.name,
24
26
  type: resolved.type,
27
+ sortable: resolved.sortable,
25
28
  role
26
29
  }];
27
30
  });
@@ -4,6 +4,7 @@ import { methodCalls } from "./existing-config.js";
4
4
  import { Node, SyntaxKind } from "ts-morph";
5
5
  //#region src/scaffold/ui-file.ts
6
6
  const auditField = /^(created|updated)(At|On|_at|_on)$/;
7
+ const createdField = /^(created|inserted)(At|On|_at|_on)$/;
7
8
  const longText = /^(notes?|description|body|comment|comments)$/;
8
9
  const listSize = 5;
9
10
  const secretWords = /* @__PURE__ */ new Set([
@@ -21,17 +22,38 @@ const isSecretLike = (name) => {
21
22
  const joined = words.join(" ");
22
23
  return words.some((word) => secretWords.has(word)) || secretPairs.some((pair) => joined.includes(pair));
23
24
  };
25
+ const relationsShown = 2;
26
+ /**
27
+ * The first useful fields: the key, unless it is a uuid nobody reads, then the records a record points at, such as an
28
+ * order line's order, then plain scalars, never a secret-like one. Without any of them, the key after all.
29
+ */
24
30
  const listColumns = (fields) => {
31
+ const keys = fields.filter((f) => f.role === "key" && f.type !== "uuid");
25
32
  const plain = fields.filter((f) => f.role === "plain" && f.type !== "json" && !auditField.test(f.name) && !isSecretLike(f.name));
33
+ const relations = plain.filter((f) => f.type === "relation").slice(0, relationsShown);
26
34
  const scalars = plain.filter((f) => f.type !== "relation" && !longText.test(f.name));
27
- const relations = plain.filter((f) => f.type === "relation");
28
- const picked = [...scalars.slice(0, listSize), ...scalars.length < 3 ? relations : []].slice(0, listSize);
35
+ const picked = [
36
+ ...keys,
37
+ ...relations,
38
+ ...scalars
39
+ ].slice(0, listSize);
29
40
  return (picked.length > 0 ? picked : fields.filter((f) => f.role === "key")).map((f) => f.name);
30
41
  };
42
+ /**
43
+ * The newest records first, by the sortable date the records were created on, else by another sortable date. Without
44
+ * one the list keeps the API's order, by key.
45
+ */
46
+ const listSort = (fields) => {
47
+ const dates = fields.filter((f) => f.sortable && (f.type === "timestamp" || f.type === "date"));
48
+ return (dates.find((f) => createdField.test(f.name)) ?? dates[0])?.name;
49
+ };
31
50
  const viewName = (identifier) => `${identifier}View`;
32
51
  const sectionText = {
33
52
  names: (t) => `.names({ singular: '${humanizeSingular(t.tableName)}', plural: '${humanize(t.tableName)}' })`,
34
- list: (t) => `.list((r) => ({ columns: [${listColumns(t.fields).map((n) => `r.${n}`).join(", ")}] }))`
53
+ list: (t) => {
54
+ const sort = listSort(t.fields);
55
+ return `.list((r) => ({ columns: [${listColumns(t.fields).map((n) => `r.${n}`).join(", ")}]${sort ? `, sort: [[r.${sort}, 'desc']]` : ""} }))`;
56
+ }
35
57
  };
36
58
  const lines = (sections, target) => sections.map((s) => ` ${sectionText[s](target)}`);
37
59
  const renderUiFile = (target, sections) => [
@@ -52,4 +74,4 @@ const addUiSections = (text, target, sections) => {
52
74
  return source.getFullText();
53
75
  };
54
76
  //#endregion
55
- export { addUiSections, isSecretLike, listColumns, renderUiFile, viewName };
77
+ export { addUiSections, isSecretLike, listColumns, listSort, renderUiFile, viewName };
package/dist/serve/app.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { isApiPath } from "../bundle/manifest.js";
2
2
  import { serveStaticSite } from "./static-site.js";
3
- import { jobsDrainApp, mobileReleaseApp, webauthnPath } from "@protobase/server";
4
3
  import { Hono } from "hono";
4
+ import { jobsDrainApp, mobileReleaseApp, webauthnPath } from "@protobase/server";
5
5
  import { logger } from "hono/logger";
6
6
  //#region src/serve/app.ts
7
7
  const createServeApp = ({ admin, requestLog, site, jobs, drainToken, mobile }) => {
@@ -1,5 +1,5 @@
1
- import { manifestFile } from "../bundle/manifest.js";
2
1
  import { protobaseVersion } from "../version/version.js";
2
+ import { manifestFile } from "../bundle/manifest.js";
3
3
  import { bundleVersionProblem } from "../version/compatibility.js";
4
4
  import { existsSync } from "node:fs";
5
5
  import path from "node:path";
@@ -1,9 +1,9 @@
1
- import { checkBundleVersion } from "./bundle-version.js";
2
- import { loadBundle } from "./load-bundle.js";
3
- import { bundleConfigFile } from "../worker/start-worker.js";
4
1
  import { readHidden } from "../users/password.js";
5
2
  import { createUserCommand } from "../users/commands.js";
6
3
  import { usersApi } from "../users/users-api.js";
4
+ import { checkBundleVersion } from "./bundle-version.js";
5
+ import { loadBundle } from "./load-bundle.js";
6
+ import { bundleConfigFile } from "../worker/start-worker.js";
7
7
  import { checkAuthSchema } from "@protobase/server";
8
8
  //#region src/serve/create-admin.ts
9
9
  const createAdminInBundle = async (bundle, email, options, out) => {
@@ -1,12 +1,8 @@
1
- import * as server from "@protobase/server";
2
- import * as postgres$1 from "postgres";
3
1
  import * as nodeServer from "@hono/node-server";
4
- import * as query from "@protobase/query";
2
+ import * as hono from "hono";
3
+ import * as server from "@protobase/server";
5
4
  import * as kysely from "kysely";
6
5
  import * as pg$1 from "pg";
7
- import * as schema from "@protobase/schema";
8
- import * as layout from "@protobase/layout";
9
- import * as hono from "hono";
10
6
  import * as reactEmailRender from "@react-email/render";
11
7
  import * as apiReference from "@scalar/hono-api-reference";
12
8
  import * as aipParsers from "aip-parsers";
@@ -16,9 +12,13 @@ import * as honoHttpException from "hono/http-exception";
16
12
  import * as honoValidator from "hono/validator";
17
13
  import * as jose from "jose";
18
14
  import * as kyselyPostgres from "kysely/helpers/postgres";
15
+ import * as postgres$1 from "postgres";
19
16
  import * as react from "react";
20
17
  import * as reactJsxRuntime from "react/jsx-runtime";
21
18
  import * as zod from "zod";
19
+ import * as layout from "@protobase/layout";
20
+ import * as query from "@protobase/query";
21
+ import * as schema from "@protobase/schema";
22
22
  //#region src/serve/host-modules.ts
23
23
  const hostModules = {
24
24
  "@protobase/schema": schema,
@@ -1,14 +1,14 @@
1
1
  import { protobaseVersion } from "../version/version.js";
2
- import { apiWebSocketServer } from "../project/api-websocket-server.js";
3
- import { withClientAddress } from "./client-address.js";
4
2
  import { projectAdmin } from "../project/project-admin.js";
5
3
  import { createPgDb } from "../project/pg-db.js";
4
+ import { withClientAddress } from "./client-address.js";
5
+ import { apiWebSocketServer } from "../project/api-websocket-server.js";
6
6
  import { createServeApp } from "./app.js";
7
7
  import { startCleanupTimer } from "./cleanup-timer.js";
8
8
  import { closeSockets } from "./close-sockets.js";
9
9
  import { servedRelease } from "./mobile-release.js";
10
- import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
11
10
  import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
11
+ import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
12
12
  import pg from "pg";
13
13
  //#region src/serve/lifecycle.ts
14
14
  const listen = (server, port) => new Promise((resolve, reject) => {
@@ -1,8 +1,8 @@
1
1
  import { nativeFingerprint } from "../mobile/fingerprint.js";
2
2
  import { withApiOrigin } from "../mobile/api-origin-page.js";
3
3
  import { siteFiles } from "./site-files.js";
4
- import { composeRelease } from "@protobase/server";
5
4
  import { readFile } from "node:fs/promises";
5
+ import { composeRelease } from "@protobase/server";
6
6
  //#region src/serve/mobile-release.ts
7
7
  const loopback = [
8
8
  "localhost",
@@ -1,6 +1,6 @@
1
1
  import { readManifest } from "../bundle/manifest.js";
2
- import { serveBundle } from "./serve-bundle.js";
3
2
  import { bundleSite } from "./bundle-site.js";
3
+ import { serveBundle } from "./serve-bundle.js";
4
4
  import { statSync } from "node:fs";
5
5
  import path from "node:path";
6
6
  //#region src/serve/serve-bundle-path.ts
@@ -1,11 +1,11 @@
1
- import { readManifest } from "../bundle/manifest.js";
2
1
  import { projectErrorReporter } from "../project/error-reporter.js";
3
- import { bundleUi } from "./bundle-ui.js";
2
+ import { readManifest } from "../bundle/manifest.js";
4
3
  import { checkBundleVersion } from "./bundle-version.js";
4
+ import { loadBundle } from "./load-bundle.js";
5
+ import { bundleUi } from "./bundle-ui.js";
5
6
  import { reportCrashes } from "./crash-reports.js";
6
7
  import { readServeEnv } from "./env.js";
7
8
  import { startServe } from "./lifecycle.js";
8
- import { loadBundle } from "./load-bundle.js";
9
9
  import { closeOnSignals } from "./signals.js";
10
10
  import path from "node:path";
11
11
  //#region src/serve/serve-bundle.ts