@brickkit/cli 0.3.0-beta.2 → 0.3.0-beta.3

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.
@@ -1,154 +1,3 @@
1
- import { Elysia } from "elysia";
2
- import { CompiledRoutePlan, DatabaseHandle, Service } from "@brickkit/core";
3
- //#region src/endpoints.d.ts
4
- type EndpointMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
5
- /** Logger subset handed to endpoint handlers (mirrors action context loggers). */
6
- interface EndpointLogger {
7
- info: (...args: any[]) => void;
8
- warn: (...args: any[]) => void;
9
- error: (...args: any[]) => void;
10
- debug: (...args: any[]) => void;
11
- }
12
- /** Context for raw endpoint handlers: Elysia route fields + Brick extras. */
13
- interface EndpointContext {
14
- params: Record<string, string>;
15
- query: Record<string, string | undefined>;
16
- body: unknown;
17
- headers: Record<string, string>;
18
- request: Request;
19
- /** Elysia response setter (status/headers). Mutate like in `app.get`. */
20
- set: {
21
- status?: number;
22
- headers: Record<string, string>;
23
- };
24
- /** Drizzle db from `service` (or first service with one); `undefined` when none. */
25
- db: any;
26
- logger: EndpointLogger;
27
- traceId: string;
28
- requestId: string;
29
- }
30
- interface EndpointDefinition {
31
- method: EndpointMethod;
32
- /** Elysia-style path, e.g. `/p/:slug`. */
33
- path: string;
34
- handler: (ctx: EndpointContext) => unknown | Promise<unknown>;
35
- /** Db source: instance or registered service name. Defaults to first service with a db. */
36
- service?: Service<any, any> | string;
37
- /** Explicit database handle, independent of a service. */
38
- database?: DatabaseHandle<unknown>;
39
- summary?: string;
40
- description?: string;
41
- tags?: string[];
42
- }
43
- /** The app object returned by `brick`: Elysia plus `endpoint()`. */
44
- type BrickApp = Elysia<any, any, any, any, any, any, any> & {
45
- /** Service definitions and prefix selected when this app was constructed. */
46
- readonly definition: {
47
- readonly services: readonly Service<any, any>[];
48
- readonly prefix: string;
49
- };
50
- /** Register a raw endpoint (outside the JSON action mesh). */
51
- endpoint(def: EndpointDefinition): void;
52
- /** All endpoints registered via `endpoint()` (declaration order). */
53
- listEndpoints(): EndpointDefinition[];
54
- };
55
- //#endregion
56
- //#region src/compiler/ir.d.ts
57
- type RouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
58
- interface RouteIR {
59
- readonly method: RouteMethod;
60
- readonly path: string;
61
- readonly service: string;
62
- readonly action: string;
63
- readonly kind: "action";
64
- readonly input: boolean;
65
- readonly output: boolean;
66
- readonly context: boolean;
67
- readonly authorize: boolean;
68
- readonly inputPrecedence: readonly ("query" | "params" | "body")[];
69
- readonly coercions: readonly {
70
- readonly key: string;
71
- readonly type: "number" | "boolean";
72
- }[];
73
- /** JSON projection for inspection and stale-artifact detection, not runtime validation. */
74
- readonly inputSchema?: unknown;
75
- readonly outputSchema?: unknown;
76
- }
77
- interface BrickIR {
78
- readonly version: 1;
79
- readonly target: "bun-elysia";
80
- readonly prefix: string;
81
- readonly services: readonly string[];
82
- readonly routes: readonly RouteIR[];
83
- readonly preparations: readonly {
84
- service: string;
85
- name: string;
86
- metadata: unknown;
87
- }[];
88
- readonly diagnostics: readonly string[];
89
- }
90
- //#endregion
91
- //#region src/compiler/runtime.d.ts
92
- type CompiledHandler = (context: any) => unknown | Promise<unknown>;
93
- type HandlerFactory = (binding: CompiledRoutePlan, runtime: typeof compilerRuntime) => CompiledHandler;
94
- /** Retains Brick's existing source precedence and treatment of empty bodies. */
95
- declare function mergeInput(first: any, second: any, third: any): any;
96
- declare function validate(check: NonNullable<CompiledRoutePlan["inputChecker"]>, value: unknown, action: string, stage: "input" | "output"): void;
97
- declare function mapError(err: any, set: any): {
98
- name: string;
99
- code: string;
100
- message: string;
101
- status: number;
102
- details: unknown;
103
- } | {
104
- name: string;
105
- message: string;
106
- status: number;
107
- errors: import("@brickkit/core").ValidationErrorItem[];
108
- } | {
109
- name: string;
110
- message: any;
111
- status: number;
112
- };
113
- declare const compilerRuntime: Readonly<{
114
- emptyServices: Readonly<{}>;
115
- defaultRequest: Request;
116
- nextSequence: () => string;
117
- mergeInput: typeof mergeInput;
118
- validate: typeof validate;
119
- mapError: typeof mapError;
120
- isThenable: (value: any) => boolean;
121
- deny: (action: string) => never;
122
- }>;
123
- //#endregion
124
- //#region src/compiler/emit.d.ts
125
- /** Emits framework code only. User callbacks remain closures bound separately. */
126
- declare function emitHandlerFactory(route: RouteIR): string;
127
- /** An ES module of real JS functions; it never stringifies application callbacks. */
128
- declare function emitCompiledApplication(ir: BrickIR, runtimeImport?: string): string;
129
- //#endregion
130
- //#region src/compiler.d.ts
131
- type ApplicationBinder = (services: Service<any, any>[]) => CompiledApplication;
132
- /** Build artifact bootstrap: bind generated handlers while evaluating the original app. */
133
- declare function loadCompiledBrickApp(load: () => Promise<{
134
- default: unknown;
135
- }>, ir: BrickIR, bind: ApplicationBinder): Promise<BrickApp>;
136
- interface CompiledRoute {
137
- readonly ir: RouteIR;
138
- readonly handler: CompiledHandler;
139
- }
140
- interface CompiledApplication {
141
- readonly ir: BrickIR;
142
- readonly routes: readonly CompiledRoute[];
143
- }
144
- /** Startup compiler: analyzes once, generates JS once, then binds live callbacks. */
145
- declare function compileBrickApplication(options: {
146
- services: Service<any, any>[];
147
- prefix?: string;
148
- mode?: "specialized" | "generic";
149
- }): CompiledApplication;
150
- /** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */
151
- declare function bindCompiledApplication(ir: BrickIR, services: Service<any, any>[], factories: readonly HandlerFactory[]): CompiledApplication;
152
- //#endregion
153
- export { EndpointMethod as _, loadCompiledBrickApp as a, CompiledHandler as c, RouteIR as d, RouteMethod as f, EndpointLogger as g, EndpointDefinition as h, compileBrickApplication as i, HandlerFactory as l, EndpointContext as m, CompiledRoute as n, emitCompiledApplication as o, BrickApp as p, bindCompiledApplication as r, emitHandlerFactory as s, CompiledApplication as t, BrickIR as u };
154
- //# sourceMappingURL=compiler.d.ts.map
1
+ import { n as emitHandlerFactory, t as emitCompiledApplication } from "./emit.js";
2
+ import { BrickIR, CompiledApplication, CompiledHandler, CompiledRoute, HandlerFactory, RouteIR, RouteMethod, bindCompiledApplication, compileBrickApplication, loadCompiledBrickApp } from "@brickkit/core";
3
+ export { type BrickIR, type CompiledApplication, type CompiledHandler, type CompiledRoute, type HandlerFactory, type RouteIR, type RouteMethod, bindCompiledApplication, compileBrickApplication, emitCompiledApplication, emitHandlerFactory, loadCompiledBrickApp };
package/dist/compiler.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as emitCompiledApplication, n as compileBrickApplication, o as emitHandlerFactory, r as loadCompiledBrickApp, t as bindCompiledApplication } from "./compiler2.js";
1
+ import { a as emitHandlerFactory, i as emitCompiledApplication, n as compileBrickApplication, r as loadCompiledBrickApp, t as bindCompiledApplication } from "./compiler2.js";
2
2
  export { bindCompiledApplication, compileBrickApplication, emitCompiledApplication, emitHandlerFactory, loadCompiledBrickApp };
package/dist/compiler2.js CHANGED
@@ -1,486 +1,10 @@
1
- import { ActionExecutionError, ValidationError, buildErrorHelpers, getCompiledCheck, getPluginActionRoute } from "@brickkit/core";
2
- import { resolve } from "node:path";
3
- import { pathToFileURL } from "node:url";
4
- //#region src/action-handler.ts
5
- let _srvSeq = 0;
6
- const EMPTY_SERVICES$1 = Object.freeze({});
7
- const DEFAULT_REQUEST$1 = new Request("http://localhost");
8
- function isNonEmpty$1(obj) {
9
- if (obj == null) return false;
10
- for (const _ in obj) return true;
11
- return false;
12
- }
13
- const MAX_INPUT_DEPTH = 128;
14
- function inputTooDeep(value) {
15
- if (!value || typeof value !== "object") return false;
16
- const stack = [{
17
- node: value,
18
- depth: 0
19
- }];
20
- while (stack.length > 0) {
21
- const { node, depth } = stack.pop();
22
- if (depth > MAX_INPUT_DEPTH) return true;
23
- if (node && typeof node === "object") {
24
- const children = Array.isArray(node) ? node : Object.values(node);
25
- for (const child of children) if (child && typeof child === "object") stack.push({
26
- node: child,
27
- depth: depth + 1
28
- });
29
- }
30
- }
31
- return false;
32
- }
33
- function compileRoutePlan(service, action, routePath, method) {
34
- const actionName = action.name;
35
- const serviceName = service.name;
36
- const isGetLike = method === "GET" || actionName.startsWith("get") || actionName.endsWith(".get") || actionName.startsWith("list") || actionName.endsWith(".list") || actionName.startsWith("find") || actionName.startsWith("read");
37
- const inputSchema = action.config?.input;
38
- const outputSchema = action.config?.output;
39
- const hasInput = Boolean(inputSchema);
40
- const inputChecker = inputSchema ? getCompiledCheck(inputSchema) : void 0;
41
- const runtimeOutputSchema = action.outputValidationSchema ?? outputSchema;
42
- const outputChecker = runtimeOutputSchema ? getCompiledCheck(runtimeOutputSchema) : void 0;
43
- let coercions;
44
- if (inputSchema && typeof inputSchema.properties === "object") {
45
- const list = [];
46
- for (const [key, prop] of Object.entries(inputSchema.properties)) {
47
- const type = prop?.type;
48
- if (type === "number" || type === "integer") list.push({
49
- key,
50
- isNumber: true,
51
- isBoolean: false
52
- });
53
- else if (type === "boolean") list.push({
54
- key,
55
- isNumber: false,
56
- isBoolean: true
57
- });
58
- }
59
- if (list.length > 0) coercions = list;
60
- }
61
- const contextHook = service.options?.context;
62
- const hasContextHook = typeof contextHook === "function";
63
- const authorize = action.config?.authorize;
64
- const hasAuthorize = typeof authorize === "function";
65
- const execute = action.config?.execute;
66
- const tag = `[${serviceName}:${actionName}]`;
67
- const logger = {
68
- info: (...args) => console.log(tag, ...args),
69
- warn: (...args) => console.warn(tag, ...args),
70
- error: (...args) => console.error(tag, ...args),
71
- debug: (...args) => console.debug(tag, ...args)
72
- };
73
- const errorBuilder = action.errorHelpers ?? buildErrorHelpers(action.config?.errors);
74
- const cachedDb = service.getDb();
75
- return {
76
- service,
77
- action,
78
- actionName,
79
- serviceName,
80
- routePath,
81
- method,
82
- isGetLike,
83
- hasInput,
84
- hasContextHook,
85
- contextHook,
86
- hasAuthorize,
87
- authorize,
88
- execute,
89
- inputChecker,
90
- outputChecker,
91
- coercions,
92
- logger,
93
- errorBuilder,
94
- cachedDb
95
- };
96
- }
97
- async function executeCompiledRoute(plan, elysiaCtx) {
98
- const { params, body, query, headers, request, set } = elysiaCtx;
99
- const seq = (++_srvSeq).toString(36);
100
- const traceId = headers && headers["x-trace-id"] || `tr_${seq}`;
101
- const requestId = headers && headers["x-request-id"] || `req_${seq}`;
102
- if (set?.headers) {
103
- set.headers["x-trace-id"] = traceId;
104
- set.headers["x-request-id"] = requestId;
105
- }
106
- let input;
107
- if (plan.hasInput) {
108
- let coercedQuery = query;
109
- if (query && plan.coercions && plan.coercions.length > 0) {
110
- coercedQuery = { ...query };
111
- for (let i = 0; i < plan.coercions.length; i++) {
112
- const c = plan.coercions[i];
113
- const val = query[c.key];
114
- if (val !== void 0) {
115
- if (c.isNumber) {
116
- const num = Number(val);
117
- if (!isNaN(num)) coercedQuery[c.key] = num;
118
- } else if (c.isBoolean) {
119
- if (val === "true" || val === "1") coercedQuery[c.key] = true;
120
- else if (val === "false" || val === "0") coercedQuery[c.key] = false;
121
- }
122
- }
123
- }
124
- }
125
- const hasP = isNonEmpty$1(params);
126
- const hasB = isNonEmpty$1(body);
127
- const hasQ = isNonEmpty$1(coercedQuery);
128
- if (plan.isGetLike) {
129
- if (hasQ && !hasP && !hasB) input = coercedQuery;
130
- else if (hasP && !hasQ && !hasB) input = params;
131
- else if (hasB && !hasP && !hasQ) input = body;
132
- else if (hasQ || hasP || hasB) input = Object.assign({}, coercedQuery, params, body);
133
- } else if (hasB && !hasP && !hasQ) input = body;
134
- else if (hasP && !hasB && !hasQ) input = params;
135
- else if (hasQ && !hasP && !hasB) input = coercedQuery;
136
- else if (hasP || hasB || hasQ) input = Object.assign({}, params, body, coercedQuery);
137
- }
138
- const ctx = {
139
- request: request instanceof Request ? request : DEFAULT_REQUEST$1,
140
- traceId,
141
- requestId,
142
- db: plan.cachedDb ?? plan.service.getDb(),
143
- logger: plan.logger,
144
- services: EMPTY_SERVICES$1,
145
- metadata: { headers },
146
- _resolved: true
147
- };
148
- try {
149
- if (plan.hasContextHook) {
150
- const extra = plan.contextHook(ctx);
151
- const resolved = extra instanceof Promise ? await extra : extra;
152
- if (resolved) Object.assign(ctx, resolved);
153
- }
154
- if (input === void 0 && plan.action.config?.input?.type === "object") input = {};
155
- if (plan.hasInput && plan.inputChecker) {
156
- if (inputTooDeep(input)) throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, [{
157
- path: "",
158
- message: "Input exceeds maximum nesting depth"
159
- }]);
160
- if (!plan.inputChecker.Check(input)) {
161
- const errors = Array.from(plan.inputChecker.Errors(input)).map((err) => ({
162
- path: err.path,
163
- message: err.message,
164
- value: err.value
165
- }));
166
- throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, errors);
167
- }
168
- }
169
- if (plan.hasAuthorize) {
170
- const authRes = plan.authorize({
171
- ctx,
172
- input,
173
- user: ctx.user
174
- });
175
- if (!(authRes instanceof Promise ? await authRes : authRes)) throw new ActionExecutionError("UNAUTHORIZED", `Access denied for action '${plan.actionName}'`, 403);
176
- }
177
- const execRes = plan.execute({
178
- input,
179
- ctx,
180
- error: plan.errorBuilder
181
- });
182
- const result = execRes instanceof Promise ? await execRes : execRes;
183
- if (plan.outputChecker) {
184
- if (!plan.outputChecker.Check(result)) {
185
- const errors = Array.from(plan.outputChecker.Errors(result)).map((err) => ({
186
- path: err.path,
187
- message: err.message,
188
- value: err.value
189
- }));
190
- throw new ValidationError(`Validation failed for action '${plan.actionName}' output`, errors, 500);
191
- }
192
- }
193
- return result;
194
- } catch (err) {
195
- if (err instanceof ValidationError || err instanceof ActionExecutionError) {
196
- set.status = err.status || 400;
197
- return err.toJSON();
198
- }
199
- set.status = 500;
200
- return {
201
- name: "InternalServerError",
202
- message: err.message || "An unexpected error occurred",
203
- status: 500
204
- };
205
- }
206
- }
207
- //#endregion
208
- //#region src/compiler/ir.ts
209
- function freezeIR(value) {
210
- if (value && typeof value === "object" && !Object.isFrozen(value)) {
211
- for (const child of Object.values(value)) freezeIR(child);
212
- Object.freeze(value);
213
- }
214
- return value;
215
- }
216
- function schemaSnapshot(schema) {
217
- return schema === void 0 ? void 0 : JSON.parse(JSON.stringify(schema));
218
- }
219
- function analyzeApplication(services, prefix = "/api") {
220
- if (!prefix.startsWith("/")) throw new Error("Brick compiler: prefix must start with '/'");
221
- const names = /* @__PURE__ */ new Set();
222
- for (const service of services) {
223
- if (names.has(service.name)) throw new Error(`Brick compiler: duplicate service '${service.name}'`);
224
- names.add(service.name);
225
- service.build();
226
- }
227
- const routes = [];
228
- const bindings = [];
229
- const registered = /* @__PURE__ */ new Map();
230
- const diagnostics = [];
231
- const add = (service, action, method, path, kind) => {
232
- if (!path.startsWith("/")) throw new Error(`Brick compiler: invalid route '${method} ${path}'`);
233
- const plugin = getPluginActionRoute(action, prefix) !== void 0;
234
- const key = `${method} ${path.replace(/:[^/]+/g, ":param")}`;
235
- const previous = registered.get(key);
236
- if (previous) {
237
- if (plugin || previous.plugin) throw new Error(`Brick compiler: duplicate plugin route '${method} ${path}'`);
238
- diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (first registration wins)`);
239
- return;
240
- }
241
- if (typeof action.config.execute !== "function") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);
242
- registered.set(key, {
243
- name: `${service.name}.${action.name}`,
244
- plugin
245
- });
246
- const readLike = method === "GET" || action.name.startsWith("get") || action.name.endsWith(".get") || action.name.startsWith("list") || action.name.endsWith(".list") || action.name.startsWith("find") || action.name.startsWith("read");
247
- const coercions = [];
248
- for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) if (prop.type === "number" || prop.type === "integer") coercions.push({
249
- key,
250
- type: "number"
251
- });
252
- else if (prop.type === "boolean") coercions.push({
253
- key,
254
- type: "boolean"
255
- });
256
- routes.push({
257
- method,
258
- path,
259
- service: service.name,
260
- action: action.name,
261
- kind,
262
- input: Boolean(action.config.input),
263
- output: Boolean(action.config.output),
264
- context: typeof service.options.context === "function",
265
- authorize: typeof action.config.authorize === "function",
266
- inputPrecedence: readLike ? [
267
- "query",
268
- "params",
269
- "body"
270
- ] : [
271
- "params",
272
- "body",
273
- "query"
274
- ],
275
- coercions,
276
- inputSchema: schemaSnapshot(action.config.input),
277
- outputSchema: schemaSnapshot(action.config.output)
278
- });
279
- bindings.push({
280
- service,
281
- action
282
- });
283
- };
284
- for (const service of services) for (const action of service.listActions()) {
285
- const pluginRoute = getPluginActionRoute(action, prefix);
286
- if (pluginRoute === false) continue;
287
- const path = pluginRoute?.path ?? action.config.path ?? `${prefix}/${service.name}/${action.name}`;
288
- add(service, action, pluginRoute?.method ?? action.config.method ?? "POST", path, "action");
289
- }
290
- const preparations = services.flatMap((service) => service.listPreparations().map((contribution) => ({
291
- service: service.name,
292
- name: contribution.name,
293
- metadata: schemaSnapshot(contribution.describe?.())
294
- })));
295
- return {
296
- ir: freezeIR({
297
- version: 1,
298
- target: "bun-elysia",
299
- prefix,
300
- services: [...names],
301
- routes,
302
- preparations,
303
- diagnostics
304
- }),
305
- bindings
306
- };
307
- }
308
- //#endregion
1
+ import { bindCompiledApplication, compileBrickApplication, emitHandlerFactory, loadCompiledBrickApp } from "@brickkit/core";
309
2
  //#region src/compiler/emit.ts
310
- /** Emits framework code only. User callbacks remain closures bound separately. */
311
- function emitHandlerFactory(route) {
312
- const name = JSON.stringify(route.action);
313
- const fields = route.input ? "params, body, query, headers, request, set" : "headers, request, set";
314
- const input = ["let input;"];
315
- if (route.input) {
316
- input.push("let coercedQuery = query;");
317
- if (route.coercions.length) {
318
- input.push("if (query) {", "coercedQuery = { ...query };");
319
- for (const [index, coercion] of route.coercions.entries()) {
320
- const key = JSON.stringify(coercion.key);
321
- input.push(`const v${index} = query[${key}];`);
322
- if (coercion.type === "number") input.push(`if (v${index} !== undefined) { const n${index} = Number(v${index}); if (!Number.isNaN(n${index})) coercedQuery[${key}] = n${index}; }`);
323
- else input.push(`if (v${index} === "true" || v${index} === "1") coercedQuery[${key}] = true; else if (v${index} === "false" || v${index} === "0") coercedQuery[${key}] = false;`);
324
- }
325
- input.push("}");
326
- }
327
- input.push(`input = mergeInput(${route.inputPrecedence.map((source) => source === "query" ? "coercedQuery" : source).join(", ")});`);
328
- if (route.inputSchema?.type === "object") input.push("input ??= {};");
329
- }
330
- const asyncStages = route.context || route.authorize;
331
- const context = route.context ? "const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);" : "";
332
- const validation = route.input ? `validate(inputChecker, input, ${name}, "input");` : "";
333
- const authorization = route.authorize ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name});` : "";
334
- const output = route.output ? `validate(outputChecker, result, ${name}, "output");` : "";
335
- const execute = asyncStages ? `const result = await execute({ input, ctx, error: errorBuilder });\n${output}\nreturn result;` : `const result = execute({ input, ctx, error: errorBuilder });
336
- if (isThenable(result)) return Promise.resolve(result).then(value => {
337
- ${route.output ? `validate(outputChecker, value, ${name}, "output");` : ""}
338
- return value;
339
- }).catch(err => mapError(err, set));
340
- ${output}
341
- return result;`;
342
- return `function bindAction(binding, runtime) {
343
- const { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;
344
- const { nextSequence, defaultRequest, emptyServices, mergeInput, validate, deny, mapError, isThenable } = runtime;
345
- return ${asyncStages ? "async " : ""}function brickAction({ ${fields} }) {
346
- const seq = nextSequence();
347
- const traceId = (headers && headers["x-trace-id"]) || "tr_" + seq;
348
- const requestId = (headers && headers["x-request-id"]) || "req_" + seq;
349
- if (set?.headers) { set.headers["x-trace-id"] = traceId; set.headers["x-request-id"] = requestId; }
350
- ${input.join("\n")}
351
- const ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,
352
- db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };
353
- try {
354
- ${context}
355
- ${validation}
356
- ${authorization}
357
- ${execute}
358
- } catch (err) { return mapError(err, set); }
359
- };
360
- }`;
361
- }
362
3
  /** An ES module of real JS functions; it never stringifies application callbacks. */
363
- function emitCompiledApplication(ir, runtimeImport = "@brickkit/cli/compiler") {
4
+ function emitCompiledApplication(ir, runtimeImport = "@brickkit/core") {
364
5
  return `// Generated by Brick compiler v1. Rebuild after changing application definitions.\nimport { bindCompiledApplication } from ${JSON.stringify(runtimeImport)};\nexport const ir = JSON.parse(${JSON.stringify(JSON.stringify(ir))});\nconst factories = [\n${ir.routes.map(emitHandlerFactory).join(",\n")}\n];\nexport function bind(services) { return bindCompiledApplication(ir, services, factories); }\n`;
365
6
  }
366
7
  //#endregion
367
- //#region src/compiler/runtime.ts
368
- const EMPTY_SERVICES = Object.freeze({});
369
- const DEFAULT_REQUEST = new Request("http://localhost");
370
- let sequence = 0;
371
- function isNonEmpty(value) {
372
- if (value == null) return false;
373
- for (const _ in value) return true;
374
- return false;
375
- }
376
- /** Retains Brick's existing source precedence and treatment of empty bodies. */
377
- function mergeInput(first, second, third) {
378
- const a = isNonEmpty(first), b = isNonEmpty(second), c = isNonEmpty(third);
379
- if (a && !b && !c) return first;
380
- if (b && !a && !c) return second;
381
- if (c && !a && !b) return third;
382
- if (a || b || c) return Object.assign({}, first, second, third);
383
- }
384
- function validate(check, value, action, stage) {
385
- if (check.Check(value)) return;
386
- const errors = Array.from(check.Errors(value)).map((err) => ({
387
- path: err.path,
388
- message: err.message,
389
- value: err.value
390
- }));
391
- throw new ValidationError(`Validation failed for action '${action}' ${stage}`, errors, stage === "output" ? 500 : 400);
392
- }
393
- function mapError(err, set) {
394
- if (err instanceof ValidationError || err instanceof ActionExecutionError) {
395
- set.status = err.status || 400;
396
- return err.toJSON();
397
- }
398
- set.status = 500;
399
- return {
400
- name: "InternalServerError",
401
- message: err?.message || "An unexpected error occurred",
402
- status: 500
403
- };
404
- }
405
- const compilerRuntime = Object.freeze({
406
- emptyServices: EMPTY_SERVICES,
407
- defaultRequest: DEFAULT_REQUEST,
408
- nextSequence: () => (++sequence).toString(36),
409
- mergeInput,
410
- validate,
411
- mapError,
412
- isThenable: (value) => value != null && typeof value.then === "function",
413
- deny: (action) => {
414
- throw new ActionExecutionError("UNAUTHORIZED", `Access denied for action '${action}'`, 403);
415
- }
416
- });
417
- //#endregion
418
- //#region src/app-entry.ts
419
- function isBrickApp(app) {
420
- if (!app || typeof app !== "object") return false;
421
- return "endpoint" in app && typeof app.endpoint === "function" && "fetch" in app && typeof app.fetch === "function" && "listen" in app && typeof app.listen === "function" && "definition" in app && !!app.definition && typeof app.definition === "object" && "services" in app.definition && Array.isArray(app.definition.services) && "prefix" in app.definition && typeof app.definition.prefix === "string";
422
- }
423
- function requireBrickApp(app) {
424
- if (!isBrickApp(app)) throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
425
- if (app.server) throw new Error("Brick: the app entry must not call .listen(); use a separate server bootstrap.");
426
- return app;
427
- }
428
- async function loadBrickApp(entry) {
429
- return requireBrickApp((await import(pathToFileURL(resolve(entry)).href)).default);
430
- }
431
- //#endregion
432
- //#region src/compiler.ts
433
- const buildBindings = /* @__PURE__ */ new Map();
434
- function applicationKey(services, prefix = "/api") {
435
- return JSON.stringify([prefix, services.map((service) => service.name)]);
436
- }
437
- /** Build artifact bootstrap: bind generated handlers while evaluating the original app. */
438
- async function loadCompiledBrickApp(load, ir, bind) {
439
- const key = JSON.stringify([ir.prefix, ir.services]);
440
- if (buildBindings.has(key)) throw new Error("Brick compiler: overlapping compiled app imports");
441
- buildBindings.set(key, bind);
442
- try {
443
- const app = requireBrickApp((await load()).default);
444
- if (applicationKey(app.definition.services, app.definition.prefix) !== key) throw new Error("Brick compiler: app services/prefix changed; rebuild the application");
445
- return app;
446
- } finally {
447
- buildBindings.delete(key);
448
- }
449
- }
450
- function bindAnalyzed(ir, bindings, factories) {
451
- if (factories.length !== ir.routes.length) throw new Error("Brick compiler: handler factory count does not match IR");
452
- const routes = ir.routes.map((route, index) => {
453
- const { service, action } = bindings[index];
454
- const plan = Object.freeze(compileRoutePlan(service, action, route.path, route.method));
455
- const handler = factories[index](plan, compilerRuntime);
456
- return Object.freeze({
457
- ir: route,
458
- handler
459
- });
460
- });
461
- return Object.freeze({
462
- ir: freezeIR(ir),
463
- routes: Object.freeze(routes)
464
- });
465
- }
466
- /** Startup compiler: analyzes once, generates JS once, then binds live callbacks. */
467
- function compileBrickApplication(options) {
468
- const bind = buildBindings.get(applicationKey(options.services, options.prefix));
469
- if (bind && options.mode !== "generic") return bind(options.services);
470
- const { ir, bindings } = analyzeApplication(options.services, options.prefix);
471
- const factories = options.mode === "generic" ? ir.routes.map(() => (plan) => (context) => executeCompiledRoute(plan, context)) : ir.routes.map((route) => new Function(`return (${emitHandlerFactory(route)});`)());
472
- if (options.mode !== "generic") for (const service of options.services) service.prepareContributions();
473
- return bindAnalyzed(ir, bindings, factories);
474
- }
475
- /** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */
476
- function bindCompiledApplication(ir, services, factories) {
477
- if (ir.version !== 1 || ir.target !== "bun-elysia") throw new Error("Brick compiler: unsupported IR version or target; rebuild the application");
478
- const analyzed = analyzeApplication(services, ir.prefix);
479
- if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir)) throw new Error("Brick compiler: application definitions differ from the compiled IR; rebuild the application");
480
- for (const service of services) service.prepareContributions();
481
- return bindAnalyzed(ir, analyzed.bindings, factories);
482
- }
483
- //#endregion
484
- export { emitCompiledApplication as a, loadBrickApp as i, compileBrickApplication as n, emitHandlerFactory as o, loadCompiledBrickApp as r, bindCompiledApplication as t };
8
+ export { emitHandlerFactory as a, emitCompiledApplication as i, compileBrickApplication as n, loadCompiledBrickApp as r, bindCompiledApplication as t };
485
9
 
486
10
  //# sourceMappingURL=compiler2.js.map