@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,10 +1,9 @@
1
- import { loadProjectAuth } from "../users/load-auth.js";
2
- import { writeAuthMigration } from "./write-migration.js";
3
1
  import path from "node:path";
4
2
  //#region src/auth/register.ts
5
3
  const out = (text) => process.stdout.write(text);
6
4
  const registerAuth = (program) => {
7
5
  program.command("auth").description("The auth schema of the project in the current directory").command("migration").description("Write the auth schema changes this Protobase version needs as the project's next SQL migration, compared with its database").option("--dir <dir>", "migrations folder", "db/migrations").option("--name <name>", "file name after the number", "auth").action(async (opts) => {
6
+ const [{ loadProjectAuth }, { writeAuthMigration }] = await Promise.all([import("../users/load-auth.js"), import("./write-migration.js")]);
8
7
  const file = await writeAuthMigration({
9
8
  auth: await loadProjectAuth(process.cwd()),
10
9
  dir: path.resolve(opts.dir),
@@ -1,7 +1,7 @@
1
1
  import { migrationText, nextMigrationName } from "./migration-file.js";
2
2
  import path from "node:path";
3
- import { authSchemaMigration } from "@protobase/server";
4
3
  import { mkdir, readdir, writeFile } from "node:fs/promises";
4
+ import { authSchemaMigration } from "@protobase/server";
5
5
  //#region src/auth/write-migration.ts
6
6
  /**
7
7
  * Writes the auth schema changes the database still needs as the next migration in `dir`, and returns its path;
@@ -1,8 +1,8 @@
1
1
  import { buildFavicon, faviconFile } from "./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 { copyFile, readFile } from "node:fs/promises";
5
+ import { pngIcons } from "@protobase/server";
6
6
  //#region src/build/app-icons.ts
7
7
  const pngSignature = Buffer.from([
8
8
  137,
@@ -1,5 +1,5 @@
1
- import { findPackageDir, packageName } from "./packages/package-dir.js";
2
1
  import { extensionImports } from "../project/extensions.js";
2
+ import { findPackageDir, packageName } from "./packages/package-dir.js";
3
3
  import { viteBundle } from "./vite-bundle.js";
4
4
  import { hostModuleIds } from "../serve/host-module-ids.js";
5
5
  import { collectComponents } from "./component-names.js";
@@ -1,12 +1,12 @@
1
+ import { protobaseVersion } from "../version/version.js";
2
+ import { buildIcons } from "./app-icons.js";
1
3
  import { bundleLayout, bundleMigrations, bundleNodeModules, manifestFile } from "../bundle/manifest.js";
2
4
  import { buildBundlePlugins } from "./bundle-plugins.js";
3
5
  import { copyMigrations } from "./bundle-migrations.js";
4
6
  import { buildConfigBundle } from "./config-bundle.js";
5
- import { protobaseVersion } from "../version/version.js";
6
7
  import { copyPackages } from "./packages/copy-packages.js";
7
8
  import { buildTheme } from "./theme.js";
8
9
  import { shellForBuild, shellManifestFile } from "./shell.js";
9
- import { buildIcons } from "./app-icons.js";
10
10
  import { checkUi } from "./ui-check.js";
11
11
  import { checkViews } from "./view-check.js";
12
12
  import { protobaseFolder } from "../project/protobase-folder.js";
@@ -1,7 +1,7 @@
1
+ import { functionFiles } from "../project/functions-folder.js";
1
2
  import { moduleFile } from "../module-file.js";
2
3
  import { exportOrder } from "./export-order.js";
3
4
  import { uiDirs } from "../project/convention-files.js";
4
- import { functionFiles } from "../project/functions-folder.js";
5
5
  import { existsSync } from "node:fs";
6
6
  import path from "node:path";
7
7
  //#region src/build/entry-code.ts
@@ -1,17 +1,17 @@
1
- import { findPackageDirSync, readPackageJson } from "./packages/package-dir.js";
2
1
  import { uiPackageDir } from "../project/admin-app.js";
3
2
  import { extensionImports } from "../project/extensions.js";
3
+ import { findPackageDirSync, readPackageJson } from "./packages/package-dir.js";
4
4
  import { sharedModules } from "../project/shared-modules.js";
5
5
  import { pluginFieldTypes } from "./plugin-fields.js";
6
6
  import { layerPluginUtilities } from "./plugin-styles.js";
7
7
  import { createRequire } from "node:module";
8
8
  import { existsSync } from "node:fs";
9
9
  import path from "node:path";
10
- import { build } from "vite";
11
10
  import { writeFile } from "node:fs/promises";
11
+ import { inRange } from "@protobase/schema/internal";
12
12
  import tailwindcss from "@tailwindcss/vite";
13
13
  import react from "@vitejs/plugin-react";
14
- import { inRange } from "@protobase/schema/internal";
14
+ import { build } from "vite";
15
15
  //#region src/build/plugin-build.ts
16
16
  /** The module a plugin's components and action handlers are exported from, as a project's are. */
17
17
  const pluginEntryFile = "protobase.ui.tsx";
@@ -3,9 +3,9 @@ import { sharedModules } from "../project/shared-modules.js";
3
3
  import { viteBundle } from "./vite-bundle.js";
4
4
  import { createRequire } from "node:module";
5
5
  import path from "node:path";
6
+ import { pathToFileURL } from "node:url";
6
7
  import { mkdtemp, rm } from "node:fs/promises";
7
8
  import { tmpdir } from "node:os";
8
- import { pathToFileURL } from "node:url";
9
9
  //#region src/build/plugin-fields.ts
10
10
  const fieldsCode = (entry) => [
11
11
  `import * as ui from ${JSON.stringify(entry)}`,
@@ -1,6 +1,6 @@
1
1
  import { faviconFile } from "./favicon.js";
2
- import { themeFile } from "./theme.js";
3
2
  import { pushHandlersCode } from "./service-worker-push-code.js";
3
+ import { themeFile } from "./theme.js";
4
4
  import { serviceWorkerFile as serviceWorkerFile$1 } from "@protobase/schema/internal";
5
5
  //#region src/build/service-worker-code.ts
6
6
  /**
@@ -1,6 +1,6 @@
1
+ import { adminAppDir, uiEntry, uiPackageDir } from "../project/admin-app.js";
1
2
  import { projectUiPlugin } from "../project/project-ui.js";
2
3
  import { readPackageJson } from "./packages/package-dir.js";
3
- import { adminAppDir, uiEntry, uiPackageDir } from "../project/admin-app.js";
4
4
  import { sharedModulesPlugin } from "../project/shared-modules.js";
5
5
  import { faviconLink } from "../project/favicon-link.js";
6
6
  import { themeLink } from "../project/theme-link.js";
@@ -10,10 +10,10 @@ import { moveSourceMaps } from "./source-maps.js";
10
10
  import { shellCodeSplitting } from "./shell-chunks.js";
11
11
  import { existsSync } from "node:fs";
12
12
  import path from "node:path";
13
- import { build } from "vite";
14
13
  import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
15
14
  import tailwindcss from "@tailwindcss/vite";
16
15
  import react from "@vitejs/plugin-react";
16
+ import { build } from "vite";
17
17
  import { tmpdir } from "node:os";
18
18
  //#region src/build/shell.ts
19
19
  /** What a shell folder holds beside its files: the `BundleShell` a bundle's manifest copies. */
@@ -1,11 +1,11 @@
1
- import { projectUiFile, projectUiId, projectUiPlugin } from "../project/project-ui.js";
2
1
  import { extensionImports } from "../project/extensions.js";
2
+ import { projectUiFile, projectUiId, projectUiPlugin } from "../project/project-ui.js";
3
3
  import { viteBundle } from "./vite-bundle.js";
4
4
  import { existsSync } from "node:fs";
5
5
  import path from "node:path";
6
+ import { pathToFileURL } from "node:url";
6
7
  import { mkdtemp, rm } from "node:fs/promises";
7
8
  import { tmpdir } from "node:os";
8
- import { pathToFileURL } from "node:url";
9
9
  //#region src/build/ui-check.ts
10
10
  const checkFile = (projectDir) => path.join(projectDir, "protobase-ui-check.js");
11
11
  const checkCode = [
@@ -1,7 +1,7 @@
1
1
  import { bunBuild } from "./bun-build.js";
2
2
  import path from "node:path";
3
- import { build } from "vite";
4
3
  import { mkdtemp, rm } from "node:fs/promises";
4
+ import { build } from "vite";
5
5
  import { tmpdir } from "node:os";
6
6
  //#region src/build/vite-bundle.ts
7
7
  const viteBuild = async ({ root, entry, outFile, plugins, logLevel = "warn" }) => {
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
- import { oauthWellKnownPaths, pngIcons } from "@protobase/server";
3
2
  import { readFile } from "node:fs/promises";
3
+ import { oauthWellKnownPaths, pngIcons } from "@protobase/server";
4
4
  //#region src/bundle/manifest.ts
5
5
  const manifestFile = "protobase.bundle.json";
6
6
  const isApiPath = (api, pathname) => api.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.46.11";
2
+ var version = "0.46.13";
3
3
  //#endregion
4
4
  export { version };
@@ -6,13 +6,5 @@ const connect = (url, options = {}) => postgres(url, {
6
6
  onnotice: () => {},
7
7
  connection: { default_transaction_read_only: true }
8
8
  });
9
- const resolveConnectionUrl = (arg, envName) => {
10
- if (arg && envName) throw new Error("Pass either a connection string or --env, not both");
11
- if (arg) return arg;
12
- if (!envName) throw new Error("Pass a connection string or --env <VARIABLE>");
13
- const value = process.env[envName];
14
- if (!value) throw new Error(`Environment variable ${envName} is not set`);
15
- return value;
16
- };
17
9
  //#endregion
18
- export { connect, resolveConnectionUrl };
10
+ export { connect };
@@ -0,0 +1,14 @@
1
+ //#region src/db/connection-url.ts
2
+ /** Whether a command's first argument is a connection string rather than a target. */
3
+ const isConnectionString = (value) => /^postgres(ql)?:\/\//.test(value);
4
+ const defaultConnectionEnv = "DATABASE_URL";
5
+ const resolveConnectionUrl = (arg, envName) => {
6
+ if (arg && envName) throw new Error("Pass either a connection string or --env, not both");
7
+ if (arg) return arg;
8
+ const value = process.env[envName ?? "DATABASE_URL"];
9
+ if (value) return value;
10
+ if (envName) throw new Error(`Environment variable ${envName} is not set`);
11
+ throw new Error(`Pass a connection string or --env <VARIABLE>, or set ${defaultConnectionEnv} in .env`);
12
+ };
13
+ //#endregion
14
+ export { defaultConnectionEnv, isConnectionString, resolveConnectionUrl };
package/dist/dev/entry.js CHANGED
@@ -1,19 +1,19 @@
1
1
  import { projectIcons } from "../build/app-icons.js";
2
- import { devJobs } from "./dev-jobs.js";
3
2
  import { projectErrorReporter } from "../project/error-reporter.js";
4
3
  import { projectAdmin } from "../project/project-admin.js";
4
+ import { devJobs } from "./dev-jobs.js";
5
5
  import { loadProject, projectDb } from "./project.js";
6
6
  import { withDevServiceWorker } from "./service-worker-route.js";
7
7
  import { setMissing, supabaseEnv } from "./supabase-env.js";
8
- import { apiKeySettings, assistantSettings, authStoreTables, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkNotificationsSchema, checkQueryRunner, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
9
8
  import { upgradeWebSocket } from "@hono/node-server";
10
9
  import { Hono } from "hono";
10
+ import { apiKeySettings, assistantSettings, authStoreTables, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkNotificationsSchema, checkQueryRunner, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
11
11
  //#region src/dev/entry.ts
12
12
  const projectDir = process.env.PROTOBASE_PROJECT;
13
13
  const project = await loadProject(projectDir, JSON.parse(process.env.PROTOBASE_EXTENSIONS ?? "[]"));
14
14
  const db = projectDb(project, projectDir);
15
15
  const { resources, views } = configExports(project.exports);
16
- if (!project.authenticate) throw new Error("No authenticator: export `authenticate` (and `auth`) from protobase.config.ts; see https://docs.protobase.net/reference/auth/");
16
+ if (!project.authenticate) throw new Error("No authenticator: export `authenticate` (and `auth`) from protobase.config.ts; see https://docs.protobase.net/guides/existing-database/#4-add-sign-in");
17
17
  const store = globalThis;
18
18
  if (project.auth && !store.__protobaseAuthSchemaChecked) {
19
19
  await checkAuthSchema(project.auth);
@@ -1,10 +1,10 @@
1
- import { functionFiles } from "../project/functions-folder.js";
2
1
  import { conventionConfig } from "../project/convention.js";
2
+ import { functionFiles } from "../project/functions-folder.js";
3
3
  import { sharedDb } from "./create-db.js";
4
4
  import { existsSync } from "node:fs";
5
5
  import path from "node:path";
6
- import { mergeConfig } from "@protobase/server";
7
6
  import { readdir } from "node:fs/promises";
7
+ import { mergeConfig } from "@protobase/server";
8
8
  //#region src/dev/project.ts
9
9
  const load = (file) => import(
10
10
  /* @vite-ignore */
package/dist/dev/run.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import { loadNearestEnvFile } from "./env.js";
2
- import { projectUiPlugin } from "../project/project-ui.js";
3
2
  import { adminAppDir, adminAppMain, uiPackageDir } from "../project/admin-app.js";
4
3
  import { extensionImports, extensionStyles } from "../project/extensions.js";
4
+ import { stopDevJobs } from "./dev-jobs.js";
5
+ import { frameHeaders } from "../serve/static-site.js";
6
+ import { projectUiPlugin } from "../project/project-ui.js";
5
7
  import { sharedModulesPlugin } from "../project/shared-modules.js";
6
8
  import { moduleFile } from "../module-file.js";
7
9
  import { layoutCheck } from "../build/layout-check.js";
@@ -10,15 +12,14 @@ import { themeLink } from "../project/theme-link.js";
10
12
  import { checkDatabase } from "./check-database.js";
11
13
  import { alsoOnIpv6, checkPortFree, devHost } from "./loopback.js";
12
14
  import { loginLine } from "./login-line.js";
13
- import { stopDevJobs } from "./dev-jobs.js";
15
+ import { startupLogger } from "./startup-logger.js";
14
16
  import { isProjectFile } from "./project-files.js";
15
17
  import { apiWebSockets } from "./api-websockets.js";
16
- import { frameHeaders } from "../serve/static-site.js";
17
18
  import { existsSync } from "node:fs";
18
19
  import path from "node:path";
19
- import { createServer, searchForWorkspaceRoot } from "vite";
20
20
  import tailwindcss from "@tailwindcss/vite";
21
21
  import react from "@vitejs/plugin-react";
22
+ import { createServer, searchForWorkspaceRoot } from "vite";
22
23
  import devServer from "@hono/vite-dev-server";
23
24
  //#region src/dev/run.ts
24
25
  const entry = moduleFile("./entry", import.meta.url);
@@ -66,9 +67,11 @@ const runDev = async (options, out) => {
66
67
  process.env.PROTOBASE_PROJECT = options.projectDir;
67
68
  process.env.PROTOBASE_EXTENSIONS = JSON.stringify(extensions);
68
69
  process.env.PROTOBASE_DATABASE_URL = url;
70
+ const logging = startupLogger();
69
71
  const server = await createServer({
70
72
  root: appDir,
71
73
  configFile: false,
74
+ customLogger: logging.logger,
72
75
  ...options.cacheDir && { cacheDir: options.cacheDir },
73
76
  optimizeDeps: {
74
77
  include: appDependencies,
@@ -117,6 +120,7 @@ const runDev = async (options, out) => {
117
120
  if (server.httpServer) await alsoOnIpv6(server.httpServer, port).catch(closeAndThrow);
118
121
  process.env.PROTOBASE_DEV_URL = `http://localhost:${port}`;
119
122
  const anyUsers = await (await server.ssrLoadModule(entry).catch(closeAndThrow)).anyUsers().catch(closeAndThrow);
123
+ logging.started();
120
124
  out(`protobase dev ready at http://localhost:${port}\n project ${options.projectDir}\n api http://localhost:${port}/api/v1 (docs at /api/docs)\n` + loginLine(anyUsers, process.env.npm_config_user_agent));
121
125
  return server;
122
126
  };
@@ -0,0 +1,24 @@
1
+ import { createLogger } from "vite";
2
+ //#region src/dev/startup-logger.ts
3
+ /**
4
+ * Vite's logger for `protobase dev`. Vite logs a module that fails to evaluate, with its stack, before
5
+ * `ssrLoadModule` throws the error. The first load is the startup check, whose error the CLI prints as one line, so
6
+ * Vite's copy is left out until `started`; a module that fails while the server runs still shows Vite's stack.
7
+ */
8
+ const startupLogger = () => {
9
+ const logger = createLogger();
10
+ const error = logger.error;
11
+ let starting = true;
12
+ logger.error = (message, options) => {
13
+ if (starting && message.includes("Error when evaluating SSR module")) return;
14
+ error(message, options);
15
+ };
16
+ return {
17
+ logger,
18
+ started: () => {
19
+ starting = false;
20
+ }
21
+ };
22
+ };
23
+ //#endregion
24
+ export { startupLogger };
@@ -5,10 +5,13 @@ import { readOnlyDb } from "../db/read-only-db.js";
5
5
  import { checkResource } from "./check.js";
6
6
  import { indexIssues } from "./index-issues.js";
7
7
  import { readShapes } from "./read-shapes.js";
8
+ import { existsSync } from "node:fs";
9
+ import path from "node:path";
8
10
  import { tableIndexes } from "@protobase/query";
9
11
  //#region src/doctor/run.ts
10
12
  const format = (issue) => ` ${issue.severity.padEnd(7)} ${issue.resource}: ${issue.message}${issue.suggestion ? `\n fix: ${issue.suggestion}` : ""}\n`;
11
13
  const runDoctor = async (options, out) => {
14
+ if (!existsSync(path.join(options.configDir, "index.ts"))) throw new Error(`No config in ${options.configDir}: write it with \`protobase scaffold\`, or pass --config <dir>`);
12
15
  const config = await loadDataConfig(options.configDir);
13
16
  const { models } = config;
14
17
  if (models.length === 0) throw new Error(`No resources exported from ${options.configDir}/index.ts`);
@@ -1,12 +1,11 @@
1
- import { loadBundleProject } from "../project/load-bundle-project.js";
2
1
  import { printStatus } from "./print-status.js";
3
2
  import { printApply } from "./print-apply.js";
4
3
  import { rebindOption } from "./rebind-option.js";
5
- import { createEncryptionTools } from "@protobase/server";
6
4
  //#region src/encryption/register.ts
7
5
  const out = (text) => void process.stdout.write(text);
8
6
  const bundleArgument = ["[bundle]", "a bundle from `protobase build` (its folder or config module); default: the project in the current directory"];
9
7
  const withTools = async (bundle, work) => {
8
+ const [{ createEncryptionTools }, { loadBundleProject }] = await Promise.all([import("@protobase/server"), import("../project/load-bundle-project.js")]);
10
9
  const project = await loadBundleProject(bundle, process.cwd());
11
10
  try {
12
11
  const tools = createEncryptionTools({
@@ -0,0 +1,15 @@
1
+ //#region src/error-message.ts
2
+ const target = ({ address, port }) => address?.includes(":") ? `[${address}]:${port}` : `${address}:${port}`;
3
+ /**
4
+ * The line the central error handler prints for an error. A connection to a host with several addresses, such as
5
+ * localhost's ::1 and 127.0.0.1, fails with an AggregateError of one error per address and no message of its own.
6
+ */
7
+ const errorMessage = (error) => {
8
+ if (error.message) return error.message;
9
+ if (!(error instanceof AggregateError) || error.errors.length === 0) return error.name;
10
+ const errors = error.errors;
11
+ if (errors.every((inner) => inner.code === "ECONNREFUSED" && inner.address)) return `Cannot connect to ${errors.map(target).join(" or ")}: the connection was refused, so nothing is listening there. Is the database running?`;
12
+ return errors.map(errorMessage).join("; ");
13
+ };
14
+ //#endregion
15
+ export { errorMessage };
@@ -0,0 +1,10 @@
1
+ //#region src/exit-signal.ts
2
+ var ExitSignal = class extends Error {
3
+ code;
4
+ constructor(code) {
5
+ super(`The command exited with code ${code}`);
6
+ this.code = code;
7
+ }
8
+ };
9
+ //#endregion
10
+ export { ExitSignal };
@@ -1,10 +1,9 @@
1
1
  import { cleanupCommand } from "./cleanup-command.js";
2
- import { loadBundleProject } from "../project/load-bundle-project.js";
3
- import { createFileCleanup } from "@protobase/server";
4
2
  //#region src/files/register.ts
5
3
  const out = (text) => process.stdout.write(text);
6
4
  const registerFiles = (program) => {
7
5
  program.command("files").description("Manage the stored files of the project in the current directory").command("cleanup").description("Delete the files whose scheduled delete is due and that no row references, such as replaced files and unused uploads").argument("[bundle]", "a bundle from `protobase build` (its folder or config module); default: the project in the current directory").action(async (bundle) => {
6
+ const [{ createFileCleanup }, { loadBundleProject }] = await Promise.all([import("@protobase/server"), import("../project/load-bundle-project.js")]);
8
7
  const project = await loadBundleProject(bundle, process.cwd());
9
8
  try {
10
9
  const cleanup = createFileCleanup(project);
@@ -27,7 +27,7 @@ const relationOf = (table, column, context) => {
27
27
  columns: fk.columns
28
28
  };
29
29
  };
30
- const auditColumn = /^(created|inserted|updated|modified)_at$/;
30
+ const auditColumn = /^(created|inserted|updated|modified)(_at|At)$/;
31
31
  const isServerManaged = (table, column) => column.identity || auditColumn.test(column.name) || table.indexes.some((index) => index.primary && index.columns.includes(column.name));
32
32
  const defaultsOf = (table, column, kind) => {
33
33
  const fallback = columnDefault(column, kind);
package/dist/main.js CHANGED
@@ -1,49 +1,43 @@
1
- import { loadNearestEnvFile } from "./dev/env.js";
2
1
  import { registerAuth } from "./auth/register.js";
3
- import { manifestFile } from "./bundle/manifest.js";
4
- import { resolveExtensions } from "./project/extensions.js";
5
- import { buildPlugin, pluginManifestFile } from "./build/plugin-build.js";
6
- import { buildShell } from "./build/shell.js";
7
- import { buildDeployBundle } from "./build/deploy-bundle.js";
8
- import { buildServeRuntime } from "./build/serve-runtime.js";
9
- import { resolveConnectionUrl } from "./db/connect.js";
2
+ import { isConnectionString, resolveConnectionUrl } from "./db/connection-url.js";
10
3
  import { parseHosts } from "./dev/hosts.js";
11
- import { runDev } from "./dev/run.js";
12
- import { runDoctor } from "./doctor/run.js";
13
- import { projectErrorReporter } from "./project/error-reporter.js";
14
- import { runScaffold } from "./scaffold/run.js";
15
- import { reportCrashes } from "./serve/crash-reports.js";
16
- import { closeOnSignals } from "./serve/signals.js";
17
- import { serveBundle } from "./serve/serve-bundle.js";
18
- import { serveBundleDir } from "./serve/serve-dir.js";
19
- import { loadWorkerBundle, startWorker } from "./worker/start-worker.js";
4
+ import { loadNearestEnvFile } from "./dev/env.js";
5
+ import { resolveExtensions } from "./project/extensions.js";
6
+ import { placeholderSecretWarning } from "./project/placeholder-secret.js";
20
7
  import { registerOrganizations } from "./organizations/register.js";
21
8
  import { registerFiles } from "./files/register.js";
22
9
  import { registerEncryption } from "./encryption/register.js";
23
10
  import { registerMigration } from "./migration/register.js";
24
11
  import { registerMobile } from "./mobile/register.js";
25
12
  import { registerNotifications } from "./notifications/register.js";
13
+ import { protobaseVersion } from "./version/version.js";
26
14
  import { registerSkill } from "./skill/register.js";
27
15
  import { registerImport } from "./supabase/register.js";
28
16
  import { registerToken, registerUsers } from "./users/register.js";
17
+ import { ExitSignal } from "./exit-signal.js";
18
+ import { errorMessage } from "./error-message.js";
29
19
  import { statSync } from "node:fs";
30
20
  import path from "node:path";
31
21
  import { Command, InvalidArgumentError } from "commander";
32
22
  //#region src/main.ts
33
23
  const out = (text) => process.stdout.write(text);
24
+ const warn = (message) => message && process.stderr.write(`warning: ${message}\n`);
34
25
  const collect = (value, previous) => [...previous, value];
35
26
  const uiSection = (value) => {
36
27
  if (value === "names" || value === "list") return value;
37
28
  throw new InvalidArgumentError("expected names or list");
38
29
  };
39
30
  const collectSection = (value, previous) => [...previous, uiSection(value)];
40
- const program = new Command("protobase").description("Protobase command line");
41
- program.command("scaffold").description("Generate or update config/<resource>/data.ts from a Postgres database").argument("[args...]", "connection string (unless --env) followed by an optional target: all, schema, schema.table, schema.table.column").option("--env <variable>", "read the connection string from this environment variable").option("--config <dir>", "config folder", "config").option("--yes", "accept all proposals without asking", false).option("--dry-run", "print a diff instead of writing files", false).option("--ui", "also write config/<resource>/ui.ts (names and list)", false).option("--ui-list", "write only the list section of ui.ts", false).option("--ui-section <name>", "write only this ui.ts section (names or list), repeatable", collectSection, []).option("--exclude <table>", "skip a schema or schema.table, repeatable", collect, []).action(async (args, opts) => {
31
+ const program = new Command("protobase").description("Protobase command line").version(protobaseVersion, "-v, --version", "print the Protobase version");
32
+ program.command("scaffold").description("Generate or update config/<resource>/data.ts from a Postgres database").argument("[args...]", "connection string (default: DATABASE_URL from the environment or .env) followed by an optional target: all, schema, schema.table, schema.table.column").option("--env <variable>", "read the connection string from this environment variable").option("--config <dir>", "config folder", "config").option("--yes", "accept all proposals without asking", false).option("--dry-run", "print a diff instead of writing files", false).option("--ui", "also write config/<resource>/ui.ts (names and list)", false).option("--ui-list", "write only the list section of ui.ts", false).option("--ui-section <name>", "write only this ui.ts section (names or list), repeatable", collectSection, []).option("--exclude <table>", "skip a schema or schema.table, repeatable", collect, []).action(async (args, opts) => {
33
+ loadNearestEnvFile(process.cwd());
42
34
  const [first, ...rest] = args;
43
- const url = resolveConnectionUrl(opts.env ? void 0 : first, opts.env);
44
- const [target, ...extra] = opts.env ? args : rest;
35
+ const fromArgument = !opts.env && first !== void 0 && isConnectionString(first);
36
+ const url = resolveConnectionUrl(fromArgument ? first : void 0, opts.env);
37
+ const [target, ...extra] = fromArgument ? rest : args;
45
38
  if (extra.length > 0) throw new Error(`Unexpected argument "${extra[0]}"`);
46
39
  const ui = opts.ui ? ["names", "list"] : [...opts.uiSection, ...opts.uiList ? ["list"] : []];
40
+ const { runScaffold } = await import("./scaffold/run.js");
47
41
  await runScaffold({
48
42
  url,
49
43
  target,
@@ -54,8 +48,10 @@ program.command("scaffold").description("Generate or update config/<resource>/da
54
48
  excludes: opts.exclude
55
49
  }, out);
56
50
  });
57
- program.command("doctor").description("Check a config folder against the database").argument("[connection]", "connection string").option("--env <variable>", "read the connection string from this environment variable").option("--config <dir>", "config folder", "config").action(async (connection, opts) => {
51
+ program.command("doctor").description("Check a config folder against the database").argument("[connection]", "connection string (default: DATABASE_URL from the environment or .env)").option("--env <variable>", "read the connection string from this environment variable").option("--config <dir>", "config folder", "config").action(async (connection, opts) => {
52
+ loadNearestEnvFile(process.cwd());
58
53
  const url = resolveConnectionUrl(connection, opts.env);
54
+ const { runDoctor } = await import("./doctor/run.js");
59
55
  const { errors } = await runDoctor({
60
56
  url,
61
57
  configDir: path.resolve(opts.config)
@@ -63,6 +59,7 @@ program.command("doctor").description("Check a config folder against the databas
63
59
  if (errors > 0) process.exitCode = 1;
64
60
  });
65
61
  program.command("dev").description("Serve the admin app and API for the project in the current directory").option("--port <port>", "port for the app and API", "5173").option("--env <variable>", "environment variable holding the database URL", "DATABASE_URL").option("--allowed-hosts <hosts>", "extra Host headers to accept, comma separated; a leading dot matches subdomains (.trycloudflare.com)").option("--cache-dir <dir>", "Vite's dependency cache, so parallel dev servers do not share one").option("--extend <dir>", "merge the protobase.config.ts and protobase.ui.tsx in this folder before the project's, repeatable", collect, []).action(async (opts) => {
62
+ const { runDev } = await import("./dev/run.js");
66
63
  const server = await runDev({
67
64
  extensions: resolveExtensions(opts.extend),
68
65
  port: Number(opts.port),
@@ -71,12 +68,14 @@ program.command("dev").description("Serve the admin app and API for the project
71
68
  cacheDir: opts.cacheDir && path.resolve(opts.cacheDir),
72
69
  allowedHosts: parseHosts(opts.allowedHosts)
73
70
  }, out);
71
+ warn(placeholderSecretWarning(process.env));
74
72
  process.once("SIGINT", () => void server.close().then(() => process.exit(0)));
75
73
  process.once("SIGTERM", () => void server.close().then(() => process.exit(0)));
76
74
  });
77
75
  program.command("build").description("Build the deploy bundle of the project in the current directory: its config module, the admin app with the project's UI as a plugin, and the manifest").option("--out <dir>", "output folder", "dist").option("--bun", "have Bun's bundler write the config module, for a bundle only Bun serves (needs bun on PATH)", false).option("--extend <dir>", "merge the protobase.config.ts and protobase.ui.tsx in this folder before the project's, repeatable", collect, []).option("--source-maps", "end each script with a //# debugId= comment and write its source map, carrying the same id, beside it", false).action(async (opts) => {
78
76
  const extensions = resolveExtensions(opts.extend);
79
77
  const onWarning = (message) => process.stderr.write(`warning: ${message}\n`);
78
+ const [{ buildDeployBundle }, { manifestFile }] = await Promise.all([import("./build/deploy-bundle.js"), import("./bundle/manifest.js")]);
80
79
  const manifest = await buildDeployBundle({
81
80
  projectDir: process.cwd(),
82
81
  outDir: path.resolve(opts.out),
@@ -92,6 +91,7 @@ program.command("build").description("Build the deploy bundle of the project in
92
91
  program.command("build-plugin").description("Build a plugin the admin app loads at runtime: its protobase.ui.tsx as one ES module, its stylesheet and plugin.json").argument("[dir]", "the plugin folder, holding protobase.ui.tsx", ".").option("--out <dir>", "output folder (default: dist in the plugin folder)").option("--name <name>", "the plugin's name (default: its package.json name)").option("--source-maps", "end each script with a //# debugId= comment and write its source map, carrying the same id, beside it", false).action(async (dir, opts) => {
93
92
  const pluginDir = path.resolve(dir);
94
93
  const outDir = path.resolve(opts.out ?? path.join(dir, "dist"));
94
+ const { buildPlugin, pluginManifestFile } = await import("./build/plugin-build.js");
95
95
  const manifest = await buildPlugin({
96
96
  pluginDir,
97
97
  outDir,
@@ -102,10 +102,12 @@ program.command("build-plugin").description("Build a plugin the admin app loads
102
102
  out(`built ${shown.startsWith("..") ? outDir : shown || "."}: ${pluginManifestFile}, ${manifest.entry} and ${manifest.css} (${manifest.name}, plugin API ${manifest.api}, Protobase ${manifest.protobase})\n`);
103
103
  });
104
104
  program.command("build-shell", { hidden: true }).description("Build the admin app every bundle shares, as @protobase/ui's package and the protobase image ship it").argument("<out>", "output folder").option("--source-maps <dir>", "end each script with a //# debugId= comment and write its source map, carrying the same id, to this folder").action(async (outDir, opts) => {
105
+ const { buildShell } = await import("./build/shell.js");
105
106
  const shell = await buildShell(path.resolve(outDir), opts.sourceMaps && path.resolve(opts.sourceMaps));
106
107
  out(`built ${outDir}: the shell of Protobase ${shell.protobase} (plugin API ${shell.pluginApi})\n`);
107
108
  });
108
109
  program.command("build-serve").description("Bundle the serve runtime into one file for Bun: bun --no-install protobase-serve.js <bundle.js>").option("--out <file>", "output file", "dist/protobase-serve.js").option("--bun", "have Bun's bundler write the file (needs bun on PATH)", false).action(async (opts) => {
110
+ const { buildServeRuntime } = await import("./build/serve-runtime.js");
109
111
  await buildServeRuntime({
110
112
  outFile: path.resolve(opts.out),
111
113
  bun: opts.bun
@@ -114,11 +116,18 @@ program.command("build-serve").description("Bundle the serve runtime into one fi
114
116
  });
115
117
  program.command("serve").description("Serve a bundle written by `protobase build` until SIGTERM or SIGINT: a folder as a host serves it, a config module as its API alone").argument("<bundle>", "the bundle folder, e.g. dist, or its dist/protobase.config.js").action(async (bundle) => {
116
118
  loadNearestEnvFile(process.cwd());
117
- if (statSync(bundle).isDirectory()) await serveBundleDir(bundle, process.env, out);
118
- else await serveBundle(bundle, process.env, out);
119
+ warn(placeholderSecretWarning(process.env));
120
+ if (statSync(bundle).isDirectory()) await (await import("./serve/serve-dir.js")).serveBundleDir(bundle, process.env, out);
121
+ else await (await import("./serve/serve-bundle.js")).serveBundle(bundle, process.env, out);
119
122
  });
120
123
  program.command("worker").description("Run the jobs of a bundle from `protobase build` in a process of their own, until SIGTERM or SIGINT, as `serve` runs them beside the API").argument("<bundle>", "the bundle folder, e.g. dist, or its dist/protobase.config.js").action(async (bundle) => {
121
124
  loadNearestEnvFile(process.cwd());
125
+ const [{ loadWorkerBundle, startWorker }, { projectErrorReporter }, { reportCrashes }, { closeOnSignals }] = await Promise.all([
126
+ import("./worker/start-worker.js"),
127
+ import("./project/error-reporter.js"),
128
+ import("./serve/crash-reports.js"),
129
+ import("./serve/signals.js")
130
+ ]);
122
131
  const project = await loadWorkerBundle(bundle);
123
132
  const reporter = await projectErrorReporter(project, process.env);
124
133
  if (reporter) reportCrashes(reporter);
@@ -141,8 +150,12 @@ registerImport(program);
141
150
  registerMobile(program);
142
151
  registerNotifications(program);
143
152
  const run = (argv) => program.parseAsync(argv).catch((error) => {
144
- process.stderr.write(`error: ${error.message}\n`);
153
+ if (error instanceof ExitSignal) {
154
+ process.exitCode = error.code;
155
+ return;
156
+ }
157
+ process.stderr.write(`error: ${errorMessage(error)}\n`);
145
158
  process.exitCode = 1;
146
159
  });
147
160
  //#endregion
148
- export { run };
161
+ export { program, run };
@@ -1,6 +1,6 @@
1
1
  import { loadNearestEnvFile } from "../dev/env.js";
2
- import { importProjectFile } from "../project/import-project-file.js";
3
2
  import { createPgDb } from "../project/pg-db.js";
3
+ import { importProjectFile } from "../project/import-project-file.js";
4
4
  import { existsSync } from "node:fs";
5
5
  import path from "node:path";
6
6
  import { assistantSettings, authStoreTables, configExports, jobDefinitions, mergeConfig } from "@protobase/server";
@@ -1,17 +1,20 @@
1
1
  import { resolveExtensions } from "../project/extensions.js";
2
- import { loadMigrationProject } from "./load-project.js";
3
- import { migrationParts } from "./parts.js";
4
- import { writeMigrations } from "./write-migrations.js";
2
+ import { migrationSummary } from "./summary.js";
5
3
  import path from "node:path";
6
4
  //#region src/migration/register.ts
7
5
  const out = (text) => process.stdout.write(text);
8
6
  const collect = (value, previous) => [...previous, value];
9
7
  const registerMigration = (program) => {
10
8
  program.command("migration").description("Write what the database still needs for every feature the config enables (auth, events, jobs) as the project's next SQL migrations").option("--dir <dir>", "migrations folder", "db/migrations").option("--extend <dir>", "merge the protobase.config.ts in this folder before the project's, as dev and build do, repeatable", collect, []).action(async (opts) => {
9
+ const [{ loadMigrationProject }, { migrationParts }, { writeMigrations }] = await Promise.all([
10
+ import("./load-project.js"),
11
+ import("./parts.js"),
12
+ import("./write-migrations.js")
13
+ ]);
11
14
  const project = await loadMigrationProject(process.cwd(), resolveExtensions(opts.extend));
12
15
  try {
13
16
  const files = await writeMigrations(migrationParts(project), path.resolve(opts.dir));
14
- out(files.length > 0 ? files.map((file) => `wrote ${path.relative(process.cwd(), file)}\n`).join("") + "apply them with the project's migrations\n" : "the database is up to date; nothing to write\n");
17
+ out(migrationSummary(files, process.cwd(), Boolean(project.auth)));
15
18
  } finally {
16
19
  await project.close();
17
20
  }
@@ -0,0 +1,15 @@
1
+ import path from "node:path";
2
+ //#region src/migration/summary.ts
3
+ /** Where to read how to add sign-in to a project that has none. */
4
+ const signInGuide = "https://docs.protobase.net/guides/existing-database/";
5
+ /**
6
+ * What `protobase migration` prints: the files it wrote, relative to `cwd`, or that the database is current for what
7
+ * the config enables. A config without `auth` enables no sign-in, so its database being current says nothing about it.
8
+ */
9
+ const migrationSummary = (files, cwd, hasAuth) => {
10
+ const written = files.length > 0 ? files.map((file) => `wrote ${path.relative(cwd, file)}\n`).join("") + "apply them with the project's migrations\n" : "the database is up to date; nothing to write\n";
11
+ if (hasAuth) return written;
12
+ return `${written}no sign-in is configured, so nothing was written for it: export auth and authenticate from protobase.config.ts, see ${signInGuide}\n`;
13
+ };
14
+ //#endregion
15
+ export { migrationSummary, signInGuide };