@protobase/cli 0.49.1 → 0.50.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 (89) hide show
  1. package/bin/protobase.mjs +3 -2
  2. package/dist/build/config-bundle.js +1 -1
  3. package/dist/build/deploy-bundle.js +3 -4
  4. package/dist/build/plugin-build.js +16 -8
  5. package/dist/build/plugin-fields.js +5 -2
  6. package/dist/build/ui-check.js +5 -0
  7. package/dist/build/view-check.js +1 -1
  8. package/dist/cli/package.js +1 -1
  9. package/dist/config/build-project.js +13 -6
  10. package/dist/config/project-files.js +4 -1
  11. package/dist/config/read-config.js +5 -1
  12. package/dist/config/source-config.js +1 -1
  13. package/dist/db/read-only-db.js +1 -1
  14. package/dist/dev/api-process.js +1 -1
  15. package/dist/dev/app-server.js +43 -35
  16. package/dist/dev/create-db.js +2 -2
  17. package/dist/dev/dev-jobs.js +5 -3
  18. package/dist/dev/entry.js +3 -3
  19. package/dist/dev/project.js +3 -2
  20. package/dist/dev/server-package.js +9 -21
  21. package/dist/doctor/run.js +1 -1
  22. package/dist/hand-over.d.ts +15 -0
  23. package/dist/hand-over.js +32 -0
  24. package/dist/main.js +22 -5
  25. package/dist/migration/load-project.js +1 -1
  26. package/dist/project/bundled-imports.js +41 -0
  27. package/dist/project/import-project-file.js +28 -8
  28. package/dist/project/load-bundle-project.js +1 -1
  29. package/dist/project/load-data-config.js +4 -3
  30. package/dist/project/project-types.js +66 -0
  31. package/dist/project-auth.d.ts +2 -0
  32. package/dist/project-auth.js +2 -0
  33. package/dist/run/preload.d.ts +1 -0
  34. package/dist/run/preload.js +20 -0
  35. package/dist/run/run-script.js +36 -0
  36. package/dist/serve/app.js +1 -1
  37. package/dist/serve/create-admin.js +1 -1
  38. package/dist/serve/host-modules.js +3 -3
  39. package/dist/serve/lifecycle.js +4 -3
  40. package/dist/supabase/load-phase.js +6 -5
  41. package/dist/users/load-auth.d.ts +10 -0
  42. package/dist/users/load-auth.js +1 -1
  43. package/dist/version/project-packages.js +39 -0
  44. package/dist/version/project-version.js +33 -12
  45. package/dist/worker/start-worker.js +3 -2
  46. package/package.json +10 -8
  47. package/skills/protobase/SKILL.md +1 -1
  48. package/skills/protobase/references/features/build-and-run.md +3 -0
  49. package/skills/protobase/references/features/events-webhooks-and-jobs.md +1 -0
  50. package/skills/protobase/references/features/files-and-images.md +1 -0
  51. package/skills/protobase/references/features/releases.md +2 -1
  52. package/skills/protobase/references/features/sign-in-and-accounts.md +1 -0
  53. package/skills/protobase/references/features/start-a-project.md +1 -1
  54. package/skills/protobase/references/getting-started.md +18 -5
  55. package/skills/protobase/references/guides/api-functions.md +1 -1
  56. package/skills/protobase/references/guides/billing-page.md +4 -4
  57. package/skills/protobase/references/guides/create-page.md +2 -2
  58. package/skills/protobase/references/guides/deploy.md +24 -8
  59. package/skills/protobase/references/guides/field-type.md +1 -1
  60. package/skills/protobase/references/guides/first-plugin.md +1 -1
  61. package/skills/protobase/references/guides/plugin-build.md +1 -1
  62. package/skills/protobase/references/guides/remote-resources.md +1 -1
  63. package/skills/protobase/references/guides/table-to-admin.md +8 -8
  64. package/skills/protobase/references/reference/ai.md +1 -1
  65. package/skills/protobase/references/reference/api.md +4 -4
  66. package/skills/protobase/references/reference/architecture.md +11 -6
  67. package/skills/protobase/references/reference/assistant.md +1 -1
  68. package/skills/protobase/references/reference/auth.md +24 -6
  69. package/skills/protobase/references/reference/blocks.md +1 -1
  70. package/skills/protobase/references/reference/bottom-bar.md +2 -2
  71. package/skills/protobase/references/reference/cli.md +51 -22
  72. package/skills/protobase/references/reference/client.md +3 -1
  73. package/skills/protobase/references/reference/config/api.md +2 -2
  74. package/skills/protobase/references/reference/config/app.md +2 -2
  75. package/skills/protobase/references/reference/config/sign-in.md +3 -4
  76. package/skills/protobase/references/reference/config.md +13 -10
  77. package/skills/protobase/references/reference/custom-components.md +3 -2
  78. package/skills/protobase/references/reference/email.md +5 -5
  79. package/skills/protobase/references/reference/events.md +1 -1
  80. package/skills/protobase/references/reference/files.md +6 -3
  81. package/skills/protobase/references/reference/jobs.md +20 -10
  82. package/skills/protobase/references/reference/layouts.md +2 -2
  83. package/skills/protobase/references/reference/mcp.md +9 -8
  84. package/skills/protobase/references/reference/notifications.md +10 -8
  85. package/skills/protobase/references/reference/plugins.md +3 -3
  86. package/skills/protobase/references/reference/ui-config.md +1 -1
  87. package/skills/protobase/references/reference/user-menu.md +3 -3
  88. package/skills/protobase/references/reference/versioning.md +21 -4
  89. package/skills/protobase/references/reference/webhooks.md +5 -5
package/dist/main.js CHANGED
@@ -28,7 +28,7 @@ const uiSection = (value) => {
28
28
  throw new InvalidArgumentError("expected names or list");
29
29
  };
30
30
  const collectSection = (value, previous) => [...previous, uiSection(value)];
31
- const program = new Command("protobase").description("Protobase command line").version(protobaseVersion, "-v, --version", "print the Protobase version");
31
+ const program = new Command("protobase").description("Protobase command line").version(protobaseVersion, "-v, --version", "print the Protobase version").enablePositionalOptions();
32
32
  program.hook("preAction", () => checkProjectVersion(process.cwd()));
33
33
  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) => {
34
34
  loadNearestEnvFile(process.cwd());
@@ -55,12 +55,18 @@ program.command("doctor").description("Check a config folder against the databas
55
55
  const { runDoctor } = await import("./doctor/run.js");
56
56
  const { errors } = await runDoctor({
57
57
  url,
58
- configDir: path.resolve(opts.config)
58
+ configDir: path.resolve(opts.config),
59
+ projectDir: process.cwd()
59
60
  }, out);
60
61
  if (errors > 0) process.exitCode = 1;
61
62
  });
62
63
  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) => {
63
- const [{ runDev }, { resolveExtensions }] = await Promise.all([import("./dev/run.js"), import("./project/extensions.js")]);
64
+ const [{ runDev }, { resolveExtensions }, { writeProjectTypes }] = await Promise.all([
65
+ import("./dev/run.js"),
66
+ import("./project/extensions.js"),
67
+ import("./project/project-types.js")
68
+ ]);
69
+ await writeProjectTypes(process.cwd());
64
70
  const server = await runDev({
65
71
  extensions: resolveExtensions(opts.extend),
66
72
  port: Number(opts.port),
@@ -74,12 +80,14 @@ program.command("dev").description("Serve the admin app and API for the project
74
80
  process.once("SIGTERM", () => void server.close().then(() => process.exit(0)));
75
81
  });
76
82
  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) => {
77
- const [{ buildDeployBundle }, { manifestFile }, { resolveExtensions }] = await Promise.all([
83
+ const [{ buildDeployBundle }, { manifestFile }, { resolveExtensions }, { writeProjectTypes }] = await Promise.all([
78
84
  import("./build/deploy-bundle.js"),
79
85
  import("./bundle/manifest.js"),
80
- import("./project/extensions.js")
86
+ import("./project/extensions.js"),
87
+ import("./project/project-types.js")
81
88
  ]);
82
89
  const extensions = resolveExtensions(opts.extend);
90
+ await writeProjectTypes(process.cwd());
83
91
  const onWarning = (message) => process.stderr.write(`warning: ${message}\n`);
84
92
  const manifest = await buildDeployBundle({
85
93
  projectDir: process.cwd(),
@@ -93,6 +101,15 @@ program.command("build").description("Build the deploy bundle of the project in
93
101
  const plugins = manifest.plugins.length > 0 ? ` with plugins ${manifest.plugins.map((plugin) => plugin.name).join(", ")}` : "";
94
102
  out(`built ${opts.out}: ${manifest.server}${packages}, ${manifest.public}/${plugins} and ${manifestFile} (api ${manifest.api.join(", ")})\n`);
95
103
  });
104
+ program.command("types").description("Write .protobase/tsconfig.json, which the project's tsconfig.json extends: the types of the @protobase packages the project builds with").action(async () => {
105
+ const { typesFile, writeProjectTypes } = await import("./project/project-types.js");
106
+ await writeProjectTypes(process.cwd());
107
+ out(`wrote ${typesFile}\n`);
108
+ });
109
+ program.command("run").description("Run a project script, such as a seed, under Bun; a bundled project's script gets the CLI's @protobase packages").argument("<file>", "the script").argument("[args...]", "the script's own arguments").passThroughOptions().allowUnknownOption().action(async (file, args) => {
110
+ const { runScript } = await import("./run/run-script.js");
111
+ process.exitCode = await runScript(process.cwd(), file, args);
112
+ });
96
113
  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) => {
97
114
  const pluginDir = path.resolve(dir);
98
115
  const outDir = path.resolve(opts.out ?? path.join(dir, "dist"));
@@ -3,8 +3,8 @@ import { projectJobs, projectNotifications, projectResources, projectWebhooks }
3
3
  import { projectAuth } from "../config/build-project.js";
4
4
  import { loadSourceConfig } from "../config/source-config.js";
5
5
  import { openAppDatabase } from "../project/pg-db.js";
6
- import { assistantSettings, authStoreTables, configExports } from "@protobase/server";
7
6
  import pg from "pg";
7
+ import { assistantSettings, authStoreTables, configExports } from "@protobase/server";
8
8
  //#region src/migration/load-project.ts
9
9
  /**
10
10
  * The project in `dir` as `protobase dev` merges it, for what its database needs: protobase.config.ts, with the
@@ -0,0 +1,41 @@
1
+ import { findPackageDirSync } from "../build/packages/package-dir.js";
2
+ import { adminAppDir, adminAppMain, uiPackageDir } from "./admin-app.js";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ //#region src/project/bundled-imports.ts
6
+ const cliDir = fileURLToPath(new URL("../..", import.meta.url));
7
+ const shared = /^(@protobase\/[^/]+|react|react-dom)(\/.*)?$/;
8
+ const appImporter = path.join(adminAppDir, adminAppMain);
9
+ const cliImporter = path.join(cliDir, "package.json");
10
+ /** The folders of the packages a bundled project's page code gets from the CLI, which the dev server must serve. */
11
+ const bundledPackageDirs = () => [uiPackageDir, ...[
12
+ "react",
13
+ "react-dom",
14
+ "@protobase/client",
15
+ "@protobase/layout",
16
+ "@protobase/schema"
17
+ ].map((name) => findPackageDirSync(name, uiPackageDir))].filter((dir) => dir !== void 0);
18
+ const inside = (file, dir) => file === dir || file.startsWith(`${dir}${path.sep}`);
19
+ /**
20
+ * In a bundled project, the page code's imports of the @protobase packages, React and React DOM resolve to the admin
21
+ * app's own copies, from the CLI, whatever the project installed: one copy of each, of the version the API runs, as the
22
+ * serve runtime's shell supplies them once deployed. `projectDirs` are the project's folder and its extensions'.
23
+ */
24
+ const bundledImports = (projectDirs) => ({
25
+ name: "protobase-bundled-imports",
26
+ enforce: "pre",
27
+ async resolveId(id, importer, options) {
28
+ if (!importer || !shared.test(id)) return void 0;
29
+ const from = importer.replace(/^\0/, "").replace(/\?.*$/, "");
30
+ if (!projectDirs.some((dir) => inside(from, dir))) return void 0;
31
+ return (id === "@protobase/ui" || id.startsWith("@protobase/ui/") ? void 0 : await this.resolve(id, appImporter, {
32
+ ...options,
33
+ skipSelf: true
34
+ })) ?? this.resolve(id, cliImporter, {
35
+ ...options,
36
+ skipSelf: true
37
+ });
38
+ }
39
+ });
40
+ //#endregion
41
+ export { bundledImports, bundledPackageDirs };
@@ -1,29 +1,49 @@
1
+ import { serverPackage } from "../dev/server-package.js";
1
2
  import path from "node:path";
2
3
  import { pathToFileURL } from "node:url";
3
4
  //#region src/project/import-project-file.ts
4
- const runnerImport = async (file, plugins = []) => {
5
- const { module } = await (await import("vite")).runnerImport(file, {
5
+ const runnerImport = async (file, projectDir, plugins = []) => {
6
+ const vite = await import("vite");
7
+ const resolution = serverPackage(projectDir);
8
+ const packages = resolution.from === "cli" ? {
9
+ root: resolution.root,
10
+ resolve: { dedupe: resolution.dedupe }
11
+ } : {};
12
+ const { module } = await vite.runnerImport(file, {
6
13
  configFile: false,
7
14
  logLevel: "error",
8
- plugins
15
+ plugins,
16
+ ...packages
9
17
  });
10
18
  return module;
11
19
  };
12
20
  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);
21
+ const bunLoads = (projectDir) => process.versions.bun !== void 0 && serverPackage(projectDir).from === "project";
22
+ /**
23
+ * Imports one of the files of the project in `projectDir`, TypeScript: Bun loads it itself, Node through Vite's module
24
+ * runner, or a package's file as it is. A bundled project's file always goes through the runner. `protobase dev` loads
25
+ * this module through Vite, which leaves these imports of a path as they are.
26
+ */
27
+ const importProjectFile = async (file, projectDir) => inPackage(file) ? import(
28
+ /* @vite-ignore */
29
+ pathToFileURL(file).href
30
+ ) : bunLoads(projectDir) ? import(
31
+ /* @vite-ignore */
32
+ file
33
+ ) : runnerImport(file, projectDir);
14
34
  /**
15
35
  * Imports several of the project's files in order, so that the modules they share are loaded once. Bun's module cache
16
36
  * does that itself; Vite's runner gets them as the imports of one module, which need not exist, beside the first file.
17
37
  */
18
- const importProjectFiles = async (files) => {
19
- if (process.versions.bun || files.length === 1) {
38
+ const importProjectFiles = async (files, projectDir) => {
39
+ if (bunLoads(projectDir) || files.length === 1) {
20
40
  const modules = [];
21
- for (const file of files) modules.push(await importProjectFile(file));
41
+ for (const file of files) modules.push(await importProjectFile(file, projectDir));
22
42
  return modules;
23
43
  }
24
44
  const id = path.join(path.dirname(files[0]), "protobase-project-files.js");
25
45
  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");
26
- return (await runnerImport(id, [{
46
+ return (await runnerImport(id, projectDir, [{
27
47
  name: "protobase-project-files",
28
48
  resolveId: (source) => source === id ? `\0${id}` : void 0,
29
49
  load: (source) => source === `\0${id}` ? code : void 0
@@ -6,8 +6,8 @@ import { readManifest } from "../bundle/manifest.js";
6
6
  import { loadBundle } from "../serve/load-bundle.js";
7
7
  import { statSync } from "node:fs";
8
8
  import path from "node:path";
9
- import { configExports } from "@protobase/server";
10
9
  import pg from "pg";
10
+ import { configExports } from "@protobase/server";
11
11
  //#region src/project/load-bundle-project.ts
12
12
  const bundleConfig = async (bundle) => {
13
13
  if (!statSync(bundle).isDirectory()) return loadBundle(bundle, "tool");
@@ -6,11 +6,12 @@ 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
9
- * every config/<dir>/ui.ts. Only those files and what they import run, not protobase.config.ts, which may need secrets.
9
+ * every config/<dir>/ui.ts, of the project in `projectDir`. Only those files and what they import run, not
10
+ * protobase.config.ts, which may need secrets.
10
11
  */
11
- const loadDataConfig = async (configDir) => {
12
+ const loadDataConfig = async (configDir, projectDir) => {
12
13
  const dirs = uiDirs(configDir);
13
- const [index, ...ui] = await importProjectFiles([path.join(configDir, "index.ts"), ...dirs.map((dir) => path.join(configDir, dir, "ui.ts"))]);
14
+ const [index, ...ui] = await importProjectFiles([path.join(configDir, "index.ts"), ...dirs.map((dir) => path.join(configDir, dir, "ui.ts"))], projectDir);
14
15
  const config = conventionConfig(index, dirs.map((dir, i) => [dir, ui[i]]));
15
16
  const { resources, views, pages } = configExports(config);
16
17
  return {
@@ -0,0 +1,66 @@
1
+ import { findPackageDirSync, packageName } from "../build/packages/package-dir.js";
2
+ import { projectPackages } from "../version/project-packages.js";
3
+ import { hostModuleIds } from "../serve/host-module-ids.js";
4
+ import { uiPackageDir } from "./admin-app.js";
5
+ import { protobaseFolder } from "./protobase-folder.js";
6
+ import { existsSync, readFileSync } from "node:fs";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { mkdir, writeFile } from "node:fs/promises";
10
+ //#region src/project/project-types.ts
11
+ /** The tsconfig a project's own extends, relative to the project. */
12
+ const typesFile = path.join(protobaseFolder, "tsconfig.json");
13
+ const cliDir = fileURLToPath(new URL("../..", import.meta.url));
14
+ const typedPackages = [.../* @__PURE__ */ new Set([
15
+ "@protobase/cli",
16
+ "@protobase/client",
17
+ "@protobase/ui",
18
+ ...hostModuleIds.map((id) => packageName(id))
19
+ ])];
20
+ const declarationOf = (dir, target) => {
21
+ if (target === null) return void 0;
22
+ if (typeof target !== "string") {
23
+ const chosen = target.types ?? target.import ?? target.default ?? target.require;
24
+ return chosen === void 0 ? void 0 : declarationOf(dir, chosen);
25
+ }
26
+ const file = path.join(dir, target);
27
+ if (/\.(d\.[mc]?ts|tsx?)$/.test(file)) return existsSync(file) ? file : void 0;
28
+ if (!/\.[mc]?js$/.test(file)) return void 0;
29
+ return [
30
+ ".d.ts",
31
+ ".d.mts",
32
+ ".d.cts"
33
+ ].map((extension) => file.replace(/\.[mc]?js$/, extension)).find((candidate) => existsSync(candidate));
34
+ };
35
+ const packagePaths = (name, dir) => {
36
+ const manifest = JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8"));
37
+ const exported = manifest.exports;
38
+ return (exported === void 0 || exported === null ? [[".", manifest.types ?? manifest.typings ?? manifest.main ?? "index.js"]] : typeof exported === "string" || !Object.keys(exported).every((key) => key.startsWith(".")) ? [[".", exported]] : Object.entries(exported).filter(([key]) => !key.includes("*"))).flatMap(([sub, target]) => {
39
+ const file = declarationOf(dir, target);
40
+ return file ? [[`${name}${sub.slice(1)}`, file]] : [];
41
+ });
42
+ };
43
+ /**
44
+ * The `paths` that point TypeScript at the CLI's own copies of the packages a bundled project gets from it, each import
45
+ * by name, never `*`, so a package the project lacks still fails as missing.
46
+ */
47
+ const cliTypePaths = (ownDir = cliDir) => Object.fromEntries(typedPackages.flatMap((name) => {
48
+ const dir = findPackageDirSync(name, ownDir) ?? findPackageDirSync(name, uiPackageDir);
49
+ return dir ? packagePaths(name, dir).map(([id, file]) => [id, [file]]) : [];
50
+ }));
51
+ /**
52
+ * Writes `.protobase/tsconfig.json` in `projectDir`, which the project's tsconfig.json extends: in a bundled project
53
+ * its `paths` give the @protobase packages and those the serve runtime supplies the types of the CLI that builds the
54
+ * app, with nothing installed; a locked project's installed packages type themselves, so it holds no paths. The
55
+ * folder ignores itself in git, since the paths are this machine's.
56
+ */
57
+ const writeProjectTypes = async (projectDir) => {
58
+ const folder = path.join(projectDir, protobaseFolder);
59
+ await mkdir(folder, { recursive: true });
60
+ const ignore = path.join(folder, ".gitignore");
61
+ if (!existsSync(ignore)) await writeFile(ignore, "*\n");
62
+ const compilerOptions = projectPackages(projectDir).mode === "bundled" ? { paths: cliTypePaths() } : {};
63
+ await writeFile(path.join(projectDir, typesFile), `${JSON.stringify({ compilerOptions }, null, 2)}\n`);
64
+ };
65
+ //#endregion
66
+ export { cliTypePaths, typesFile, writeProjectTypes };
@@ -0,0 +1,2 @@
1
+ import { loadProjectAuth } from "./users/load-auth.js";
2
+ export { loadProjectAuth };
@@ -0,0 +1,2 @@
1
+ import { loadProjectAuth } from "./users/load-auth.js";
2
+ export { loadProjectAuth };
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,20 @@
1
+ import { hostModuleIds } from "../serve/host-module-ids.js";
2
+ import { provideHostModules } from "../serve/host-modules.js";
3
+ import { cliTypePaths } from "../project/project-types.js";
4
+ import { fileURLToPath } from "node:url";
5
+ //#region src/run/preload.ts
6
+ const bun = globalThis.Bun;
7
+ const cliDir = fileURLToPath(new URL("../..", import.meta.url));
8
+ provideHostModules();
9
+ const others = Object.keys(cliTypePaths()).filter((id) => id.startsWith("@protobase/") && !hostModuleIds.includes(id));
10
+ bun.plugin({
11
+ name: "protobase-cli-modules",
12
+ setup: (build) => {
13
+ for (const id of others) build.module(id, async () => ({
14
+ exports: await import(bun.resolveSync(id, cliDir)),
15
+ loader: "object"
16
+ }));
17
+ }
18
+ });
19
+ //#endregion
20
+ export {};
@@ -0,0 +1,36 @@
1
+ import { projectPackages } from "../version/project-packages.js";
2
+ import { moduleFile } from "../module-file.js";
3
+ import { spawn } from "node:child_process";
4
+ //#region src/run/run-script.ts
5
+ const preload = moduleFile("./preload", import.meta.url);
6
+ /**
7
+ * The Bun command line that runs `file` with `args` for the project in `projectDir`: never installing a missing package,
8
+ * and in a bundled project with the CLI's own copies of the @protobase packages and those the serve runtime supplies
9
+ * (see preload.ts). A locked project's script imports its installed packages.
10
+ */
11
+ const scriptCommand = (projectDir, file, args) => [
12
+ "--no-install",
13
+ ...projectPackages(projectDir).mode === "bundled" ? ["--preload", preload] : [],
14
+ file,
15
+ ...args
16
+ ];
17
+ /**
18
+ * Runs a project script, such as a seed or a migration, under Bun in a process of its own, in `projectDir`, and
19
+ * resolves with its exit code. Its output goes to this process's, so a host that captures that captures it too.
20
+ */
21
+ const runScript = (projectDir, file, args) => new Promise((resolve, reject) => {
22
+ const child = spawn("bun", scriptCommand(projectDir, file, args), {
23
+ cwd: projectDir,
24
+ stdio: [
25
+ "inherit",
26
+ "pipe",
27
+ "pipe"
28
+ ]
29
+ });
30
+ child.stdout.on("data", (chunk) => process.stdout.write(chunk));
31
+ child.stderr.on("data", (chunk) => process.stderr.write(chunk));
32
+ child.once("error", (error) => reject(error.code === "ENOENT" ? /* @__PURE__ */ new Error("protobase run needs Bun: install it from https://bun.sh") : error));
33
+ child.once("close", (code, signal) => resolve(code ?? (signal ? 1 : 0)));
34
+ });
35
+ //#endregion
36
+ export { runScript, scriptCommand };
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 { Hono } from "hono";
4
3
  import { jobsDrainApp, mobileReleaseApp, webauthnPath } from "@protobase/server";
4
+ import { Hono } from "hono";
5
5
  import { logger } from "hono/logger";
6
6
  //#region src/serve/app.ts
7
7
  const createServeApp = ({ admin, requestLog, site, jobs, drainToken, mobile }) => {
@@ -6,8 +6,8 @@ import { usersApi } from "../users/users-api.js";
6
6
  import { checkBundleManifest } from "./bundle-manifest.js";
7
7
  import { loadBundle } from "./load-bundle.js";
8
8
  import { bundleConfigFile } from "../worker/start-worker.js";
9
- import { checkAuthSchema } from "@protobase/server";
10
9
  import pg from "pg";
10
+ import { checkAuthSchema } from "@protobase/server";
11
11
  //#region src/serve/create-admin.ts
12
12
  const createAdminInBundle = async (bundle, email, options, out) => {
13
13
  const file = await bundleConfigFile(bundle);
@@ -1,9 +1,9 @@
1
- import * as nodeServer from "@hono/node-server";
2
- import * as hono from "hono";
1
+ import * as pg$1 from "pg";
3
2
  import * as server from "@protobase/server";
4
3
  import * as layout from "@protobase/layout";
5
4
  import * as kysely from "kysely";
6
- import * as pg$1 from "pg";
5
+ import * as nodeServer from "@hono/node-server";
6
+ import * as hono from "hono";
7
7
  import * as reactEmailRender from "@react-email/render";
8
8
  import * as apiReference from "@scalar/hono-api-reference";
9
9
  import * as aipParsers from "aip-parsers";
@@ -1,16 +1,16 @@
1
1
  import { protobaseVersion } from "../version/version.js";
2
- import { projectAdmin } from "../project/project-admin.js";
3
2
  import { buildProject } from "../config/build-project.js";
4
3
  import { openAppDatabase } from "../project/pg-db.js";
4
+ import { projectAdmin } from "../project/project-admin.js";
5
5
  import { apiWebSocketServer } from "../project/api-websocket-server.js";
6
6
  import { withClientAddress } from "./client-address.js";
7
7
  import { createServeApp } from "./app.js";
8
8
  import { startCleanupTimer } from "./cleanup-timer.js";
9
9
  import { closeSockets } from "./close-sockets.js";
10
10
  import { servedRelease } from "./mobile-release.js";
11
- import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
12
- import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkResourcesOutsideAuthStore, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
13
11
  import pg from "pg";
12
+ import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkResourcesOutsideAuthStore, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
13
+ import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
14
14
  //#region src/serve/lifecycle.ts
15
15
  const listen = (server, port) => new Promise((resolve, reject) => {
16
16
  server.once("error", reject);
@@ -47,6 +47,7 @@ const startServe = async ({ config, env, openDb = (url) => openAppDatabase(pg, u
47
47
  db,
48
48
  jobs: definitions,
49
49
  work: env.runJobs,
50
+ ...project.mailer && { mailer: project.mailer },
50
51
  onError: (error) => console.error(error)
51
52
  }) : void 0;
52
53
  const release = project.mobile ? await servedRelease({
@@ -1,3 +1,4 @@
1
+ import { loadProjectAuth } from "../users/load-auth.js";
1
2
  import { writeAuthMigration } from "../auth/write-migration.js";
2
3
  import { connect } from "../db/connect.js";
3
4
  import { runDoctor } from "../doctor/run.js";
@@ -10,7 +11,6 @@ import { loadScript, qualified } from "./load-script.js";
10
11
  import { existingTables, filledTables, otherTables } from "./target-checks.js";
11
12
  import { providerCounts } from "./identity-providers.js";
12
13
  import { accountsMigration } from "./users-migrations.js";
13
- import { loadProjectAuth } from "../users/load-auth.js";
14
14
  import { cronJobFilesInTheWay, writeCronJobs } from "./cron-jobs-write.js";
15
15
  import { importReport } from "./report.js";
16
16
  import { existsSync } from "node:fs";
@@ -37,13 +37,14 @@ const checkReady = async (url, projectDir, manifest) => {
37
37
  await sql.end();
38
38
  }
39
39
  };
40
- /** `protobase doctor`'s output on the config at `configDir`, or `undefined` when there is none. */
41
- const doctorOutput = async (url, configDir) => {
40
+ /** `protobase doctor`'s output on the config at `configDir` of the project in `projectDir`, or `undefined` when there is none. */
41
+ const doctorOutput = async (url, configDir, projectDir) => {
42
42
  if (!existsSync(path.join(configDir, "index.ts"))) return void 0;
43
43
  let text = "";
44
44
  await runDoctor({
45
45
  url,
46
- configDir
46
+ configDir,
47
+ projectDir
47
48
  }, (line) => text += line);
48
49
  return text;
49
50
  };
@@ -106,7 +107,7 @@ const runLoadPhase = async (options, out) => {
106
107
  out(`wrote ${path.relative(options.projectDir, path.join(options.migrationsDir, accountsFile))}, the users' accounts with their Supabase passwords and social providers\n`);
107
108
  const target = connect(options.targetUrl);
108
109
  const providers = await providerCounts(target).finally(() => target.end());
109
- await writeFile(state.report, importReport(manifest, await doctorOutput(options.targetUrl, options.configDir), jobsWired, live, providers), { mode: 384 });
110
+ await writeFile(state.report, importReport(manifest, await doctorOutput(options.targetUrl, options.configDir, options.projectDir), jobsWired, live, providers), { mode: 384 });
110
111
  out(`wrote ${path.relative(options.projectDir, state.report)}: what the import could not carry over\n`);
111
112
  out("next: apply the migrations with the project's migrations; Supabase's users then sign in with their own passwords\n");
112
113
  };
@@ -0,0 +1,10 @@
1
+ import { AdminAuth } from "@protobase/server";
2
+ //#region src/users/load-auth.d.ts
3
+ /**
4
+ * The sign-in of the project in `projectDir`, built from its config's `auth` over DATABASE_URL, with only the plugins
5
+ * it turns on. With a device or history store of the app's own (notifications/store.ts, notifications/history-store.ts),
6
+ * deleting a user removes their devices or history from it too; the built-in tables go with the user by their foreign
7
+ * keys.
8
+ */
9
+ export declare const loadProjectAuth: (projectDir: string) => Promise<AdminAuth>;
10
+ //#endregion
@@ -3,8 +3,8 @@ import { projectNotifications } from "../config/project-parts.js";
3
3
  import { projectAuth } from "../config/build-project.js";
4
4
  import { loadSourceConfig } from "../config/source-config.js";
5
5
  import { openAppDatabase } from "../project/pg-db.js";
6
- import { removeDevicesWithUsers, removeHistoryWithUsers } from "@protobase/server";
7
6
  import pg from "pg";
7
+ import { removeDevicesWithUsers, removeHistoryWithUsers } from "@protobase/server";
8
8
  //#region src/users/load-auth.ts
9
9
  /**
10
10
  * The sign-in of the project in `projectDir`, built from its config's `auth` over DATABASE_URL, with only the plugins
@@ -0,0 +1,39 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ //#region src/version/project-packages.ts
4
+ const fields = [
5
+ "dependencies",
6
+ "devDependencies",
7
+ "optionalDependencies",
8
+ "peerDependencies"
9
+ ];
10
+ /** The @protobase packages the package.json in `projectDir` lists, each with its field and specifier; none without one. */
11
+ const listedPackages = (projectDir) => {
12
+ const file = path.join(projectDir, "package.json");
13
+ if (!existsSync(file)) return [];
14
+ const manifest = JSON.parse(readFileSync(file, "utf8"));
15
+ return fields.flatMap((field) => Object.entries(manifest[field] ?? {}).flatMap(([name, specifier]) => name.startsWith("@protobase/") ? [{
16
+ field,
17
+ name,
18
+ specifier
19
+ }] : []));
20
+ };
21
+ /** Locked when any @protobase package is listed in dependencies, otherwise bundled. */
22
+ const modeOf = (listed) => listed.some((entry) => entry.field === "dependencies") ? "locked" : "bundled";
23
+ /**
24
+ * The project's mode and Protobase version specifier, from the package.json in `projectDir`. Every @protobase package
25
+ * it lists must carry the same specifier: they are released together and pass values to each other.
26
+ */
27
+ const projectPackages = (projectDir) => {
28
+ const listed = listedPackages(projectDir);
29
+ const [first] = listed;
30
+ if (!first) return { mode: "bundled" };
31
+ const other = listed.find((entry) => entry.specifier !== first.specifier);
32
+ if (other) throw new Error(`${path.join(projectDir, "package.json")} lists ${first.name} at ${first.specifier} and ${other.name} at ${other.specifier}; list every @protobase package at the same version`);
33
+ return {
34
+ mode: modeOf(listed),
35
+ specifier: first.specifier
36
+ };
37
+ };
38
+ //#endregion
39
+ export { listedPackages, modeOf, projectPackages };
@@ -1,35 +1,56 @@
1
1
  import { protobaseVersion } from "./version.js";
2
2
  import { findPackageDirSync } from "../build/packages/package-dir.js";
3
+ import { projectPackages } from "./project-packages.js";
3
4
  import { readFileSync } from "node:fs";
4
5
  import path from "node:path";
5
6
  import semver from "semver";
6
7
  //#region src/version/project-version.ts
7
- const projectPackages = [
8
+ const installedPackages = [
8
9
  "@protobase/cli",
9
10
  "@protobase/server",
10
11
  "@protobase/ui"
11
12
  ];
12
13
  /**
13
- * The Protobase version the project in `projectDir` is pinned to: the version its lockfile installed, read from the
14
+ * The Protobase version installed for the project in `projectDir`: the version its lockfile installed, read from the
14
15
  * @protobase package Node's resolution finds from there. Undefined outside a project, or before its install.
15
16
  */
16
17
  const projectProtobaseVersion = (projectDir) => {
17
- for (const name of projectPackages) {
18
+ for (const name of installedPackages) {
18
19
  const dir = findPackageDirSync(name, projectDir);
19
20
  if (dir) return JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8")).version;
20
21
  }
21
22
  };
22
23
  /**
23
- * Refuses a project whose Protobase version this CLI is not compatible with, the one version check the CLI makes: the
24
- * CLI's version must be in the caret range of the project's, so from 1.0 on the same major and below 1.0, where a minor
25
- * may break, the same minor, and never older. Outside a project, or before its install, there is nothing to check.
24
+ * The Protobase version a bundle of the project in `projectDir` runs on, its manifest's `protobase`: the version of the
25
+ * copies the build uses, the CLI's own in a bundled project and the installed ones in a locked project, which fails
26
+ * before its install.
26
27
  */
27
- const checkProjectVersion = (projectDir, cliVersion = protobaseVersion) => {
28
- const project = projectProtobaseVersion(projectDir);
29
- if (project === void 0) return;
30
- const range = `^${project}`;
28
+ const bundleProtobaseVersion = (projectDir, cliVersion = protobaseVersion) => {
29
+ if (projectPackages(projectDir).mode === "bundled") return cliVersion;
30
+ const installed = projectProtobaseVersion(projectDir);
31
+ if (installed === void 0) throw new Error(`${projectDir} lists its @protobase packages in dependencies and has none installed; install the project's dependencies first`);
32
+ return installed;
33
+ };
34
+ const checkInstalled = (projectDir, cliVersion) => {
35
+ const installed = projectProtobaseVersion(projectDir);
36
+ if (installed === void 0) return;
37
+ const range = `^${installed}`;
31
38
  if (semver.satisfies(cliVersion, range)) return;
32
- throw new Error(`This project is on Protobase ${project}, and this CLI is Protobase ${cliVersion}: run it with a Protobase ${range} CLI`);
39
+ throw new Error(`This project has Protobase ${installed} installed, and this CLI is Protobase ${cliVersion}: run it with a Protobase ${range} CLI`);
40
+ };
41
+ /**
42
+ * Refuses a project whose Protobase version this CLI does not satisfy, the one version check the CLI makes: the
43
+ * specifier its package.json lists the @protobase packages at must hold the CLI's version, by semver, and in a locked
44
+ * project, whose installed copies run, those must be ones the CLI runs. A specifier that is no semver range, such as
45
+ * `workspace:*`, says no version, so the installed copies are checked instead. Outside a project, or one that lists no
46
+ * @protobase package, there is nothing to check.
47
+ */
48
+ const checkProjectVersion = (projectDir, cliVersion = protobaseVersion) => {
49
+ const { mode, specifier } = projectPackages(projectDir);
50
+ if (specifier === void 0) return;
51
+ const range = semver.validRange(specifier) !== null;
52
+ if (range && !semver.satisfies(cliVersion, specifier)) throw new Error(`This project asks for Protobase ${specifier}, and this CLI is Protobase ${cliVersion}: run it with a CLI whose version ${specifier} holds`);
53
+ if (mode === "locked" || !range) checkInstalled(projectDir, cliVersion);
33
54
  };
34
55
  //#endregion
35
- export { checkProjectVersion, projectProtobaseVersion };
56
+ export { bundleProtobaseVersion, checkProjectVersion, projectProtobaseVersion };
@@ -1,13 +1,13 @@
1
- import { projectAdmin } from "../project/project-admin.js";
2
1
  import { buildProject } from "../config/build-project.js";
3
2
  import { openAppDatabase } from "../project/pg-db.js";
3
+ import { projectAdmin } from "../project/project-admin.js";
4
4
  import { readManifest } from "../bundle/manifest.js";
5
5
  import { checkBundleManifest } from "../serve/bundle-manifest.js";
6
6
  import { loadBundle } from "../serve/load-bundle.js";
7
7
  import { statSync } from "node:fs";
8
8
  import path from "node:path";
9
- import { checkJobsSchema, configExports, isCaptured, startJobs } from "@protobase/server";
10
9
  import pg from "pg";
10
+ import { checkJobsSchema, configExports, isCaptured, startJobs } from "@protobase/server";
11
11
  //#region src/worker/start-worker.ts
12
12
  const bundleConfigFile = async (bundle) => {
13
13
  if (!statSync(bundle).isDirectory()) return bundle;
@@ -36,6 +36,7 @@ const startWorker = async ({ config, databaseUrl, openDb = (url) => openAppDatab
36
36
  runtime: await startJobs({
37
37
  db,
38
38
  jobs: definitions,
39
+ ...project.mailer && { mailer: project.mailer },
39
40
  onError: (error) => console.error(error)
40
41
  })
41
42
  };