@brickkit/cli 0.0.0-stage → 0.2.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.
package/README.md CHANGED
@@ -1,3 +1,63 @@
1
- # Temporary Holding Version
1
+ # @brickkit/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ CLI and server engine for the Brick-TS framework. Mounts services,
4
+ actions, and resources as a typed HTTP API (Elysia) with OpenAPI 3.1,
5
+ Scalar/Swagger docs, request logging, and MCP routes.
6
+
7
+ ```sh
8
+ bun add @brickkit/cli @brickkit/core
9
+ ```
10
+
11
+ ```ts
12
+ import { brick } from "@brickkit/cli";
13
+
14
+ const app = brick({ title: "Pages API", version: "1.0.0" });
15
+ app.listen(3333);
16
+ ```
17
+
18
+ Prefer a single source of truth? Define the client contract once and derive
19
+ the server from it — no separate `services` list:
20
+
21
+ ```ts
22
+ import { brickFromContract } from "@brickkit/cli";
23
+ import { defineAppContract } from "@brickkit/core/client";
24
+
25
+ export const contract = defineAppContract({
26
+ page: pagesResource,
27
+ billing: { charge: chargeAction },
28
+ });
29
+ export type AppServer = typeof contract;
30
+
31
+ const app = brickFromContract(contract);
32
+ ```
33
+
34
+ Frontends then call it fully typed via `createBrickClient<AppServer>()`
35
+ (`@brickkit/core/client`, type-only import). See
36
+ `www/content/docs/(brick)/typed-client.mdx` for routing, error handling, and
37
+ options.
38
+
39
+ The `brick` binary ships in this package for local dev and inspection:
40
+
41
+ ```sh
42
+ brick dev --port 4000
43
+ brick gen openapi --output openapi.json
44
+ brick info
45
+ ```
46
+
47
+ Source: <https://github.com/Chandraprakash-Darji/brick>.
48
+
49
+ ## Compiler
50
+
51
+ The server compiles specialized JavaScript handlers for all resource CRUD and
52
+ custom actions at startup, pre-renders documentation, and caches OpenAPI and
53
+ architecture JSON with definition/endpoint invalidation. Health retains live
54
+ uptime and timestamps. Build a
55
+ definitions module into a runnable Bun server with:
56
+
57
+ ```sh
58
+ brick build src/definitions.ts --outdir dist/brick
59
+ bun dist/brick/server.js
60
+ ```
61
+
62
+ See [the compilation plan and artifact contract](COMPILER.md) for implemented
63
+ stages, limitations and the next optimizations.
package/dist/bin.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {}
package/dist/bin.js ADDED
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env bun
2
+ import { n as startDevServer, t as buildApplication } from "./build.js";
3
+ import { generateOpenApiSpec, getGlobalRegistry } from "@brickkit/core";
4
+ //#region src/bin.ts
5
+ const args = process.argv.slice(2);
6
+ const command = args[0] || "dev";
7
+ async function main() {
8
+ switch (command) {
9
+ case "dev":
10
+ case "start": {
11
+ const entry = args[1] && !args[1].startsWith("-") ? args[1] : void 0;
12
+ const portArgIdx = args.indexOf("--port");
13
+ const port = portArgIdx !== -1 ? Number(args[portArgIdx + 1]) : 4e3;
14
+ await startDevServer({
15
+ entry,
16
+ port
17
+ });
18
+ break;
19
+ }
20
+ case "build": {
21
+ const entry = args[1] && !args[1].startsWith("-") ? args[1] : void 0;
22
+ if (!entry) throw new Error("Usage: brick build <definitions.ts> [--outdir <directory>] [--prefix <path>] [--port <number>]");
23
+ const value = (flag) => {
24
+ const index = args.indexOf(flag);
25
+ if (index === -1) return void 0;
26
+ if (!args[index + 1] || args[index + 1].startsWith("--")) throw new Error(`Missing value for ${flag}`);
27
+ return args[index + 1];
28
+ };
29
+ const port = value("--port");
30
+ const result = await buildApplication({
31
+ entry,
32
+ outdir: value("--outdir"),
33
+ prefix: value("--prefix"),
34
+ port: port === void 0 ? void 0 : Number(port),
35
+ requestLogging: !args.includes("--no-request-logging")
36
+ });
37
+ for (const warning of result.ir.diagnostics) console.warn(`[Brick compiler] ${warning}`);
38
+ console.log(`Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`);
39
+ console.log(`IR: ${result.outdir}/brick-ir.json`);
40
+ console.log(`Run: bun ${result.entry}`);
41
+ break;
42
+ }
43
+ case "gen": {
44
+ const subCommand = args[1];
45
+ if (subCommand === "openapi") {
46
+ const outIdx = args.indexOf("--output");
47
+ const outputFile = outIdx !== -1 ? args[outIdx + 1] : void 0;
48
+ const spec = generateOpenApiSpec();
49
+ const jsonOutput = JSON.stringify(spec, null, 2);
50
+ if (outputFile) {
51
+ await Bun.write(outputFile, jsonOutput);
52
+ console.log(`✅ OpenAPI 3.1 specification written to ${outputFile}`);
53
+ } else console.log(jsonOutput);
54
+ break;
55
+ }
56
+ console.error(`Unknown generator: ${subCommand}. Available: openapi`);
57
+ process.exit(1);
58
+ break;
59
+ }
60
+ case "info":
61
+ case "services": {
62
+ const registry = getGlobalRegistry();
63
+ console.log(JSON.stringify(registry.exportArchitecture(), null, 2));
64
+ break;
65
+ }
66
+ default:
67
+ console.log(`
68
+ 🧱 Brick-TS CLI
69
+
70
+ Usage:
71
+ brick dev [entry] [--port <number>] Start development server with live reload
72
+ brick start [entry] Start production server
73
+ brick build <entry> [--outdir <dir>] Compile definitions into a Bun server
74
+ brick gen openapi [--output <file>] Generate OpenAPI 3.1 JSON specification
75
+ brick info Export architecture JSON schema
76
+ `);
77
+ process.exit(0);
78
+ }
79
+ }
80
+ main().catch((err) => {
81
+ console.error("Fatal error:", err);
82
+ process.exit(1);
83
+ });
84
+ //#endregion
85
+ export {};
86
+
87
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env bun\nimport { startDevServer } from \"./runner\";\nimport { buildApplication } from \"./build\";\nimport { getGlobalRegistry, generateOpenApiSpec } from \"@brickkit/core\";\n\nconst args = process.argv.slice(2);\nconst command = args[0] || \"dev\";\n\nasync function main() {\n switch (command) {\n case \"dev\":\n case \"start\": {\n const entry = args[1] && !args[1].startsWith(\"-\") ? args[1] : undefined;\n const portArgIdx = args.indexOf(\"--port\");\n const port = portArgIdx !== -1 ? Number(args[portArgIdx + 1]) : 4000;\n\n await startDevServer({ entry, port });\n break;\n }\n\n case \"build\": {\n const entry = args[1] && !args[1].startsWith(\"-\") ? args[1] : undefined;\n if (!entry)\n throw new Error(\n \"Usage: brick build <definitions.ts> [--outdir <directory>] [--prefix <path>] [--port <number>]\",\n );\n const value = (flag: string) => {\n const index = args.indexOf(flag);\n if (index === -1) return undefined;\n if (!args[index + 1] || args[index + 1]!.startsWith(\"--\"))\n throw new Error(`Missing value for ${flag}`);\n return args[index + 1];\n };\n const port = value(\"--port\");\n const result = await buildApplication({\n entry,\n outdir: value(\"--outdir\"),\n prefix: value(\"--prefix\"),\n port: port === undefined ? undefined : Number(port),\n requestLogging: !args.includes(\"--no-request-logging\"),\n });\n for (const warning of result.ir.diagnostics)\n console.warn(`[Brick compiler] ${warning}`);\n console.log(\n `Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`,\n );\n console.log(`IR: ${result.outdir}/brick-ir.json`);\n console.log(`Run: bun ${result.entry}`);\n break;\n }\n\n case \"gen\": {\n const subCommand = args[1];\n if (subCommand === \"openapi\") {\n const outIdx = args.indexOf(\"--output\");\n const outputFile = outIdx !== -1 ? args[outIdx + 1] : undefined;\n\n const spec = generateOpenApiSpec();\n const jsonOutput = JSON.stringify(spec, null, 2);\n\n if (outputFile) {\n await Bun.write(outputFile, jsonOutput);\n console.log(`✅ OpenAPI 3.1 specification written to ${outputFile}`);\n } else {\n console.log(jsonOutput);\n }\n break;\n }\n console.error(`Unknown generator: ${subCommand}. Available: openapi`);\n process.exit(1);\n break;\n }\n\n case \"info\":\n case \"services\": {\n const registry = getGlobalRegistry();\n console.log(JSON.stringify(registry.exportArchitecture(), null, 2));\n break;\n }\n\n default:\n console.log(`\n🧱 Brick-TS CLI\n\nUsage:\n brick dev [entry] [--port <number>] Start development server with live reload\n brick start [entry] Start production server\n brick build <entry> [--outdir <dir>] Compile definitions into a Bun server\n brick gen openapi [--output <file>] Generate OpenAPI 3.1 JSON specification\n brick info Export architecture JSON schema\n`);\n process.exit(0);\n }\n}\n\nmain().catch((err) => {\n console.error(\"Fatal error:\", err);\n process.exit(1);\n});\n"],"mappings":";;;;AAKA,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,MAAM,UAAU,KAAK,MAAM;AAE3B,eAAe,OAAO;CACpB,QAAQ,SAAR;EACE,KAAK;EACL,KAAK,SAAS;GACZ,MAAM,QAAQ,KAAK,MAAM,CAAC,KAAK,EAAE,CAAC,WAAW,GAAG,IAAI,KAAK,KAAK,KAAA;GAC9D,MAAM,aAAa,KAAK,QAAQ,QAAQ;GACxC,MAAM,OAAO,eAAe,KAAK,OAAO,KAAK,aAAa,EAAE,IAAI;GAEhE,MAAM,eAAe;IAAE;IAAO;GAAK,CAAC;GACpC;EACF;EAEA,KAAK,SAAS;GACZ,MAAM,QAAQ,KAAK,MAAM,CAAC,KAAK,EAAE,CAAC,WAAW,GAAG,IAAI,KAAK,KAAK,KAAA;GAC9D,IAAI,CAAC,OACH,MAAM,IAAI,MACR,gGACF;GACF,MAAM,SAAS,SAAiB;IAC9B,MAAM,QAAQ,KAAK,QAAQ,IAAI;IAC/B,IAAI,UAAU,IAAI,OAAO,KAAA;IACzB,IAAI,CAAC,KAAK,QAAQ,MAAM,KAAK,QAAQ,EAAE,CAAE,WAAW,IAAI,GACtD,MAAM,IAAI,MAAM,qBAAqB,MAAM;IAC7C,OAAO,KAAK,QAAQ;GACtB;GACA,MAAM,OAAO,MAAM,QAAQ;GAC3B,MAAM,SAAS,MAAM,iBAAiB;IACpC;IACA,QAAQ,MAAM,UAAU;IACxB,QAAQ,MAAM,UAAU;IACxB,MAAM,SAAS,KAAA,IAAY,KAAA,IAAY,OAAO,IAAI;IAClD,gBAAgB,CAAC,KAAK,SAAS,sBAAsB;GACvD,CAAC;GACD,KAAK,MAAM,WAAW,OAAO,GAAG,aAC9B,QAAQ,KAAK,oBAAoB,SAAS;GAC5C,QAAQ,IACN,YAAY,OAAO,GAAG,SAAS,OAAO,cAAc,OAAO,GAAG,OAAO,OAAO,QAC9E;GACA,QAAQ,IAAI,OAAO,OAAO,OAAO,eAAe;GAChD,QAAQ,IAAI,YAAY,OAAO,OAAO;GACtC;EACF;EAEA,KAAK,OAAO;GACV,MAAM,aAAa,KAAK;GACxB,IAAI,eAAe,WAAW;IAC5B,MAAM,SAAS,KAAK,QAAQ,UAAU;IACtC,MAAM,aAAa,WAAW,KAAK,KAAK,SAAS,KAAK,KAAA;IAEtD,MAAM,OAAO,oBAAoB;IACjC,MAAM,aAAa,KAAK,UAAU,MAAM,MAAM,CAAC;IAE/C,IAAI,YAAY;KACd,MAAM,IAAI,MAAM,YAAY,UAAU;KACtC,QAAQ,IAAI,0CAA0C,YAAY;IACpE,OACE,QAAQ,IAAI,UAAU;IAExB;GACF;GACA,QAAQ,MAAM,sBAAsB,WAAW,qBAAqB;GACpE,QAAQ,KAAK,CAAC;GACd;EACF;EAEA,KAAK;EACL,KAAK,YAAY;GACf,MAAM,WAAW,kBAAkB;GACnC,QAAQ,IAAI,KAAK,UAAU,SAAS,mBAAmB,GAAG,MAAM,CAAC,CAAC;GAClE;EACF;EAEA;GACE,QAAQ,IAAI;;;;;;;;;CASjB;GACK,QAAQ,KAAK,CAAC;CAClB;AACF;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CACpB,QAAQ,MAAM,gBAAgB,GAAG;CACjC,QAAQ,KAAK,CAAC;AAChB,CAAC"}
package/dist/build.js ADDED
@@ -0,0 +1,469 @@
1
+ import { n as compileBrickApplication, r as emitCompiledApplication } from "./compiler2.js";
2
+ import { Elysia } from "elysia";
3
+ import { ActionExecutionError, ValidationError, generateOpenApiSpec, getGlobalRegistry, resolveSecrets } from "@brickkit/core";
4
+ import { existsSync } from "fs";
5
+ import { resolve } from "path";
6
+ import { mkdir, mkdtemp, rename, rm } from "node:fs/promises";
7
+ import { dirname, join, resolve as resolve$1 } from "node:path";
8
+ import { pathToFileURL } from "node:url";
9
+ //#region src/request-logger.ts
10
+ function formatLog(method, path, status, elapsedMs) {
11
+ return `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;
12
+ }
13
+ /**
14
+ * Status carried by the thrown error (Elysia sets e.g. 404 on NotFoundError
15
+ * while `set.status` may still hold the 200 default when onError runs).
16
+ */
17
+ function thrownStatus(error) {
18
+ if (typeof error === "object" && error !== null && "status" in error) {
19
+ const status = error.status;
20
+ if (typeof status === "number") return status;
21
+ }
22
+ }
23
+ /**
24
+ * Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.
25
+ * Timing is tracked per-Request via a WeakMap. The onError hook only logs and
26
+ * returns undefined so existing error mapping is preserved. Logging only —
27
+ * no CORS headers are set here.
28
+ *
29
+ * Hooks are registered with `{ as: "global" }` so they propagate to the
30
+ * parent app when mounted via `app.use(...)` — Elysia scopes plain instance
31
+ * hooks to the plugin's own routes. Timing is captured in onBeforeHandle
32
+ * because onRequest offers no `as` option and is never propagated from a
33
+ * used instance. Unmatched routes (no beforeHandle) fall back to Date.now().
34
+ */
35
+ function requestLoggingPlugin(opts = {}) {
36
+ const plugin = new Elysia();
37
+ if (!(opts.enabled ?? true)) return plugin;
38
+ const logger = opts.logger ?? console.log;
39
+ const startedAt = /* @__PURE__ */ new WeakMap();
40
+ const markStarted = ({ request }) => {
41
+ startedAt.set(request, Date.now());
42
+ };
43
+ const logSuccess = ({ request, set }) => {
44
+ const start = startedAt.get(request) ?? Date.now();
45
+ const path = new URL(request.url).pathname;
46
+ logger(formatLog(request.method, path, set.status ?? 200, Date.now() - start));
47
+ };
48
+ const logError = ({ request, set, error }) => {
49
+ if (request) {
50
+ const start = startedAt.get(request) ?? Date.now();
51
+ const path = new URL(request.url).pathname;
52
+ const status = thrownStatus(error) ?? set.status ?? 500;
53
+ logger(formatLog(request.method, path, status, Date.now() - start));
54
+ }
55
+ };
56
+ plugin.onBeforeHandle({ as: "global" }, markStarted);
57
+ plugin.onAfterHandle({ as: "global" }, logSuccess);
58
+ plugin.onError({ as: "global" }, logError);
59
+ return plugin;
60
+ }
61
+ //#endregion
62
+ //#region src/docs.ts
63
+ /** Renders the Scalar API reference page for the given OpenAPI URL. */
64
+ function scalarDocsHTML(specUrl, title) {
65
+ return `<!doctype html>
66
+ <html>
67
+ <head>
68
+ <title>${title} — API Reference</title>
69
+ <meta charset="utf-8" />
70
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
71
+ <link rel="icon" type="image/svg+xml" href="https://scalar.com/favicon.svg" />
72
+ <style>
73
+ body { margin: 0; padding: 0; height: 100vh; }
74
+ </style>
75
+ </head>
76
+ <body>
77
+ <script
78
+ id="api-reference"
79
+ data-url="${specUrl}"
80
+ data-configuration='{"theme": "purple", "layout": "modern"}'
81
+ src="https://cdn.jsdelivr.net/npm/@scalar/api-reference">
82
+ <\/script>
83
+ </body>
84
+ </html>`;
85
+ }
86
+ /** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */
87
+ function referencePlugin(opts = {}) {
88
+ const path = opts.path ?? "/reference";
89
+ const title = opts.title ?? "Brick-TS API Mesh";
90
+ const specUrl = opts.specUrl ?? "/openapi.json";
91
+ const plugin = new Elysia();
92
+ plugin.get(path, ({ set }) => {
93
+ set.headers["content-type"] = "text/html; charset=utf-8";
94
+ return scalarDocsHTML(specUrl, title);
95
+ });
96
+ return plugin;
97
+ }
98
+ /** Mounts the Scalar reference route onto an existing app. */
99
+ function registerReferenceRoute(app, opts = {}) {
100
+ return app.use(referencePlugin(opts));
101
+ }
102
+ /** Renders the Swagger UI page. */
103
+ function swaggerDocsHTML(specUrl, title) {
104
+ return `<!DOCTYPE html>
105
+ <html lang="en">
106
+ <head>
107
+ <meta charset="UTF-8">
108
+ <title>${title} — Swagger UI</title>
109
+ <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css" />
110
+ <style>
111
+ html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }
112
+ *, *:before, *:after { box-sizing: inherit; }
113
+ body { margin:0; background: #fafafa; }
114
+ </style>
115
+ </head>
116
+ <body>
117
+ <div id="swagger-ui"></div>
118
+ <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js" charset="UTF-8"><\/script>
119
+ <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js" charset="UTF-8"><\/script>
120
+ <script>
121
+ window.onload = function() {
122
+ SwaggerUIBundle({
123
+ url: "${specUrl}",
124
+ dom_id: '#swagger-ui',
125
+ deepLinking: true,
126
+ presets: [
127
+ SwaggerUIBundle.presets.apis,
128
+ SwaggerUIStandalonePreset
129
+ ],
130
+ plugins: [
131
+ SwaggerUIBundle.plugins.DownloadUrl
132
+ ],
133
+ layout: "StandaloneLayout"
134
+ });
135
+ };
136
+ <\/script>
137
+ </body>
138
+ </html>`;
139
+ }
140
+ //#endregion
141
+ //#region src/endpoints.ts
142
+ /** Resolve the db for an endpoint: explicit service first, else first service holding one. */
143
+ function resolveEndpointDb(service, services) {
144
+ if (service) return (typeof service === "string" ? services.find((s) => s.name === service) : service)?.getDb() ?? void 0;
145
+ for (const svc of services) {
146
+ const db = svc.getDb();
147
+ if (db) return db;
148
+ }
149
+ }
150
+ /** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */
151
+ function createEndpointHandler(def, services) {
152
+ return async ({ params, body, query, headers, request, set }) => {
153
+ const traceId = headers?.["x-trace-id"] || `tr_${Math.random().toString(36).substring(2, 10)}`;
154
+ const requestId = headers?.["x-request-id"] || `req_${Math.random().toString(36).substring(2, 10)}`;
155
+ if (set?.headers) {
156
+ set.headers["x-trace-id"] = traceId;
157
+ set.headers["x-request-id"] = requestId;
158
+ }
159
+ const tag = `endpoint:${def.method} ${def.path}`;
160
+ const ctx = {
161
+ body,
162
+ db: def.database ? def.database.getDb() : resolveEndpointDb(def.service, services),
163
+ headers: headers ?? {},
164
+ logger: {
165
+ info: (...args) => console.log(`[${tag}]`, ...args),
166
+ warn: (...args) => console.warn(`[${tag}]`, ...args),
167
+ error: (...args) => console.error(`[${tag}]`, ...args),
168
+ debug: (...args) => console.debug(`[${tag}]`, ...args)
169
+ },
170
+ params: params ?? {},
171
+ query: query ?? {},
172
+ request: request instanceof Request ? request : new Request(`http://localhost${def.path}`, {
173
+ headers: new Headers(headers ?? {}),
174
+ method: def.method
175
+ }),
176
+ requestId,
177
+ set,
178
+ traceId
179
+ };
180
+ try {
181
+ return await def.handler(ctx);
182
+ } catch (err) {
183
+ if (err instanceof ValidationError) {
184
+ set.status = err.status || 400;
185
+ return err.toJSON();
186
+ }
187
+ if (err instanceof ActionExecutionError) {
188
+ set.status = err.status || 400;
189
+ return err.toJSON();
190
+ }
191
+ if (typeof err?.status === "number") {
192
+ set.status = err.status;
193
+ return {
194
+ message: err.message || "Endpoint error",
195
+ status: err.status
196
+ };
197
+ }
198
+ set.status = 500;
199
+ return {
200
+ message: err?.message || "An unexpected error occurred",
201
+ status: 500
202
+ };
203
+ }
204
+ };
205
+ }
206
+ /** `/p/:slug` → `/p/{slug}` for OpenAPI. */
207
+ function toOpenApiPath(elysiaPath) {
208
+ return elysiaPath.replace(/:([A-Za-z0-9_]+)/g, "{$1}");
209
+ }
210
+ /** Parameter names (`:slug`) extracted for the OpenAPI path item. */
211
+ function pathParamNames(elysiaPath) {
212
+ return [...elysiaPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);
213
+ }
214
+ /** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */
215
+ function endpointPaths(defs) {
216
+ const paths = {};
217
+ for (const def of defs) {
218
+ const openApiPath = toOpenApiPath(def.path);
219
+ if (!paths[openApiPath]) paths[openApiPath] = {};
220
+ const params = pathParamNames(def.path).map((name) => ({
221
+ in: "path",
222
+ name,
223
+ required: true,
224
+ schema: { type: "string" }
225
+ }));
226
+ paths[openApiPath][def.method.toLowerCase()] = {
227
+ ...def.summary ? { summary: def.summary } : {},
228
+ ...def.description ? { description: def.description } : {},
229
+ ...def.tags ? { tags: def.tags } : {},
230
+ ...params.length > 0 ? { parameters: params } : {},
231
+ responses: { 200: { description: "Successful response" } }
232
+ };
233
+ }
234
+ return paths;
235
+ }
236
+ //#endregion
237
+ //#region src/server.ts
238
+ function brick(options = {}) {
239
+ const prefix = options.prefix ?? options.compilation?.ir.prefix ?? "/api";
240
+ const title = options.title ?? "Brick-TS API Mesh";
241
+ const version = options.version ?? "1.0.0";
242
+ const compiled = options.compiler !== false;
243
+ const enableDocs = options.docs ?? true;
244
+ const openApiPath = options.openApiPath ?? "/openapi.json";
245
+ const docsPath = options.docsPath ?? "/docs";
246
+ const swaggerPath = options.swaggerPath ?? "/swagger";
247
+ const app = new Elysia();
248
+ if (options.secrets?.validate !== false) resolveSecrets({ source: options.secrets?.source });
249
+ app.get("/_health", () => ({
250
+ status: "ok",
251
+ uptime: process.uptime(),
252
+ timestamp: Date.now()
253
+ }));
254
+ app.get("/_brick/services", compiled ? cachedJsonRoute(() => getGlobalRegistry().exportArchitecture(), () => {
255
+ const registry = getGlobalRegistry();
256
+ return [registry, registry.revision];
257
+ }) : () => getGlobalRegistry().exportArchitecture());
258
+ const requestLogging = options.requestLogging ?? true;
259
+ if (requestLogging !== false) {
260
+ const pluginOpts = requestLogging === true ? {} : requestLogging;
261
+ if (pluginOpts.enabled !== false) app.use(requestLoggingPlugin(pluginOpts));
262
+ }
263
+ const reference = options.reference ?? false;
264
+ if (reference !== false) {
265
+ const refOpts = reference === true ? {} : reference;
266
+ const settings = {
267
+ path: refOpts.path ?? "/reference",
268
+ title: refOpts.title ?? title,
269
+ specUrl: refOpts.specUrl ?? openApiPath
270
+ };
271
+ if (compiled) app.get(settings.path, htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)));
272
+ else registerReferenceRoute(app, settings);
273
+ }
274
+ const services = options.services ?? getGlobalRegistry().list();
275
+ for (const service of services) if (typeof service.build === "function") service.build();
276
+ const endpointDefs = [];
277
+ let endpointRevision = 0;
278
+ if (enableDocs) {
279
+ const buildSpec = () => {
280
+ const spec = generateOpenApiSpec({
281
+ title,
282
+ version,
283
+ description: options.description,
284
+ prefix,
285
+ services
286
+ });
287
+ return {
288
+ ...spec,
289
+ paths: {
290
+ ...spec.paths,
291
+ ...endpointPaths(endpointDefs)
292
+ }
293
+ };
294
+ };
295
+ app.get(openApiPath, compiled ? cachedJsonRoute(buildSpec, () => [getGlobalRegistry(), getGlobalRegistry().revision + endpointRevision]) : buildSpec);
296
+ if (compiled) {
297
+ app.get(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));
298
+ app.get(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));
299
+ } else {
300
+ app.get(docsPath, ({ set }) => {
301
+ set.headers["content-type"] = "text/html; charset=utf-8";
302
+ return scalarDocsHTML(openApiPath, title);
303
+ });
304
+ app.get(swaggerPath, ({ set }) => {
305
+ set.headers["content-type"] = "text/html; charset=utf-8";
306
+ return swaggerDocsHTML(openApiPath, title);
307
+ });
308
+ }
309
+ }
310
+ const registeredRoutes = /* @__PURE__ */ new Set();
311
+ const mountRoute = (method, path, handler) => {
312
+ const routeKey = `${method} ${path}`;
313
+ if (registeredRoutes.has(routeKey)) return;
314
+ registeredRoutes.add(routeKey);
315
+ switch (method) {
316
+ case "GET":
317
+ app.get(path, handler);
318
+ break;
319
+ case "POST":
320
+ app.post(path, handler);
321
+ break;
322
+ case "PUT":
323
+ app.put(path, handler);
324
+ break;
325
+ case "PATCH":
326
+ app.patch(path, handler);
327
+ break;
328
+ case "DELETE": app.delete(path, handler);
329
+ }
330
+ };
331
+ const mountEndpoint = (def) => {
332
+ endpointDefs.push(def);
333
+ endpointRevision++;
334
+ mountRoute(def.method, def.path, createEndpointHandler(def, services));
335
+ };
336
+ for (const def of options.endpoints ?? []) mountEndpoint(def);
337
+ const brickApp = app;
338
+ brickApp.endpoint = (def) => {
339
+ mountEndpoint(def);
340
+ };
341
+ brickApp.listEndpoints = () => [...endpointDefs];
342
+ const compilation = options.compilation ?? compileBrickApplication({
343
+ services,
344
+ prefix,
345
+ mode: options.compiler === false ? "generic" : "specialized"
346
+ });
347
+ if (compilation.ir.prefix !== prefix || JSON.stringify(compilation.ir.services) !== JSON.stringify(services.map((service) => service.name))) throw new Error("Brick compiler: server services/prefix differ from the bound compilation");
348
+ for (const route of compilation.routes) mountRoute(route.ir.method, route.ir.path, route.handler);
349
+ return brickApp;
350
+ }
351
+ function htmlResponse(html) {
352
+ return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
353
+ }
354
+ /** Reuse serialized JSON, without sharing a mutable response body between requests. */
355
+ function cachedJsonRoute(build, revision) {
356
+ let [owner, version] = revision();
357
+ let json = JSON.stringify(build());
358
+ return ({ set }) => {
359
+ const [currentOwner, currentVersion] = revision();
360
+ if (currentOwner !== owner || currentVersion !== version) {
361
+ json = JSON.stringify(build());
362
+ owner = currentOwner;
363
+ version = currentVersion;
364
+ }
365
+ set.headers["content-type"] = "application/json;charset=utf-8";
366
+ return json;
367
+ };
368
+ }
369
+ //#endregion
370
+ //#region src/runner.ts
371
+ async function startDevServer(options = {}) {
372
+ const port = options.port ?? (Number(process.env.PORT) || 4e3);
373
+ const entry = options.entry;
374
+ if (entry) {
375
+ const resolvedEntry = resolve(process.cwd(), entry);
376
+ if (existsSync(resolvedEntry)) {
377
+ console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);
378
+ await import(resolvedEntry);
379
+ } else console.warn(`[Brick-TS] Specified entry not found: ${resolvedEntry}`);
380
+ }
381
+ const services = getGlobalRegistry().list();
382
+ console.log(`\n🧱 Brick-TS Development Server`);
383
+ console.log(` Registered Services: ${services.length}`);
384
+ for (const svc of services) {
385
+ console.log(` • ${svc.name} (${svc.listActions().length} actions)`);
386
+ if (typeof svc.listResources === "function") for (const res of svc.listResources()) console.log(` -> Resource: /api/${res.name} (REST: GET, POST, /:id: GET, PATCH, DELETE)`);
387
+ for (const act of svc.listActions()) console.log(` -> Action: /api/${svc.name}/${act.name}`);
388
+ }
389
+ const app = brick({
390
+ port,
391
+ prefix: options.prefix
392
+ });
393
+ app.listen(port);
394
+ console.log(`\n⚡ API Gateway running on: http://localhost:${port}`);
395
+ console.log(`🩺 Health check: http://localhost:${port}/_health`);
396
+ console.log(`🗺️ Architecture graph: http://localhost:${port}/_brick/services\n`);
397
+ return app;
398
+ }
399
+ //#endregion
400
+ //#region src/build.ts
401
+ /** Analyze definitions and bundle the emitted handlers with the user's callbacks. */
402
+ async function buildApplication(options) {
403
+ const entry = resolve$1(options.entry);
404
+ if (!await Bun.file(entry).exists()) throw new Error(`Brick compiler: entry not found: ${entry}`);
405
+ const outdir = resolve$1(options.outdir ?? "dist/brick");
406
+ if (entry === join(outdir, "server.js") || entry === join(outdir, "routes.js")) throw new Error("Brick compiler: output would overwrite the application entry");
407
+ const port = options.port ?? 4e3;
408
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error("Brick compiler: port must be an integer between 0 and 65535");
409
+ await import(pathToFileURL(entry).href);
410
+ const services = getGlobalRegistry().list();
411
+ if (!services.length) throw new Error("Brick compiler: entry registered no services; use a definitions module");
412
+ const compilation = compileBrickApplication({
413
+ services,
414
+ prefix: options.prefix
415
+ });
416
+ await mkdir(dirname(outdir), { recursive: true });
417
+ const staging = await mkdtemp(join(dirname(outdir), ".brick-build-"));
418
+ try {
419
+ await Bun.write(join(staging, "routes.js"), emitCompiledApplication(compilation.ir));
420
+ const source = `import ${JSON.stringify(entry)};
421
+ import { brick } from "@brickkit/cli";
422
+ import { getGlobalRegistry } from "@brickkit/core";
423
+ import { bind } from "./routes.js";
424
+ const services = getGlobalRegistry().list();
425
+ export const app = brick({ services, compilation: bind(services), requestLogging: ${options.requestLogging ?? true} });
426
+ if (import.meta.main) {
427
+ const port = Number(process.env.PORT ?? ${port});
428
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error("Invalid PORT");
429
+ app.listen(port);
430
+ console.log("Brick compiled server listening on http://localhost:" + app.server.port);
431
+ const stop = async () => { await app.stop(); process.exit(0); };
432
+ process.once("SIGINT", stop);
433
+ process.once("SIGTERM", stop);
434
+ }
435
+ `;
436
+ await Bun.write(join(staging, "entry.ts"), source);
437
+ const result = await Bun.build({
438
+ entrypoints: [join(staging, "entry.ts")],
439
+ target: "bun",
440
+ format: "esm",
441
+ outdir: staging,
442
+ naming: "server.js",
443
+ sourcemap: "external"
444
+ });
445
+ if (!result.success) throw new AggregateError(result.logs, "Brick compiler: bundling failed");
446
+ await Bun.write(join(staging, "brick-ir.json"), JSON.stringify(compilation.ir, null, 2) + "\n");
447
+ await mkdir(outdir, { recursive: true });
448
+ for (const name of [
449
+ "routes.js",
450
+ "brick-ir.json",
451
+ "server.js.map",
452
+ "server.js"
453
+ ]) await rename(join(staging, name), join(outdir, name));
454
+ return {
455
+ outdir,
456
+ entry: join(outdir, "server.js"),
457
+ ir: compilation.ir
458
+ };
459
+ } finally {
460
+ await rm(staging, {
461
+ recursive: true,
462
+ force: true
463
+ });
464
+ }
465
+ }
466
+ //#endregion
467
+ export { registerReferenceRoute as a, referencePlugin as i, startDevServer as n, scalarDocsHTML as o, brick as r, requestLoggingPlugin as s, buildApplication as t };
468
+
469
+ //# sourceMappingURL=build.js.map