@brickkit/cli 0.10.0 → 0.11.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 (76) hide show
  1. package/README.md +1 -1
  2. package/dashboard-dist/CollapsiblePanel-BX79_W-b.js +2 -0
  3. package/dashboard-dist/CompositeRoot-xzybXjnx.js +1 -0
  4. package/dashboard-dist/PopoverPopup-CvlmC7EL.js +1 -0
  5. package/dashboard-dist/{api-reference-r893F8zi.js → api-reference-BcAYVYwJ.js} +8 -8
  6. package/dashboard-dist/app.css +1 -1
  7. package/dashboard-dist/app.js +13 -13
  8. package/dashboard-dist/core-BGO9JZ1r.js +1 -0
  9. package/dashboard-dist/docs-DHikPD2v.js +4 -0
  10. package/dashboard-dist/kit.js +1 -0
  11. package/dashboard-dist/popover-DG498XHH.js +1 -0
  12. package/dashboard-dist/react-dom-client.js +3 -0
  13. package/dashboard-dist/react-dom.js +3 -0
  14. package/dashboard-dist/react-jsx-runtime.js +1 -1
  15. package/dashboard-dist/react.js +3 -3
  16. package/dashboard-dist/theme.css +123 -0
  17. package/dist/bin.d.ts.map +1 -1
  18. package/dist/bin.js +440 -44
  19. package/dist/bin.js.map +1 -1
  20. package/dist/client-contract-file2.js +1 -1
  21. package/dist/client-contract2.js +12 -6
  22. package/dist/client-contract2.js.map +1 -1
  23. package/dist/config.js +252 -0
  24. package/dist/config.js.map +1 -0
  25. package/dist/dashboard-extension.d.ts +27 -0
  26. package/dist/dashboard-extension.d.ts.map +1 -0
  27. package/dist/dashboard.d.ts +3127 -0
  28. package/dist/dev-telemetry-store.js +1407 -952
  29. package/dist/dev-telemetry-store.js.map +1 -1
  30. package/dist/dev-worker.js +2 -2
  31. package/dist/index.d.ts +95 -6
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +4 -4
  34. package/dist/lint/eslint.d.ts +2 -0
  35. package/dist/lint/eslint.js +1 -0
  36. package/dist/lint/oxlint.d.ts +19 -0
  37. package/dist/lint/oxlint.d.ts.map +1 -0
  38. package/dist/lint/oxlint.js +19 -0
  39. package/dist/lint/oxlint.js.map +1 -0
  40. package/dist/plugin.d.ts +76 -0
  41. package/dist/plugin.d.ts.map +1 -0
  42. package/dist/plugin.js +66 -0
  43. package/dist/plugin.js.map +1 -0
  44. package/dist/presets.js +1070 -0
  45. package/dist/presets.js.map +1 -0
  46. package/dist/runner.js +112 -26
  47. package/dist/runner.js.map +1 -1
  48. package/dist/vite.d.ts +6 -3
  49. package/dist/vite.d.ts.map +1 -1
  50. package/dist/vite.js +9 -3
  51. package/dist/vite.js.map +1 -1
  52. package/dist/workflows2.js +1 -1
  53. package/inspector-dist/client/assets/app-CvoGgWcV.css +1 -0
  54. package/inspector-dist/client/assets/{manifest-4baa7c6f.js → manifest-139c9319.js} +1 -1
  55. package/inspector-dist/client/assets/root-BMHd_XHz.css +1 -0
  56. package/inspector-dist/server/assets/{app-C-ZVJtic.js → app-DUP5RybL.js} +11 -11
  57. package/inspector-dist/server/assets/{highlighted-body-B3W2YXNL-C8sq8F_D.js → highlighted-body-B3W2YXNL-D2g4hL2-.js} +1 -1
  58. package/inspector-dist/server/assets/{index-CYlmUaKx.js → index-D71yP6AL.js} +2 -2
  59. package/inspector-dist/server/assets/{index-CWJr34WJ.js → index-wGSWRns3.js} +1 -1
  60. package/inspector-dist/server/assets/{mermaid-3ZIDBTTL-Dv5rjfMN.js → mermaid-3ZIDBTTL-DsvuKoEV.js} +1 -1
  61. package/inspector-dist/server/assets/{token-DnLp3wBO.js → token-ClUZZwXl.js} +1 -1
  62. package/inspector-dist/server/assets/{token-util-Bpfp-B0w.js → token-util-DSxMZ6nI.js} +1 -1
  63. package/inspector-dist/server/assets/{wrapper-D5LIcZ_u.js → wrapper-B3vstpCO.js} +2 -2
  64. package/inspector-dist/server/assets/{zstd-browser-decoder-BM8GpVB8.js → zstd-browser-decoder-Dn82m2BU.js} +1 -1
  65. package/inspector-dist/server/index.js +1 -1
  66. package/package.json +30 -6
  67. package/dashboard-dist/CollapsiblePanel-a54TwMKb.js +0 -2
  68. package/dashboard-dist/PopoverPopup-BLzjTqsi.js +0 -1
  69. package/dashboard-dist/core-BWAwhSFf.js +0 -1
  70. package/dashboard-dist/docs-CkMy3Y5i.js +0 -4
  71. package/dashboard-dist/preload-helper-CjQDFR0M.js +0 -1
  72. package/dist/build.js +0 -119
  73. package/dist/build.js.map +0 -1
  74. package/inspector-dist/client/assets/app-CY7CQBRo.css +0 -1
  75. package/inspector-dist/client/assets/root-CfCr265_.css +0 -1
  76. /package/inspector-dist/client/assets/{root-Bmn5n3jF.js → root-cbi6iYwg.js} +0 -0
package/dist/bin.js CHANGED
@@ -1,20 +1,316 @@
1
1
  #!/usr/bin/env bun
2
- import { r as DEFAULT_DASHBOARD_PORT } from "./dev-telemetry-store.js";
3
- import { a as parsePort, i as startWorker, n as startDevServer, r as startProdServer } from "./runner.js";
4
- import { t as buildApplication } from "./build.js";
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";
5
4
  import { t as loadBrickApp } from "./app-entry2.js";
6
5
  import { t as writeClientContract } from "./client-contract-file2.js";
7
- import { generateOpenApiSpec, getGlobalRegistry } from "@brickkit/core";
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";
8
+ import { createRequire } from "node:module";
9
+ import { generateOpenApiSpec, getGlobalRegistry, getPluginActionRoute, kebabCase } from "@brickkit/core";
10
+ import { fileURLToPath } from "node:url";
11
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
12
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
13
  import { Command, InvalidArgumentError } from "commander";
14
+ import { spawnSync } from "node:child_process";
15
+ import { tmpdir } from "node:os";
16
+ //#region src/lint/run.ts
17
+ /** The built lint/oxlint entry, which oxlint loads under Node. */
18
+ function pluginPath() {
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");
21
+ }
22
+ function oxlintBin(root) {
23
+ for (const base of [join(root, "package.json"), fileURLToPath(import.meta.url)]) try {
24
+ const pkg = createRequire(base).resolve("oxlint/package.json");
25
+ return join(dirname(pkg), "bin/oxlint");
26
+ } catch {}
27
+ throw new ConfigError("Brick: brick lint needs oxlint; add it: bun add -d oxlint");
28
+ }
29
+ /**
30
+ * Run the file rules over a project with oxlint, as `brick lint` does.
31
+ * Only rules set to "error" or "warn" run; `ignore` globs are relative to `root`.
32
+ */
33
+ function runFileRules(options) {
34
+ const rules = Object.fromEntries(Object.entries(options.rules).filter(([, severity]) => severity !== "off"));
35
+ if (Object.keys(rules).length === 0) return [];
36
+ const directory = mkdtempSync(join(tmpdir(), "brick-lint-"));
37
+ try {
38
+ const config = join(directory, "oxlintrc.json");
39
+ writeFileSync(config, JSON.stringify({
40
+ plugins: [],
41
+ categories: { correctness: "off" },
42
+ jsPlugins: [{
43
+ name: "brick",
44
+ specifier: pluginPath()
45
+ }],
46
+ settings: { brick: options.settings },
47
+ rules
48
+ }));
49
+ const result = spawnSync(oxlintBin(options.root), [
50
+ "-c",
51
+ config,
52
+ "--format",
53
+ "json",
54
+ "--disable-nested-config",
55
+ "--no-error-on-unmatched-pattern",
56
+ ...options.fix ? ["--fix"] : [],
57
+ ...(options.ignore ?? []).flatMap((pattern) => ["--ignore-pattern", pattern]),
58
+ ...options.paths ?? ["."]
59
+ ], {
60
+ cwd: options.root,
61
+ encoding: "utf8",
62
+ maxBuffer: 67108864
63
+ });
64
+ if (result.error) throw result.error;
65
+ let report;
66
+ try {
67
+ report = JSON.parse(result.stdout);
68
+ } catch {
69
+ throw new Error(`Brick: oxlint failed (exit ${result.status}):\n${result.stderr || result.stdout}`);
70
+ }
71
+ return (report.diagnostics ?? []).map((diagnostic) => ({
72
+ file: diagnostic.filename,
73
+ line: diagnostic.labels?.[0]?.span.line ?? 1,
74
+ column: diagnostic.labels?.[0]?.span.column ?? 1,
75
+ rule: diagnostic.code?.replace(/^brick\((.*)\)$/, "brick/$1") ?? "syntax",
76
+ severity: diagnostic.severity === "error" ? "error" : "warn",
77
+ message: diagnostic.message
78
+ }));
79
+ } finally {
80
+ rmSync(directory, {
81
+ recursive: true,
82
+ force: true
83
+ });
84
+ }
85
+ }
86
+ //#endregion
87
+ //#region src/lint.ts
88
+ const posix$1 = (path) => path.split(sep).join("/");
89
+ const SOURCE = new Bun.Glob("**/*.{ts,tsx,mts,cts}");
90
+ /**
91
+ * `brick lint`: the file rules through oxlint, then the app
92
+ * rules against the loaded app. Prints `file:line:col` lines and returns the
93
+ * exit code: 1 when anything is an error.
94
+ */
95
+ 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)}/**`];
110
+ const messages = runFileRules({
111
+ 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
+ },
120
+ ignore
121
+ });
122
+ const globs = ignore.map((pattern) => new Bun.Glob(pattern));
123
+ if (existsSync(entry)) {
124
+ if (project) await writeServiceManifest(project);
125
+ messages.push(...await checkApp({
126
+ root,
127
+ entry,
128
+ services,
129
+ severity: (rule) => rule === "no-cross-service-tables" ? "error" : resolved[`brick/${rule}`] ?? "off",
130
+ ignored: (rel) => rel.split("/").includes("node_modules") || globs.some((glob) => glob.match(rel))
131
+ }));
132
+ } else if (options.entry || project) throw new Error(`Brick: entry not found: ${entry}`);
133
+ return report(messages);
134
+ }
135
+ function report(messages) {
136
+ messages.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column);
137
+ for (const m of messages) console.log(`${m.file}:${m.line}:${m.column} ${m.severity === "error" ? "error" : "warning"} ${m.message} ${m.rule}`);
138
+ const errors = messages.filter((m) => m.severity === "error").length;
139
+ const warnings = messages.length - errors;
140
+ console.log(messages.length ? `\n✖ ${messages.length} problem${messages.length === 1 ? "" : "s"} (${errors} error${errors === 1 ? "" : "s"}, ${warnings} warning${warnings === 1 ? "" : "s"})` : "✔ No lint problems");
141
+ return errors > 0 ? 1 : 0;
142
+ }
143
+ /** Project source files, from the root, without tests, ignored and generated files. */
144
+ function sourceFiles(check, under = check.root) {
145
+ if (!existsSync(under)) return [];
146
+ return [...SOURCE.scanSync({
147
+ cwd: under,
148
+ onlyFiles: true
149
+ })].map((file) => resolve(under, file)).filter((file) => {
150
+ const rel = posix$1(relative(check.root, file));
151
+ return !check.ignored(rel) && !/\.(test|spec)\.[cm]?tsx?$/.test(rel) && !rel.startsWith("dist/");
152
+ });
153
+ }
154
+ function lineOf(source, index) {
155
+ return source.slice(0, index).split("\n").length;
156
+ }
157
+ /** The app rules: they need the loaded app, so only brick lint runs them. */
158
+ async function checkApp(check) {
159
+ 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
+ };
172
+ let app;
173
+ try {
174
+ app = await loadBrickApp(check.entry);
175
+ } catch (error) {
176
+ const message = error.message;
177
+ if (/duplicate/i.test(message)) {
178
+ add("unique-names", check.entry, message);
179
+ return messages;
180
+ }
181
+ throw error;
182
+ }
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);
188
+ return messages;
189
+ }
190
+ function singleAppEntry(check, files, add) {
191
+ if (check.severity("single-app-entry") === "off") return;
192
+ let calls = 0;
193
+ for (const file of files) {
194
+ const source = readFileSync(file, "utf8");
195
+ if (!/import\s*\{[^}]*\bbrick\b[^}]*\}\s*from\s*["']@brickkit\/core["']/.test(source)) continue;
196
+ for (const match of source.matchAll(/(?<![.\w])brick\s*\(/g)) {
197
+ 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
+ }
200
+ }
201
+ }
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
+ /** Which service owns each table: its resources' and registered tables, or a database it alone uses. */
221
+ function tableOwners(app) {
222
+ const owners = /* @__PURE__ */ new Map();
223
+ const users = /* @__PURE__ */ new Map();
224
+ 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;
227
+ if (database) users.set(database, [...users.get(database) ?? [], service.name]);
228
+ }
229
+ 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]);
231
+ }
232
+ return owners;
233
+ }
234
+ function serviceOfFolder(app, folder) {
235
+ return app.definition.services.find((service) => service.name === folder || kebabCase(service.name) === folder)?.name;
236
+ }
237
+ const IMPORT = /import\s+(type\s+)?([\w$]+\s*,?\s*)?(\*\s+as\s+[\w$]+|\{[^}]*\})?\s*from\s*["']([^"']+)["']/g;
238
+ async function noCrossServiceTables(check, app, add) {
239
+ const owners = tableOwners(app);
240
+ for (const file of sourceFiles(check, check.services)) {
241
+ const folder = posix$1(relative(check.services, file)).split("/")[0];
242
+ const service = serviceOfFolder(app, folder);
243
+ if (!service) continue;
244
+ const source = readFileSync(file, "utf8");
245
+ for (const match of source.matchAll(IMPORT)) {
246
+ const [, typeOnly, defaultName, rest, specifier] = match;
247
+ if (typeOnly || !specifier.startsWith(".")) continue;
248
+ let target;
249
+ try {
250
+ target = Bun.resolveSync(specifier, dirname(file));
251
+ } catch {
252
+ continue;
253
+ }
254
+ const line = lineOf(source, match.index);
255
+ const where = posix$1(relative(check.services, target)).split("/");
256
+ 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);
259
+ continue;
260
+ }
261
+ const module = await import(target).catch(() => ({}));
262
+ const names = [];
263
+ if (defaultName?.trim()) names.push("default");
264
+ if (rest?.startsWith("*")) names.push(...Object.keys(module));
265
+ else if (rest) for (const part of rest.slice(1, -1).split(",")) {
266
+ const name = part.trim().split(/\s+as\s+/)[0];
267
+ if (name && !name.startsWith("type ")) names.push(name);
268
+ }
269
+ for (const name of names) {
270
+ 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);
272
+ }
273
+ }
274
+ }
275
+ }
276
+ function declaredEvents(check, app, add) {
277
+ if (check.severity("declared-events") === "off") return;
278
+ for (const service of app.definition.services) {
279
+ if (!service.options.events) continue;
280
+ const names = new Set(Object.values(service.events).map((e) => e.name));
281
+ 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);
288
+ for (const file of folder ? sourceFiles(check, folder) : []) {
289
+ 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));
291
+ }
292
+ }
293
+ }
294
+ function testColocated(check, add) {
295
+ if (check.severity("test-colocated") === "off") return;
296
+ 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.`);
301
+ }
302
+ }
9
303
  //#endregion
10
304
  //#region src/bin.ts
11
- const CLI_VERSION = "0.10.0";
305
+ const CLI_VERSION = "0.11.0";
12
306
  const PORT_HELP = "Port to listen on (CLI --port overrides PORT env, default 4000)";
307
+ const EXTENSION_HELP = "Dashboard extension module (default export defineDashboard(...)), or the dashboard folder brick build wrote";
13
308
  const PORT_RESOLUTION_HELP = `
14
309
  Port Resolution (dev/start commands):
15
310
  - CLI --port flag takes precedence
16
311
  - Falls back to PORT environment variable
17
- - Defaults to 4000 if neither is set
312
+ - Then dev.port in brick.config.ts (brick dev only)
313
+ - Defaults to 4000 if none is set
18
314
  - Valid range: 1-65535
19
315
 
20
316
  Examples:
@@ -23,6 +319,7 @@ Examples:
23
319
  PORT=3000 brick dev app.ts # port 3000 (from env)
24
320
  brick dev app.ts --port 6000 # port 6000 (CLI overrides PORT=3000)
25
321
  `;
322
+ const CONFIG_HELP = "Path to brick.config.ts (default: the nearest one in this folder or its parents)";
26
323
  function parsePortOption(value) {
27
324
  try {
28
325
  return parsePort(value, void 0);
@@ -39,9 +336,46 @@ function parseFileOption(value, usage) {
39
336
  if (value.startsWith("-")) throw new InvalidArgumentError(`${usage} (got flag-like value '${value}')`);
40
337
  return value;
41
338
  }
42
- function resolveDevPort(cliPort) {
43
- if (cliPort !== void 0) return cliPort;
44
- return parsePort(void 0, process.env.PORT);
339
+ /** `--config` on a `gen` subcommand: commander hands it to `gen`, which takes it too. */
340
+ function configOf(command) {
341
+ return command.optsWithGlobals().config;
342
+ }
343
+ /** The entry argument, else the config's entry; without either, commander's usual error. */
344
+ function requireEntry(command, entry, project) {
345
+ const resolved = entry ?? project?.entry;
346
+ if (!resolved) command.error("error: missing required argument 'entry'", {
347
+ exitCode: 1,
348
+ code: "commander.missingArgument"
349
+ });
350
+ return resolved;
351
+ }
352
+ /** Load the app after refreshing the services manifest it imports. */
353
+ async function loadProjectApp(entry, project) {
354
+ if (project) await writeServiceManifest(project);
355
+ return loadBrickApp(entry);
356
+ }
357
+ /** A config path, made absolute from the config file's folder. */
358
+ function fromRoot(project, path) {
359
+ return path && project ? resolve(project.root, path) : path;
360
+ }
361
+ /** The config's dashboard settings; a `--dashboard-extension` flag replaces its extension. */
362
+ function configDashboard(project, extensionFlag) {
363
+ const dashboard = project?.config.dashboard;
364
+ if (!dashboard && !extensionFlag) return void 0;
365
+ return {
366
+ extension: extensionFlag ?? fromRoot(project, dashboard?.extension),
367
+ theme: dashboard?.theme
368
+ };
369
+ }
370
+ async function writeOpenApi(entry, output, project) {
371
+ 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);
377
+ if (output) await Bun.write(output, json);
378
+ return json;
45
379
  }
46
380
  function createProgram() {
47
381
  const program = new Command();
@@ -53,68 +387,121 @@ Usage:
53
387
  brick build <app.ts> [--outdir <dir>] [--port <number>] [--no-aot] Compile a default-exported BrickApp into a Bun server
54
388
  brick gen openapi <entry> [--output <file>] Generate OpenAPI 3.1 JSON specification
55
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
56
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>.
57
396
  ${PORT_RESOLUTION_HELP}`);
58
- 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").argument("[entry]", "Application entry file").option("--port <number>", PORT_HELP, parsePortOption).addHelpText("after", PORT_RESOLUTION_HELP).action(async (entry, opts) => {
59
- const port = resolveDevPort(opts.port);
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);
60
402
  if (opts.dashboard === false && opts.dashboardPort !== void 0) throw new Error("Brick: --dashboard-port cannot be combined with --no-dashboard.");
61
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.");
62
408
  await startDevServer({
63
409
  entry,
64
410
  port,
65
- clientOutput: opts.client,
66
- frontend: opts.frontend,
67
- dashboard: entry && opts.dashboard !== false ? {
68
- port: opts.dashboardPort ?? 9400,
69
- historyDays: opts.historyDays
70
- } : false
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,
416
+ ...configDashboard(project, opts.dashboardExtension)
417
+ } : false,
418
+ manifest: project
71
419
  });
72
420
  });
73
- program.command("start").description("Start production server").argument("[entry]", "Application entry file").option("--port <number>", PORT_HELP, parsePortOption).addHelpText("after", PORT_RESOLUTION_HELP).action(async (entry, opts) => {
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);
74
423
  const port = resolveDevPort(opts.port);
75
424
  await startProdServer({
76
- entry,
77
- port
425
+ entry: entry ?? project?.entry,
426
+ port,
427
+ dashboard: configDashboard(project, opts.dashboardExtension)
78
428
  });
79
429
  });
80
- 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) => {
81
- await startWorker({ entry });
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);
432
+ await startWorker({ entry: requireEntry(command, entry, project) });
82
433
  });
83
- 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("--prefix <path>", "DEPRECATED: configure prefix in brick() app instead").option("--no-request-logging", "DEPRECATED: configure requestLogging in brick() app instead").action(async (entry, opts) => {
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) => {
84
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.");
439
+ const entry = requireEntry(command, entryArg, project);
440
+ if (project) await writeServiceManifest(project);
85
441
  const result = await buildApplication({
86
442
  entry,
87
- outdir: opts.outdir,
443
+ outdir: opts.outdir ?? fromRoot(project, build?.outdir),
88
444
  port: opts.port,
89
- aot: opts.aot
445
+ aot: opts.aot === false ? false : build?.aot,
446
+ dashboard: configDashboard(project, opts.dashboardExtension)
90
447
  });
91
448
  for (const warning of result.ir.diagnostics) console.warn(`[Brick compiler] ${warning}`);
92
449
  console.log(`Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`);
93
450
  console.log(`IR: ${result.outdir}/brick-ir.json`);
451
+ if (result.dashboard) console.log(`Dashboard extension: ${result.dashboard}`);
94
452
  console.log(`Run: bun ${result.entry}`);
95
453
  });
96
- const gen = program.command("gen").description("Generate artifacts from a BrickApp entry").argument("[subcommand]", "Generator to run (openapi, client)").action((subcommand) => {
97
- console.error(`Unknown generator: ${subcommand ?? "(none)"}. Available: openapi, client`);
98
- process.exit(1);
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) {
457
+ console.error(`Unknown generator: ${subcommand ?? "(none)"}. Available: openapi, client, manifest`);
458
+ process.exit(1);
459
+ }
460
+ const manifest = await writeServiceManifest(project);
461
+ 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}`);
466
+ }
467
+ const openapi = fromRoot(project, project.config.openapi?.output);
468
+ if (openapi) {
469
+ await writeOpenApi(project.entry, openapi, project);
470
+ console.log(`✅ OpenAPI 3.1 specification written to ${openapi}`);
471
+ }
99
472
  });
100
- 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) => {
101
- const app = await loadBrickApp(entry);
102
- const spec = generateOpenApiSpec({
103
- services: [...app.definition.services],
104
- prefix: app.definition.prefix
105
- });
106
- const jsonOutput = JSON.stringify(spec, null, 2);
107
- if (opts.output) {
108
- await Bun.write(opts.output, jsonOutput);
109
- console.log(`✅ OpenAPI 3.1 specification written to ${opts.output}`);
110
- } else console.log(jsonOutput);
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);
476
+ const json = await writeOpenApi(requireEntry(command, entry, project), output, project);
477
+ if (output) console.log(`✅ OpenAPI 3.1 specification written to ${output}`);
478
+ else console.log(json);
111
479
  });
112
- 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) => {
113
- const output = await writeClientContract(entry, opts.output);
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));
482
+ 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")));
114
485
  console.log(`Client contract written to ${output}`);
115
486
  });
116
- program.command("info").alias("services").description("Export architecture JSON schema").argument("<entry>", "Application entry file").action(async (entry) => {
117
- const app = await loadBrickApp(entry);
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
+ });
493
+ console.log(`Services manifest written to ${output}`);
494
+ });
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) => {
496
+ const code = await runLint({
497
+ entry,
498
+ project: await loadConfig(opts.config)
499
+ });
500
+ if (code !== 0) process.exit(code);
501
+ });
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);
504
+ const app = await loadProjectApp(requireEntry(command, entry, project), project);
118
505
  const architecture = getGlobalRegistry().exportArchitecture(app.definition);
119
506
  console.log(JSON.stringify(architecture, null, 2));
120
507
  });
@@ -122,7 +509,12 @@ ${PORT_RESOLUTION_HELP}`);
122
509
  }
123
510
  async function main() {
124
511
  const program = createProgram();
125
- if (process.argv.slice(2).length === 0) {
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) {
126
518
  const port = parsePort(void 0, process.env.PORT);
127
519
  await startDevServer({ port });
128
520
  return;
@@ -132,6 +524,10 @@ async function main() {
132
524
  main().catch((err) => {
133
525
  if (err?.exitCode !== void 0) process.exit(err.exitCode);
134
526
  if (err?.code?.startsWith?.("commander.")) process.exit(1);
527
+ if (err instanceof ConfigError) {
528
+ console.error(err.message);
529
+ process.exit(1);
530
+ }
135
531
  console.error("Fatal error:", err);
136
532
  process.exit(1);
137
533
  });