@protobase/cli 0.47.1 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/dist/build/config-bundle.js +6 -1
  2. package/dist/build/entry-code.js +30 -17
  3. package/dist/cli/package.js +1 -1
  4. package/dist/config/build-project.js +70 -0
  5. package/dist/config/called-config.js +11 -0
  6. package/dist/config/config-defaults.js +30 -0
  7. package/dist/config/env-values.js +20 -0
  8. package/dist/config/lazy-imports.js +18 -0
  9. package/dist/config/merge-config.js +72 -0
  10. package/dist/config/project-files.js +48 -0
  11. package/dist/config/project-parts.js +201 -0
  12. package/dist/config/read-config.js +31 -0
  13. package/dist/config/source-config.js +37 -0
  14. package/dist/dev/api-child.js +2 -1
  15. package/dist/dev/api-process.d.ts +1 -0
  16. package/dist/dev/api-process.js +5 -2
  17. package/dist/dev/auth-drift-lines.js +8 -0
  18. package/dist/dev/create-db.js +2 -2
  19. package/dist/dev/entry.d.ts +5 -0
  20. package/dist/dev/entry.js +17 -12
  21. package/dist/dev/project.js +23 -47
  22. package/dist/dev/run.js +3 -2
  23. package/dist/main.js +3 -3
  24. package/dist/migration/load-project.js +34 -34
  25. package/dist/migration/parts.js +2 -2
  26. package/dist/migration/summary.js +2 -2
  27. package/dist/mobile/api-origin.js +4 -4
  28. package/dist/mobile/load-project.js +13 -12
  29. package/dist/mobile/register.js +1 -1
  30. package/dist/mobile/run.js +1 -1
  31. package/dist/organizations/register.js +1 -1
  32. package/dist/project/error-reporter.js +3 -3
  33. package/dist/project/import-project-file.js +4 -2
  34. package/dist/project/load-bundle-project.js +16 -25
  35. package/dist/project/load-data-config.js +2 -2
  36. package/dist/project/pg-db.js +10 -4
  37. package/dist/project/placeholder-secret.js +2 -2
  38. package/dist/project/project-admin.js +12 -11
  39. package/dist/scaffold/plan.js +7 -3
  40. package/dist/scaffold/protobase-tables.js +8 -13
  41. package/dist/scaffold/run.js +1 -1
  42. package/dist/serve/create-admin.js +9 -4
  43. package/dist/serve/host-module-ids.js +1 -0
  44. package/dist/serve/host-modules.js +3 -1
  45. package/dist/serve/lifecycle.js +19 -14
  46. package/dist/serve/load-bundle.js +41 -11
  47. package/dist/serve/mobile-release.js +1 -1
  48. package/dist/serve/serve-bundle.js +3 -3
  49. package/dist/supabase/auth-config.js +33 -28
  50. package/dist/supabase/config-jobs.js +28 -27
  51. package/dist/supabase/config-object.js +25 -0
  52. package/dist/supabase/cron-job-file.js +13 -14
  53. package/dist/supabase/cron-jobs-write.js +6 -12
  54. package/dist/supabase/cron-plan.js +3 -51
  55. package/dist/supabase/project-files.js +4 -9
  56. package/dist/supabase/report.js +3 -3
  57. package/dist/users/load-auth.js +16 -15
  58. package/dist/worker/start-worker.js +18 -15
  59. package/package.json +8 -6
  60. package/skills/protobase/SKILL.md +2 -1
  61. package/skills/protobase/references/features/notifications.md +1 -1
  62. package/skills/protobase/references/features/sign-in-and-accounts.md +1 -0
  63. package/skills/protobase/references/features/start-a-project.md +3 -0
  64. package/skills/protobase/references/getting-started.md +2 -2
  65. package/skills/protobase/references/guides/api-functions.md +4 -4
  66. package/skills/protobase/references/guides/deploy.md +8 -8
  67. package/skills/protobase/references/guides/existing-database.md +11 -31
  68. package/skills/protobase/references/guides/first-plugin.md +1 -1
  69. package/skills/protobase/references/guides/mobile-app.md +5 -3
  70. package/skills/protobase/references/guides/plugin-build.md +1 -1
  71. package/skills/protobase/references/guides/push-notifications.md +6 -7
  72. package/skills/protobase/references/guides/remote-resources.md +22 -31
  73. package/skills/protobase/references/reference/access.md +3 -3
  74. package/skills/protobase/references/reference/ai.md +1 -9
  75. package/skills/protobase/references/reference/api.md +15 -15
  76. package/skills/protobase/references/reference/app-identity.md +9 -10
  77. package/skills/protobase/references/reference/assistant.md +6 -6
  78. package/skills/protobase/references/reference/auth.md +126 -96
  79. package/skills/protobase/references/reference/bottom-bar.md +1 -1
  80. package/skills/protobase/references/reference/cli.md +36 -86
  81. package/skills/protobase/references/reference/comments.md +0 -8
  82. package/skills/protobase/references/reference/config.md +152 -0
  83. package/skills/protobase/references/reference/data-config.md +2 -2
  84. package/skills/protobase/references/reference/email.md +36 -37
  85. package/skills/protobase/references/reference/events.md +1 -1
  86. package/skills/protobase/references/reference/files.md +18 -23
  87. package/skills/protobase/references/reference/forms.md +5 -17
  88. package/skills/protobase/references/reference/history.md +2 -3
  89. package/skills/protobase/references/reference/installable-app.md +1 -1
  90. package/skills/protobase/references/reference/jobs.md +53 -56
  91. package/skills/protobase/references/reference/languages.md +4 -2
  92. package/skills/protobase/references/reference/mcp.md +11 -11
  93. package/skills/protobase/references/reference/notifications.md +26 -24
  94. package/skills/protobase/references/reference/plugins.md +11 -14
  95. package/skills/protobase/references/reference/remote-resources.md +18 -24
  96. package/skills/protobase/references/reference/supabase-realtime.md +1 -1
  97. package/skills/protobase/references/reference/supabase-rest.md +1 -1
  98. package/skills/protobase/references/reference/supabase-storage.md +1 -1
  99. package/skills/protobase/references/reference/ui-config.md +15 -17
  100. package/skills/protobase/references/reference/versioning.md +1 -1
  101. package/skills/protobase/references/reference/webhooks.md +6 -7
@@ -5,6 +5,7 @@ export type ApiProcessMessage = {
5
5
  ready: {
6
6
  port: number;
7
7
  anyUsers?: boolean;
8
+ authDrift: string[];
8
9
  };
9
10
  } | {
10
11
  failed: string;
@@ -53,7 +53,9 @@ const stop = async () => {
53
53
  const start = async () => {
54
54
  sockets = (await vite.ssrLoadModule(support)).apiWebSocketServer();
55
55
  process.env.PROTOBASE_DEV_URL = await devUrl;
56
- const anyUsers = await (await vite.ssrLoadModule(entry)).anyUsers();
56
+ const api = await vite.ssrLoadModule(entry);
57
+ const anyUsers = await api.anyUsers();
58
+ const authDrift = await api.authDrift();
57
59
  logging.started();
58
60
  server = createAdaptorServer({
59
61
  fetch,
@@ -63,7 +65,8 @@ const start = async () => {
63
65
  const port = await listen(server);
64
66
  process.send({ ready: {
65
67
  port,
66
- anyUsers
68
+ anyUsers,
69
+ authDrift
67
70
  } });
68
71
  };
69
72
  process.on("SIGINT", () => void 0);
@@ -0,0 +1,8 @@
1
+ //#region src/dev/auth-drift-lines.ts
2
+ /**
3
+ * The banner's warning that the auth store's tables drifted from its migrations, such as a column changed by hand, one
4
+ * line per difference; nothing when they match.
5
+ */
6
+ const authDriftLines = (drift) => drift.length === 0 ? "" : ` warning the auth store drifted from its migrations; apply the project's migrations, or write a change made by hand as a migration of the project's own:\n${drift.map((finding) => ` ${finding}\n`).join("")}`;
7
+ //#endregion
8
+ export { authDriftLines };
@@ -1,4 +1,4 @@
1
- import { createPgDb } from "../project/pg-db.js";
1
+ import { openAppDatabase } from "../project/pg-db.js";
2
2
  import { createRequire } from "node:module";
3
3
  import path from "node:path";
4
4
  //#region src/dev/create-db.ts
@@ -6,7 +6,7 @@ const sharedDb = (projectDir, url) => {
6
6
  const store = globalThis;
7
7
  if (store.__protobaseDb) return store.__protobaseDb;
8
8
  const load = createRequire(path.join(projectDir, "package.json"));
9
- store.__protobaseDb = createPgDb(load("pg"), url);
9
+ store.__protobaseDb = openAppDatabase(load("pg"), url);
10
10
  return store.__protobaseDb;
11
11
  };
12
12
  //#endregion
@@ -2,5 +2,10 @@
2
2
  declare const _default: import("hono/hono-base").HonoBase<import("hono/types").BlankEnv, import("hono/types").BlankSchema | import("hono/types").MergeSchemaPath<import("hono/types").BlankSchema, "/">, "/", "/">;
3
3
  /** Whether the auth store has a user yet, for the banner's sign-in line; undefined without one. */
4
4
  export declare const anyUsers: () => Promise<boolean> | Promise<undefined>;
5
+ /**
6
+ * How the auth store's tables differ from what the project's Better Auth needs, for the banner's warnings: the one
7
+ * comparison of the store's tables, made in development only, since a deploy reads the store's record of migrations.
8
+ */
9
+ export declare const authDrift: () => Promise<string[]>;
5
10
  //#endregion
6
11
  export { _default as default };
package/dist/dev/entry.js CHANGED
@@ -1,24 +1,27 @@
1
1
  import { projectIcons } from "../build/app-icons.js";
2
2
  import { projectErrorReporter } from "../project/error-reporter.js";
3
3
  import { projectAdmin } from "../project/project-admin.js";
4
+ import { buildProject } from "../config/build-project.js";
4
5
  import { devJobs } from "./dev-jobs.js";
5
- import { loadProject, projectDb } from "./project.js";
6
+ import { devDatabase, loadDevConfig } from "./project.js";
6
7
  import { withDevServiceWorker } from "./service-worker-route.js";
7
8
  import { setMissing, supabaseEnv } from "./supabase-env.js";
8
9
  import { upgradeWebSocket } from "@hono/node-server";
9
10
  import { Hono } from "hono";
10
- import { apiKeySettings, assistantSettings, authStoreTables, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkNotificationsSchema, checkQueryRunner, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
11
+ import { apiKeySettings, assistantSettings, authSchemaDrift, authStoreTables, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkNotificationsSchema, checkQueryRunner, checkResourcesOutsideAuthStore, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
11
12
  //#region src/dev/entry.ts
12
13
  const projectDir = process.env.PROTOBASE_PROJECT;
13
- const project = await loadProject(projectDir, JSON.parse(process.env.PROTOBASE_EXTENSIONS ?? "[]"));
14
- const db = projectDb(project, projectDir);
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/guides/existing-database/#4-add-sign-in");
14
+ const config = await loadDevConfig(projectDir, JSON.parse(process.env.PROTOBASE_EXTENSIONS ?? "[]"));
15
+ const database = devDatabase(projectDir);
16
+ const { db } = database;
17
+ const project = await buildProject(config, database);
18
+ const { resources, views } = configExports(project.config);
17
19
  const store = globalThis;
18
20
  if (project.auth && !store.__protobaseAuthSchemaChecked) {
19
21
  await checkAuthSchema(project.auth);
20
22
  store.__protobaseAuthSchemaChecked = true;
21
23
  }
24
+ if (project.auth) await checkResourcesOutsideAuthStore(db, resources.map((resource) => resource.toModel()), project.auth);
22
25
  await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
23
26
  await checkComments(db, resources.map((resource) => resource.toModel()));
24
27
  await checkComputed(db, resources.map((resource) => resource.toModel()));
@@ -37,19 +40,21 @@ setMissing(process.env, supabaseEnv({
37
40
  keys: apiKeySettings(project.options?.apiKeys, process.env),
38
41
  withAuth: Boolean(project.auth)
39
42
  }));
40
- const reporter = await projectErrorReporter(project, process.env);
43
+ const reporter = await projectErrorReporter(config, process.env);
41
44
  const ui = {
42
45
  plugins: [],
43
46
  fieldTypes: {},
44
47
  icons: projectIcons(projectDir)
45
48
  };
46
- const { admin, jobs } = projectAdmin({
47
- ...project,
48
- authenticate: project.authenticate
49
- }, project.exports, db, ui, reporter, upgradeWebSocket);
49
+ const { admin, jobs } = projectAdmin(project, db, ui, reporter, upgradeWebSocket);
50
50
  await devJobs(db, jobs);
51
51
  var entry_default = withDevServiceWorker(new Hono(), Boolean(project.notifications)).route("/", admin);
52
52
  /** Whether the auth store has a user yet, for the banner's sign-in line; undefined without one. */
53
53
  const anyUsers = () => project.auth ? hasUsers(project.auth) : Promise.resolve(void 0);
54
+ /**
55
+ * How the auth store's tables differ from what the project's Better Auth needs, for the banner's warnings: the one
56
+ * comparison of the store's tables, made in development only, since a deploy reads the store's record of migrations.
57
+ */
58
+ const authDrift = () => project.auth ? authSchemaDrift(project.auth) : Promise.resolve([]);
54
59
  //#endregion
55
- export { anyUsers, entry_default as default };
60
+ export { anyUsers, authDrift, entry_default as default };
@@ -1,58 +1,34 @@
1
- import { conventionConfig } from "../project/convention.js";
2
- import { functionFiles } from "../project/functions-folder.js";
1
+ import { loadSourceConfig } from "../config/source-config.js";
3
2
  import { sharedDb } from "./create-db.js";
4
- import { existsSync } from "node:fs";
5
- import path from "node:path";
6
- import { readdir } from "node:fs/promises";
7
- import { mergeConfig } from "@protobase/server";
3
+ import { pathToFileURL } from "node:url";
8
4
  //#region src/dev/project.ts
9
- const load = (file) => import(
5
+ const load = (file) => file.split("/").includes("node_modules") ? import(
6
+ /* @vite-ignore */
7
+ pathToFileURL(file).href
8
+ ) : import(
10
9
  /* @vite-ignore */
11
10
  `/@fs${file}`
12
11
  );
13
- const conventionExports = async (projectDir) => {
14
- const configDir = path.join(projectDir, "config");
15
- const index = path.join(configDir, "index.ts");
16
- if (!existsSync(index)) throw new Error(`No config/index.ts in ${projectDir}; run \`protobase scaffold\` or add a protobase.config.ts`);
17
- const indexExports = await load(index);
18
- const dirs = (await readdir(configDir, { withFileTypes: true })).filter((entry) => entry.isDirectory());
19
- const uiModules = [];
20
- for (const { name } of dirs) {
21
- const ui = path.join(configDir, name, "ui.ts");
22
- if (existsSync(ui)) uiModules.push([name, await load(ui)]);
23
- }
24
- return conventionConfig(indexExports, uiModules);
25
- };
26
- const conventionFunctions = async (projectDir) => {
27
- const files = functionFiles(projectDir);
28
- if (files.length === 0) return void 0;
29
- return Object.fromEntries(await Promise.all(files.map(async ({ name, file }) => [name, (await load(file)).default])));
12
+ const importModules = async (files) => {
13
+ const modules = [];
14
+ for (const file of files) modules.push(await load(file));
15
+ return modules;
30
16
  };
31
- const named = (config, file) => ({
32
- ...config,
33
- name: config.name ?? file
17
+ /**
18
+ * The project's config as `protobase dev` reads it on every load: protobase.config.ts, with the convention's resources
19
+ * and functions when it names none, merged after the extensions' configs, as `protobase build` merges them. What its
20
+ * references name loads through Vite's module graph, so an edit to it reloads the API.
21
+ */
22
+ const loadDevConfig = (projectDir, extensions = []) => loadSourceConfig(projectDir, {
23
+ command: "dev",
24
+ extensions,
25
+ importModules
34
26
  });
35
- const loadProject = async (projectDir, extensions = []) => {
36
- const file = path.join(projectDir, "protobase.config.ts");
37
- const custom = existsSync(file) ? (await load(file)).default ?? {} : {};
38
- const extended = [];
39
- for (const extension of extensions) if (extension.config) extended.push(named((await load(extension.config)).default ?? {}, extension.config));
40
- const own = named({
41
- ...custom,
42
- config: custom.config ?? await conventionExports(projectDir),
43
- functions: custom.functions ?? await conventionFunctions(projectDir)
44
- }, existsSync(file) ? "protobase.config.ts" : "config/index.ts");
45
- const project = mergeConfig(...extended, own);
46
- return {
47
- ...project,
48
- exports: project.config ?? {}
49
- };
50
- };
51
- const projectDb = (project, projectDir) => {
52
- if (project.db) return project.db;
27
+ /** The app's database, shared across reloads. */
28
+ const devDatabase = (projectDir) => {
53
29
  const url = process.env.PROTOBASE_DATABASE_URL;
54
- if (!url) throw new Error("No database: set DATABASE_URL (or pass --env) or export `db` from protobase.config.ts");
30
+ if (!url) throw new Error("No database: set DATABASE_URL (or pass --env)");
55
31
  return sharedDb(projectDir, url);
56
32
  };
57
33
  //#endregion
58
- export { loadProject, projectDb };
34
+ export { devDatabase, loadDevConfig };
package/dist/dev/run.js CHANGED
@@ -2,6 +2,7 @@ import { loadNearestEnvFile } from "./env.js";
2
2
  import { adminAppDir, adminAppMain } from "../project/admin-app.js";
3
3
  import { alsoOnIpv6, checkPortFree } from "./loopback.js";
4
4
  import { checkDatabase } from "./check-database.js";
5
+ import { authDriftLines } from "./auth-drift-lines.js";
5
6
  import { loginLine } from "./login-line.js";
6
7
  import { apiForward } from "./api-forward.js";
7
8
  import { forkApiChild } from "./api-child.js";
@@ -61,8 +62,8 @@ const runDev = async (options, out) => {
61
62
  if (server.httpServer) await alsoOnIpv6(server.httpServer, port).catch(closeAndThrow);
62
63
  const started = await apiChild.start(`http://localhost:${port}`).catch(closeAndThrow);
63
64
  apiReady(started);
64
- const { anyUsers } = started;
65
- 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));
65
+ const { anyUsers, authDrift } = started;
66
+ 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) + authDriftLines(authDrift));
66
67
  return server;
67
68
  };
68
69
  //#endregion
package/dist/main.js CHANGED
@@ -133,11 +133,11 @@ program.command("worker").description("Run the jobs of a bundle from `protobase
133
133
  import("./serve/crash-reports.js"),
134
134
  import("./serve/signals.js")
135
135
  ]);
136
- const project = await loadWorkerBundle(bundle);
137
- const reporter = await projectErrorReporter(project, process.env);
136
+ const config = await loadWorkerBundle(bundle);
137
+ const reporter = await projectErrorReporter(config, process.env);
138
138
  if (reporter) reportCrashes(reporter);
139
139
  const worker = await startWorker({
140
- project,
140
+ config,
141
141
  databaseUrl: process.env.DATABASE_URL || void 0
142
142
  });
143
143
  closeOnSignals(worker.stop);
@@ -1,49 +1,49 @@
1
1
  import { loadNearestEnvFile } from "../dev/env.js";
2
- import { createPgDb } from "../project/pg-db.js";
3
- import { importProjectFile } from "../project/import-project-file.js";
4
- import { existsSync } from "node:fs";
5
- import path from "node:path";
6
- import { assistantSettings, authStoreTables, configExports, jobDefinitions, mergeConfig } from "@protobase/server";
2
+ import { projectJobs, projectNotifications, projectResources, projectWebhooks } from "../config/project-parts.js";
3
+ import { projectAuth } from "../config/build-project.js";
4
+ import { loadSourceConfig } from "../config/source-config.js";
5
+ import { openAppDatabase } from "../project/pg-db.js";
6
+ import { assistantSettings, authStoreTables, configExports } from "@protobase/server";
7
7
  import pg from "pg";
8
8
  //#region src/migration/load-project.ts
9
- const configOf = async (file) => (await importProjectFile(file)).default ?? {};
10
9
  /**
11
- * The project in `dir` as `protobase dev` merges it, for what its database needs: protobase.config.ts, or
12
- * config/index.ts when that has no `config`, after the configs of `extensions` and the configs it extends. `close`
13
- * ends the pool it opened; a `db` the project exports stays the project's.
10
+ * The project in `dir` as `protobase dev` merges it, for what its database needs: protobase.config.ts, with the
11
+ * convention's resources when it names none, after the configs of `extensions` and the configs it extends. `close`
12
+ * ends the pool it opened.
14
13
  */
15
14
  const loadMigrationProject = async (dir, extensions = []) => {
16
15
  loadNearestEnvFile(dir);
17
- const file = path.join(dir, "protobase.config.ts");
18
- const custom = existsSync(file) ? await configOf(file) : {};
19
- const index = path.join(dir, "config", "index.ts");
20
- if (!custom.config && !existsSync(index)) throw new Error(`No config/index.ts or protobase.config.ts in ${dir}; run this inside a project`);
21
- const own = {
22
- ...custom,
23
- config: custom.config ?? await importProjectFile(index)
24
- };
25
- const extended = await Promise.all(extensions.flatMap((extension) => extension.config ? [configOf(extension.config)] : []));
26
- return migrationProject(mergeConfig(...extended, own), process.env.DATABASE_URL);
16
+ return migrationProject(await loadSourceConfig(dir, {
17
+ command: "tool",
18
+ extensions
19
+ }), process.env.DATABASE_URL);
27
20
  };
28
21
  /**
29
- * A merged project config, for what its database needs: its resources' models, its database (the one it exports, or a
30
- * pool on `url`) and the features that write migrations. `close` ends the pool it opened.
22
+ * A merged project config, for what its database needs: its resources' models, a pool on `url`, its auth, and the
23
+ * features that write migrations. `close` ends the pool.
31
24
  */
32
- const migrationProject = (project, url) => {
33
- if (!project.db && !url) throw new Error("No database: set DATABASE_URL or export `db` from protobase.config.ts");
34
- const ownDb = project.db ? void 0 : createPgDb(pg, url);
25
+ const migrationProject = async (config, url) => {
26
+ if (!url) throw new Error("No database: set DATABASE_URL");
27
+ const database = openAppDatabase(pg, url);
28
+ const [resources, jobs, webhooks, notifications, auth] = await Promise.all([
29
+ projectResources(config),
30
+ projectJobs(config),
31
+ projectWebhooks(config),
32
+ projectNotifications(config),
33
+ projectAuth(config, database)
34
+ ]);
35
35
  return {
36
- models: configExports(project.config ?? {}).resources.map((source) => source.toModel()),
37
- db: project.db ?? ownDb,
38
- ...project.auth && { auth: project.auth },
39
- ...project.events && { events: project.events },
40
- ...project.webhooks && { webhooks: project.webhooks },
41
- ...project.notifications && { notifications: project.notifications },
42
- jobs: jobDefinitions(project.jobs ?? {}),
43
- readOnlyQueries: assistantSettings(project.options?.assistant, process.env)?.kind === "built-in",
44
- authTables: project.auth ? authStoreTables(project.auth) : [],
36
+ models: configExports(resources).resources.map((source) => source.toModel()),
37
+ db: database.db,
38
+ ...auth && { auth },
39
+ ...config.events && { events: config.events },
40
+ ...webhooks && { webhooks },
41
+ ...notifications && { notifications },
42
+ jobs,
43
+ readOnlyQueries: assistantSettings(config.assistant, process.env)?.kind === "built-in",
44
+ authTables: auth ? authStoreTables(auth) : [],
45
45
  close: async () => {
46
- await ownDb?.destroy();
46
+ await database.db.destroy();
47
47
  }
48
48
  };
49
49
  };
@@ -38,12 +38,12 @@ const migrationParts = (project) => {
38
38
  }] : [],
39
39
  ...project.webhooks ? [{
40
40
  name: "webhooks",
41
- title: "The webhook subscriptions of webhooks()",
41
+ title: "The webhook subscriptions of webhooks",
42
42
  sql: () => webhooksMigration(project.db, project.webhooks, project.events)
43
43
  }] : [],
44
44
  ...project.notifications && !(project.notifications.store && project.notifications.historyStore) ? [{
45
45
  name: "notifications",
46
- title: "The tables of notifications()",
46
+ title: "The tables of notifications",
47
47
  sql: () => notificationsMigration(project.db, project.notifications, project.auth)
48
48
  }] : []
49
49
  ];
@@ -4,12 +4,12 @@ import path from "node:path";
4
4
  const signInGuide = "https://docs.protobase.net/guides/existing-database/";
5
5
  /**
6
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.
7
+ * the config enables. A config with sign-in off (`auth: false`) has none, so its database being current says nothing about it.
8
8
  */
9
9
  const migrationSummary = (files, cwd, hasAuth) => {
10
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
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`;
12
+ return `${written}sign-in is off, so nothing was written for it: see ${signInGuide}\n`;
13
13
  };
14
14
  //#endregion
15
15
  export { migrationSummary, signInGuide };
@@ -5,14 +5,14 @@ const httpHosts = {
5
5
  android: [...loopback, "10.0.2.2"]
6
6
  };
7
7
  /**
8
- * The server the app calls: `--api` when given, else the auth issuer (`baseURL`). It must be an http or https origin
8
+ * The server the app calls: `--api` when given, else the app's URL (`url`, `PROTOBASE_URL`), its tokens' issuer. It must be an http or https origin
9
9
  * with nothing after it; plain http only to this machine, or the Android emulator's host, since anyone on the network
10
10
  * between could read or change what it sends.
11
11
  */
12
12
  const apiUrl = (given, issuer, platform) => {
13
13
  const value = given ?? issuer;
14
- const what = given === void 0 ? `The auth issuer (baseURL) "${value}"` : `--api ${given}`;
15
- if (value === void 0) throw new Error("This project has no auth issuer (baseURL) for the app to call: pass --api https://…");
14
+ const what = given === void 0 ? `The app's URL (url or PROTOBASE_URL) "${value}"` : `--api ${given}`;
15
+ if (value === void 0) throw new Error("This project has no url (PROTOBASE_URL) for the app to call: set it, or pass --api https://…");
16
16
  if (!URL.canParse(value)) throw new Error(`${what} is not a URL such as https://shop.example.com`);
17
17
  const url = new URL(value);
18
18
  if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error(`${what} must be an http or https URL`);
@@ -37,7 +37,7 @@ const isLocalHost = (hostname) => hostname === "localhost" || hostname.endsWith(
37
37
  */
38
38
  const checkReleaseUrl = (url) => {
39
39
  const { cleartext, mixedContent } = httpAllowances(url);
40
- if (cleartext || mixedContent || url.protocol !== "https:" || isLocalHost(url.hostname)) throw new Error(`A release build calls its server over https, since anyone between could read or change plain http, and not ${url.origin} on this machine: pass --api https://… or give auth an https baseURL`);
40
+ if (cleartext || mixedContent || url.protocol !== "https:" || isLocalHost(url.hostname)) throw new Error(`A release build calls its server over https, since anyone between could read or change plain http, and not ${url.origin} on this machine: pass --api https://… or give the app an https url (PROTOBASE_URL)`);
41
41
  };
42
42
  //#endregion
43
43
  export { apiUrl, checkReleaseUrl, forwardedPort, httpAllowances };
@@ -1,24 +1,25 @@
1
1
  import { loadNearestEnvFile } from "../dev/env.js";
2
- import { importProjectFile } from "../project/import-project-file.js";
3
- import { noMobileSection } from "./mobile-config.js";
4
- import { existsSync } from "node:fs";
5
- import path from "node:path";
6
- import { mergeConfig } from "@protobase/server";
2
+ import { loadSourceConfig } from "../config/source-config.js";
3
+ import { appNameOver } from "@protobase/server";
7
4
  //#region src/mobile/load-project.ts
8
- const configOf = async (file) => (await importProjectFile(file)).default ?? {};
9
5
  /**
10
6
  * What a mobile build needs of the project in `dir`, merged as `protobase dev` merges it after the configs of
11
- * `extensions`: its mobile section, unchecked, and its auth. The project's .env is loaded first, as other commands do.
7
+ * `extensions`: its mobile section, unchecked, and with sign-in on the app's URL, its tokens' issuer, and its name.
8
+ * The project's .env is loaded first, as other commands do; nothing but the configs runs.
12
9
  */
13
10
  const loadMobileProject = async (dir, extensions) => {
14
11
  loadNearestEnvFile(dir);
15
- const file = path.join(dir, "protobase.config.ts");
16
- if (!existsSync(file)) throw new Error(noMobileSection);
17
- const extended = await Promise.all(extensions.flatMap((extension) => extension.config ? [configOf(extension.config)] : []));
18
- const { mobile, auth } = mergeConfig(...extended, await configOf(file));
12
+ const { mobile, auth, url, name } = await loadSourceConfig(dir, {
13
+ command: "tool",
14
+ extensions
15
+ });
16
+ const appName = appNameOver(process.env, name);
19
17
  return {
20
18
  mobile,
21
- auth
19
+ auth: auth && url ? {
20
+ issuer: url,
21
+ ...appName && { appName }
22
+ } : void 0
22
23
  };
23
24
  };
24
25
  //#endregion
@@ -6,7 +6,7 @@ const collect = (value, previous) => [...previous, value];
6
6
  const registerMobile = (program) => {
7
7
  const mobile = program.command("mobile").description("Build the project in the current directory as an iOS or Android app, from the mobile section of its protobase.config.ts");
8
8
  const api = "--api <url>";
9
- const apiHelp = "the server the app calls (default: the auth issuer, the project's baseURL)";
9
+ const apiHelp = "the server the app calls (default: the app's URL, url or PROTOBASE_URL)";
10
10
  const extend = "merge the protobase.config.ts and protobase.ui.tsx in this folder before the project's, repeatable";
11
11
  mobile.command("run").description("Generate the native project and run the app in a simulator, an emulator or on a device").argument("<platform>", "ios or android", parsePlatform).option(api, apiHelp).option("--target <id>", "the device or simulator to run on (default: Capacitor asks)").option("--team <id>", "iOS: your Apple Developer team id, which signs the app to run on your iPhone", parseTeamId).option("--live", "open the running protobase dev instead of the app's own files, reloading as you save", false).option("--port <port>", "the port of protobase dev, for --live", parsePort, 5173).option("--extend <dir>", extend, collect, []).action(async (chosen, opts) => {
12
12
  const [{ mobileRun }, { resolveExtensions }] = await Promise.all([import("./run.js"), import("../project/extensions.js")]);
@@ -10,8 +10,8 @@ import { capacitorConfig, writeCapacitorConfig } from "./capacitor-config.js";
10
10
  import { childEnv, envFileKeys, projectEnvFiles } from "./child-env.js";
11
11
  import { deviceAppName } from "./device-app-name.js";
12
12
  import { generatePlatform } from "./generate.js";
13
- import { checkMobileConfig } from "./mobile-config.js";
14
13
  import { loadMobileProject } from "./load-project.js";
14
+ import { checkMobileConfig } from "./mobile-config.js";
15
15
  import { signForDevelopment } from "./development-signing.js";
16
16
  import { checkIosPlugins, checkProtobasePlugin, guardLiveUpdate } from "./protobase-plugin.js";
17
17
  import { mobileSpec, prepareWorkspace, workspaceDir, workspacePackageJson } from "./workspace.js";
@@ -7,7 +7,7 @@ const projectApi = async () => {
7
7
  const finish = (code) => process.exit(code);
8
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`)");
9
9
  const registerOrganizations = (program) => {
10
- const organizations = program.command("organizations").description("Manage the organizations of the project in the current directory (with `organizations` in createAuth)");
10
+ const organizations = program.command("organizations").description("Manage the organizations of the project in the current directory (with `auth.organizations` in protobase.config.ts)");
11
11
  organizations.command("list").description("List organizations with their members and roles").action(async () => {
12
12
  const { listOrganizationsCommand } = await import("./commands.js");
13
13
  await listOrganizationsCommand(await projectApi(), out);
@@ -1,8 +1,8 @@
1
1
  import { errorReportingSettings, startErrorReporting } from "@protobase/server";
2
2
  //#region src/project/error-reporter.ts
3
- /** The project's error reporter, when its `options.errorReporting` or `PROTOBASE_SENTRY_DSN` sets a DSN. */
4
- const projectErrorReporter = async (project, env) => {
5
- const settings = errorReportingSettings(project.options?.errorReporting, env);
3
+ /** The project's error reporter, when its `errorReporting` or `PROTOBASE_SENTRY_DSN` sets a DSN. */
4
+ const projectErrorReporter = async (config, env) => {
5
+ const settings = errorReportingSettings(config.errorReporting, env);
6
6
  return settings ? startErrorReporting(settings) : void 0;
7
7
  };
8
8
  //#endregion
@@ -1,4 +1,5 @@
1
1
  import path from "node:path";
2
+ import { pathToFileURL } from "node:url";
2
3
  //#region src/project/import-project-file.ts
3
4
  const runnerImport = async (file, plugins = []) => {
4
5
  const { module } = await (await import("vite")).runnerImport(file, {
@@ -8,13 +9,14 @@ const runnerImport = async (file, plugins = []) => {
8
9
  });
9
10
  return module;
10
11
  };
11
- const importProjectFile = async (file) => process.versions.bun ? import(file) : runnerImport(file);
12
+ const inPackage = (file) => file.split(path.sep).includes("node_modules");
13
+ const importProjectFile = async (file) => process.versions.bun ? import(file) : inPackage(file) ? import(pathToFileURL(file).href) : runnerImport(file);
12
14
  /**
13
15
  * Imports several of the project's files in order, so that the modules they share are loaded once. Bun's module cache
14
16
  * does that itself; Vite's runner gets them as the imports of one module, which need not exist, beside the first file.
15
17
  */
16
18
  const importProjectFiles = async (files) => {
17
- if (process.versions.bun) {
19
+ if (process.versions.bun || files.length === 1) {
18
20
  const modules = [];
19
21
  for (const file of files) modules.push(await importProjectFile(file));
20
22
  return modules;
@@ -1,46 +1,37 @@
1
1
  import { loadNearestEnvFile } from "../dev/env.js";
2
+ import { projectFiles, projectResources } from "../config/project-parts.js";
3
+ import { loadSourceConfig } from "../config/source-config.js";
2
4
  import { createPgDb } from "./pg-db.js";
3
5
  import { readManifest } from "../bundle/manifest.js";
4
6
  import { loadBundle } from "../serve/load-bundle.js";
5
- import { importProjectFile } from "./import-project-file.js";
6
- import { existsSync, statSync } from "node:fs";
7
+ import { statSync } from "node:fs";
7
8
  import path from "node:path";
8
9
  import { configExports } from "@protobase/server";
9
10
  import pg from "pg";
10
11
  //#region src/project/load-bundle-project.ts
11
- const bundleProject = async (bundle) => {
12
- if (!statSync(bundle).isDirectory()) return loadBundle(bundle);
12
+ const bundleConfig = async (bundle) => {
13
+ if (!statSync(bundle).isDirectory()) return loadBundle(bundle, "tool");
13
14
  const manifest = await readManifest(bundle);
14
- return loadBundle(path.join(bundle, manifest.server));
15
- };
16
- const sourceProject = async (dir) => {
17
- const file = path.join(dir, "protobase.config.ts");
18
- const custom = existsSync(file) ? (await importProjectFile(file)).default ?? {} : {};
19
- if (custom.config) return custom;
20
- const index = path.join(dir, "config", "index.ts");
21
- if (!existsSync(index)) throw new Error(`No config/index.ts or protobase.config.ts in ${dir}; run this inside a project, or name a bundle`);
22
- return {
23
- ...custom,
24
- config: await importProjectFile(index)
25
- };
15
+ return loadBundle(path.join(bundle, manifest.server), "tool");
26
16
  };
27
17
  /**
28
18
  * What a command over a project's data needs: its resources, its files and events options and a database, from a bundle
29
- * or from the project in `dir`. `close` ends the pool it opened; a `db` the project exports stays the project's.
19
+ * or from the project in `dir`. `close` ends the pool it opened.
30
20
  */
31
21
  const loadBundleProject = async (bundle, dir) => {
32
22
  loadNearestEnvFile(dir);
33
- const project = bundle ? await bundleProject(bundle) : await sourceProject(dir);
23
+ const config = bundle ? await bundleConfig(bundle) : await loadSourceConfig(dir, { command: "tool" });
34
24
  const url = process.env.DATABASE_URL;
35
- if (!project.db && !url) throw new Error("No database: set DATABASE_URL or export `db` from protobase.config.ts");
36
- const ownDb = project.db ? void 0 : createPgDb(pg, url);
25
+ if (!url) throw new Error("No database: set DATABASE_URL");
26
+ const [resources, files] = await Promise.all([projectResources(config), projectFiles(config)]);
27
+ const db = createPgDb(pg, url);
37
28
  return {
38
- resources: configExports(project.config ?? {}).resources,
39
- db: project.db ?? ownDb,
40
- ...project.files && { files: project.files },
41
- ...project.events && { events: project.events },
29
+ resources: configExports(resources).resources,
30
+ db,
31
+ ...files && { files },
32
+ ...config.events && { events: config.events },
42
33
  close: async () => {
43
- await ownDb?.destroy();
34
+ await db.destroy();
44
35
  }
45
36
  };
46
37
  };
@@ -1,8 +1,8 @@
1
+ import { importProjectFiles } from "./import-project-file.js";
1
2
  import { conventionConfig } from "./convention.js";
2
3
  import { uiDirs } from "./convention-files.js";
3
- import { importProjectFiles } from "./import-project-file.js";
4
4
  import path from "node:path";
5
- import { configExports } from "@protobase/server";
5
+ import { configExports } from "@protobase/server/config-exports";
6
6
  //#region src/project/load-data-config.ts
7
7
  /**
8
8
  * The resources, views and pages of a config folder, as the config module has them by convention: config/index.ts and
@@ -1,10 +1,13 @@
1
1
  import { gateBackgroundWork } from "./background-gate.js";
2
2
  import { connectLong } from "./long-connect.js";
3
3
  import { connectOrBusy } from "./pool-wait.js";
4
- import { appPool, longQueryPool, readDbConnections, wantsLongQueries } from "@protobase/server";
4
+ import { readDbConnections, wantsLongQueries } from "@protobase/server";
5
+ import { appPool, longQueryPool } from "@protobase/server/internal";
5
6
  import { Kysely, PostgresDialect } from "kysely";
6
7
  //#region src/project/pg-db.ts
7
- const createPgDb = (pg, url, max = readDbConnections(process.env)) => {
8
+ const createPgDb = (pg, url, max = readDbConnections(process.env)) => openAppDatabase(pg, url, max).db;
9
+ /** Kysely over the app's pool, as `createPgDb` makes it, and the pool itself, which the app's Better Auth store shares. */
10
+ const openAppDatabase = (pg, url, max = readDbConnections(process.env)) => {
8
11
  const pool = appPool(pg, url, max);
9
12
  const long = longQueryPool(pg, url);
10
13
  const shortConnect = connectOrBusy(pool);
@@ -16,7 +19,10 @@ const createPgDb = (pg, url, max = readDbConnections(process.env)) => {
16
19
  await Promise.all([pool.end(), long.end()]);
17
20
  }
18
21
  };
19
- return new Kysely({ dialect: new PostgresDialect({ pool: gateBackgroundWork(routed, Math.max(1, max - 1)) }) });
22
+ return {
23
+ db: new Kysely({ dialect: new PostgresDialect({ pool: gateBackgroundWork(routed, Math.max(1, max - 1)) }) }),
24
+ pool
25
+ };
20
26
  };
21
27
  //#endregion
22
- export { createPgDb };
28
+ export { createPgDb, openAppDatabase };
@@ -1,9 +1,9 @@
1
1
  //#region src/project/placeholder-secret.ts
2
2
  const placeholder = /^change-?me/i;
3
3
  /**
4
- * A warning when BETTER_AUTH_SECRET is still the placeholder of .env.example: whoever knows it can sign session
4
+ * A warning when PROTOBASE_SECRET is still the placeholder of .env.example: whoever knows it can sign session
5
5
  * cookies for the app. Undefined otherwise.
6
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;
7
+ const placeholderSecretWarning = (env) => env.PROTOBASE_SECRET && placeholder.test(env.PROTOBASE_SECRET) ? "PROTOBASE_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
8
  //#endregion
9
9
  export { placeholderSecretWarning };