@protobase/cli 0.49.2 → 0.50.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) 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/project-files.js +4 -1
  10. package/dist/config/source-config.js +1 -1
  11. package/dist/dev/api-process.js +1 -1
  12. package/dist/dev/app-server.js +43 -35
  13. package/dist/dev/create-db.js +2 -2
  14. package/dist/dev/project.js +3 -2
  15. package/dist/dev/server-package.js +9 -21
  16. package/dist/doctor/run.js +1 -1
  17. package/dist/hand-over.d.ts +15 -0
  18. package/dist/hand-over.js +32 -0
  19. package/dist/main.js +22 -5
  20. package/dist/project/bundled-imports.js +41 -0
  21. package/dist/project/import-project-file.js +28 -8
  22. package/dist/project/load-data-config.js +4 -3
  23. package/dist/project/project-types.js +66 -0
  24. package/dist/run/preload.d.ts +1 -0
  25. package/dist/run/preload.js +20 -0
  26. package/dist/run/run-script.js +36 -0
  27. package/dist/supabase/dump-phase.js +9 -4
  28. package/dist/supabase/load-phase.js +5 -4
  29. package/dist/supabase/realtime-policies.js +60 -0
  30. package/dist/version/project-packages.js +39 -0
  31. package/dist/version/project-version.js +33 -12
  32. package/package.json +9 -8
  33. package/skills/protobase/SKILL.md +1 -1
  34. package/skills/protobase/references/features/build-and-run.md +3 -0
  35. package/skills/protobase/references/features/compatibility.md +1 -1
  36. package/skills/protobase/references/features/releases.md +2 -1
  37. package/skills/protobase/references/getting-started.md +18 -5
  38. package/skills/protobase/references/guides/api-functions.md +1 -1
  39. package/skills/protobase/references/guides/billing-page.md +4 -4
  40. package/skills/protobase/references/guides/create-page.md +2 -2
  41. package/skills/protobase/references/guides/deploy.md +24 -8
  42. package/skills/protobase/references/guides/field-type.md +1 -1
  43. package/skills/protobase/references/guides/first-plugin.md +1 -1
  44. package/skills/protobase/references/guides/plugin-build.md +1 -1
  45. package/skills/protobase/references/guides/remote-resources.md +1 -1
  46. package/skills/protobase/references/guides/table-to-admin.md +8 -8
  47. package/skills/protobase/references/reference/ai.md +1 -1
  48. package/skills/protobase/references/reference/api.md +4 -4
  49. package/skills/protobase/references/reference/architecture.md +11 -6
  50. package/skills/protobase/references/reference/assistant.md +1 -1
  51. package/skills/protobase/references/reference/auth.md +17 -4
  52. package/skills/protobase/references/reference/blocks.md +1 -1
  53. package/skills/protobase/references/reference/bottom-bar.md +2 -2
  54. package/skills/protobase/references/reference/cli.md +51 -22
  55. package/skills/protobase/references/reference/client.md +3 -1
  56. package/skills/protobase/references/reference/config/api.md +2 -2
  57. package/skills/protobase/references/reference/config/app.md +2 -2
  58. package/skills/protobase/references/reference/config/sign-in.md +2 -3
  59. package/skills/protobase/references/reference/config.md +11 -9
  60. package/skills/protobase/references/reference/custom-components.md +3 -2
  61. package/skills/protobase/references/reference/email.md +4 -4
  62. package/skills/protobase/references/reference/events.md +1 -1
  63. package/skills/protobase/references/reference/jobs.md +6 -5
  64. package/skills/protobase/references/reference/layouts.md +2 -2
  65. package/skills/protobase/references/reference/mcp.md +9 -8
  66. package/skills/protobase/references/reference/notifications.md +10 -8
  67. package/skills/protobase/references/reference/plugins.md +3 -3
  68. package/skills/protobase/references/reference/supabase-realtime.md +36 -2
  69. package/skills/protobase/references/reference/ui-config.md +1 -1
  70. package/skills/protobase/references/reference/user-menu.md +3 -3
  71. package/skills/protobase/references/reference/versioning.md +21 -4
  72. package/skills/protobase/references/reference/webhooks.md +5 -5
package/bin/protobase.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { run } from '../dist/index.js'
2
+ import { fileURLToPath } from 'node:url'
3
+ import { runHandingOver } from '../dist/hand-over.js'
3
4
 
4
- await run(process.argv)
5
+ await runHandingOver(fileURLToPath(new URL('..', import.meta.url)), async () => (await import('../dist/index.js')).run, process.argv)
@@ -1,9 +1,9 @@
1
1
  import { findPackageDir, packageName } from "./packages/package-dir.js";
2
+ import { hostModuleIds } from "../serve/host-module-ids.js";
2
3
  import { loadSourceConfig } from "../config/source-config.js";
3
4
  import { layoutCheck } from "./layout-check.js";
4
5
  import { extensionImports } from "../project/extensions.js";
5
6
  import { viteBundle } from "./vite-bundle.js";
6
- import { hostModuleIds } from "../serve/host-module-ids.js";
7
7
  import { collectComponents } from "./component-names.js";
8
8
  import { bundleEntryCode } from "./entry-code.js";
9
9
  import { hostPackages } from "./packages/host-packages.js";
@@ -1,6 +1,7 @@
1
- import { projectProtobaseVersion } from "../version/project-version.js";
1
+ import { bundleProtobaseVersion } from "../version/project-version.js";
2
2
  import { buildIcons } from "./app-icons.js";
3
3
  import { bundleLayout, bundleMigrations, bundleNodeModules, manifestFile } from "../bundle/manifest.js";
4
+ import { protobaseFolder } from "../project/protobase-folder.js";
4
5
  import { buildBundlePlugins } from "./bundle-plugins.js";
5
6
  import { copyMigrations } from "./bundle-migrations.js";
6
7
  import { buildConfigBundle } from "./config-bundle.js";
@@ -9,7 +10,6 @@ import { buildTheme } from "./theme.js";
9
10
  import { shellForBuild, shellManifestFile } from "./shell.js";
10
11
  import { checkUi } from "./ui-check.js";
11
12
  import { checkViews } from "./view-check.js";
12
- import { protobaseFolder } from "../project/protobase-folder.js";
13
13
  import { pinnedNative } from "../mobile/pinned-packages.js";
14
14
  import { existsSync } from "node:fs";
15
15
  import path from "node:path";
@@ -46,8 +46,7 @@ const copyShell = async (publicDir, sourceMaps) => {
46
46
  return shell;
47
47
  };
48
48
  const buildDeployBundle = async ({ projectDir, outDir, bun, extensions = [], sourceMaps = false, onWarning }) => {
49
- const protobase = projectProtobaseVersion(projectDir);
50
- if (protobase === void 0) throw new Error(`${projectDir} has no @protobase packages installed; install the project's dependencies first`);
49
+ const protobase = bundleProtobaseVersion(projectDir);
51
50
  await removeOwnFolder(outDir, bundleNodeModules, "nodeModules");
52
51
  await removeOwnFolder(outDir, bundleMigrations, "migrations");
53
52
  const components = /* @__PURE__ */ new Set();
@@ -1,6 +1,8 @@
1
1
  import { findPackageDirSync, readPackageJson } from "./packages/package-dir.js";
2
+ import { projectPackages } from "../version/project-packages.js";
2
3
  import { uiPackageDir } from "../project/admin-app.js";
3
4
  import { extensionImports } from "../project/extensions.js";
5
+ import { bundledImports } from "../project/bundled-imports.js";
4
6
  import { sharedModules } from "../project/shared-modules.js";
5
7
  import { pluginFieldTypes } from "./plugin-fields.js";
6
8
  import { layerPluginUtilities } from "./plugin-styles.js";
@@ -18,14 +20,17 @@ const pluginEntryFile = "protobase.ui.tsx";
18
20
  /** What `build-plugin` writes beside the plugin's files, which the app reads first. */
19
21
  const pluginManifestFile = "plugin.json";
20
22
  const tailwindDir = path.dirname(createRequire(path.join(uiPackageDir, "package.json")).resolve("tailwindcss/package.json"));
23
+ const targetUiDir = (pluginDir, projectDir, bundled) => {
24
+ if (bundled) return uiPackageDir;
25
+ return findPackageDirSync("@protobase/ui", pluginDir) ?? (projectDir === void 0 ? void 0 : findPackageDirSync("@protobase/ui", projectDir)) ?? uiPackageDir;
26
+ };
21
27
  /**
22
- * What the plugin is built for, from the @protobase/ui installed for it (else for the project it extends): its plugin
23
- * API, and Protobase from its version on, unless the plugin's package.json names other versions in `engines.protobase`.
24
- * Also that version's theme, which the plugin's stylesheet draws with, and its folder.
28
+ * What the plugin is built for, from its @protobase/ui (see `targetUiDir`): its plugin API, and Protobase from its
29
+ * version on, unless the plugin's package.json names other versions in `engines.protobase`. Also that version's theme,
30
+ * which the plugin's stylesheet draws with, and its folder.
25
31
  */
26
- const pluginTarget = async (pluginDir, own, projectDir) => {
27
- const uiDir = findPackageDirSync("@protobase/ui", pluginDir) ?? (projectDir === void 0 ? void 0 : findPackageDirSync("@protobase/ui", projectDir));
28
- if (!uiDir) throw new Error(`@protobase/ui is not installed for ${pluginDir}; add it to the plugin's dependencies, as the version it is built for`);
32
+ const pluginTarget = async (pluginDir, own, projectDir, bundled) => {
33
+ const uiDir = targetUiDir(pluginDir, projectDir, bundled);
29
34
  const ui = await readPackageJson(uiDir);
30
35
  const api = ui.protobase?.pluginApi;
31
36
  const theme = ui.exports?.["./theme.css"];
@@ -96,7 +101,8 @@ const buildPlugin = async ({ pluginDir, outDir, name, projectDir, ignore = [], s
96
101
  const own = existsSync(path.join(pluginDir, "package.json")) ? await readPackageJson(pluginDir) : {};
97
102
  const pluginName = (name ?? own.name ?? path.basename(pluginDir)).trim();
98
103
  if (pluginName === "") throw new Error("The plugin needs a name: give its package.json a name, or pass --name");
99
- const target = await pluginTarget(pluginDir, own, projectDir);
104
+ const bundled = projectDir !== void 0 && projectPackages(projectDir).mode === "bundled";
105
+ const target = await pluginTarget(pluginDir, own, projectDir, bundled);
100
106
  const styles = path.join(pluginDir, "protobase-plugin.css");
101
107
  const nodeEnv = process.env.NODE_ENV;
102
108
  process.env.NODE_ENV = "production";
@@ -109,6 +115,7 @@ const buildPlugin = async ({ pluginDir, outDir, name, projectDir, ignore = [], s
109
115
  logLevel: "warn",
110
116
  plugins: [
111
117
  pluginImports(),
118
+ ...bundled ? [bundledImports([projectDir, pluginDir])] : [],
112
119
  ...projectDir === void 0 ? [] : [extensionImports(projectDir, [{ dir: pluginDir }])],
113
120
  pluginStyles(styles, styleCode(pluginDir, target.theme, [outDir, ...ignore])),
114
121
  react(),
@@ -147,7 +154,8 @@ const buildPlugin = async ({ pluginDir, outDir, name, projectDir, ignore = [], s
147
154
  pluginDir,
148
155
  entry,
149
156
  uiDir: target.uiDir,
150
- projectDir
157
+ projectDir,
158
+ bundled
151
159
  });
152
160
  const manifest = {
153
161
  name: pluginName,
@@ -1,4 +1,5 @@
1
1
  import { extensionImports } from "../project/extensions.js";
2
+ import { bundledImports } from "../project/bundled-imports.js";
2
3
  import { sharedModules } from "../project/shared-modules.js";
3
4
  import { viteBundle } from "./vite-bundle.js";
4
5
  import { createRequire } from "node:module";
@@ -31,9 +32,10 @@ const isStorageTypes = (value) => Array.isArray(value) && value.every((item) =>
31
32
  /**
32
33
  * The field types a plugin registers (`definePlugin({ fields })`), each with the storage types it shows (`of`), which
33
34
  * the server checks the views against at startup. The plugin's module is loaded once in Node, everything bundled into
34
- * a scratch file, as `protobase build` loads a project's UI to check its names; nothing is rendered.
35
+ * a scratch file, as `protobase build` loads a project's UI to check its names; nothing is rendered. A plugin of a
36
+ * bundled project imports the CLI's @protobase packages, as its build does.
35
37
  */
36
- const pluginFieldTypes = async ({ pluginDir, entry, uiDir, projectDir }) => {
38
+ const pluginFieldTypes = async ({ pluginDir, entry, uiDir, projectDir, bundled = false }) => {
37
39
  const file = path.join(pluginDir, "protobase-plugin-fields.js");
38
40
  const scratch = await mkdtemp(path.join(tmpdir(), "protobase-plugin-fields-"));
39
41
  const outFile = path.join(scratch, "fields.mjs");
@@ -41,6 +43,7 @@ const pluginFieldTypes = async ({ pluginDir, entry, uiDir, projectDir }) => {
41
43
  const plugins = [
42
44
  fieldsEntry(file, fieldsCode(entry)),
43
45
  sharedFromUi(uiDir),
46
+ ...bundled && projectDir !== void 0 ? [bundledImports([projectDir, pluginDir])] : [],
44
47
  ...projectDir === void 0 ? [] : [extensionImports(projectDir, [{ dir: pluginDir }])]
45
48
  ];
46
49
  await viteBundle({
@@ -1,5 +1,7 @@
1
+ import { projectPackages } from "../version/project-packages.js";
1
2
  import { extensionImports } from "../project/extensions.js";
2
3
  import { projectUiFile, projectUiId, projectUiPlugin } from "../project/project-ui.js";
4
+ import { bundledImports } from "../project/bundled-imports.js";
3
5
  import { viteBundle } from "./vite-bundle.js";
4
6
  import { existsSync } from "node:fs";
5
7
  import path from "node:path";
@@ -24,9 +26,12 @@ const registeredComponents = async (projectDir, extensions) => {
24
26
  const scratch = await mkdtemp(path.join(tmpdir(), "protobase-ui-check-"));
25
27
  const outFile = path.join(scratch, "ui-check.mjs");
26
28
  try {
29
+ const bundled = projectPackages(projectDir).mode === "bundled";
30
+ const projectDirs = [projectDir, ...extensions.map((extension) => extension.dir)];
27
31
  const plugins = [
28
32
  checkEntry(checkFile(projectDir)),
29
33
  projectUiPlugin(projectDir, extensions),
34
+ ...bundled ? [bundledImports(projectDirs)] : [],
30
35
  extensionImports(projectDir, extensions)
31
36
  ];
32
37
  await viteBundle({
@@ -11,7 +11,7 @@ import { checkViewQueries } from "@protobase/server";
11
11
  const checkViews = async (projectDir) => {
12
12
  const configDir = path.join(projectDir, "config");
13
13
  if (!existsSync(path.join(configDir, "index.ts"))) return;
14
- const { models, views } = await loadDataConfig(configDir);
14
+ const { models, views } = await loadDataConfig(configDir, projectDir);
15
15
  checkViewQueries(models, views);
16
16
  };
17
17
  //#endregion
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.49.2";
2
+ var version = "0.50.1";
3
3
  //#endregion
4
4
  export { version };
@@ -41,7 +41,10 @@ const sourceFiles = (projectDir, importModules) => {
41
41
  } },
42
42
  functions: Object.fromEntries(functionFiles(projectDir).map(({ name, file }) => [name, one(file)])),
43
43
  module: (file) => existsSync(path.join(projectDir, file)) ? one(path.join(projectDir, file)) : void 0,
44
- package: (name) => import(pathToFileURL(createRequire(path.join(projectDir, "package.json")).resolve(name)).href)
44
+ package: (name) => import(
45
+ /* @vite-ignore */
46
+ pathToFileURL(createRequire(path.join(projectDir, "package.json")).resolve(name)).href
47
+ )
45
48
  };
46
49
  };
47
50
  //#endregion
@@ -10,7 +10,7 @@ import path from "node:path";
10
10
  * extensions' configs, with the code each folder's conventions find. Only the config files run here; that code loads
11
11
  * when a command asks for it.
12
12
  */
13
- const loadSourceConfig = async (dir, { command, extensions = [], importModules = importProjectFiles }) => {
13
+ const loadSourceConfig = async (dir, { command, extensions = [], importModules = (files) => importProjectFiles(files, dir) }) => {
14
14
  const configEnv = {
15
15
  command,
16
16
  env: process.env,
@@ -1,9 +1,9 @@
1
1
  import { errorMessage } from "../error-message.js";
2
+ import { serverPackage } from "./server-package.js";
2
3
  import { moduleFile } from "../module-file.js";
3
4
  import { createApiVite } from "./api-vite.js";
4
5
  import { devHost } from "./loopback.js";
5
6
  import { isProjectFile } from "./project-files.js";
6
- import { serverPackage } from "./server-package.js";
7
7
  import { startupLogger } from "./startup-logger.js";
8
8
  import { createAdaptorServer } from "@hono/node-server";
9
9
  //#region src/dev/api-process.ts
@@ -1,9 +1,11 @@
1
+ import { projectPackages } from "../version/project-packages.js";
1
2
  import { uiPackageDir } from "../project/admin-app.js";
2
3
  import { layoutCheck } from "../build/layout-check.js";
3
4
  import { extensionImports, extensionStyles } from "../project/extensions.js";
4
5
  import { devHost } from "./loopback.js";
5
6
  import { frameHeaders } from "../serve/static-site.js";
6
7
  import { projectUiPlugin } from "../project/project-ui.js";
8
+ import { bundledImports, bundledPackageDirs } from "../project/bundled-imports.js";
7
9
  import { sharedModulesPlugin } from "../project/shared-modules.js";
8
10
  import { faviconLink } from "../project/favicon-link.js";
9
11
  import { themeLink } from "../project/theme-link.js";
@@ -30,41 +32,47 @@ const appDependencies = [
30
32
  ];
31
33
  /**
32
34
  * The Vite server of `protobase dev` that serves the admin app from `appDir`, with the project's UI, theme and icons,
33
- * on `port`; `plugins` come first, such as the one that hands the API's requests to its process.
35
+ * on `port`; `plugins` come first, such as the one that hands the API's requests to its process. A bundled project's
36
+ * page code gets the admin app's own @protobase packages and React.
34
37
  */
35
- const createAppServer = (options, plugins) => createServer({
36
- root: options.appDir,
37
- configFile: false,
38
- ...options.cacheDir && { cacheDir: options.cacheDir },
39
- optimizeDeps: {
40
- include: appDependencies,
41
- exclude: ["@protobase/ui"]
42
- },
43
- server: {
44
- headers: frameHeaders,
45
- host: devHost,
46
- port: options.port,
47
- strictPort: true,
48
- ...options.allowedHosts.length > 0 && { allowedHosts: options.allowedHosts },
49
- fs: { allow: [
50
- searchForWorkspaceRoot(options.projectDir),
51
- uiPackageDir,
52
- options.projectDir,
53
- ...options.extensions.map((extension) => extension.dir)
54
- ] }
55
- },
56
- plugins: [
57
- ...plugins,
58
- sharedModulesPlugin(),
59
- themeLink(options.projectDir),
60
- faviconLink(options.projectDir),
61
- projectUiPlugin(options.projectDir, options.extensions),
62
- extensionImports(options.projectDir, options.extensions),
63
- extensionStyles(options.extensions),
64
- layoutCheck(),
65
- react(),
66
- tailwindcss()
67
- ]
68
- });
38
+ const createAppServer = (options, plugins) => {
39
+ const projectDirs = [options.projectDir, ...options.extensions.map((extension) => extension.dir)];
40
+ const bundled = projectPackages(options.projectDir).mode === "bundled";
41
+ return createServer({
42
+ root: options.appDir,
43
+ configFile: false,
44
+ ...options.cacheDir && { cacheDir: options.cacheDir },
45
+ optimizeDeps: {
46
+ include: appDependencies,
47
+ exclude: ["@protobase/ui"]
48
+ },
49
+ server: {
50
+ headers: frameHeaders,
51
+ host: devHost,
52
+ port: options.port,
53
+ strictPort: true,
54
+ ...options.allowedHosts.length > 0 && { allowedHosts: options.allowedHosts },
55
+ fs: { allow: [
56
+ searchForWorkspaceRoot(options.projectDir),
57
+ uiPackageDir,
58
+ ...projectDirs,
59
+ ...bundled ? bundledPackageDirs() : []
60
+ ] }
61
+ },
62
+ plugins: [
63
+ ...plugins,
64
+ sharedModulesPlugin(),
65
+ themeLink(options.projectDir),
66
+ faviconLink(options.projectDir),
67
+ projectUiPlugin(options.projectDir, options.extensions),
68
+ ...bundled ? [bundledImports(projectDirs)] : [],
69
+ extensionImports(options.projectDir, options.extensions),
70
+ extensionStyles(options.extensions),
71
+ layoutCheck(),
72
+ react(),
73
+ tailwindcss()
74
+ ]
75
+ });
76
+ };
69
77
  //#endregion
70
78
  export { createAppServer };
@@ -2,10 +2,10 @@ 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
5
- const sharedDb = (projectDir, url) => {
5
+ const sharedDb = (packagesDir, url) => {
6
6
  const store = globalThis;
7
7
  if (store.__protobaseDb) return store.__protobaseDb;
8
- const load = createRequire(path.join(projectDir, "package.json"));
8
+ const load = createRequire(path.join(packagesDir, "package.json"));
9
9
  store.__protobaseDb = openAppDatabase(load("pg"), url);
10
10
  return store.__protobaseDb;
11
11
  };
@@ -1,3 +1,4 @@
1
+ import { serverPackage } from "./server-package.js";
1
2
  import { loadSourceConfig } from "../config/source-config.js";
2
3
  import { sharedDb } from "./create-db.js";
3
4
  import { pathToFileURL } from "node:url";
@@ -24,11 +25,11 @@ const loadDevConfig = (projectDir, extensions = []) => loadSourceConfig(projectD
24
25
  extensions,
25
26
  importModules
26
27
  });
27
- /** The app's database, shared across reloads. */
28
+ /** The app's database, over the `pg` the project's config gets, shared across reloads. */
28
29
  const devDatabase = (projectDir) => {
29
30
  const url = process.env.PROTOBASE_DATABASE_URL;
30
31
  if (!url) throw new Error("No database: set DATABASE_URL (or pass --env)");
31
- return sharedDb(projectDir, url);
32
+ return sharedDb(serverPackage(projectDir).root, url);
32
33
  };
33
34
  //#endregion
34
35
  export { devDatabase, loadDevConfig };
@@ -1,30 +1,18 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import path from "node:path";
1
+ import { packageName } from "../build/packages/package-dir.js";
2
+ import { projectPackages } from "../version/project-packages.js";
3
+ import { hostModuleIds } from "../serve/host-module-ids.js";
3
4
  import { fileURLToPath } from "node:url";
4
5
  //#region src/dev/server-package.ts
5
6
  const server = "@protobase/server";
6
- const framework = [
7
- "@protobase/layout",
8
- "@protobase/query",
9
- "@protobase/schema",
10
- server
11
- ];
12
- const dependencyFields = [
13
- "dependencies",
14
- "devDependencies",
15
- "optionalDependencies",
16
- "peerDependencies"
17
- ];
7
+ const supplied = [...new Set(hostModuleIds.map((id) => packageName(id)))];
18
8
  const cliDir = fileURLToPath(new URL("../..", import.meta.url));
19
9
  /**
20
- * Where the API of `protobase dev` gets @protobase/server: from the project's node_modules when its package.json lists
21
- * it, so a project that is not installed fails as any missing package does; otherwise, with no package.json or one
22
- * without it, the CLI's own, with the CLI's other framework packages.
10
+ * Where the API of `protobase dev` gets @protobase/server: from the project's node_modules when the project is locked,
11
+ * so one that is not installed fails as any missing package does; otherwise, bundled, the CLI's own, with the other
12
+ * packages the serve runtime supplies.
23
13
  */
24
14
  const serverPackage = (projectDir, ownDir = cliDir) => {
25
- const file = path.join(projectDir, "package.json");
26
- const manifest = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
27
- if (dependencyFields.some((field) => manifest[field]?.[server] !== void 0)) return {
15
+ if (projectPackages(projectDir).mode === "locked") return {
28
16
  from: "project",
29
17
  root: projectDir,
30
18
  dedupe: [server]
@@ -32,7 +20,7 @@ const serverPackage = (projectDir, ownDir = cliDir) => {
32
20
  return {
33
21
  from: "cli",
34
22
  root: ownDir,
35
- dedupe: framework
23
+ dedupe: supplied
36
24
  };
37
25
  };
38
26
  //#endregion
@@ -12,7 +12,7 @@ import { tableIndexes } from "@protobase/query";
12
12
  const format = (issue) => ` ${issue.severity.padEnd(7)} ${issue.resource}: ${issue.message}${issue.suggestion ? `\n fix: ${issue.suggestion}` : ""}\n`;
13
13
  const runDoctor = async (options, out) => {
14
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>`);
15
- const config = await loadDataConfig(options.configDir);
15
+ const config = await loadDataConfig(options.configDir, options.projectDir);
16
16
  const { models } = config;
17
17
  if (models.length === 0) throw new Error(`No resources exported from ${options.configDir}/index.ts`);
18
18
  const sql = connect(options.url);
@@ -0,0 +1,15 @@
1
+ //#region src/hand-over.d.ts
2
+ /**
3
+ * The folder of the @protobase/cli a locked project in `projectDir` has installed, when it is another CLI than the one
4
+ * in `ownDir`: that one runs the project, at the version it is locked to. Undefined for a bundled project, which the
5
+ * CLI that is started runs, and for a locked one without its own CLI installed.
6
+ */
7
+ export declare const projectCliDir: (projectDir: string, ownDir: string) => string | undefined;
8
+ type Run = (argv: string[]) => Promise<void>;
9
+ /**
10
+ * Runs the command in `argv` with the CLI the project in the current directory is locked to, the Angular CLI's and
11
+ * Gulp's hand-over: a CLI installed globally, in CI or in an image, runs a locked project as its own CLI would, with a
12
+ * line on stderr naming that CLI. Otherwise it runs `own`, the started CLI.
13
+ */
14
+ export declare const runHandingOver: (ownDir: string, own: () => Promise<Run>, argv: string[]) => Promise<void>;
15
+ //#endregion
@@ -0,0 +1,32 @@
1
+ import { findPackageDirSync } from "./build/packages/package-dir.js";
2
+ import { listedPackages, modeOf } from "./version/project-packages.js";
3
+ import { realpathSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ //#region src/hand-over.ts
7
+ /**
8
+ * The folder of the @protobase/cli a locked project in `projectDir` has installed, when it is another CLI than the one
9
+ * in `ownDir`: that one runs the project, at the version it is locked to. Undefined for a bundled project, which the
10
+ * CLI that is started runs, and for a locked one without its own CLI installed.
11
+ */
12
+ const projectCliDir = (projectDir, ownDir) => {
13
+ if (modeOf(listedPackages(projectDir)) !== "locked") return void 0;
14
+ const dir = findPackageDirSync("@protobase/cli", projectDir);
15
+ if (!dir || realpathSync(dir) === realpathSync(ownDir)) return void 0;
16
+ return dir;
17
+ };
18
+ /**
19
+ * Runs the command in `argv` with the CLI the project in the current directory is locked to, the Angular CLI's and
20
+ * Gulp's hand-over: a CLI installed globally, in CI or in an image, runs a locked project as its own CLI would, with a
21
+ * line on stderr naming that CLI. Otherwise it runs `own`, the started CLI.
22
+ */
23
+ const runHandingOver = async (ownDir, own, argv) => {
24
+ const projectDir = projectCliDir(process.cwd(), ownDir);
25
+ if (!projectDir) return (await own())(argv);
26
+ const { version } = (await import(pathToFileURL(path.join(projectDir, "package.json")).href, { with: { type: "json" } })).default;
27
+ process.stderr.write(`protobase: this project is locked; running its own @protobase/cli ${version}\n`);
28
+ const { run } = await import(pathToFileURL(path.join(projectDir, "dist/index.js")).href);
29
+ return run(argv);
30
+ };
31
+ //#endregion
32
+ export { projectCliDir, runHandingOver };
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"));
@@ -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