@brickkit/cli 0.11.0 → 0.13.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 (177) hide show
  1. package/dashboard-dist/CollapsiblePanel-CbUysOp5.js +2 -0
  2. package/dashboard-dist/CompositeRoot-D4sRkYq3.js +1 -0
  3. package/dashboard-dist/Geist-Variable.woff2 +0 -0
  4. package/dashboard-dist/GeistMono-Variable.woff2 +0 -0
  5. package/dashboard-dist/PopoverPopup-CiI2avT_.js +1 -0
  6. package/dashboard-dist/api-reference-mT9VNcPb.js +265 -0
  7. package/dashboard-dist/app.css +2 -2
  8. package/dashboard-dist/app.js +12 -13
  9. package/dashboard-dist/ccount-CcG1m-Yh.js +1 -0
  10. package/dashboard-dist/client-CwATkLJa.js +1 -0
  11. package/dashboard-dist/core-BEUWp6B5.js +1 -0
  12. package/dashboard-dist/docs-BRrtyxDB.js +4 -0
  13. package/dashboard-dist/docs.css +1 -1
  14. package/dashboard-dist/kit.js +1 -1
  15. package/dashboard-dist/popover-Bj9x-88h.js +1 -0
  16. package/dist/bin.d.ts +0 -2
  17. package/dist/bin.js +309 -211
  18. package/dist/bin.js.map +1 -1
  19. package/dist/build.js +463 -0
  20. package/dist/build.js.map +1 -0
  21. package/dist/client-contract-file.js +356 -1
  22. package/dist/client-contract-file.js.map +1 -0
  23. package/dist/compiler.d.ts +12 -3
  24. package/dist/compiler.js +1 -1
  25. package/dist/compiler2.js +13 -7
  26. package/dist/compiler2.js.map +1 -1
  27. package/dist/config.d.ts +3 -0
  28. package/dist/config.js +1 -252
  29. package/dist/config2.d.ts +122 -0
  30. package/dist/config2.js +207 -0
  31. package/dist/config2.js.map +1 -0
  32. package/dist/dashboard-extension.d.ts +3 -2
  33. package/dist/{dev-telemetry-store.js → dashboard-host.js} +1381 -1432
  34. package/dist/dashboard-host.js.map +1 -0
  35. package/dist/dashboard-protocol.js +189 -0
  36. package/dist/dashboard-protocol.js.map +1 -0
  37. package/dist/dashboard.d.ts +8 -135
  38. package/dist/definitions.js +33 -0
  39. package/dist/definitions.js.map +1 -0
  40. package/dist/dev-application.js +34 -0
  41. package/dist/dev-application.js.map +1 -0
  42. package/dist/dev-protocol.js +21 -0
  43. package/dist/dev-protocol.js.map +1 -0
  44. package/dist/dev-reporter.d.ts +0 -2
  45. package/dist/dev-reporter.js +3 -3
  46. package/dist/dev-reporter.js.map +1 -1
  47. package/dist/dev-telemetry.js +8 -24
  48. package/dist/dev-telemetry.js.map +1 -1
  49. package/dist/dev-worker.js +80 -21
  50. package/dist/dev-worker.js.map +1 -1
  51. package/dist/index.d.ts +18 -87
  52. package/dist/index.js +12 -6
  53. package/dist/index.js.map +1 -0
  54. package/dist/lint/oxlint.d.ts +0 -2
  55. package/dist/lint/oxlint.js +6 -5
  56. package/dist/lint/oxlint.js.map +1 -1
  57. package/dist/own-module.js +7 -0
  58. package/dist/own-module.js.map +1 -0
  59. package/dist/plugin.d.ts +6 -11
  60. package/dist/plugin.js +6 -42
  61. package/dist/plugin.js.map +1 -1
  62. package/dist/production-dashboard.d.ts +2 -0
  63. package/dist/production-dashboard.js +51 -0
  64. package/dist/production-dashboard.js.map +1 -0
  65. package/dist/production-dashboard2.d.ts +34 -0
  66. package/dist/{presets.js → project.js} +107 -113
  67. package/dist/project.js.map +1 -0
  68. package/dist/serve.d.ts +24 -0
  69. package/dist/serve.js +1 -0
  70. package/dist/serve2.js +49 -0
  71. package/dist/serve2.js.map +1 -0
  72. package/dist/vite.d.ts +0 -2
  73. package/dist/vite.js +28 -51
  74. package/dist/vite.js.map +1 -1
  75. package/dist/workflows.d.ts +2 -4
  76. package/dist/workflows2.js +60 -39
  77. package/dist/workflows2.js.map +1 -1
  78. package/inspector-dist/client/assets/api.rpc-BvRk9kiK.js +0 -0
  79. package/inspector-dist/client/assets/api.stream._streamId-BvRk9kiK.js +0 -0
  80. package/inspector-dist/client/assets/app-CeSwVsRm.css +2 -0
  81. package/inspector-dist/client/assets/dist-BK8w6xOr.js +3930 -0
  82. package/inspector-dist/client/assets/dist-CG2aVufI.js +197 -0
  83. package/inspector-dist/client/assets/entry.client-D9jbgmTR.js +9391 -0
  84. package/inspector-dist/client/assets/highlighted-body-B3W2YXNL-CfRnuITN.js +34 -0
  85. package/inspector-dist/client/assets/home-hwPlkNhv.js +4034 -0
  86. package/inspector-dist/client/assets/jsx-runtime-CPEah4WQ.js +7084 -0
  87. package/inspector-dist/client/assets/manifest-0e76e9ac.js +1 -0
  88. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-ZDR2PNY_.js +1 -0
  89. package/inspector-dist/client/assets/root-ChBNTZd2.css +2 -0
  90. package/inspector-dist/client/assets/root-SLeEf-sT.js +320 -0
  91. package/inspector-dist/client/assets/run-detail-DYbVkIFH.js +1871 -0
  92. package/inspector-dist/client/assets/tabs-CaJisoyb.js +73751 -0
  93. package/inspector-dist/client/assets/tabs-L5XKzOpP.css +1 -0
  94. package/inspector-dist/client/assets/zstd-browser-decoder-D94wmfAU.js +41 -0
  95. package/inspector-dist/server/assets/app-DGlfWVUI.js +99330 -0
  96. package/inspector-dist/server/assets/chunk-RLXIAIE6-F0SJZlei.js +42975 -0
  97. package/inspector-dist/server/assets/dist-BCbwm6jl.js +10325 -0
  98. package/inspector-dist/server/assets/dist-CG2aVufI.js +197 -0
  99. package/inspector-dist/server/assets/dist-Ce0I2PUv.js +1137 -0
  100. package/inspector-dist/server/assets/dist-DY0UlahA.js +1642 -0
  101. package/inspector-dist/server/assets/encryption-DdQgC8Rk.js +886 -0
  102. package/inspector-dist/server/assets/event-metadata-n7E4zEmT.js +145 -0
  103. package/inspector-dist/server/assets/functions-CNVQtbgg.js +1170 -0
  104. package/inspector-dist/server/assets/global-singleton-D8sIN5du.js +80 -0
  105. package/inspector-dist/server/assets/highlighted-body-B3W2YXNL-CWRzMxYD.js +34 -0
  106. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-D0v0ngVr.js +1 -0
  107. package/inspector-dist/server/assets/parse-Begau9cA.js +469 -0
  108. package/inspector-dist/server/assets/rolldown-runtime-C1I3wEg2.js +43 -0
  109. package/inspector-dist/server/assets/serialization-format-BbuGfHog.js +476 -0
  110. package/inspector-dist/server/assets/token-BgMmJNP5.js +60 -0
  111. package/inspector-dist/server/assets/token-BrUX0bxz.js +55 -0
  112. package/inspector-dist/server/assets/token-util-DZN32qmT.js +455 -0
  113. package/inspector-dist/server/assets/wrapper-CIC3w0oC.js +3624 -0
  114. package/inspector-dist/server/assets/ws-transport-CxTYB11n.js +29476 -0
  115. package/inspector-dist/server/assets/zstd-browser-decoder-D7bCXbGg.js +38 -0
  116. package/inspector-dist/server/index.js +1 -58
  117. package/package.json +39 -28
  118. package/vite-client.d.ts +1 -1
  119. package/dashboard-dist/CollapsiblePanel-BX79_W-b.js +0 -2
  120. package/dashboard-dist/CompositeRoot-xzybXjnx.js +0 -1
  121. package/dashboard-dist/PopoverPopup-CvlmC7EL.js +0 -1
  122. package/dashboard-dist/api-reference-BcAYVYwJ.js +0 -260
  123. package/dashboard-dist/core-BGO9JZ1r.js +0 -1
  124. package/dashboard-dist/docs-DHikPD2v.js +0 -4
  125. package/dashboard-dist/popover-DG498XHH.js +0 -1
  126. package/dist/app-entry.js +0 -1
  127. package/dist/app-entry2.js +0 -19
  128. package/dist/app-entry2.js.map +0 -1
  129. package/dist/bin.d.ts.map +0 -1
  130. package/dist/client-contract-file2.js +0 -34
  131. package/dist/client-contract-file2.js.map +0 -1
  132. package/dist/client-contract.js +0 -1
  133. package/dist/client-contract2.js +0 -294
  134. package/dist/client-contract2.js.map +0 -1
  135. package/dist/config.js.map +0 -1
  136. package/dist/dashboard-extension.d.ts.map +0 -1
  137. package/dist/dev-reporter.d.ts.map +0 -1
  138. package/dist/dev-telemetry-store.js.map +0 -1
  139. package/dist/emit.d.ts +0 -7
  140. package/dist/emit.d.ts.map +0 -1
  141. package/dist/index.d.ts.map +0 -1
  142. package/dist/lint/oxlint.d.ts.map +0 -1
  143. package/dist/plugin.d.ts.map +0 -1
  144. package/dist/presets.js.map +0 -1
  145. package/dist/runner.js +0 -523
  146. package/dist/runner.js.map +0 -1
  147. package/dist/vite.d.ts.map +0 -1
  148. package/dist/workflows.d.ts.map +0 -1
  149. package/inspector-dist/client/assets/api.rpc-l0sNRNKZ.js +0 -1
  150. package/inspector-dist/client/assets/api.stream._streamId-l0sNRNKZ.js +0 -1
  151. package/inspector-dist/client/assets/app-CvoGgWcV.css +0 -1
  152. package/inspector-dist/client/assets/entry.client-BJ6G3n5t.js +0 -11697
  153. package/inspector-dist/client/assets/highlighted-body-B3W2YXNL-C-3wZnxf.js +0 -19
  154. package/inspector-dist/client/assets/home-CSKAS4P2.js +0 -4979
  155. package/inspector-dist/client/assets/index-DECCyMR0.js +0 -4482
  156. package/inspector-dist/client/assets/index-Dot7CgrA.js +0 -9837
  157. package/inspector-dist/client/assets/index-HqNj_XIX.js +0 -200
  158. package/inspector-dist/client/assets/manifest-139c9319.js +0 -1
  159. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-DC0K8uTy.js +0 -58626
  160. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-F88p7PFX.css +0 -1
  161. package/inspector-dist/client/assets/root-BMHd_XHz.css +0 -1
  162. package/inspector-dist/client/assets/root-cbi6iYwg.js +0 -305
  163. package/inspector-dist/client/assets/run-detail-CWoGxu_0.css +0 -1
  164. package/inspector-dist/client/assets/run-detail-Cc7tSGNq.js +0 -6237
  165. package/inspector-dist/client/assets/world-config-context-BAD1QCrR.js +0 -26
  166. package/inspector-dist/client/assets/zstd-browser-decoder-BQoRpP7L.js +0 -28
  167. package/inspector-dist/server/assets/app-DUP5RybL.js +0 -174880
  168. package/inspector-dist/server/assets/highlighted-body-B3W2YXNL-D2g4hL2-.js +0 -71
  169. package/inspector-dist/server/assets/index-BfLBLRRi.js +0 -204
  170. package/inspector-dist/server/assets/index-BzrGWk7J.js +0 -1164
  171. package/inspector-dist/server/assets/index-D71yP6AL.js +0 -191
  172. package/inspector-dist/server/assets/index-wGSWRns3.js +0 -1296
  173. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-DsvuKoEV.js +0 -58
  174. package/inspector-dist/server/assets/token-ClUZZwXl.js +0 -95
  175. package/inspector-dist/server/assets/token-util-DSxMZ6nI.js +0 -33
  176. package/inspector-dist/server/assets/wrapper-B3vstpCO.js +0 -67
  177. package/inspector-dist/server/assets/zstd-browser-decoder-Dn82m2BU.js +0 -77
package/dist/bin.js CHANGED
@@ -1,23 +1,40 @@
1
1
  #!/usr/bin/env bun
2
- import { n as DEFAULT_DASHBOARD_PORT } from "./dev-telemetry-store.js";
3
- import { c as resolveDevPort, i as startWorker, n as startDevServer, o as writeServiceManifest, r as startProdServer, s as parsePort } from "./runner.js";
4
- import { t as loadBrickApp } from "./app-entry2.js";
5
- import { t as writeClientContract } from "./client-contract-file2.js";
6
- import { i as buildApplication, r as loadConfig, t as ConfigError } from "./config.js";
7
- import { i as resolveRules, r as fileRules } from "./presets.js";
2
+ import { a as writeServiceManifest, i as startWorker, n as startDevServer, r as startProdServer, t as buildApplication } from "./build.js";
3
+ import { r as writeClientContract, s as loadBrickApp } from "./client-contract-file.js";
4
+ import { d as resolveDevDashboard, f as resolvePort, n as ConfigError, o as DEFAULT_PORT, p as resolveProject, r as DEFAULT_DASHBOARD_PORT } from "./config2.js";
5
+ import { o as version, s as serviceFolders, t as projectRules } from "./project.js";
6
+ import { a as TEST_FILE, n as DEFINITION_FILE, t as DEFINITION_EXTENSIONS } from "./definitions.js";
8
7
  import { createRequire } from "node:module";
9
- import { generateOpenApiSpec, getGlobalRegistry, getPluginActionRoute, kebabCase } from "@brickkit/core";
10
- import { fileURLToPath } from "node:url";
8
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
11
9
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
12
- import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
10
+ import { drizzleSchema, getGlobalRegistry, getTableName, isCrudEvent, migrateDatabase, sql } from "@brickkit/core";
11
+ import { fileURLToPath } from "node:url";
13
12
  import { Command, InvalidArgumentError } from "commander";
14
13
  import { spawnSync } from "node:child_process";
15
14
  import { tmpdir } from "node:os";
16
- //#region src/lint/run.ts
17
- /** The built lint/oxlint entry, which oxlint loads under Node. */
15
+ // src/lint/run.ts
16
+ let fromSource;
17
+ /** The lint/oxlint entry oxlint loads under Node: the bundle beside this code, or, run from source, a fresh bundle of it. */
18
18
  function pluginPath() {
19
19
  const here = fileURLToPath(import.meta.url);
20
- return here.endsWith(".ts") ? resolve(dirname(here), "../../dist/lint/oxlint.js") : resolve(dirname(here), "lint/oxlint.js");
20
+ if (!here.endsWith(".ts")) return resolve(dirname(here), "lint/oxlint.js");
21
+ if (fromSource) return fromSource;
22
+ const file = resolve(here, "../../../node_modules/.cache/brick-lint.js");
23
+ const building = `${file}.${process.pid}`;
24
+ const result = spawnSync(process.execPath, [
25
+ "build",
26
+ resolve(dirname(here), "oxlint.ts"),
27
+ "--target",
28
+ "node"
29
+ ].concat([
30
+ "--packages",
31
+ "external",
32
+ "--outfile",
33
+ building
34
+ ]), { encoding: "utf8" });
35
+ if (result.status !== 0) throw new Error(`Brick: building the lint plugin failed:\n${result.stderr}`);
36
+ renameSync(building, file);
37
+ return fromSource = file;
21
38
  }
22
39
  function oxlintBin(root) {
23
40
  for (const base of [join(root, "package.json"), fileURLToPath(import.meta.url)]) try {
@@ -55,7 +72,7 @@ function runFileRules(options) {
55
72
  "--no-error-on-unmatched-pattern",
56
73
  ...options.fix ? ["--fix"] : [],
57
74
  ...(options.ignore ?? []).flatMap((pattern) => ["--ignore-pattern", pattern]),
58
- ...options.paths ?? ["."]
75
+ "."
59
76
  ], {
60
77
  cwd: options.root,
61
78
  encoding: "utf8",
@@ -83,53 +100,39 @@ function runFileRules(options) {
83
100
  });
84
101
  }
85
102
  }
86
- //#endregion
87
- //#region src/lint.ts
103
+ // src/lint.ts
88
104
  const posix$1 = (path) => path.split(sep).join("/");
89
- const SOURCE = new Bun.Glob("**/*.{ts,tsx,mts,cts}");
105
+ const SOURCE = new Bun.Glob(`**/*.{${[...DEFINITION_EXTENSIONS, "cts"].join(",")}}`);
90
106
  /**
91
107
  * `brick lint`: the file rules through oxlint, then the app
92
108
  * rules against the loaded app. Prints `file:line:col` lines and returns the
93
109
  * exit code: 1 when anything is an error.
94
110
  */
95
111
  async function runLint(options) {
96
- const { project } = options;
97
- const root = project?.root ?? process.cwd();
98
- const config = project?.config.lint ?? {};
99
- let resolved;
100
- try {
101
- resolved = resolveRules(config.presets, config.rules);
102
- } catch (error) {
103
- throw new ConfigError(`brick.config.ts: lint.rules: ${error.message}`);
104
- }
105
- const fromRoot = (path) => posix$1(relative(root, path)) || ".";
106
- const services = project?.services ?? resolve(root, "src/services");
107
- const generated = project?.generated ?? resolve(root, "_brick");
108
- const entry = options.entry ? resolve(options.entry) : project?.entry ?? resolve(root, "src/app.ts");
109
- const ignore = [...config.ignore ?? [], `${fromRoot(generated)}/**`];
112
+ const entry = options.entry ? resolve(options.entry) : options.project.entry;
113
+ const project = {
114
+ ...options.project,
115
+ entry
116
+ };
117
+ const { root, services } = project;
118
+ const { resolved, rules, settings, ignore } = projectRules(project);
110
119
  const messages = runFileRules({
111
120
  root,
112
- rules: fileRules(resolved),
113
- settings: {
114
- root,
115
- services: fromRoot(services),
116
- entry: fromRoot(entry),
117
- generated: fromRoot(generated),
118
- web: "web"
119
- },
121
+ rules,
122
+ settings,
120
123
  ignore
121
124
  });
122
125
  const globs = ignore.map((pattern) => new Bun.Glob(pattern));
123
126
  if (existsSync(entry)) {
124
- if (project) await writeServiceManifest(project);
127
+ if (project.file) await writeServiceManifest(project);
125
128
  messages.push(...await checkApp({
126
129
  root,
127
130
  entry,
128
131
  services,
129
- severity: (rule) => rule === "no-cross-service-tables" ? "error" : resolved[`brick/${rule}`] ?? "off",
132
+ severity: (rule) => resolved[`brick/${rule}`] ?? "off",
130
133
  ignored: (rel) => rel.split("/").includes("node_modules") || globs.some((glob) => glob.match(rel))
131
134
  }));
132
- } else if (options.entry || project) throw new Error(`Brick: entry not found: ${entry}`);
135
+ } else if (options.entry || project.file) throw new Error(`Brick: entry not found: ${entry}`);
133
136
  return report(messages);
134
137
  }
135
138
  function report(messages) {
@@ -148,93 +151,73 @@ function sourceFiles(check, under = check.root) {
148
151
  onlyFiles: true
149
152
  })].map((file) => resolve(under, file)).filter((file) => {
150
153
  const rel = posix$1(relative(check.root, file));
151
- return !check.ignored(rel) && !/\.(test|spec)\.[cm]?tsx?$/.test(rel) && !rel.startsWith("dist/");
154
+ return !check.ignored(rel) && !TEST_FILE.test(rel) && !rel.startsWith("dist/");
152
155
  });
153
156
  }
154
157
  function lineOf(source, index) {
155
158
  return source.slice(0, index).split("\n").length;
156
159
  }
157
- /** The app rules: they need the loaded app, so only brick lint runs them. */
160
+ /** Each app rule's check; a rule in APP_RULES without one fails to compile. */
161
+ const APP_CHECKS = {
162
+ "single-app-entry": singleAppEntry,
163
+ "no-cross-service-tables": noCrossServiceTables,
164
+ "unique-names": () => {},
165
+ "declared-events": declaredEvents,
166
+ "test-colocated": testColocated
167
+ };
158
168
  async function checkApp(check) {
159
169
  const messages = [];
160
- const add = (rule, file, message, line = 1) => {
161
- const severity = check.severity(rule);
162
- if (severity === "off") return;
163
- messages.push({
164
- file: posix$1(relative(check.root, file)),
165
- line,
166
- column: 1,
167
- rule: `brick/${rule}`,
168
- severity,
169
- message
170
- });
171
- };
170
+ const message = (rule, severity, file, text, line = 1) => ({
171
+ file: posix$1(relative(check.root, file)),
172
+ line,
173
+ column: 1,
174
+ rule: `brick/${rule}`,
175
+ severity,
176
+ message: text
177
+ });
172
178
  let app;
173
179
  try {
174
180
  app = await loadBrickApp(check.entry);
175
181
  } catch (error) {
176
- const message = error.message;
177
- if (/duplicate/i.test(message)) {
178
- add("unique-names", check.entry, message);
179
- return messages;
180
- }
182
+ if (error.name === "DuplicateNameError") return [message("unique-names", "error", check.entry, error.message)];
181
183
  throw error;
182
184
  }
183
- singleAppEntry(check, sourceFiles(check), add);
184
- uniqueNames(check, app, add);
185
- await noCrossServiceTables(check, app, add);
186
- declaredEvents(check, app, add);
187
- testColocated(check, add);
185
+ for (const [rule, run] of Object.entries(APP_CHECKS)) {
186
+ const severity = check.severity(rule);
187
+ if (severity === "off") continue;
188
+ await run(check, app, (file, text, line) => messages.push(message(rule, severity, file, text, line)));
189
+ }
188
190
  return messages;
189
191
  }
190
- function singleAppEntry(check, files, add) {
191
- if (check.severity("single-app-entry") === "off") return;
192
+ function singleAppEntry(check, _app, add) {
192
193
  let calls = 0;
193
- for (const file of files) {
194
+ for (const file of sourceFiles(check)) {
194
195
  const source = readFileSync(file, "utf8");
195
196
  if (!/import\s*\{[^}]*\bbrick\b[^}]*\}\s*from\s*["']@brickkit\/core["']/.test(source)) continue;
196
197
  for (const match of source.matchAll(/(?<![.\w])brick\s*\(/g)) {
197
198
  if (file === check.entry && ++calls === 1) continue;
198
- add("single-app-entry", file, file === check.entry ? "The entry calls brick() more than once; keep one app." : `brick() is called outside the entry (${posix$1(relative(check.root, check.entry))}); keep one app.`, lineOf(source, match.index));
199
+ add(file, file === check.entry ? "The entry calls brick() more than once; keep one app." : `brick() is called outside the entry (${posix$1(relative(check.root, check.entry))}); keep one app.`, lineOf(source, match.index));
199
200
  }
200
201
  }
201
202
  }
202
- function uniqueNames(check, app, add) {
203
- const services = [...app.definition.services];
204
- const seen = /* @__PURE__ */ new Set();
205
- for (const service of services) {
206
- if (seen.has(service.name)) add("unique-names", check.entry, `Two services are named "${service.name}".`);
207
- seen.add(service.name);
208
- const owners = /* @__PURE__ */ new Map();
209
- const claim = (name, what) => {
210
- const segment = kebabCase(name);
211
- const other = owners.get(segment);
212
- if (other) add("unique-names", check.entry, `In service "${service.name}", ${what} and ${other} share the name "${segment}".`);
213
- else owners.set(segment, what);
214
- };
215
- for (const action of service.listActions()) if (action.config.path === void 0 && !action.resourceAction && getPluginActionRoute(action) === void 0) claim(action.name, `action "${action.name}"`);
216
- for (const socket of service.listSockets()) if (socket.schema.path === void 0) claim(socket.schema.name, `socket "${socket.schema.name}"`);
217
- for (const resource of service.listResources()) claim(resource.name, `resource "${resource.name}"`);
218
- }
219
- }
220
203
  /** Which service owns each table: its resources' and registered tables, or a database it alone uses. */
221
204
  function tableOwners(app) {
222
205
  const owners = /* @__PURE__ */ new Map();
223
206
  const users = /* @__PURE__ */ new Map();
224
207
  for (const service of app.definition.services) {
225
- for (const table of service.tables?.values() ?? []) owners.set(table, service.name);
226
- const database = service.options.database;
208
+ for (const table of service.tables.values()) owners.set(table, service.name);
209
+ const { database } = service.options;
227
210
  if (database) users.set(database, [...users.get(database) ?? [], service.name]);
228
211
  }
229
212
  for (const [database, names] of users) if (names.length === 1) {
230
- for (const table of Object.values(database.tables ?? {})) if (!owners.has(table)) owners.set(table, names[0]);
213
+ for (const table of Object.values(database.tables)) if (!owners.has(table)) owners.set(table, names[0]);
231
214
  }
232
215
  return owners;
233
216
  }
234
217
  function serviceOfFolder(app, folder) {
235
- return app.definition.services.find((service) => service.name === folder || kebabCase(service.name) === folder)?.name;
218
+ return app.definition.services.find((service) => serviceFolders(service.name).includes(folder))?.name;
236
219
  }
237
- const IMPORT = /import\s+(type\s+)?([\w$]+\s*,?\s*)?(\*\s+as\s+[\w$]+|\{[^}]*\})?\s*from\s*["']([^"']+)["']/g;
220
+ const IMPORT = /(?:import|export)\s+(type\s+)?([\w$]+\s*,?\s*)?(\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})?\s*from\s*["']([^"']+)["']/g;
238
221
  async function noCrossServiceTables(check, app, add) {
239
222
  const owners = tableOwners(app);
240
223
  for (const file of sourceFiles(check, check.services)) {
@@ -254,8 +237,8 @@ async function noCrossServiceTables(check, app, add) {
254
237
  const line = lineOf(source, match.index);
255
238
  const where = posix$1(relative(check.services, target)).split("/");
256
239
  const otherFolder = !where[0].startsWith("..") && where.length > 1 ? where[0] : void 0;
257
- if (otherFolder && otherFolder !== folder && /\.table\.[cm]?tsx?$/.test(target)) {
258
- add("no-cross-service-tables", file, `Service "${service}" imports ${basename(target)} from ${otherFolder}/; call that service's actions or listen to its events instead.`, line);
240
+ if (otherFolder && otherFolder !== folder && DEFINITION_FILE.exec(basename(target))?.[2] === "table") {
241
+ add(file, `Service "${service}" imports ${basename(target)} from ${otherFolder}/; call that service's actions or listen to its events instead.`, line);
259
242
  continue;
260
243
  }
261
244
  const module = await import(target).catch(() => ({}));
@@ -268,49 +251,188 @@ async function noCrossServiceTables(check, app, add) {
268
251
  }
269
252
  for (const name of names) {
270
253
  const owner = owners.get(module[name]);
271
- if (owner && owner !== service) add("no-cross-service-tables", file, `Service "${service}" imports table ${name === "default" ? basename(target) : `"${name}"`} owned by "${owner}"; call ${owner}'s actions or listen to its events instead.`, line);
254
+ if (owner && owner !== service) add(file, `Service "${service}" imports table ${name === "default" ? basename(target) : `"${name}"`} owned by "${owner}"; call ${owner}'s actions or listen to its events instead.`, line);
272
255
  }
273
256
  }
274
257
  }
275
258
  }
276
259
  function declaredEvents(check, app, add) {
277
- if (check.severity("declared-events") === "off") return;
278
260
  for (const service of app.definition.services) {
279
261
  if (!service.options.events) continue;
280
262
  const names = new Set(Object.values(service.events).map((e) => e.name));
281
263
  const resources = service.listResources().map((r) => r.name);
282
- const declared = (name) => {
283
- const [owner, event] = name.split(".", 2);
284
- return names.has(name) || resources.includes(owner) && /^(create|update|delete)$/.test(event);
285
- };
286
- for (const action of service.listActions()) for (const name of action.config.emits ?? []) if (!declared(name)) add("declared-events", check.entry, `Action "${service.name}.${action.name}" emits "${name}", which is not in ${service.name}'s event catalog.`);
287
- const folder = [kebabCase(service.name), service.name].map((name) => resolve(check.services, name)).find(existsSync);
264
+ const declared = (name) => names.has(name) || isCrudEvent(name, resources);
265
+ for (const action of service.listActions()) for (const name of action.config.emits ?? []) if (!declared(name)) add(check.entry, `Action "${service.name}.${action.name}" emits "${name}", which is not in ${service.name}'s event catalog.`);
266
+ const folder = serviceFolders(service.name).map((name) => resolve(check.services, name)).find(existsSync);
288
267
  for (const file of folder ? sourceFiles(check, folder) : []) {
289
268
  const source = readFileSync(file, "utf8");
290
- for (const match of source.matchAll(/emitEvent\s*\([^,]+,\s*["'`]([^"'`]+)["'`]/g)) if (!declared(match[1])) add("declared-events", file, `"${match[1]}" is not in ${service.name}'s event catalog.`, lineOf(source, match.index));
269
+ for (const match of source.matchAll(/emitEvent\s*\([^,]+,\s*["'`]([^"'`]+)["'`]/g)) if (!declared(match[1])) add(file, `"${match[1]}" is not in ${service.name}'s event catalog.`, lineOf(source, match.index));
291
270
  }
292
271
  }
293
272
  }
294
- function testColocated(check, add) {
295
- if (check.severity("test-colocated") === "off") return;
273
+ function testColocated(check, _app, add) {
296
274
  for (const file of sourceFiles(check, check.services)) {
297
- const match = /^(.*)\.(action|command)\.[cm]?tsx?$/.exec(basename(file));
298
- if (!match) continue;
299
- const test = resolve(dirname(file), `${match[1]}.test.ts`);
300
- if (!existsSync(test) && !existsSync(`${test}x`)) add("test-colocated", file, `${basename(file)} has no ${match[1]}.test.ts beside it.`);
275
+ const match = DEFINITION_FILE.exec(basename(file));
276
+ if (match?.[2] !== "action" && match?.[2] !== "command") continue;
277
+ if (!readdirSync(dirname(file)).some((sibling) => TEST_FILE.test(sibling) && sibling.replace(TEST_FILE, "") === match[1])) add(file, `${basename(file)} has no ${match[1]}.test.ts beside it.`);
278
+ }
279
+ }
280
+ // src/db.ts
281
+ /**
282
+ * The app's databases and their tables: those passed to `defineDatabase`
283
+ * (outbox tables included), resource tables, and the tables plugins own.
284
+ * Throws when two handles share a name, since the name picks the migrations folder.
285
+ */
286
+ function appDatabases(app) {
287
+ const found = /* @__PURE__ */ new Map();
288
+ for (const service of app.definition.services) {
289
+ const database = service.getDatabaseHandle?.();
290
+ if (!database) continue;
291
+ let entry = found.get(database);
292
+ if (!entry) {
293
+ entry = {
294
+ name: database.name ?? service.name,
295
+ services: 0,
296
+ tables: /* @__PURE__ */ new Set()
297
+ };
298
+ found.set(database, entry);
299
+ }
300
+ entry.services++;
301
+ for (const table of [...Object.values(database.tables), ...service.tables.values()]) entry.tables.add(table);
302
+ }
303
+ const databases = [...found].filter(([, entry]) => entry.tables.size > 0);
304
+ const names = /* @__PURE__ */ new Map();
305
+ for (const [database, entry] of databases) {
306
+ if (!database.name && entry.services > 1) throw new Error(`Brick: services share a database without a name, so its migrations folder would follow service order; give it \`defineDatabase({ name })\`.`);
307
+ if (names.has(entry.name)) throw new Error(`Brick: two databases are named "${entry.name}"; give each \`defineDatabase({ name })\` its own name, or share one handle between the services.`);
308
+ names.set(entry.name, database);
309
+ }
310
+ return databases.map(([database, entry]) => ({
311
+ name: entry.name,
312
+ database,
313
+ tables: [...entry.tables]
314
+ }));
315
+ }
316
+ /** Run `brick db generate|migrate|push` against every database of the app. */
317
+ async function runDbCommand(command, app, options) {
318
+ const databases = appDatabases(app);
319
+ if (!databases.length) throw new Error("Brick: the app has no database with tables.");
320
+ try {
321
+ if (command === "migrate") for (const entry of databases) {
322
+ const folder = join(options.out, entry.name);
323
+ if (!existsSync(join(folder, "meta", "_journal.json"))) throw new Error(`Brick: no migrations in ${folder}; run \`brick db generate\` first.`);
324
+ }
325
+ for (const entry of databases) {
326
+ const folder = join(options.out, entry.name);
327
+ const label = `${entry.name} (${entry.database.engine})`;
328
+ if (command === "generate") {
329
+ const file = await generate(entry, folder, options.name);
330
+ console.log(file ? `${label}: wrote ${file}` : `${label}: no schema changes`);
331
+ } else if (command === "migrate") {
332
+ await migrateDatabase(entry.database, folder);
333
+ console.log(`${label}: migrations in ${folder} applied`);
334
+ } else {
335
+ const applied = await push(entry, options.force ?? false);
336
+ console.log(applied ? `${label}: applied ${applied} change${applied === 1 ? "" : "s"}` : `${label}: no schema changes`);
337
+ }
338
+ }
339
+ } finally {
340
+ await Promise.all(databases.map((entry) => entry.database.close?.()));
341
+ }
342
+ }
343
+ const kit = () => import("drizzle-kit/api");
344
+ /**
345
+ * Diff the tables against the folder's last snapshot with drizzle-kit and write
346
+ * the SQL, snapshot and journal in drizzle-kit's layout, so drizzle-kit and
347
+ * Drizzle's migrator read the folder too. Returns the SQL file, if any.
348
+ */
349
+ async function generate(entry, folder, name = "migration") {
350
+ const { generateDrizzleJson, generateMigration, ...sqlite } = await kit();
351
+ const postgres = entry.database.engine === "postgres";
352
+ const meta = join(folder, "meta");
353
+ const journalFile = join(meta, "_journal.json");
354
+ const journal = existsSync(journalFile) ? JSON.parse(readFileSync(journalFile, "utf8")) : {
355
+ version: "7",
356
+ dialect: postgres ? "postgresql" : "sqlite",
357
+ entries: []
358
+ };
359
+ const last = journal.entries.at(-1);
360
+ const idx = last ? last.idx + 1 : 0;
361
+ const prev = last ? JSON.parse(readFileSync(join(meta, `${last.tag.slice(0, 4)}_snapshot.json`), "utf8")) : void 0;
362
+ const schema = drizzleSchema(entry.tables);
363
+ let cur;
364
+ let statements;
365
+ if (postgres) {
366
+ const next = generateDrizzleJson(schema, prev?.id);
367
+ statements = await generateMigration(prev ?? generateDrizzleJson({}), next);
368
+ cur = next;
369
+ } else {
370
+ const next = await sqlite.generateSQLiteDrizzleJson(schema, prev?.id);
371
+ statements = await sqlite.generateSQLiteMigration(prev ?? await sqlite.generateSQLiteDrizzleJson({}), next);
372
+ cur = next;
301
373
  }
374
+ if (!statements.length) return void 0;
375
+ const prefix = String(idx).padStart(4, "0");
376
+ const tag = `${prefix}_${name}`;
377
+ mkdirSync(meta, { recursive: true });
378
+ const file = join(folder, `${tag}.sql`);
379
+ writeFileSync(file, statements.join("\n--> statement-breakpoint\n"));
380
+ writeFileSync(join(meta, `${prefix}_snapshot.json`), JSON.stringify(cur, null, 2));
381
+ journal.entries.push({
382
+ idx,
383
+ version: cur.version,
384
+ when: Date.now(),
385
+ tag,
386
+ breakpoints: true
387
+ });
388
+ writeFileSync(journalFile, JSON.stringify(journal, null, 2));
389
+ return file;
302
390
  }
303
- //#endregion
304
- //#region src/bin.ts
305
- const CLI_VERSION = "0.11.0";
306
- const PORT_HELP = "Port to listen on (CLI --port overrides PORT env, default 4000)";
391
+ /**
392
+ * Make the database match the tables with drizzle-kit's push, touching only
393
+ * the tables Brick knows. Returns how many statements ran.
394
+ */
395
+ async function push(entry, force) {
396
+ const { pushSchema, pushSQLiteSchema } = await kit();
397
+ const db = entry.database.getDb();
398
+ const names = new Set(entry.tables.map((table) => getTableName(table)));
399
+ const schema = drizzleSchema(entry.tables);
400
+ const postgres = entry.database.engine === "postgres";
401
+ const result = postgres ? await pushSchema(schema, { execute: async (query) => ({ rows: await db.execute(query) }) }, [...new Set(entry.tables.map((table) => table[Symbol.for("drizzle:Schema")] ?? "public"))], [...names]) : await pushSQLiteSchema(schema, onlyTables(db, names));
402
+ const statements = result.statementsToExecute;
403
+ if (!statements.length) return 0;
404
+ for (const warning of result.warnings) console.log(warning);
405
+ if (result.hasDataLoss && !force) throw new Error(`Brick: pushing ${entry.name} would lose data (see above). Rerun with --force to apply it, or use \`brick db generate\` and edit the migration.`);
406
+ if (postgres) await db.transaction(async (tx) => {
407
+ for (const statement of statements) await tx.execute(sql.raw(statement));
408
+ });
409
+ else await result.apply();
410
+ return statements.length;
411
+ }
412
+ /**
413
+ * drizzle-kit's SQLite push has no table filter: hide the tables Brick does not
414
+ * know (FTS sidecars, other apps' tables) from what it reads, so it neither
415
+ * drops them nor asks whether a new table renames one.
416
+ */
417
+ function onlyTables(db, names) {
418
+ return {
419
+ all: (query) => db.all(query).filter((row) => {
420
+ const table = row.tableName ?? row.tableFrom ?? row.tbl_name ?? row.view_name;
421
+ return table === void 0 || names.has(table);
422
+ }),
423
+ run: (query) => db.run(query)
424
+ };
425
+ }
426
+ // src/bin.ts
427
+ const CLI_VERSION = version;
428
+ const PORT_HELP = `Port to listen on (CLI --port overrides PORT env, default ${DEFAULT_PORT})`;
307
429
  const EXTENSION_HELP = "Dashboard extension module (default export defineDashboard(...)), or the dashboard folder brick build wrote";
308
430
  const PORT_RESOLUTION_HELP = `
309
431
  Port Resolution (dev/start commands):
310
432
  - CLI --port flag takes precedence
311
433
  - Falls back to PORT environment variable
312
434
  - Then dev.port in brick.config.ts (brick dev only)
313
- - Defaults to 4000 if none is set
435
+ - Defaults to ${DEFAULT_PORT} if none is set
314
436
  - Valid range: 1-65535
315
437
 
316
438
  Examples:
@@ -322,7 +444,7 @@ Examples:
322
444
  const CONFIG_HELP = "Path to brick.config.ts (default: the nearest one in this folder or its parents)";
323
445
  function parsePortOption(value) {
324
446
  try {
325
- return parsePort(value, void 0);
447
+ return resolvePort(value);
326
448
  } catch (err) {
327
449
  throw new InvalidArgumentError(err.message);
328
450
  }
@@ -336,13 +458,16 @@ function parseFileOption(value, usage) {
336
458
  if (value.startsWith("-")) throw new InvalidArgumentError(`${usage} (got flag-like value '${value}')`);
337
459
  return value;
338
460
  }
339
- /** `--config` on a `gen` subcommand: commander hands it to `gen`, which takes it too. */
340
- function configOf(command) {
341
- return command.optsWithGlobals().config;
461
+ /** The project of the program-level `--config`, else the nearest config file. */
462
+ function projectOf(command) {
463
+ return resolveProject(command.optsWithGlobals().config);
342
464
  }
343
- /** The entry argument, else the config's entry; without either, commander's usual error. */
465
+ function entryOf(entry, project) {
466
+ return entry ?? (project.file ? project.entry : void 0);
467
+ }
468
+ /** Without an entry argument or config entry, commander's usual error. */
344
469
  function requireEntry(command, entry, project) {
345
- const resolved = entry ?? project?.entry;
470
+ const resolved = entryOf(entry, project);
346
471
  if (!resolved) command.error("error: missing required argument 'entry'", {
347
472
  exitCode: 1,
348
473
  code: "commander.missingArgument"
@@ -351,16 +476,15 @@ function requireEntry(command, entry, project) {
351
476
  }
352
477
  /** Load the app after refreshing the services manifest it imports. */
353
478
  async function loadProjectApp(entry, project) {
354
- if (project) await writeServiceManifest(project);
479
+ if (project.file) await writeServiceManifest(project);
355
480
  return loadBrickApp(entry);
356
481
  }
357
- /** A config path, made absolute from the config file's folder. */
358
482
  function fromRoot(project, path) {
359
- return path && project ? resolve(project.root, path) : path;
483
+ return path && resolve(project.root, path);
360
484
  }
361
485
  /** The config's dashboard settings; a `--dashboard-extension` flag replaces its extension. */
362
486
  function configDashboard(project, extensionFlag) {
363
- const dashboard = project?.config.dashboard;
487
+ const dashboard = project.config.dashboard;
364
488
  if (!dashboard && !extensionFlag) return void 0;
365
489
  return {
366
490
  extension: extensionFlag ?? fromRoot(project, dashboard?.extension),
@@ -369,78 +493,55 @@ function configDashboard(project, extensionFlag) {
369
493
  }
370
494
  async function writeOpenApi(entry, output, project) {
371
495
  const app = await loadProjectApp(entry, project);
372
- const spec = generateOpenApiSpec({
373
- services: [...app.definition.services],
374
- prefix: app.definition.prefix
375
- });
376
- const json = JSON.stringify(spec, null, 2);
496
+ const json = JSON.stringify(app.openApiDocument(), null, 2);
377
497
  if (output) await Bun.write(output, json);
378
498
  return json;
379
499
  }
380
500
  function createProgram() {
381
501
  const program = new Command();
382
- program.name("brick").description("🧱 Brick-TS CLI").version(CLI_VERSION).showHelpAfterError().addHelpText("after", `
383
- Usage:
384
- brick dev [entry] [--port <number>] [--dashboard-port <number>] [--history-days <number>] [--no-dashboard] Start development server with live reload and dashboard
385
- brick start [entry] [--port <number>] Start production server
386
- brick worker <entry> Deliver events without serving HTTP
387
- brick build <app.ts> [--outdir <dir>] [--port <number>] [--no-aot] Compile a default-exported BrickApp into a Bun server
388
- brick gen openapi <entry> [--output <file>] Generate OpenAPI 3.1 JSON specification
389
- brick gen client <entry> [--output <file>] Generate a typed browser client contract
390
- brick gen manifest Write <generated>/services.gen.ts
391
- brick lint [entry] Check the project against the Brick lint rules
392
- brick info <entry> Export architecture JSON schema
393
-
394
- With a brick.config.ts, the entry and most flags come from the config file,
395
- and every command takes --config <path>.
502
+ program.name("brick").description("🧱 Brick-TS CLI").version(CLI_VERSION).showHelpAfterError().configureHelp({ showGlobalOptions: true }).option("--config <path>", CONFIG_HELP).addHelpText("after", `
503
+ With a brick.config.ts, the entry and most flags come from the config file.
396
504
  ${PORT_RESOLUTION_HELP}`);
397
- program.command("dev").description("Start development server with live reload").option("--client <file>", "Generate and watch a browser contract before startup").option("--frontend <command>", "Start frontend after contract generation; requires --client").option("--dashboard-port <number>", `Port for the local dashboard (default ${DEFAULT_DASHBOARD_PORT})`, parsePortOption).option("--history-days <number>", `Days of requests the dashboard keeps on disk, 0 for none (default 90)`, parseHistoryDays).option("--no-dashboard", "Do not start the local dashboard").option("--dashboard-extension <file>", EXTENSION_HELP).argument("[entry]", "Application entry file").option("--port <number>", PORT_HELP, parsePortOption).option("--config <path>", CONFIG_HELP).addHelpText("after", PORT_RESOLUTION_HELP).action(async (entryArg, opts) => {
398
- const project = await loadConfig(opts.config);
399
- const config = project?.config;
400
- const entry = entryArg ?? project?.entry;
401
- const port = resolveDevPort(opts.port, config?.dev?.port);
402
- if (opts.dashboard === false && opts.dashboardPort !== void 0) throw new Error("Brick: --dashboard-port cannot be combined with --no-dashboard.");
403
- if (opts.dashboard === false && opts.historyDays !== void 0) throw new Error("Brick: --history-days cannot be combined with --no-dashboard.");
404
- const configured = config?.dev?.dashboard;
405
- const dashboardOff = opts.dashboard === false || configured === false && opts.dashboardPort === void 0 && opts.historyDays === void 0;
406
- const dashboardConfig = configured || void 0;
407
- if (dashboardOff && opts.dashboardExtension) throw new Error("Brick: --dashboard-extension cannot be combined with --no-dashboard.");
505
+ program.command("dev").description("Start development server with live reload").option("--client <file>", "Generate and watch a browser contract before startup").option("--frontend <command>", "Start frontend after contract generation; requires --client").option("--dashboard-port <number>", `Port for the local dashboard (default ${DEFAULT_DASHBOARD_PORT})`, parsePortOption).option("--history-days <number>", `Days of requests the dashboard keeps on disk, 0 for none (default 90)`, parseHistoryDays).option("--no-dashboard", "Do not start the local dashboard").option("--dashboard-extension <file>", EXTENSION_HELP).argument("[entry]", "Application entry file").option("--port <number>", PORT_HELP, parsePortOption).addHelpText("after", PORT_RESOLUTION_HELP).action(async (entryArg, opts, command) => {
506
+ const project = await projectOf(command);
507
+ const { config } = project;
508
+ const entry = entryOf(entryArg, project);
509
+ const port = resolvePort(opts.port, config.dev?.port);
510
+ const dashboard = resolveDevDashboard(config.dev?.dashboard, opts);
408
511
  await startDevServer({
409
512
  entry,
410
513
  port,
411
- clientOutput: opts.client ?? fromRoot(project, config?.client?.output),
412
- frontend: opts.frontend ?? config?.dev?.frontend,
413
- dashboard: entry && !dashboardOff ? {
414
- port: opts.dashboardPort ?? dashboardConfig?.port ?? 9400,
415
- historyDays: opts.historyDays ?? dashboardConfig?.historyDays,
514
+ clientOutput: opts.client ?? fromRoot(project, config.client?.output),
515
+ frontend: opts.frontend ?? config.dev?.frontend,
516
+ dashboard: entry && dashboard ? {
517
+ ...dashboard,
416
518
  ...configDashboard(project, opts.dashboardExtension)
417
519
  } : false,
418
- manifest: project
520
+ manifest: project.file ? project : void 0
419
521
  });
420
522
  });
421
- program.command("start").description("Start production server").argument("[entry]", "Application entry file").option("--port <number>", PORT_HELP, parsePortOption).option("--dashboard-extension <file>", EXTENSION_HELP).option("--config <path>", CONFIG_HELP).addHelpText("after", PORT_RESOLUTION_HELP).action(async (entry, opts) => {
422
- const project = await loadConfig(opts.config);
423
- const port = resolveDevPort(opts.port);
523
+ program.command("start").description("Start production server").argument("[entry]", "Application entry file").option("--port <number>", PORT_HELP, parsePortOption).option("--dashboard-extension <file>", EXTENSION_HELP).addHelpText("after", PORT_RESOLUTION_HELP).action(async (entry, opts, command) => {
524
+ const project = await projectOf(command);
424
525
  await startProdServer({
425
- entry: entry ?? project?.entry,
426
- port,
526
+ entry: entryOf(entry, project),
527
+ port: resolvePort(opts.port),
427
528
  dashboard: configDashboard(project, opts.dashboardExtension)
428
529
  });
429
530
  });
430
- program.command("worker").description("Deliver the app's events without serving HTTP").argument("[entry]", "Application entry file (must default-export a BrickApp)").option("--config <path>", CONFIG_HELP).action(async (entry, opts, command) => {
431
- const project = await loadConfig(opts.config);
531
+ program.command("worker").description("Deliver the app's events without serving HTTP").argument("[entry]", "Application entry file (must default-export a BrickApp)").action(async (entry, _opts, command) => {
532
+ const project = await projectOf(command);
432
533
  await startWorker({ entry: requireEntry(command, entry, project) });
433
534
  });
434
- program.command("build").description("Compile a default-exported BrickApp into a Bun server").argument("[entry]", "Application entry file (must default-export a BrickApp)").option("--config <path>", CONFIG_HELP).option("--outdir <dir>", "Output directory", (v) => parseFileOption(v, "Usage: brick build <app.ts> [--outdir <directory>]")).option("--port <number>", "Default listening port", parsePortOption).option("--no-aot", "Disable ahead-of-time compilation").option("--dashboard-extension <file>", "Dashboard extension module to build into <outdir>/dashboard").option("--prefix <path>", "DEPRECATED: configure prefix in brick() app instead").option("--no-request-logging", "DEPRECATED: configure requestLogging in brick() app instead").action(async (entryArg, opts, command) => {
435
- if (opts.prefix !== void 0 || opts.requestLogging === false) throw new Error("Brick: configure prefix and requestLogging in your default-exported brick() app instead of build flags.");
436
- const project = await loadConfig(opts.config);
437
- const build = project?.config.build;
438
- if (build?.requestLogging === false) throw new Error("Brick: configure requestLogging in your default-exported brick() app instead of build.requestLogging.");
535
+ program.command("build").description("Compile a default-exported BrickApp into a Bun server").argument("[entry]", "Application entry file (must default-export a BrickApp)").option("--outdir <dir>", "Output directory", (v) => parseFileOption(v, "Usage: brick build <app.ts> [--outdir <directory>]")).option("--port <number>", "Default listening port", parsePortOption).option("--no-aot", "Disable ahead-of-time compilation").option("--dashboard-extension <file>", "Dashboard extension module to build into <outdir>/dashboard").option("--prefix <path>", "DEPRECATED: configure prefix in brick() app instead").option("--no-request-logging", "DEPRECATED: configure requestLogging in brick() app instead").action(async (entryArg, opts, command) => {
536
+ if (opts.prefix !== void 0 || opts.requestLogging === false) throw new ConfigError("Brick: configure prefix and requestLogging in your default-exported brick() app instead of build flags.");
537
+ const project = await projectOf(command);
538
+ const build = project.config.build;
539
+ if (build?.requestLogging === false) throw new ConfigError("Brick: configure requestLogging in your default-exported brick() app instead of build.requestLogging.");
439
540
  const entry = requireEntry(command, entryArg, project);
440
- if (project) await writeServiceManifest(project);
541
+ if (project.file) await writeServiceManifest(project);
441
542
  const result = await buildApplication({
442
543
  entry,
443
- outdir: opts.outdir ?? fromRoot(project, build?.outdir),
544
+ outdir: opts.outdir ?? project.outdir,
444
545
  port: opts.port,
445
546
  aot: opts.aot === false ? false : build?.aot,
446
547
  dashboard: configDashboard(project, opts.dashboardExtension)
@@ -451,18 +552,17 @@ ${PORT_RESOLUTION_HELP}`);
451
552
  if (result.dashboard) console.log(`Dashboard extension: ${result.dashboard}`);
452
553
  console.log(`Run: bun ${result.entry}`);
453
554
  });
454
- const gen = program.command("gen").description("Generate artifacts from a BrickApp entry").argument("[subcommand]", "Generator to run (openapi, client, manifest)").option("--config <path>", CONFIG_HELP).action(async (subcommand, opts) => {
455
- const project = subcommand === void 0 ? await loadConfig(opts.config) : void 0;
456
- if (!project) {
555
+ const gen = program.command("gen").description("Generate artifacts from a BrickApp entry").argument("[subcommand]", "Generator to run (openapi, client, manifest)").action(async (subcommand, _opts, command) => {
556
+ const project = await projectOf(command);
557
+ if (subcommand !== void 0 || !project.file) {
457
558
  console.error(`Unknown generator: ${subcommand ?? "(none)"}. Available: openapi, client, manifest`);
458
559
  process.exit(1);
459
560
  }
460
561
  const manifest = await writeServiceManifest(project);
461
562
  console.log(`Services manifest written to ${manifest}`);
462
- const client = fromRoot(project, project.config.client?.output);
463
- if (client) {
464
- await writeClientContract(project.entry, client);
465
- console.log(`Client contract written to ${client}`);
563
+ if (project.config.client?.output) {
564
+ await writeClientContract(project.entry, project.contract);
565
+ console.log(`Client contract written to ${project.contract}`);
466
566
  }
467
567
  const openapi = fromRoot(project, project.config.openapi?.output);
468
568
  if (openapi) {
@@ -470,37 +570,47 @@ ${PORT_RESOLUTION_HELP}`);
470
570
  console.log(`✅ OpenAPI 3.1 specification written to ${openapi}`);
471
571
  }
472
572
  });
473
- gen.command("openapi").description("Generate OpenAPI 3.1 JSON specification").argument("[entry]", "Application entry file").option("--config <path>", CONFIG_HELP).option("--output <file>", "Write specification to file instead of stdout", (v) => parseFileOption(v, "Usage: brick gen openapi <entry> [--output <file>]")).action(async (entry, opts, command) => {
474
- const project = await loadConfig(configOf(command));
475
- const output = opts.output ?? fromRoot(project, project?.config.openapi?.output);
573
+ gen.command("openapi").description("Generate OpenAPI 3.1 JSON specification").argument("[entry]", "Application entry file").option("--output <file>", "Write specification to file instead of stdout", (v) => parseFileOption(v, "Usage: brick gen openapi <entry> [--output <file>]")).action(async (entry, opts, command) => {
574
+ const project = await projectOf(command);
575
+ const output = opts.output ?? fromRoot(project, project.config.openapi?.output);
476
576
  const json = await writeOpenApi(requireEntry(command, entry, project), output, project);
477
577
  if (output) console.log(`✅ OpenAPI 3.1 specification written to ${output}`);
478
578
  else console.log(json);
479
579
  });
480
- gen.command("client").description("Generate a typed browser client contract").argument("[entry]", "Application entry file").option("--config <path>", CONFIG_HELP).option("--output <file>", "Write contract to file (default _brick/contract.ts)", (v) => parseFileOption(v, "Usage: brick gen client <entry> [--output <file>]")).action(async (entry, opts, command) => {
481
- const project = await loadConfig(configOf(command));
580
+ gen.command("client").description("Generate a typed browser client contract").argument("[entry]", "Application entry file").option("--output <file>", "Write contract to file (default _brick/contract.ts)", (v) => parseFileOption(v, "Usage: brick gen client <entry> [--output <file>]")).action(async (entry, opts, command) => {
581
+ const project = await projectOf(command);
482
582
  const target = requireEntry(command, entry, project);
483
- if (project) await writeServiceManifest(project);
484
- const output = await writeClientContract(target, opts.output ?? fromRoot(project, project?.config.client?.output) ?? (project && join(project.generated, "contract.ts")));
583
+ if (project.file) await writeServiceManifest(project);
584
+ const output = await writeClientContract(target, opts.output ?? project.contract);
485
585
  console.log(`Client contract written to ${output}`);
486
586
  });
487
- gen.command("manifest").description("Write <generated>/services.gen.ts, which imports every definition file").option("--config <path>", CONFIG_HELP).action(async (_opts, command) => {
488
- const project = await loadConfig(configOf(command));
489
- const output = await writeServiceManifest(project ?? {
490
- services: resolve("src/services"),
491
- generated: resolve("_brick")
492
- });
587
+ gen.command("manifest").description("Write <generated>/services.gen.ts, which imports every definition file").action(async (_opts, command) => {
588
+ const output = await writeServiceManifest(await projectOf(command));
493
589
  console.log(`Services manifest written to ${output}`);
494
590
  });
495
- program.command("lint").description("Check the project against the Brick lint rules").argument("[entry]", "Application entry file").option("--config <path>", CONFIG_HELP).action(async (entry, opts) => {
591
+ const db = program.command("db").description("Manage the app's database schema with drizzle-kit: generate, migrate, push");
592
+ const dbCommand = (name, description) => db.command(name).description(description).argument("[entry]", "Application entry file");
593
+ const OUT_HELP = "Migrations folder (default drizzle, beside brick.config.ts); each database gets a subfolder named after it";
594
+ const dbAction = (name) => async (entry, opts, command) => {
595
+ const project = await projectOf(command);
596
+ await runDbCommand(name, await loadProjectApp(requireEntry(command, entry, project), project), {
597
+ out: opts.out ?? fromRoot(project, "drizzle"),
598
+ name: opts.name,
599
+ force: opts.force
600
+ });
601
+ };
602
+ dbCommand("generate", "Write a SQL migration for the schema changes since the last one").option("--out <dir>", OUT_HELP).option("--name <name>", "Migration name (default migration)").action(dbAction("generate"));
603
+ dbCommand("migrate", "Apply the migrations that have not run yet").option("--out <dir>", OUT_HELP).action(dbAction("migrate"));
604
+ dbCommand("push", "Change the database to match the schema directly, without migration files (development)").option("--force", "Apply changes that drop data").action(dbAction("push"));
605
+ program.command("lint").description("Check the project against the Brick lint rules").argument("[entry]", "Application entry file").action(async (entry, _opts, command) => {
496
606
  const code = await runLint({
497
607
  entry,
498
- project: await loadConfig(opts.config)
608
+ project: await projectOf(command)
499
609
  });
500
610
  if (code !== 0) process.exit(code);
501
611
  });
502
- program.command("info").alias("services").description("Export architecture JSON schema").argument("[entry]", "Application entry file").option("--config <path>", CONFIG_HELP).action(async (entry, opts, command) => {
503
- const project = await loadConfig(opts.config);
612
+ program.command("info").alias("services").description("Export architecture JSON schema").argument("[entry]", "Application entry file").action(async (entry, _opts, command) => {
613
+ const project = await projectOf(command);
504
614
  const app = await loadProjectApp(requireEntry(command, entry, project), project);
505
615
  const architecture = getGlobalRegistry().exportArchitecture(app.definition);
506
616
  console.log(JSON.stringify(architecture, null, 2));
@@ -508,18 +618,7 @@ ${PORT_RESOLUTION_HELP}`);
508
618
  return program;
509
619
  }
510
620
  async function main() {
511
- const program = createProgram();
512
- const userArgs = process.argv.slice(2);
513
- if (userArgs.length === 0 && await loadConfig()) {
514
- await program.parseAsync([...process.argv, "dev"]);
515
- return;
516
- }
517
- if (userArgs.length === 0) {
518
- const port = parsePort(void 0, process.env.PORT);
519
- await startDevServer({ port });
520
- return;
521
- }
522
- await program.parseAsync(process.argv);
621
+ await createProgram().parseAsync(process.argv.length > 2 ? process.argv : [...process.argv, "dev"]);
523
622
  }
524
623
  main().catch((err) => {
525
624
  if (err?.exitCode !== void 0) process.exit(err.exitCode);
@@ -531,7 +630,6 @@ main().catch((err) => {
531
630
  console.error("Fatal error:", err);
532
631
  process.exit(1);
533
632
  });
534
- //#endregion
535
633
  export { createProgram };
536
634
 
537
635
  //# sourceMappingURL=bin.js.map