@brickkit/core 0.4.1 → 0.5.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/dist/index.js CHANGED
@@ -1,1247 +1,226 @@
1
- import { a as isBrickTransportError, i as isBrickServerError, n as BrickTransportError, o as ActionExecutionError, r as createBrickClient, s as ValidationError, t as BrickServerError } from "./chunks/client.js";
2
- import { createRequire } from "node:module";
3
- import { Type, Type as t } from "@sinclair/typebox";
4
- import { TypeCompiler } from "@sinclair/typebox/compiler";
5
- import { Elysia } from "elysia";
6
- import { blob, foreignKey, index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
7
- import postgres from "postgres";
8
- import { drizzle } from "drizzle-orm/postgres-js";
9
- import { Table, and, asc, desc, eq, getTableColumns, getTableColumns as getTableColumns$1, getTableName, getTableName as getTableName$1, gt, gte, ilike, inArray, is, isNotNull, isNull, like, lt, lte, ne, not, notInArray, or, relations, sql, sql as sql$1 } from "drizzle-orm";
10
- import { mkdirSync } from "node:fs";
11
- import { dirname } from "node:path";
12
- //#region \0rolldown/runtime.js
13
- var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
14
- //#endregion
15
- //#region src/compiler/ir.ts
16
- function freezeIR(value) {
17
- if (value && typeof value === "object" && !Object.isFrozen(value)) {
18
- for (const child of Object.values(value)) freezeIR(child);
19
- Object.freeze(value);
20
- }
21
- return value;
22
- }
23
- function schemaSnapshot(schema) {
24
- return schema === void 0 ? void 0 : JSON.parse(JSON.stringify(schema));
25
- }
26
- function analyzeApplication(services, prefix = "/api") {
27
- for (const service of services) service.build();
28
- return analyzeDeclaredApplication(services, prefix);
29
- }
30
- /** Inspect current declarations without closing service/plugin setup. */
31
- function analyzeDeclaredApplication(services, prefix = "/api") {
32
- if (!prefix.startsWith("/")) throw new Error("Brick compiler: prefix must start with '/'");
33
- const names = /* @__PURE__ */ new Set();
34
- for (const service of services) {
35
- if (names.has(service.name)) throw new Error(`Brick compiler: duplicate service '${service.name}'`);
36
- names.add(service.name);
37
- }
38
- const routes = [];
39
- const bindings = [];
40
- const registered = /* @__PURE__ */ new Map();
41
- const diagnostics = [];
42
- const add = (service, action, method, path, kind) => {
43
- if (!path.startsWith("/")) throw new Error(`Brick compiler: invalid route '${method} ${path}'`);
44
- const plugin = getPluginActionRoute(action, prefix) !== void 0;
45
- const key = `${method} ${path.replace(/:[^/]+/g, ":param")}`;
46
- const previous = registered.get(key);
47
- if (previous) {
48
- if (plugin || previous.plugin) throw new Error(`Brick compiler: duplicate plugin route '${method} ${path}'`);
49
- diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (first registration wins)`);
50
- return;
51
- }
52
- if (typeof action.config.execute !== "function") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);
53
- registered.set(key, {
54
- name: `${service.name}.${action.name}`,
55
- plugin
56
- });
57
- 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");
58
- const coercions = [];
59
- for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) if (prop.type === "number" || prop.type === "integer") coercions.push({
60
- key,
61
- type: "number"
62
- });
63
- else if (prop.type === "boolean") coercions.push({
64
- key,
65
- type: "boolean"
66
- });
67
- routes.push({
68
- method,
69
- path,
70
- service: service.name,
71
- action: action.name,
72
- kind,
73
- input: Boolean(action.config.input),
74
- output: Boolean(action.config.output),
75
- context: typeof service.options.context === "function",
76
- authorize: typeof action.config.authorize === "function",
77
- inputPrecedence: readLike ? [
78
- "query",
79
- "params",
80
- "body"
81
- ] : [
82
- "params",
83
- "body",
84
- "query"
85
- ],
86
- coercions,
87
- inputSchema: schemaSnapshot(action.config.input),
88
- outputSchema: schemaSnapshot(action.config.output)
89
- });
90
- bindings.push({
91
- service,
92
- action
93
- });
94
- };
95
- for (const service of services) for (const action of service.listActions()) {
96
- const pluginRoute = getPluginActionRoute(action, prefix);
97
- if (pluginRoute === false) continue;
98
- const path = pluginRoute?.path ?? action.config.path ?? `${prefix}/${service.name}/${action.name}`;
99
- add(service, action, pluginRoute?.method ?? action.config.method ?? "POST", path, "action");
100
- }
101
- const preparations = services.flatMap((service) => service.listPreparations().map((contribution) => ({
102
- service: service.name,
103
- name: contribution.name,
104
- metadata: schemaSnapshot(contribution.describe?.())
105
- })));
106
- return {
107
- ir: freezeIR({
108
- version: 1,
109
- target: "bun-elysia",
110
- prefix,
111
- services: [...names],
112
- routes,
113
- preparations,
114
- diagnostics
115
- }),
116
- bindings
117
- };
118
- }
119
- //#endregion
120
- //#region src/registry.ts
121
- var ServiceRegistry = class {
122
- _revision = 0;
123
- /** Definition revision for invalidating serialized architecture snapshots. */
124
- get revision() {
125
- return this._revision;
126
- }
127
- touch() {
128
- this._revision++;
129
- }
130
- services = /* @__PURE__ */ new Map();
131
- routes = /* @__PURE__ */ new Map();
132
- /** Remember the actual registered routes for subsequent registry exports. */
133
- setApplicationRoutes(application) {
134
- for (const service of application.services) this.routes.set(service, application.routes.filter((route) => route.service === service.name));
135
- this.touch();
136
- }
137
- register(service) {
138
- if (this.services.has(service.name)) console.warn(`[Brick-TS] Service '${service.name}' is already registered. Overwriting.`);
139
- const previous = this.services.get(service.name);
140
- if (previous) this.routes.delete(previous);
141
- this.services.set(service.name, service);
142
- this.touch();
143
- }
144
- get(name) {
145
- return this.services.get(name);
146
- }
147
- has(name) {
148
- return this.services.has(name);
149
- }
150
- list() {
151
- return Array.from(this.services.values());
152
- }
153
- clear() {
154
- this.services.clear();
155
- this.routes.clear();
156
- this.touch();
157
- }
158
- exportArchitecture(application) {
159
- return {
160
- version: "1.0.0",
161
- services: (application?.services ?? this.list()).map((service) => {
162
- const routes = application ? application.routes.filter((route) => route.service === service.name) : this.routes.get(service) ?? analyzeDeclaredApplication([service]).ir.routes;
163
- const byAction = new Map(routes.map((route) => [route.action, route]));
164
- const schema = service.introspect();
165
- return {
166
- ...schema,
167
- actions: schema.actions.map((action) => {
168
- const route = byAction.get(action.name);
169
- return route ? {
170
- ...action,
171
- method: route.method,
172
- path: route.path
173
- } : action;
174
- })
175
- };
176
- })
177
- };
178
- }
179
- };
180
- let globalRegistry = new ServiceRegistry();
181
- function getGlobalRegistry() {
182
- return globalRegistry;
183
- }
184
- function resetGlobalRegistry() {
185
- globalRegistry = new ServiceRegistry();
186
- }
187
- //#endregion
188
- //#region src/error-response.ts
189
- /** Preserve declared failures, log and wrap unexpected throws without exposing internals. */
190
- function normalizeActionError(err, { logger, requestId }) {
191
- if (err instanceof ActionExecutionError || err instanceof ValidationError) return err;
192
- logger.error("Unexpected action error", { requestId }, err);
193
- const failure = new ActionExecutionError("INTERNAL_SERVER_ERROR", "Internal Server Error", 500, void 0, { cause: err });
194
- failure.name = "InternalServerError";
195
- return failure;
196
- }
197
- function toErrorResponse(err, context) {
198
- const failure = normalizeActionError(err, context);
199
- if (failure.status >= 500 && (err instanceof ActionExecutionError || err instanceof ValidationError)) context.logger.error("Server action error", { requestId: context.requestId }, err);
200
- if (failure instanceof ValidationError && failure.status >= 500) return {
201
- name: failure.name,
202
- code: failure.code,
203
- message: failure.message,
204
- status: failure.status,
205
- requestId: context.requestId
206
- };
207
- return {
208
- ...failure.toJSON(),
209
- requestId: context.requestId
210
- };
211
- }
212
- //#endregion
213
- //#region src/typebox.ts
214
- const compilerCache = /* @__PURE__ */ new WeakMap();
215
- function getCompiledCheck(schema) {
216
- let compiled = compilerCache.get(schema);
217
- if (!compiled) {
218
- compiled = TypeCompiler.Compile(schema);
219
- compilerCache.set(schema, compiled);
220
- }
221
- return compiled;
222
- }
223
- function validateWithSchema(schema, value) {
224
- if (!schema) return {
225
- success: true,
226
- data: value
227
- };
228
- const check = getCompiledCheck(schema);
229
- if (check.Check(value)) return {
230
- success: true,
231
- data: value
232
- };
233
- const errors = [];
234
- for (const error of check.Errors(value)) errors.push({
235
- path: error.path,
236
- message: error.message,
237
- value: error.value,
238
- type: error.type
1
+ import { c as action, l as endpoint, s as errors_exports } from "./chunks/errors.js";
2
+ import { Context, Effect, Exit, Fiber, Layer, Scope } from "effect";
3
+ import { HttpApi, HttpApiBuilder, HttpApiGroup, HttpApiScalar, OpenApi } from "effect/http-api";
4
+ import { HttpEffect, HttpRouter, HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";
5
+ import { RpcGroup, RpcSerialization, RpcServer } from "effect/rpc";
6
+ import { McpServer, Toolkit } from "effect/ai";
7
+ //#region src/native/transports.ts
8
+ /** The same schema-only metadata can construct groups on both sides of the wire. */
9
+ const rpcGroup = (actions) => RpcGroup.make(...Object.values(actions).map((action) => action.rpc));
10
+ function rpcRoutes(actions, options) {
11
+ const group = rpcGroup(actions);
12
+ const build = Effect.gen(function* () {
13
+ const context = yield* Effect.context();
14
+ return Object.fromEntries(Object.values(actions).map((action) => [action.rpc._tag, (input) => Effect.flatMap(Effect.context(), (current) => action.handler(input).pipe(Effect.provideContext(Context.merge(context, current))))]));
239
15
  });
240
- return {
241
- success: false,
242
- errors
243
- };
244
- }
245
- //#endregion
246
- //#region src/action.ts
247
- const defaultLogger$1 = {
248
- info: (...args) => console.log("[INFO]", ...args),
249
- warn: (...args) => console.warn("[WARN]", ...args),
250
- error: (...args) => console.error("[ERROR]", ...args),
251
- debug: (...args) => console.debug("[DEBUG]", ...args)
252
- };
253
- const DEFAULT_REQUEST$3 = new Request("http://localhost");
254
- let _defaultCtxSeq = 0;
255
- const RESOLVED_SYMBOL$1 = Symbol("resolved");
256
- const standardErrorDefaults = {
257
- BAD_REQUEST: {
258
- status: 400,
259
- message: "Bad Request"
260
- },
261
- UNAUTHORIZED: {
262
- status: 401,
263
- message: "Unauthorized"
264
- },
265
- FORBIDDEN: {
266
- status: 403,
267
- message: "Forbidden"
268
- },
269
- NOT_FOUND: {
270
- status: 404,
271
- message: "Not Found"
272
- },
273
- CONFLICT: {
274
- status: 409,
275
- message: "Conflict"
276
- },
277
- INTERNAL_SERVER_ERROR: {
278
- status: 500,
279
- message: "Internal Server Error"
280
- }
281
- };
282
- function createDefaultContext(partial) {
283
- if (partial?.[RESOLVED_SYMBOL$1]) return partial;
284
- const seq = (++_defaultCtxSeq).toString(36);
285
- return {
286
- request: partial?.request ?? DEFAULT_REQUEST$3,
287
- traceId: partial?.traceId || `tr_${seq}`,
288
- requestId: partial?.requestId || `req_${seq}`,
289
- db: partial?.db,
290
- user: partial?.user,
291
- logger: partial?.logger || defaultLogger$1,
292
- services: partial?.services || {},
293
- metadata: partial?.metadata || {},
294
- ...partial,
295
- [RESOLVED_SYMBOL$1]: true
296
- };
297
- }
298
- function buildErrorHelpers(errorsDef) {
299
- const helpers = {};
300
- for (const [code, def] of Object.entries(standardErrorDefaults)) helpers[code] = (overrideMessage, details, options) => {
301
- const message = overrideMessage || def.message;
302
- const status = def.status;
303
- throw new ActionExecutionError(code, message, status, details, options);
304
- };
305
- if (errorsDef) for (const [code, def] of Object.entries(errorsDef)) helpers[code] = (overrideMessage, details, options) => {
306
- const message = overrideMessage || def.message;
307
- const status = def.status || 400;
308
- throw new ActionExecutionError(code, message, status, details, options);
309
- };
310
- return helpers;
311
- }
312
- function defineAction(config) {
313
- const errorHelpers = buildErrorHelpers(config.errors);
314
- const actionFn = (async (params) => {
315
- return actionFn.execute(params);
16
+ return RpcServer.layerHttp({
17
+ group,
18
+ path: options.path,
19
+ protocol: "http",
20
+ disableFatalDefects: true
21
+ }).pipe(Layer.provide(group.toLayer(build)), Layer.provide(RpcSerialization.layerJson));
22
+ }
23
+ function mcpRoutes(actions, options) {
24
+ const exposed = Object.values(actions).filter((action) => action.mcp);
25
+ const tools = Toolkit.make(...exposed.map((action) => action.tool));
26
+ const build = Effect.gen(function* () {
27
+ const context = yield* Effect.context();
28
+ return Object.fromEntries(exposed.map((action) => [action.tool.name, (input) => Effect.flatMap(Effect.context(), (current) => action.handler(input).pipe(Effect.provideContext(Context.merge(context, current))))]));
316
29
  });
317
- Object.defineProperty(actionFn, "name", {
318
- value: config.name,
319
- configurable: true
320
- });
321
- actionFn.config = config;
322
- actionFn.errorHelpers = errorHelpers;
323
- actionFn.validateInput = (input) => {
324
- return validateWithSchema(config.input, input);
325
- };
326
- actionFn.validateOutput = (output) => {
327
- return validateWithSchema(actionFn.outputValidationSchema ?? config.output, output);
328
- };
329
- actionFn.run = async (input, ctx) => {
330
- return actionFn.execute({
331
- input,
332
- ctx
333
- });
334
- };
335
- actionFn.execute = async (params) => {
336
- let fullCtx;
337
- const boundService = actionFn.service;
338
- if (params?.ctx?.[RESOLVED_SYMBOL$1] === boundService) fullCtx = params.ctx;
339
- else if (boundService && typeof boundService.resolveContext === "function") fullCtx = await boundService.resolveContext(params?.ctx);
340
- else fullCtx = createDefaultContext(params?.ctx);
341
- try {
342
- if (!fullCtx.db) {
343
- if (actionFn.service?.getDb()) fullCtx.db = actionFn.service.getDb();
344
- else if (actionFn.serviceName) {
345
- const s = getGlobalRegistry().get(actionFn.serviceName);
346
- if (s?.getDb()) fullCtx.db = s.getDb();
347
- }
348
- }
349
- if (config.input) {
350
- const inputValidation = actionFn.validateInput(params?.input);
351
- if (!inputValidation.success) throw new ValidationError(`Validation failed for action '${config.name}' input`, inputValidation.errors);
352
- }
353
- if (config.authorize) {
354
- if (!await config.authorize({
355
- user: fullCtx.user,
356
- input: params?.input,
357
- ctx: fullCtx
358
- })) throw new ActionExecutionError(fullCtx.user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${config.name}'`, fullCtx.user == null ? 401 : 403);
359
- }
360
- const result = await config.execute({
361
- input: params?.input,
362
- ctx: fullCtx,
363
- error: errorHelpers
364
- });
365
- if (actionFn.outputValidationSchema ?? config.output) {
366
- const outputValidation = actionFn.validateOutput(result);
367
- if (!outputValidation.success) throw new ValidationError(`Validation failed for action '${config.name}' output`, outputValidation.errors, 500);
368
- }
369
- return result;
370
- } catch (err) {
371
- throw normalizeActionError(err, fullCtx);
372
- }
373
- };
374
- return actionFn;
30
+ return Layer.effectDiscard(McpServer.registerToolkit(tools)).pipe(Layer.provide(tools.toLayer(build)), Layer.provide(McpServer.layerHttp(options)));
375
31
  }
376
32
  //#endregion
377
- //#region src/plugin.ts
378
- const pluginKind = Symbol.for("brickkit.plugin.kind");
379
- function defineServicePlugin(definition) {
380
- validateName(definition.name);
381
- return Object.freeze({
382
- ...definition,
383
- routes: copyControls(definition.routes),
384
- [pluginKind]: "service"
385
- });
33
+ //#region src/native/route.ts
34
+ /** Capture application services once, and use request services at invocation. */
35
+ function route(method, path, handler) {
36
+ return Layer.unwrap(Effect.gen(function* () {
37
+ const context = yield* Effect.context();
38
+ return HttpRouter.add(method, path, Effect.flatMap(Effect.context(), (current) => handler.pipe(Effect.provideContext(Context.merge(context, current)))));
39
+ }));
386
40
  }
387
- function defineResourcePlugin(definition) {
388
- validateName(definition.name);
41
+ //#endregion
42
+ //#region src/native/kernel.ts
43
+ const service = (name, options) => {
44
+ const { actions } = options;
45
+ for (const [key, value] of Object.entries(actions)) if (key !== value.endpoint.identifier) throw new Error("Action key and identifier differ");
46
+ let group = HttpApiGroup.make(name);
47
+ for (const a of Object.values(actions)) group = group.add(a.endpoint);
389
48
  return Object.freeze({
390
- ...definition,
391
- routes: copyControls(definition.routes),
392
- [pluginKind]: "resource"
49
+ name,
50
+ actions: Object.freeze({ ...actions }),
51
+ group
393
52
  });
394
- }
395
- function validateName(name) {
396
- if (!name || name.trim() !== name) throw new Error("Plugin and route names must be nonempty and have no surrounding whitespace");
397
- }
398
- function validatePath(path) {
399
- if (!path.startsWith("/") || path.includes("?") || path.includes("#") || path.includes("//") || path.split("/").some((part) => part === "." || part === "..")) throw new Error(`Invalid plugin route path '${path}'`);
400
- }
401
- function copyControls(controls) {
402
- if (controls === void 0 || controls === false) return controls;
403
- const result = Object.create(null);
404
- for (const [name, value] of Object.entries(controls)) {
405
- validateName(name);
406
- if (value === false) {
407
- result[name] = false;
408
- continue;
409
- }
410
- if (value.path !== void 0) validatePath(value.path);
411
- if (value.scope !== void 0 && ![
412
- "app",
413
- "service",
414
- "resource"
415
- ].includes(value.scope)) throw new Error(`Invalid plugin route scope '${value.scope}'`);
416
- result[name] = Object.freeze({ ...value });
417
- }
418
- return Object.freeze(result);
419
- }
420
- const states = /* @__PURE__ */ new WeakMap();
421
- const actionBindings = /* @__PURE__ */ new WeakMap();
422
- /**
423
- * Cross-copy binding protocol. Bundler SSR runtimes (Vite, Nitro, Vitest)
424
- * may load a second copy of core that owns a different WeakMap, while the
425
- * action objects themselves cross the boundary by reference. The binding
426
- * travels on the action under a process-global symbol so route lookups
427
- * (including disabled-route suppression) keep working there.
428
- */
429
- const actionBindingKey = Symbol.for("brickkit.plugin.actionBinding");
430
- function stateOf(service) {
431
- let state = states.get(service);
432
- if (!state) {
433
- state = {
434
- hosts: /* @__PURE__ */ new Map(),
435
- actions: /* @__PURE__ */ new Map(),
436
- endpoints: []
437
- };
438
- states.set(service, state);
439
- }
440
- return state;
441
- }
442
- function isInstallingPlugin(service) {
443
- return [...states.get(service)?.hosts.values() ?? []].some((installations) => [...installations.values()].some((item) => item.status === "installing"));
444
- }
445
- function pathOf(binding, prefix) {
446
- const scope = binding.scope === "app" ? "" : `/${binding.scope === "resource" ? binding.resource.name : binding.service.name}`;
447
- return `${prefix.replace(/\/$/, "")}${scope}${binding.path === "/" ? "" : binding.path}` || "/";
448
- }
449
- function getPluginActionRoute(action, prefix = "/api") {
450
- const binding = action[actionBindingKey] ?? actionBindings.get(action);
451
- if (!binding) return void 0;
452
- if (!binding.enabled) return false;
453
- return {
454
- path: pathOf(binding, prefix),
455
- method: binding.method,
456
- clientPath: binding.clientPath,
457
- plugin: binding.plugin,
458
- resource: binding.resource?.name
459
- };
460
- }
461
- function getPluginEndpoints(service, prefix = "/api") {
462
- return stateOf(service).endpoints.filter((binding) => binding.enabled).map((binding) => ({
463
- path: pathOf(binding, prefix),
464
- method: binding.method,
465
- service,
466
- summary: binding.summary,
467
- description: binding.description,
468
- tags: binding.tags,
469
- handler: async (context) => binding.handler({
470
- ...context,
471
- ctx: await service.resolveContext({ request: context.request })
472
- })
53
+ };
54
+ function compileService(s) {
55
+ const api = HttpApi.make("brick").add(s.group);
56
+ const runtimeApi = api;
57
+ const checkedImplementation = HttpApiBuilder.group(runtimeApi, String(s.name), (h) => Effect.gen(function* () {
58
+ const context = yield* Effect.context();
59
+ const handlers = {};
60
+ for (const a of Object.values(s.actions)) handlers[a.endpoint.identifier] = (input) => Effect.flatMap(Effect.context(), (requestContext) => a.httpHandler(input).pipe(Effect.provideContext(Context.merge(context, requestContext))));
61
+ return h.handleAll(handlers);
473
62
  }));
474
- }
475
- /** Descriptor identity is scoped to the service or resource installation host. */
476
- function installPlugin(service, resource, descriptor) {
477
- if (service.isBuilt) throw new Error("Plugins must be installed before service build");
478
- if (descriptor[pluginKind] !== (resource ? "resource" : "service")) throw new Error("Plugin does not support this installation host");
479
- const state = stateOf(service);
480
- const host = resource ?? service;
481
- const existing = state.hosts.get(host)?.get(descriptor.name);
482
- if (existing) {
483
- if (existing.status === "installing") throw new Error(`Plugin dependency cycle at '${descriptor.name}'`);
484
- if (existing.descriptor !== descriptor) throw new Error(`Plugin '${descriptor.name}' already installed with a different descriptor; reuse the original descriptor`);
485
- return resource ?? existing.api;
486
- }
487
- const snapshots = {
488
- actions: new Map(service.actions),
489
- tools: new Map(service.tools),
490
- tables: new Map(service.tables),
491
- resources: new Map(service.resources),
492
- preparations: new Map(service.preparations),
493
- hosts: new Map([...state.hosts].map(([key, installations]) => [key, new Map(installations)])),
494
- bindings: new Map(state.actions),
495
- endpoints: [...state.endpoints],
496
- properties: new Map([...service.resources.values()].map((item) => [item, Object.getOwnPropertyDescriptors(item)]))
497
- };
498
- const installations = state.hosts.get(host) ?? /* @__PURE__ */ new Map();
499
- state.hosts.set(host, installations);
500
- installations.set(descriptor.name, {
501
- descriptor,
502
- status: "installing"
63
+ return Object.freeze({
64
+ api,
65
+ implementation: checkedImplementation
503
66
  });
504
- const names = /* @__PURE__ */ new Set();
505
- const ownedActions = /* @__PURE__ */ new Set();
506
- let active = true;
507
- const bindingFor = (config) => {
508
- if (!active || service.isBuilt) throw new Error("Plugin routes can only be registered during setup");
509
- validateName(config.name);
510
- validatePath(config.path);
511
- if (names.has(config.name)) throw new Error(`Duplicate plugin route name '${config.name}'`);
512
- names.add(config.name);
513
- const control = descriptor.routes === false ? false : descriptor.routes?.[config.name];
514
- const scope = control && control.scope || config.scope || (resource ? "resource" : "service");
515
- if (scope === "resource" && !resource) throw new Error("Service plugin routes cannot use resource scope");
516
- if (![
517
- "app",
518
- "service",
519
- "resource"
520
- ].includes(scope)) throw new Error(`Invalid plugin route scope '${scope}'`);
521
- if (![
522
- "GET",
523
- "POST",
524
- "PUT",
525
- "PATCH",
526
- "DELETE"
527
- ].includes(config.method)) throw new Error(`Invalid plugin route method '${config.method}'`);
528
- const path = control && control.path || config.path;
529
- validatePath(path);
530
- return {
531
- service,
532
- resource,
533
- plugin: descriptor.name,
534
- path,
535
- method: config.method,
536
- scope,
537
- enabled: control !== false
538
- };
539
- };
540
- const routes = {
541
- action(config) {
542
- const binding = bindingFor(config);
543
- for (const match of binding.path.matchAll(/:([A-Za-z0-9_]+)/g)) if (!config.input?.properties || !Object.hasOwn(config.input.properties, match[1])) throw new Error(`Plugin action path parameter '${match[1]}' must be declared in its input schema`);
544
- const name = `${resource ? `${resource.name}.` : ""}${config.name}`;
545
- if (service.actions.has(name)) throw new Error(`Duplicate plugin action '${name}' (from plugin '${descriptor.name}')`);
546
- const { scope: _scope, ...actionConfig } = config;
547
- const action = defineAction({
548
- ...actionConfig,
549
- name
550
- });
551
- action.plugin = descriptor.name;
552
- if (resource) action.resource = resource.name;
553
- service.action(action);
554
- ownedActions.add(action);
555
- state.actions.set(action, binding);
556
- actionBindings.set(action, binding);
557
- action[actionBindingKey] = binding;
558
- return action;
559
- },
560
- endpoint(config) {
561
- const binding = bindingFor(config);
562
- state.endpoints.push({
563
- ...binding,
564
- handler: config.handler,
565
- summary: config.summary,
566
- description: config.description,
567
- tags: config.tags
568
- });
569
- }
570
- };
571
- try {
572
- const api = resource ? descriptor.setup({
573
- service,
574
- resource,
575
- routes
576
- }) : descriptor.setup({
577
- service,
578
- routes
579
- });
580
- if (api && typeof api === "object" && "then" in api) throw new Error("Plugin setup must be synchronous");
581
- if (descriptor.routes && Object.keys(descriptor.routes).some((name) => !names.has(name))) throw new Error(`Plugin '${descriptor.name}' has an override for an unknown route`);
582
- const walk = (value, path, ancestors) => {
583
- if (typeof value === "function") {
584
- const binding = state.actions.get(value);
585
- if (binding && ownedActions.has(value)) {
586
- if (binding.clientPath) throw new Error("Plugin actions must have one returned API path");
587
- binding.clientPath = [resource?.name ?? service.name, ...path];
588
- }
589
- } else if (value && typeof value === "object" && !ancestors.has(value)) {
590
- const next = new Set(ancestors).add(value);
591
- for (const [key, child] of Object.entries(value)) walk(child, [...path, key], next);
592
- }
593
- };
594
- walk(api, [], /* @__PURE__ */ new Set());
595
- if (resource) {
596
- if (!api || typeof api !== "object" || Array.isArray(api)) throw new Error("Resource plugins must return named API contributions");
597
- for (const key of Object.keys(api)) if (key in resource || [
598
- "__proto__",
599
- "prototype",
600
- "constructor"
601
- ].includes(key)) throw new Error(`Resource plugin contribution '${key}' collides with an existing property`);
602
- Object.assign(resource, api);
603
- }
604
- state.hosts.get(host).set(descriptor.name, {
605
- descriptor,
606
- status: "installed",
607
- api
608
- });
609
- getGlobalRegistry().touch();
610
- return resource ?? api;
611
- } catch (error) {
612
- for (const action of state.actions.keys()) if (!snapshots.bindings.has(action)) {
613
- actionBindings.delete(action);
614
- delete action[actionBindingKey];
615
- }
616
- restoreMap(service.actions, snapshots.actions);
617
- restoreMap(service.tools, snapshots.tools);
618
- restoreMap(service.tables, snapshots.tables);
619
- restoreMap(service.resources, snapshots.resources);
620
- restoreMap(service.preparations, snapshots.preparations);
621
- state.hosts = snapshots.hosts;
622
- state.actions = snapshots.bindings;
623
- state.endpoints = snapshots.endpoints;
624
- for (const [item, properties] of snapshots.properties) {
625
- for (const key of Reflect.ownKeys(item)) if (!Object.hasOwn(properties, key)) Reflect.deleteProperty(item, key);
626
- Object.defineProperties(item, properties);
627
- }
628
- getGlobalRegistry().touch();
629
- throw error;
630
- } finally {
631
- active = false;
632
- }
633
- }
634
- function restoreMap(target, snapshot) {
635
- target.clear();
636
- for (const [key, value] of snapshot) target.set(key, value);
637
67
  }
638
- //#endregion
639
- //#region src/compiler/runtime.ts
640
- const EMPTY_SERVICES$2 = Object.freeze({});
641
- const DEFAULT_REQUEST$2 = new Request("http://localhost");
642
- let sequence = 0;
643
- function isNonEmpty$1(value) {
644
- if (value == null) return false;
645
- for (const _ in value) return true;
646
- return false;
647
- }
648
- /** Retains Brick's existing source precedence and treatment of empty bodies. */
649
- function mergeInput(first, second, third) {
650
- const a = isNonEmpty$1(first), b = isNonEmpty$1(second), c = isNonEmpty$1(third);
651
- if (a && !b && !c) return first;
652
- if (b && !a && !c) return second;
653
- if (c && !a && !b) return third;
654
- if (a || b || c) return Object.assign({}, first, second, third);
655
- }
656
- const MAX_INPUT_DEPTH = 128;
657
- function inputTooDeep(value) {
658
- if (!value || typeof value !== "object") return false;
659
- const stack = [{
660
- node: value,
661
- depth: 0
662
- }];
663
- while (stack.length > 0) {
664
- const { node, depth } = stack.pop();
665
- if (depth > MAX_INPUT_DEPTH) return true;
666
- if (node && typeof node === "object") {
667
- const children = Array.isArray(node) ? node : Object.values(node);
668
- for (const child of children) if (child && typeof child === "object") stack.push({
669
- node: child,
670
- depth: depth + 1
671
- });
672
- }
673
- }
674
- return false;
675
- }
676
- function checkDepth(value, action) {
677
- if (!inputTooDeep(value)) return;
678
- throw new ValidationError(`Validation failed for action '${action}' input`, [{
679
- path: "",
680
- message: "Input exceeds maximum nesting depth"
681
- }]);
682
- }
683
- function validate(check, value, action, stage) {
684
- if (check.Check(value)) return;
685
- const errors = Array.from(check.Errors(value)).map((err) => ({
686
- path: err.path,
687
- message: err.message,
688
- value: err.value
689
- }));
690
- throw new ValidationError(`Validation failed for action '${action}' ${stage}`, errors, stage === "output" ? 500 : 400);
691
- }
692
- function mapError(err, set, options) {
693
- const response = toErrorResponse(err, options);
694
- set.status = response.status;
695
- return response;
696
- }
697
- const compilerRuntime = Object.freeze({
698
- emptyServices: EMPTY_SERVICES$2,
699
- defaultRequest: DEFAULT_REQUEST$2,
700
- nextSequence: () => (++sequence).toString(36),
701
- mergeInput,
702
- checkDepth,
703
- validate,
704
- mapError,
705
- isThenable: (value) => value != null && typeof value.then === "function",
706
- deny: (action, user) => {
707
- throw new ActionExecutionError(user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${action}'`, user == null ? 401 : 403);
708
- }
709
- });
710
- //#endregion
711
- //#region src/action-handler.ts
712
- let _srvSeq = 0;
713
- const EMPTY_SERVICES$1 = Object.freeze({});
714
- const DEFAULT_REQUEST$1 = new Request("http://localhost");
715
- function isNonEmpty(obj) {
716
- if (obj == null) return false;
717
- for (const _ in obj) return true;
718
- return false;
719
- }
720
- function compileRoutePlan(service, action, routePath, method) {
721
- const actionName = action.name;
722
- const serviceName = service.name;
723
- const isGetLike = method === "GET" || actionName.startsWith("get") || actionName.endsWith(".get") || actionName.startsWith("list") || actionName.endsWith(".list") || actionName.startsWith("find") || actionName.startsWith("read");
724
- const inputSchema = action.config?.input;
725
- const outputSchema = action.config?.output;
726
- const hasInput = Boolean(inputSchema);
727
- const inputChecker = inputSchema ? getCompiledCheck(inputSchema) : void 0;
728
- const runtimeOutputSchema = action.outputValidationSchema ?? outputSchema;
729
- const outputChecker = runtimeOutputSchema ? getCompiledCheck(runtimeOutputSchema) : void 0;
730
- let coercions;
731
- if (inputSchema && typeof inputSchema.properties === "object") {
732
- const list = [];
733
- for (const [key, prop] of Object.entries(inputSchema.properties)) {
734
- const type = prop?.type;
735
- if (type === "number" || type === "integer") list.push({
736
- key,
737
- isNumber: true,
738
- isBoolean: false
739
- });
740
- else if (type === "boolean") list.push({
741
- key,
742
- isNumber: false,
743
- isBoolean: true
744
- });
745
- }
746
- if (list.length > 0) coercions = list;
747
- }
748
- const contextHook = service.options?.context;
749
- const hasContextHook = typeof contextHook === "function";
750
- const authorize = action.config?.authorize;
751
- const hasAuthorize = typeof authorize === "function";
752
- const execute = action.config?.execute;
753
- const tag = `[${serviceName}:${actionName}]`;
754
- const logger = {
755
- info: (...args) => console.log(tag, ...args),
756
- warn: (...args) => console.warn(tag, ...args),
757
- error: (...args) => console.error(tag, ...args),
758
- debug: (...args) => console.debug(tag, ...args)
759
- };
760
- const errorBuilder = action.errorHelpers ?? buildErrorHelpers(action.config?.errors);
761
- const cachedDb = service.getDb();
762
- return {
763
- service,
764
- action,
765
- actionName,
766
- serviceName,
767
- routePath,
768
- method,
769
- isGetLike,
770
- hasInput,
771
- hasContextHook,
772
- contextHook,
773
- hasAuthorize,
774
- authorize,
775
- execute,
776
- inputChecker,
777
- outputChecker,
778
- coercions,
779
- logger,
780
- errorBuilder,
781
- cachedDb
782
- };
783
- }
784
- async function executeCompiledRoute(plan, elysiaCtx) {
785
- const { params, body, query, headers, request, set } = elysiaCtx;
786
- const seq = (++_srvSeq).toString(36);
787
- const traceId = headers && headers["x-trace-id"] || `tr_${seq}`;
788
- const requestId = headers && headers["x-request-id"] || `req_${seq}`;
789
- if (set?.headers) {
790
- set.headers["x-trace-id"] = traceId;
791
- set.headers["x-request-id"] = requestId;
792
- }
793
- let input;
794
- if (plan.hasInput) {
795
- let coercedQuery = query;
796
- if (query && plan.coercions && plan.coercions.length > 0) {
797
- coercedQuery = { ...query };
798
- for (let i = 0; i < plan.coercions.length; i++) {
799
- const c = plan.coercions[i];
800
- const val = query[c.key];
801
- if (val !== void 0) {
802
- if (c.isNumber) {
803
- const num = Number(val);
804
- if (!isNaN(num)) coercedQuery[c.key] = num;
805
- } else if (c.isBoolean) {
806
- if (val === "true" || val === "1") coercedQuery[c.key] = true;
807
- else if (val === "false" || val === "0") coercedQuery[c.key] = false;
68
+ function layer(s) {
69
+ const compiled = compileService(s);
70
+ return HttpApiBuilder.layer(compiled.api).pipe(Layer.provide(compiled.implementation), Layer.provide(HttpServer.layerServices));
71
+ }
72
+ const mount = (routes) => {
73
+ let handler;
74
+ let startup;
75
+ let startupFiber;
76
+ let closing;
77
+ const scope = Scope.makeUnsafe();
78
+ let disposed = false;
79
+ const active = /* @__PURE__ */ new Map();
80
+ const ready = () => {
81
+ if (disposed) return Promise.reject(/* @__PURE__ */ new Error("Brick application is disposed"));
82
+ if (!startup) {
83
+ startupFiber = Effect.runFork(Effect.gen(function* () {
84
+ const context = yield* Layer.buildWithScope(Layer.provideMerge(routes, HttpRouter.layer), scope);
85
+ const router = Context.get(context, HttpRouter.HttpRouter);
86
+ const tracked = Effect.gen(function* () {
87
+ const request = yield* HttpServerRequest.HttpServerRequest;
88
+ if (request.source instanceof Request) {
89
+ const entry = active.get(request.source.signal);
90
+ if (entry) yield* Effect.addFinalizer(() => Effect.sync(entry.complete));
808
91
  }
809
- }
810
- }
811
- }
812
- const hasP = isNonEmpty(params);
813
- const hasB = isNonEmpty(body);
814
- const hasQ = isNonEmpty(coercedQuery);
815
- if (plan.isGetLike) {
816
- if (hasQ && !hasP && !hasB) input = coercedQuery;
817
- else if (hasP && !hasQ && !hasB) input = params;
818
- else if (hasB && !hasP && !hasQ) input = body;
819
- else if (hasQ || hasP || hasB) input = Object.assign({}, coercedQuery, params, body);
820
- } else if (hasB && !hasP && !hasQ) input = body;
821
- else if (hasP && !hasB && !hasQ) input = params;
822
- else if (hasQ && !hasP && !hasB) input = coercedQuery;
823
- else if (hasP || hasB || hasQ) input = Object.assign({}, params, body, coercedQuery);
824
- }
825
- const ctx = {
826
- request: request instanceof Request ? request : DEFAULT_REQUEST$1,
827
- traceId,
828
- requestId,
829
- db: plan.cachedDb ?? plan.service.getDb(),
830
- logger: plan.logger,
831
- services: EMPTY_SERVICES$1,
832
- metadata: { headers },
833
- _resolved: true
834
- };
835
- try {
836
- if (plan.hasContextHook) {
837
- const extra = plan.contextHook(ctx);
838
- const resolved = extra instanceof Promise ? await extra : extra;
839
- if (resolved) Object.assign(ctx, resolved);
840
- }
841
- if (input === void 0 && plan.action.config?.input?.type === "object") input = {};
842
- if (plan.hasInput && plan.inputChecker) {
843
- if (inputTooDeep(input)) throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, [{
844
- path: "",
845
- message: "Input exceeds maximum nesting depth"
846
- }]);
847
- if (!plan.inputChecker.Check(input)) {
848
- const errors = Array.from(plan.inputChecker.Errors(input)).map((err) => ({
849
- path: err.path,
850
- message: err.message,
851
- value: err.value
852
- }));
853
- throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, errors);
854
- }
855
- }
856
- if (plan.hasAuthorize) {
857
- const authRes = plan.authorize({
858
- ctx,
859
- input,
860
- user: ctx.user
861
- });
862
- if (!(authRes instanceof Promise ? await authRes : authRes)) throw new ActionExecutionError(ctx.user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${plan.actionName}'`, ctx.user == null ? 401 : 403);
863
- }
864
- const execRes = plan.execute({
865
- input,
866
- ctx,
867
- error: plan.errorBuilder
868
- });
869
- const result = execRes instanceof Promise ? await execRes : execRes;
870
- if (plan.outputChecker) {
871
- if (!plan.outputChecker.Check(result)) {
872
- const errors = Array.from(plan.outputChecker.Errors(result)).map((err) => ({
873
- path: err.path,
874
- message: err.message,
875
- value: err.value
876
- }));
877
- throw new ValidationError(`Validation failed for action '${plan.actionName}' output`, errors, 500);
878
- }
879
- }
880
- return result;
881
- } catch (err) {
882
- const response = toErrorResponse(err, {
883
- logger: ctx.logger,
884
- requestId
885
- });
886
- set.status = response.status;
887
- return response;
888
- }
889
- }
890
- function createActionHandler(service, action, routePath, method) {
891
- const plan = compileRoutePlan(service, action, routePath, method);
892
- return (elysiaCtx) => executeCompiledRoute(plan, elysiaCtx);
893
- }
894
- //#endregion
895
- //#region src/compiler/handler.ts
896
- function coerceQueryValue(value, type) {
897
- if (type === "number" && value !== void 0) {
898
- const number = Number(value);
899
- return Number.isNaN(number) ? value : number;
900
- }
901
- if (type === "boolean") {
902
- if (value === "true" || value === "1") return true;
903
- if (value === "false" || value === "0") return false;
904
- }
905
- return value;
906
- }
907
- /** Bind route metadata with ordinary closures; emitted factories remain build-only. */
908
- function createHandlerFactory(route) {
909
- return (binding, runtime) => {
910
- const { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;
911
- const readLike = route.inputPrecedence[0] === "query";
912
- const objectInput = binding.action.config.input?.type === "object";
913
- const readInput = route.input ? ({ params, body, query }) => {
914
- let coercedQuery = query;
915
- if (query && route.coercions.length) {
916
- coercedQuery = { ...query };
917
- for (const { key, type } of route.coercions) if (query[key] !== void 0) coercedQuery[key] = coerceQueryValue(query[key], type);
918
- }
919
- let input = readLike ? runtime.mergeInput(coercedQuery, params, body) : runtime.mergeInput(params, body, coercedQuery);
920
- if (objectInput) input ??= {};
921
- return input;
922
- } : () => void 0;
923
- const validateInput = (input) => {
924
- if (inputChecker) {
925
- runtime.checkDepth(input, route.action);
926
- runtime.validate(inputChecker, input, route.action, "input");
927
- }
928
- };
929
- const validateOutput = (result) => {
930
- if (route.output && outputChecker) runtime.validate(outputChecker, result, route.action, "output");
931
- return result;
932
- };
933
- const createContext = ({ headers, request, set }) => {
934
- const seq = runtime.nextSequence();
935
- const traceId = headers?.["x-trace-id"] || "tr_" + seq;
936
- const requestId = headers?.["x-request-id"] || "req_" + seq;
937
- if (set?.headers) {
938
- set.headers["x-trace-id"] = traceId;
939
- set.headers["x-request-id"] = requestId;
940
- }
941
- return {
942
- request: request instanceof Request ? request : runtime.defaultRequest,
943
- traceId,
944
- requestId,
945
- db: cachedDb ?? service.getDb(),
946
- logger,
947
- services: runtime.emptyServices,
948
- metadata: { headers },
949
- _resolved: true
950
- };
951
- };
952
- if (contextHook || authorize) return async function brickAction(context) {
953
- const input = readInput(context);
954
- const ctx = createContext(context);
955
- try {
956
- if (contextHook) {
957
- const extra = await contextHook(ctx);
958
- if (extra) Object.assign(ctx, extra);
959
- }
960
- validateInput(input);
961
- if (authorize && !await authorize({
962
- ctx,
963
- input,
964
- user: ctx.user
965
- })) runtime.deny(route.action, ctx.user);
966
- return validateOutput(await execute({
967
- input,
968
- ctx,
969
- error: errorBuilder
970
- }));
971
- } catch (err) {
972
- return runtime.mapError(err, context.set, ctx);
973
- }
974
- };
975
- return function brickAction(context) {
976
- const input = readInput(context);
977
- const ctx = createContext(context);
978
- try {
979
- validateInput(input);
980
- const result = execute({
981
- input,
982
- ctx,
983
- error: errorBuilder
92
+ return yield* router.asHttpEffect();
984
93
  });
985
- if (runtime.isThenable(result)) return Promise.resolve(result).then(validateOutput).catch((err) => runtime.mapError(err, context.set, ctx));
986
- return validateOutput(result);
987
- } catch (err) {
988
- return runtime.mapError(err, context.set, ctx);
989
- }
94
+ handler = HttpEffect.toWebHandlerWith(context)(tracked);
95
+ }));
96
+ startup = Effect.runPromise(Fiber.join(startupFiber));
97
+ startup.catch(() => {});
98
+ }
99
+ return startup;
100
+ };
101
+ const fetch = async (request) => {
102
+ await ready();
103
+ if (disposed || !handler) throw new Error("Brick application is disposed");
104
+ const controller = new AbortController();
105
+ const abort = () => controller.abort(request.signal.reason);
106
+ request.signal.addEventListener("abort", abort, { once: true });
107
+ if (request.signal.aborted) abort();
108
+ const internal = new Request(request, { signal: controller.signal });
109
+ let resolve;
110
+ const done = new Promise((yes) => {
111
+ resolve = yes;
112
+ });
113
+ const complete = () => {
114
+ request.signal.removeEventListener("abort", abort);
115
+ active.delete(internal.signal);
116
+ resolve();
990
117
  };
991
- };
992
- }
993
- //#endregion
994
- //#region src/app-entry.ts
995
- function isBrickApp(app) {
996
- if (!app || typeof app !== "object") return false;
997
- 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";
998
- }
999
- function requireBrickApp(app) {
1000
- if (!isBrickApp(app)) throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
1001
- if (app.server) throw new Error("Brick: the app entry must not call .listen(); use a separate server bootstrap.");
1002
- return app;
1003
- }
1004
- //#endregion
1005
- //#region src/compiler.ts
1006
- const buildBindings = /* @__PURE__ */ new Map();
1007
- function applicationKey(services, prefix = "/api") {
1008
- return JSON.stringify([prefix, services.map((service) => service.name)]);
1009
- }
1010
- /** Build artifact bootstrap: bind generated handlers while evaluating the original app. */
1011
- async function loadCompiledBrickApp(load, ir, bind) {
1012
- const key = JSON.stringify([ir.prefix, ir.services]);
1013
- if (buildBindings.has(key)) throw new Error("Brick compiler: overlapping compiled app imports");
1014
- buildBindings.set(key, bind);
1015
- try {
1016
- const app = requireBrickApp((await load()).default);
1017
- if (applicationKey(app.definition.services, app.definition.prefix) !== key) throw new Error("Brick compiler: app services/prefix changed; rebuild the application");
1018
- return app;
1019
- } finally {
1020
- buildBindings.delete(key);
1021
- }
1022
- }
1023
- function bindAnalyzed(ir, bindings, factories) {
1024
- if (factories.length !== ir.routes.length) throw new Error("Brick compiler: handler factory count does not match IR");
1025
- const routes = ir.routes.map((route, index) => {
1026
- const { service, action } = bindings[index];
1027
- const plan = Object.freeze(compileRoutePlan(service, action, route.path, route.method));
1028
- const handler = factories[index](plan, compilerRuntime);
1029
- return Object.freeze({
1030
- ir: route,
1031
- handler
118
+ active.set(internal.signal, {
119
+ controller,
120
+ done,
121
+ complete
1032
122
  });
123
+ try {
124
+ return await handler(internal);
125
+ } catch (error) {
126
+ complete();
127
+ throw error;
128
+ }
129
+ };
130
+ const dispose = () => {
131
+ disposed = true;
132
+ closing ??= (async () => {
133
+ if (startupFiber) await Effect.runPromise(Fiber.interrupt(startupFiber));
134
+ const requests = [...active.values()];
135
+ for (const request of requests) request.controller.abort();
136
+ await Promise.all(requests.map((request) => request.done));
137
+ await Effect.runPromise(Scope.close(scope, Exit.void));
138
+ })();
139
+ return closing;
140
+ };
141
+ return Object.freeze({
142
+ fetch,
143
+ ready,
144
+ dispose
1033
145
  });
146
+ };
147
+ /** Compose closed applications. Handler and schema requirements must be supplied. */
148
+ function app(options) {
149
+ let api = HttpApi.make("brick");
150
+ let implementation = Layer.empty;
151
+ const names = /* @__PURE__ */ new Set();
152
+ const paths = /* @__PURE__ */ new Set();
153
+ for (const s of options.services) {
154
+ if (names.has(s.name)) throw new Error(`Duplicate service: ${s.name}`);
155
+ names.add(s.name);
156
+ for (const a of Object.values(s.actions)) {
157
+ const route = `${a.method} ${a.path}`;
158
+ if (paths.has(route)) throw new Error(`Duplicate route: ${route}`);
159
+ paths.add(route);
160
+ }
161
+ api = api.add(s.group);
162
+ const compiled = compileService(s);
163
+ implementation = Layer.merge(implementation, compiled.implementation);
164
+ }
165
+ const typedApi = api;
166
+ const typedImplementation = implementation;
167
+ const http = HttpApiBuilder.layer(typedApi).pipe(Layer.provide(typedImplementation));
168
+ const actions = {};
169
+ if (options.transports?.rpc || options.transports?.mcp) for (const s of options.services) for (const a of Object.values(s.actions)) {
170
+ if (Object.hasOwn(actions, a.rpc._tag)) throw new Error(`Duplicate transport action: ${a.rpc._tag}`);
171
+ actions[a.rpc._tag] = a;
172
+ }
173
+ const rpc = options.transports?.rpc ? rpcRoutes(actions, options.transports.rpc) : Layer.empty;
174
+ const mcp = options.transports?.mcp ? mcpRoutes(actions, options.transports.mcp) : Layer.empty;
175
+ const architecture = {
176
+ version: "1.0.0",
177
+ services: options.services.map((s) => ({
178
+ name: s.name,
179
+ actions: Object.values(s.actions).map((a) => ({
180
+ name: a.endpoint.identifier,
181
+ method: a.method,
182
+ path: a.path,
183
+ mcp: a.mcp
184
+ }))
185
+ }))
186
+ };
187
+ const builtin = Layer.mergeAll(route("GET", "/_health", Effect.succeed(HttpServerResponse.jsonUnsafe({
188
+ status: "ok",
189
+ uptime: process.uptime(),
190
+ timestamp: Date.now()
191
+ }))), route("GET", "/_brick/services", Effect.succeed(HttpServerResponse.jsonUnsafe(architecture))));
192
+ const routes = Layer.mergeAll(http, rpc, mcp, builtin, options.routes ?? Layer.empty).pipe(Layer.provide(options.layer), Layer.provide(HttpServer.layerServices));
193
+ const withDocs = options.docs ? Layer.merge(routes, HttpApiScalar.layer(typedApi, options.docs)) : routes;
194
+ const mounted = mount(withDocs);
1034
195
  return Object.freeze({
1035
- ir: freezeIR(ir),
1036
- routes: Object.freeze(routes)
196
+ ...mounted,
197
+ kind: "brick-native-app",
198
+ services: Object.freeze([...options.services]),
199
+ client: options.client && Object.freeze({ ...options.client }),
200
+ layer: withDocs,
201
+ api: typedApi,
202
+ openApi: () => OpenApi.fromApi(typedApi)
1037
203
  });
1038
204
  }
1039
- /** Startup compiler: analyzes once, then binds live callbacks. */
1040
- function compileBrickApplication(options) {
1041
- const bind = buildBindings.get(applicationKey(options.services, options.prefix));
1042
- if (bind && options.mode !== "generic") return bind(options.services);
1043
- const { ir, bindings } = analyzeApplication(options.services, options.prefix);
1044
- const factories = options.mode === "generic" ? ir.routes.map(() => (plan) => (context) => executeCompiledRoute(plan, context)) : ir.routes.map(createHandlerFactory);
1045
- if (options.mode !== "generic") for (const service of options.services) service.prepareContributions();
1046
- return bindAnalyzed(ir, bindings, factories);
1047
- }
1048
- /** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */
1049
- function bindCompiledApplication(ir, services, factories) {
1050
- if (ir.version !== 1 || ir.target !== "bun-elysia") throw new Error("Brick compiler: unsupported IR version or target; rebuild the application");
1051
- const analyzed = analyzeApplication(services, ir.prefix);
1052
- if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir)) throw new Error("Brick compiler: application definitions differ from the compiled IR; rebuild the application");
1053
- for (const service of services) service.prepareContributions();
1054
- return bindAnalyzed(ir, analyzed.bindings, factories);
1055
- }
1056
205
  //#endregion
1057
- //#region src/access.ts
1058
- /**
1059
- * Cross-copy access metadata protocol. CRUD enforces its access policy
1060
- * inside `execute`, so `config.authorize` is absent and introspection
1061
- * can't see it. The plugin stamps each action under this process-global
1062
- * symbol; introspection and OpenAPI read it back. Uses `Symbol.for` so
1063
- * the binding survives a second copy of core (bundler SSR, Vitest),
1064
- * same as the plugin action-binding key.
1065
- */
1066
- const ACTION_ACCESS_KEY = Symbol.for("brickkit.action.access");
1067
- function setActionAccess(action, info) {
1068
- action[ACTION_ACCESS_KEY] = {
1069
- hasAuthorize: info.hasAuthorize,
1070
- hasScope: info.hasScope,
1071
- policy: info.policy
1072
- };
1073
- }
1074
- function getActionAccess(action) {
1075
- const meta = action[ACTION_ACCESS_KEY];
1076
- const configAuthorize = Boolean(action?.config && typeof action.config === "object" && "authorize" in action.config && typeof action.config.authorize === "function");
1077
- if (!meta) return {
1078
- hasAuthorize: configAuthorize,
1079
- hasScope: false,
1080
- policy: configAuthorize ? "authorized" : "public"
1081
- };
1082
- const hasAuthorize = configAuthorize || Boolean(meta.hasAuthorize);
1083
- const hasScope = Boolean(meta.hasScope);
1084
- let policy = meta.policy ?? (hasAuthorize ? hasScope ? "scoped" : "authorized" : "public");
1085
- if (policy === "public" && hasAuthorize) policy = hasScope ? "scoped" : "authorized";
1086
- else if (policy !== "public" && !hasAuthorize) policy = "public";
1087
- else if (policy === "scoped" && !hasScope) policy = "authorized";
1088
- return {
1089
- hasAuthorize,
1090
- hasScope,
1091
- policy
1092
- };
1093
- }
206
+ //#region src/native/index.ts
207
+ /** Effect-native contracts and scoped HTTP applications. */
208
+ const Brick = Object.freeze({
209
+ action,
210
+ endpoint,
211
+ service,
212
+ app,
213
+ compileService,
214
+ layer,
215
+ mount,
216
+ errors: errors_exports,
217
+ rpcGroup,
218
+ route
219
+ });
1094
220
  //#endregion
1095
- //#region src/openapi.ts
1096
- function generateOpenApiSpec(options = {}) {
1097
- const title = options.title ?? "Brick-TS API Mesh";
1098
- const version = options.version ?? "1.0.0";
1099
- const description = options.description ?? "Automated OpenAPI 3.1.0 specification for Brick-TS modular service mesh.";
1100
- const prefix = options.prefix ?? "/api";
1101
- const services = options.services ?? (options.registry ? options.registry.list() : getGlobalRegistry().list());
1102
- const paths = {};
1103
- const tagsSet = /* @__PURE__ */ new Set();
1104
- let hasAnyAuthorizedAction = false;
1105
- for (const service of services) {
1106
- tagsSet.add(service.name);
1107
- for (const action of service.listActions()) {
1108
- const pluginRoute = getPluginActionRoute(action, prefix);
1109
- if (pluginRoute === false) continue;
1110
- const routePath = pluginRoute?.path ?? action.config.path ?? `${prefix}/${service.name}/${action.name}`;
1111
- const method = (pluginRoute?.method ?? action.config.method ?? "POST").toLowerCase();
1112
- const pathParams = [...routePath.matchAll(/:([^/]+)/g)].map((match) => match[1]);
1113
- const actionPath = routePath.replace(/:([^/]+)/g, "{$1}");
1114
- if (!paths[actionPath]) paths[actionPath] = {};
1115
- if (paths[actionPath][method]) continue;
1116
- const hasAuth = getActionAccess(action).hasAuthorize;
1117
- if (hasAuth) hasAnyAuthorizedAction = true;
1118
- const responses = {};
1119
- if (action.config.output) responses["200"] = {
1120
- description: "Successful response",
1121
- content: { "application/json": { schema: action.config.output } }
1122
- };
1123
- else responses["200"] = { description: "Successful response" };
1124
- const errorAlternatives = /* @__PURE__ */ new Set();
1125
- const addError = (code, status, message) => {
1126
- const key = `${status}:${code}`;
1127
- if (errorAlternatives.has(key)) return;
1128
- errorAlternatives.add(key);
1129
- const schema = { allOf: [{ $ref: "#/components/schemas/ErrorEnvelope" }, {
1130
- type: "object",
1131
- properties: {
1132
- code: { const: code },
1133
- status: { const: status }
1134
- }
1135
- }] };
1136
- const existing = responses[String(status)];
1137
- if (existing) {
1138
- existing.description += "; " + message;
1139
- existing.content["application/json"].schema.oneOf.push(schema);
1140
- } else responses[String(status)] = {
1141
- description: message,
1142
- content: { "application/json": { schema: { oneOf: [schema] } } }
1143
- };
1144
- };
1145
- if (action.config.input) addError("VALIDATION_FAILED", 400, "Validation error");
1146
- if (hasAuth) {
1147
- addError("UNAUTHORIZED", 401, "Authentication required");
1148
- addError("FORBIDDEN", 403, "Access denied");
1149
- }
1150
- if (action.config.errors) for (const [code, errorDef] of Object.entries(action.config.errors)) {
1151
- const def = errorDef;
1152
- addError(code, def.status || 400, def.message || code);
1153
- }
1154
- addError("INTERNAL_SERVER_ERROR", 500, "Internal server error");
1155
- if (action.config.output) addError("VALIDATION_FAILED", 500, "Output validation error");
1156
- const operation = {
1157
- operationId: `${service.name}_${action.name}_${method}`,
1158
- summary: `${service.name}.${action.name}`,
1159
- description: action.config.description ?? `Execute action '${action.name}' on service '${service.name}'`,
1160
- tags: action.config.tags && action.config.tags.length > 0 ? action.config.tags : [service.name],
1161
- ...action.plugin ? { "x-brick-plugin": action.plugin } : {},
1162
- ...action.resource ? { "x-brick-resource": action.resource } : {},
1163
- responses
1164
- };
1165
- const inputSchema = action.config.input;
1166
- const properties = inputSchema?.properties ?? {};
1167
- const parameters = [...new Set(pathParams)].map((key) => ({
1168
- name: key,
1169
- in: "path",
1170
- required: true,
1171
- schema: properties[key] ?? { type: "string" }
1172
- }));
1173
- if (method === "get" || method === "delete") for (const [key, schema] of Object.entries(properties)) {
1174
- if (pathParams.includes(key)) continue;
1175
- parameters.push({
1176
- name: key,
1177
- in: "query",
1178
- required: inputSchema?.required?.includes(key) ?? false,
1179
- schema
1180
- });
1181
- }
1182
- else if (inputSchema) operation.requestBody = {
1183
- required: true,
1184
- content: { "application/json": { schema: pathParams.length && inputSchema.properties ? {
1185
- ...inputSchema,
1186
- properties: Object.fromEntries(Object.entries(properties).filter(([key]) => !pathParams.includes(key))),
1187
- required: (inputSchema.required ?? []).filter((key) => !pathParams.includes(key))
1188
- } : inputSchema } }
1189
- };
1190
- if (parameters.length) operation.parameters = parameters;
1191
- if (hasAuth) operation.security = [{ bearerAuth: [] }];
1192
- paths[actionPath][method] = operation;
1193
- }
1194
- }
1195
- const spec = {
1196
- openapi: "3.1.0",
1197
- info: {
1198
- title,
1199
- version,
1200
- description
1201
- },
1202
- paths,
1203
- tags: Array.from(tagsSet).map((name) => ({
1204
- name,
1205
- description: `Actions exposed by '${name}' service`
1206
- }))
1207
- };
1208
- spec.components = { schemas: { ErrorEnvelope: {
1209
- type: "object",
1210
- required: [
1211
- "name",
1212
- "code",
1213
- "message",
1214
- "status",
1215
- "requestId"
1216
- ],
1217
- properties: {
1218
- name: { type: "string" },
1219
- code: { type: "string" },
1220
- message: { type: "string" },
1221
- status: { type: "integer" },
1222
- requestId: { type: "string" },
1223
- details: {},
1224
- errors: {
1225
- type: "array",
1226
- items: {
1227
- type: "object",
1228
- required: ["path", "message"],
1229
- properties: {
1230
- path: { type: "string" },
1231
- message: { type: "string" },
1232
- value: {}
1233
- }
1234
- }
1235
- }
1236
- }
1237
- } } };
1238
- if (hasAnyAuthorizedAction) Object.assign(spec.components, { securitySchemes: { bearerAuth: {
1239
- type: "http",
1240
- scheme: "bearer",
1241
- bearerFormat: "JWT",
1242
- description: "Enter your Bearer authentication token"
1243
- } } });
1244
- return spec;
221
+ //#region src/native-app-entry.ts
222
+ function isNativeBrickApp(value) {
223
+ return typeof value === "object" && value !== null && "kind" in value && value.kind === "brick-native-app" && "fetch" in value && typeof value.fetch === "function" && "ready" in value && typeof value.ready === "function" && "dispose" in value && typeof value.dispose === "function" && "api" in value && HttpApi.isHttpApi(value.api) && "services" in value && Array.isArray(value.services) && "openApi" in value && typeof value.openApi === "function";
1245
224
  }
1246
225
  //#endregion
1247
226
  //#region src/secrets.ts
@@ -1385,1170 +364,6 @@ function resetSecrets() {
1385
364
  overrides.clear();
1386
365
  }
1387
366
  //#endregion
1388
- //#region src/request-logger.ts
1389
- function formatLog(method, path, status, elapsedMs) {
1390
- return `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;
1391
- }
1392
- /**
1393
- * Status carried by the thrown error (Elysia sets e.g. 404 on NotFoundError
1394
- * while `set.status` may still hold the 200 default when onError runs).
1395
- */
1396
- function thrownStatus(error) {
1397
- if (typeof error === "object" && error !== null && "status" in error) {
1398
- const status = error.status;
1399
- if (typeof status === "number") return status;
1400
- }
1401
- }
1402
- /**
1403
- * Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.
1404
- * Timing is tracked per-Request via a WeakMap. The onError hook only logs and
1405
- * returns undefined so existing error mapping is preserved. Logging only —
1406
- * no CORS headers are set here.
1407
- *
1408
- * Hooks are registered with the "global" scope so they propagate to the
1409
- * parent app when mounted via `app.use(...)` — Elysia scopes plain instance
1410
- * hooks to the plugin's own routes. Timing is captured in beforeHandle
1411
- * because request hooks are not propagated from a
1412
- * used instance. Unmatched routes (no beforeHandle) fall back to Date.now().
1413
- */
1414
- function requestLoggingPlugin(opts = {}) {
1415
- const plugin = new Elysia();
1416
- if (!(opts.enabled ?? true)) return plugin;
1417
- const logger = opts.logger ?? console.log;
1418
- const startedAt = /* @__PURE__ */ new WeakMap();
1419
- const markStarted = ({ request }) => {
1420
- startedAt.set(request, Date.now());
1421
- };
1422
- const logSuccess = ({ request, set }) => {
1423
- const start = startedAt.get(request) ?? Date.now();
1424
- const path = new URL(request.url).pathname;
1425
- logger(formatLog(request.method, path, set.status ?? 200, Date.now() - start));
1426
- };
1427
- const logError = ({ request, set, error }) => {
1428
- if (request) {
1429
- const start = startedAt.get(request) ?? Date.now();
1430
- const path = new URL(request.url).pathname;
1431
- const status = thrownStatus(error) ?? set.status ?? 500;
1432
- logger(formatLog(request.method, path, status, Date.now() - start));
1433
- }
1434
- };
1435
- plugin.beforeHandle("global", markStarted);
1436
- plugin.afterHandle("global", logSuccess);
1437
- plugin.error("global", logError);
1438
- return plugin;
1439
- }
1440
- //#endregion
1441
- //#region src/docs.ts
1442
- /** Renders the Scalar API reference page for the given OpenAPI URL. */
1443
- function scalarDocsHTML(specUrl, title) {
1444
- return `<!doctype html>
1445
- <html>
1446
- <head>
1447
- <title>${title} — API Reference</title>
1448
- <meta charset="utf-8" />
1449
- <meta name="viewport" content="width=device-width, initial-scale=1" />
1450
- <link rel="icon" type="image/svg+xml" href="https://scalar.com/favicon.svg" />
1451
- <style>
1452
- body { margin: 0; padding: 0; height: 100vh; }
1453
- </style>
1454
- </head>
1455
- <body>
1456
- <script
1457
- id="api-reference"
1458
- data-url="${specUrl}"
1459
- data-configuration='{"theme": "purple", "layout": "modern"}'
1460
- src="https://cdn.jsdelivr.net/npm/@scalar/api-reference">
1461
- <\/script>
1462
- </body>
1463
- </html>`;
1464
- }
1465
- /** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */
1466
- function referencePlugin(opts = {}) {
1467
- const path = opts.path ?? "/reference";
1468
- const title = opts.title ?? "Brick-TS API Mesh";
1469
- const specUrl = opts.specUrl ?? "/openapi.json";
1470
- const plugin = new Elysia();
1471
- plugin.get(path, ({ set }) => {
1472
- set.headers["content-type"] = "text/html; charset=utf-8";
1473
- return scalarDocsHTML(specUrl, title);
1474
- });
1475
- return plugin;
1476
- }
1477
- /** Mounts the Scalar reference route onto an existing app. */
1478
- function registerReferenceRoute(app, opts = {}) {
1479
- return app.use(referencePlugin(opts));
1480
- }
1481
- /** Renders the Swagger UI page. */
1482
- function swaggerDocsHTML(specUrl, title) {
1483
- return `<!DOCTYPE html>
1484
- <html lang="en">
1485
- <head>
1486
- <meta charset="UTF-8">
1487
- <title>${title} — Swagger UI</title>
1488
- <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css" />
1489
- <style>
1490
- html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }
1491
- *, *:before, *:after { box-sizing: inherit; }
1492
- body { margin:0; background: #fafafa; }
1493
- </style>
1494
- </head>
1495
- <body>
1496
- <div id="swagger-ui"></div>
1497
- <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js" charset="UTF-8"><\/script>
1498
- <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js" charset="UTF-8"><\/script>
1499
- <script>
1500
- window.onload = function() {
1501
- SwaggerUIBundle({
1502
- url: "${specUrl}",
1503
- dom_id: '#swagger-ui',
1504
- deepLinking: true,
1505
- presets: [
1506
- SwaggerUIBundle.presets.apis,
1507
- SwaggerUIStandalonePreset
1508
- ],
1509
- plugins: [
1510
- SwaggerUIBundle.plugins.DownloadUrl
1511
- ],
1512
- layout: "StandaloneLayout"
1513
- });
1514
- };
1515
- <\/script>
1516
- </body>
1517
- </html>`;
1518
- }
1519
- //#endregion
1520
- //#region src/endpoints.ts
1521
- /** Resolve the db for an endpoint: explicit service first, else first service holding one. */
1522
- function resolveEndpointDb(service, services) {
1523
- if (service) return (typeof service === "string" ? services.find((s) => s.name === service) : service)?.getDb() ?? void 0;
1524
- for (const svc of services) {
1525
- const db = svc.getDb();
1526
- if (db) return db;
1527
- }
1528
- }
1529
- /** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */
1530
- function createEndpointHandler(def, services) {
1531
- return async ({ params, body, query, headers, request, set }) => {
1532
- const traceId = headers?.["x-trace-id"] || `tr_${crypto.randomUUID()}`;
1533
- const requestId = headers?.["x-request-id"] || `req_${crypto.randomUUID()}`;
1534
- if (set?.headers) {
1535
- set.headers["x-trace-id"] = traceId;
1536
- set.headers["x-request-id"] = requestId;
1537
- }
1538
- const tag = `endpoint:${def.method} ${def.path}`;
1539
- const ctx = {
1540
- body,
1541
- db: def.database ? def.database.getDb() : resolveEndpointDb(def.service, services),
1542
- headers: headers ?? {},
1543
- logger: {
1544
- info: (...args) => console.log(`[${tag}]`, ...args),
1545
- warn: (...args) => console.warn(`[${tag}]`, ...args),
1546
- error: (...args) => console.error(`[${tag}]`, ...args),
1547
- debug: (...args) => console.debug(`[${tag}]`, ...args)
1548
- },
1549
- params: params ?? {},
1550
- query: query ?? {},
1551
- request: request instanceof Request ? request : new Request(`http://localhost${def.path}`, {
1552
- headers: new Headers(headers ?? {}),
1553
- method: def.method
1554
- }),
1555
- requestId,
1556
- set,
1557
- traceId
1558
- };
1559
- try {
1560
- return await def.handler(ctx);
1561
- } catch (err) {
1562
- const response = toErrorResponse(!(err instanceof ActionExecutionError || err instanceof ValidationError) && err !== null && typeof err === "object" && "status" in err && typeof err.status === "number" && Number.isInteger(err.status) && err.status >= 400 && err.status < 500 ? new ActionExecutionError("HTTP_ERROR", "message" in err && typeof err.message === "string" ? err.message : "Endpoint error", err.status, void 0, { cause: err }) : err, {
1563
- logger: ctx.logger,
1564
- requestId
1565
- });
1566
- set.status = response.status;
1567
- return response;
1568
- }
1569
- };
1570
- }
1571
- /** `/p/:slug` → `/p/{slug}` for OpenAPI. */
1572
- function toOpenApiPath(elysiaPath) {
1573
- return elysiaPath.replace(/:([A-Za-z0-9_]+)/g, "{$1}");
1574
- }
1575
- /** Parameter names (`:slug`) extracted for the OpenAPI path item. */
1576
- function pathParamNames(elysiaPath) {
1577
- return [...elysiaPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);
1578
- }
1579
- /** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */
1580
- function endpointPaths(defs) {
1581
- const paths = {};
1582
- for (const def of defs) {
1583
- const openApiPath = toOpenApiPath(def.path);
1584
- if (!paths[openApiPath]) paths[openApiPath] = {};
1585
- const params = pathParamNames(def.path).map((name) => ({
1586
- in: "path",
1587
- name,
1588
- required: true,
1589
- schema: { type: "string" }
1590
- }));
1591
- paths[openApiPath][def.method.toLowerCase()] = {
1592
- ...def.summary ? { summary: def.summary } : {},
1593
- ...def.description ? { description: def.description } : {},
1594
- ...def.tags ? { tags: def.tags } : {},
1595
- ...params.length > 0 ? { parameters: params } : {},
1596
- responses: { 200: { description: "Successful response" } }
1597
- };
1598
- }
1599
- return paths;
1600
- }
1601
- //#endregion
1602
- //#region src/server.ts
1603
- function brick(options = {}) {
1604
- const prefix = options.prefix ?? options.compilation?.ir.prefix ?? "/api";
1605
- const title = options.title ?? "Brick-TS API Mesh";
1606
- const version = options.version ?? "1.0.0";
1607
- const compiled = options.compiler !== false;
1608
- const enableDocs = options.docs ?? true;
1609
- const openApiPath = options.openApiPath ?? "/openapi.json";
1610
- const docsPath = options.docsPath ?? "/docs";
1611
- const swaggerPath = options.swaggerPath ?? "/swagger";
1612
- const app = new Elysia();
1613
- if (options.secrets?.validate !== false) resolveSecrets({ source: options.secrets?.source });
1614
- app.get("/_health", () => ({
1615
- status: "ok",
1616
- uptime: process.uptime(),
1617
- timestamp: Date.now()
1618
- }));
1619
- const requestLogging = options.requestLogging ?? true;
1620
- if (requestLogging !== false) {
1621
- const pluginOpts = requestLogging === true ? {} : requestLogging;
1622
- if (pluginOpts.enabled !== false) app.use(requestLoggingPlugin(pluginOpts));
1623
- }
1624
- const reference = options.reference ?? false;
1625
- if (reference !== false) {
1626
- const refOpts = reference === true ? {} : reference;
1627
- const settings = {
1628
- path: refOpts.path ?? "/reference",
1629
- title: refOpts.title ?? title,
1630
- specUrl: refOpts.specUrl ?? openApiPath
1631
- };
1632
- if (compiled) app.get(settings.path, htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)));
1633
- else registerReferenceRoute(app, settings);
1634
- }
1635
- const services = options.services ?? getGlobalRegistry().list();
1636
- for (const service of services) if (typeof service.build === "function") service.build();
1637
- const endpointDefs = [];
1638
- let endpointRevision = 0;
1639
- if (enableDocs) {
1640
- const buildSpec = () => {
1641
- const spec = generateOpenApiSpec({
1642
- title,
1643
- version,
1644
- description: options.description,
1645
- prefix,
1646
- services
1647
- });
1648
- const paths = { ...spec.paths };
1649
- for (const [path, operations] of Object.entries(endpointPaths(endpointDefs))) paths[path] = {
1650
- ...paths[path],
1651
- ...operations
1652
- };
1653
- return {
1654
- ...spec,
1655
- paths
1656
- };
1657
- };
1658
- app.get(openApiPath, compiled ? cachedJsonRoute(buildSpec, () => [getGlobalRegistry(), getGlobalRegistry().revision + endpointRevision]) : buildSpec);
1659
- if (compiled) {
1660
- app.get(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));
1661
- app.get(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));
1662
- } else {
1663
- app.get(docsPath, ({ set }) => {
1664
- set.headers["content-type"] = "text/html; charset=utf-8";
1665
- return scalarDocsHTML(openApiPath, title);
1666
- });
1667
- app.get(swaggerPath, ({ set }) => {
1668
- set.headers["content-type"] = "text/html; charset=utf-8";
1669
- return swaggerDocsHTML(openApiPath, title);
1670
- });
1671
- }
1672
- }
1673
- const registeredRoutes = /* @__PURE__ */ new Map();
1674
- const routeKey = (method, path) => `${method} ${path.replace(/:[^/]+/g, ":param")}`;
1675
- registeredRoutes.set(routeKey("GET", "/_health"), false);
1676
- registeredRoutes.set(routeKey("GET", "/_brick/services"), false);
1677
- if (enableDocs) for (const path of [
1678
- openApiPath,
1679
- docsPath,
1680
- swaggerPath
1681
- ]) registeredRoutes.set(routeKey("GET", path), false);
1682
- if (reference !== false) registeredRoutes.set(routeKey("GET", reference === true ? "/reference" : reference.path ?? "/reference"), false);
1683
- const mountRoute = (method, path, handler, plugin = false) => {
1684
- const key = routeKey(method, path);
1685
- if (registeredRoutes.has(key)) {
1686
- if (plugin || registeredRoutes.get(key)) throw new Error(`Brick: duplicate plugin route '${method} ${path}'`);
1687
- return false;
1688
- }
1689
- switch (method) {
1690
- case "GET":
1691
- app.get(path, handler);
1692
- break;
1693
- case "POST":
1694
- app.post(path, handler);
1695
- break;
1696
- case "PUT":
1697
- app.put(path, handler);
1698
- break;
1699
- case "PATCH":
1700
- app.patch(path, handler);
1701
- break;
1702
- case "DELETE": app.delete(path, handler);
1703
- }
1704
- registeredRoutes.set(key, plugin);
1705
- return true;
1706
- };
1707
- const mountEndpoint = (def, plugin = false) => {
1708
- mountRoute(def.method, def.path, createEndpointHandler(def, services), plugin);
1709
- endpointDefs.push(def);
1710
- endpointRevision++;
1711
- };
1712
- for (const service of services) for (const def of getPluginEndpoints(service, prefix)) mountEndpoint(def, true);
1713
- for (const def of options.endpoints ?? []) mountEndpoint(def);
1714
- const brickApp = app;
1715
- brickApp.endpoint = (def) => {
1716
- mountEndpoint(def);
1717
- };
1718
- brickApp.listEndpoints = () => [...endpointDefs];
1719
- const compilation = options.compilation ?? compileBrickApplication({
1720
- services,
1721
- prefix,
1722
- mode: options.compiler === false ? "generic" : "specialized"
1723
- });
1724
- 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");
1725
- const mountedRoutes = [];
1726
- for (const route of compilation.routes) {
1727
- const action = services.find((candidate) => candidate.name === route.ir.service).listActions().find((candidate) => candidate.name === route.ir.action);
1728
- if (mountRoute(route.ir.method, route.ir.path, (context) => {
1729
- const result = route.handler(context);
1730
- return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
1731
- }, getPluginActionRoute(action, prefix) !== void 0)) mountedRoutes.push(route.ir);
1732
- }
1733
- const definition = Object.freeze({
1734
- services: Object.freeze([...services]),
1735
- prefix,
1736
- routes: Object.freeze(mountedRoutes)
1737
- });
1738
- Object.defineProperty(brickApp, "definition", { value: definition });
1739
- getGlobalRegistry().setApplicationRoutes(definition);
1740
- app.get("/_brick/services", compiled ? cachedJsonRoute(() => getGlobalRegistry().exportArchitecture(definition), () => {
1741
- const registry = getGlobalRegistry();
1742
- return [registry, registry.revision];
1743
- }) : () => getGlobalRegistry().exportArchitecture(definition));
1744
- return brickApp;
1745
- }
1746
- function jsonActionResult(value) {
1747
- return value === null ? new Response("null", { headers: { "content-type": "application/json" } }) : value;
1748
- }
1749
- function htmlResponse(html) {
1750
- return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
1751
- }
1752
- /** Reuse serialized JSON, without sharing a mutable response body between requests. */
1753
- function cachedJsonRoute(build, revision) {
1754
- let [owner, version] = revision();
1755
- let json = JSON.stringify(build());
1756
- return ({ set }) => {
1757
- const [currentOwner, currentVersion] = revision();
1758
- if (currentOwner !== owner || currentVersion !== version) {
1759
- json = JSON.stringify(build());
1760
- owner = currentOwner;
1761
- version = currentVersion;
1762
- }
1763
- set.headers["content-type"] = "application/json;charset=utf-8";
1764
- return json;
1765
- };
1766
- }
1767
- //#endregion
1768
- //#region src/compiler/emit.ts
1769
- /** Emits framework code only. User callbacks remain closures bound separately. */
1770
- function emitHandlerFactory(route) {
1771
- const name = JSON.stringify(route.action);
1772
- const fields = route.input ? "params, body, query, headers, request, set" : "headers, request, set";
1773
- const input = ["let input;"];
1774
- if (route.input) {
1775
- input.push("let coercedQuery = query;");
1776
- if (route.coercions.length) {
1777
- input.push("if (query) {", "coercedQuery = { ...query };");
1778
- for (const [index, coercion] of route.coercions.entries()) {
1779
- const key = JSON.stringify(coercion.key);
1780
- input.push(`const v${index} = query[${key}];`);
1781
- 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}; }`);
1782
- else input.push(`if (v${index} === "true" || v${index} === "1") coercedQuery[${key}] = true; else if (v${index} === "false" || v${index} === "0") coercedQuery[${key}] = false;`);
1783
- }
1784
- input.push("}");
1785
- }
1786
- input.push(`input = mergeInput(${route.inputPrecedence.map((source) => source === "query" ? "coercedQuery" : source).join(", ")});`);
1787
- if (route.inputSchema?.type === "object") input.push("input ??= {};");
1788
- }
1789
- const asyncStages = route.context || route.authorize;
1790
- const context = route.context ? "const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);" : "";
1791
- const validation = route.input ? `checkDepth(input, ${name}); validate(inputChecker, input, ${name}, "input");` : "";
1792
- const authorization = route.authorize ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name}, ctx.user);` : "";
1793
- const output = route.output ? `validate(outputChecker, result, ${name}, "output");` : "";
1794
- const execute = asyncStages ? `const result = await execute({ input, ctx, error: errorBuilder });\n${output}\nreturn result;` : `const result = execute({ input, ctx, error: errorBuilder });
1795
- if (isThenable(result)) return Promise.resolve(result).then(value => {
1796
- ${route.output ? `validate(outputChecker, value, ${name}, "output");` : ""}
1797
- return value;
1798
- }).catch(err => mapError(err, set, ctx));
1799
- ${output}
1800
- return result;`;
1801
- return `function bindAction(binding, runtime) {
1802
- const { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;
1803
- const { nextSequence, defaultRequest, emptyServices, mergeInput, checkDepth, validate, deny, mapError, isThenable } = runtime;
1804
- return ${asyncStages ? "async " : ""}function brickAction({ ${fields} }) {
1805
- const seq = nextSequence();
1806
- const traceId = (headers && headers["x-trace-id"]) || "tr_" + seq;
1807
- const requestId = (headers && headers["x-request-id"]) || "req_" + seq;
1808
- if (set?.headers) { set.headers["x-trace-id"] = traceId; set.headers["x-request-id"] = requestId; }
1809
- ${input.join("\n")}
1810
- const ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,
1811
- db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };
1812
- try {
1813
- ${context}
1814
- ${validation}
1815
- ${authorization}
1816
- ${execute}
1817
- } catch (err) { return mapError(err, set, ctx); }
1818
- };
1819
- }`;
1820
- }
1821
- //#endregion
1822
- //#region src/tool.ts
1823
- function defineTool(config) {
1824
- if (config.input && config.input.type !== "object") throw new Error(`Tool '${config.name}' input must be an object schema`);
1825
- const tool = defineAction(config);
1826
- Object.defineProperty(tool, "kind", { value: "tool" });
1827
- return tool;
1828
- }
1829
- function isTool(value) {
1830
- return typeof value === "function" && value.kind === "tool";
1831
- }
1832
- //#endregion
1833
- //#region src/db/sqlite.ts
1834
- const requireSQLite = createRequire(import.meta.url);
1835
- /**
1836
- * Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine
1837
- * and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).
1838
- *
1839
- * Bun-only: the driver is loaded lazily so importing `@brickkit/core` on
1840
- * other runtimes (e.g. Node) stays safe until this function is actually
1841
- * called.
1842
- */
1843
- function createSQLiteDatabase(config = {}) {
1844
- let Database;
1845
- let drizzle;
1846
- try {
1847
- ({Database} = requireSQLite("bun:sqlite"));
1848
- ({drizzle} = __require("drizzle-orm/bun-sqlite"));
1849
- } catch (err) {
1850
- throw new Error(`[Brick-TS DB] SQLite engine requires the Bun runtime ('bun:sqlite' is unavailable here). Original error: ${err?.message ?? err}`);
1851
- }
1852
- const filePath = config.filename ?? config.path ?? ":memory:";
1853
- const client = config.client ?? new Database(filePath);
1854
- if (config.foreignKeys !== false) client.run("PRAGMA foreign_keys = ON;");
1855
- if (config.wal !== false && filePath !== ":memory:") client.run("PRAGMA journal_mode = WAL;");
1856
- const db = config.schema ? drizzle(client, { schema: config.schema }) : drizzle(client);
1857
- if (!db.$client) db.$client = client;
1858
- return db;
1859
- }
1860
- //#endregion
1861
- //#region src/db/postgres.ts
1862
- /**
1863
- * Creates a PostgreSQL Drizzle instance using postgres-js.
1864
- * Static imports (both are hard dependencies in package.json) so bundlers
1865
- * (Nitro/Rollup) trace and ship the driver. `bun:sqlite` stays lazy in
1866
- * `sqlite.ts` since it only exists under Bun.
1867
- */
1868
- function createPostgresDatabase(config = {}) {
1869
- const connectionUrl = config.url ?? config.connectionString ?? (typeof process !== "undefined" ? process.env?.DATABASE_URL : void 0);
1870
- const client = config.client ?? (connectionUrl ? postgres(connectionUrl, {
1871
- max: config.max,
1872
- prepare: config.prepare,
1873
- ssl: config.ssl
1874
- }) : postgres({
1875
- host: config.host ?? "localhost",
1876
- port: config.port ?? 5432,
1877
- user: config.user,
1878
- password: config.password,
1879
- database: config.database,
1880
- max: config.max,
1881
- prepare: config.prepare,
1882
- ssl: config.ssl
1883
- }));
1884
- return drizzle(client, {
1885
- schema: config.schema,
1886
- ...config.schemaName ? { schemaFilter: [config.schemaName] } : {}
1887
- });
1888
- }
1889
- //#endregion
1890
- //#region src/db/define.ts
1891
- function isDatabaseHandle(value) {
1892
- return typeof value === "object" && value !== null && "kind" in value && value.kind === "brick-database";
1893
- }
1894
- function defineDatabase(options = {}) {
1895
- const engine = options.engine ?? "sqlite";
1896
- if (engine !== "sqlite" && engine !== "postgres") throw new Error(`Unsupported database engine: ${engine}`);
1897
- const forbidden = engine === "sqlite" ? [
1898
- "url",
1899
- "connectionString",
1900
- "host",
1901
- "port",
1902
- "user",
1903
- "password",
1904
- "database",
1905
- "ssl",
1906
- "max",
1907
- "schemaName"
1908
- ] : [
1909
- "path",
1910
- "filename",
1911
- "wal",
1912
- "foreignKeys"
1913
- ];
1914
- for (const key of forbidden) if (key in options) throw new Error(`Database option "${key}" is not valid for ${engine}`);
1915
- const declared = options.tables ?? {};
1916
- const tables = Array.isArray(declared) ? Object.fromEntries(declared.map((table) => [getTableName$1(table), table])) : { ...declared };
1917
- const schema = options.schema ?? tables;
1918
- let db;
1919
- return {
1920
- kind: "brick-database",
1921
- name: options.name,
1922
- engine,
1923
- tables: Object.freeze(tables),
1924
- schema,
1925
- getDb() {
1926
- if (db !== void 0) return db;
1927
- const config = {};
1928
- for (const [key, value] of Object.entries(options)) {
1929
- if ([
1930
- "tables",
1931
- "schema",
1932
- "name",
1933
- "engine"
1934
- ].includes(key)) continue;
1935
- if (engine === "postgres" && options.client && key !== "client" && key !== "schemaName") continue;
1936
- config[key] = value instanceof SecretRef ? value.require() : value;
1937
- }
1938
- if (engine === "sqlite") {
1939
- const path = config.filename ?? config.path ?? ":memory:";
1940
- if (!config.client && path !== ":memory:") mkdirSync(dirname(path), { recursive: true });
1941
- db = createSQLiteDatabase({
1942
- ...config,
1943
- schema
1944
- });
1945
- } else db = createPostgresDatabase({
1946
- ...config,
1947
- schema
1948
- });
1949
- return db;
1950
- }
1951
- };
1952
- }
1953
- //#endregion
1954
- //#region src/db/index.ts
1955
- /**
1956
- * Creates a database instance based on the provided configuration.
1957
- * Zero-config: calling `createDatabase()` returns an ultra-fast Bun-native SQLite
1958
- * database in `:memory:` mode wrapped with Drizzle ORM.
1959
- */
1960
- function createDatabase(config = {}) {
1961
- const engine = config.engine ?? "sqlite";
1962
- if (engine === "sqlite") return createSQLiteDatabase(config);
1963
- if (engine === "postgres") return createPostgresDatabase(config);
1964
- throw new Error(`[Brick-TS DB] Unsupported database engine: '${engine}'`);
1965
- }
1966
- /** Attach a defined database. Schema changes remain the caller's responsibility. */
1967
- function attachDatabase(service, database) {
1968
- service.setDb(database);
1969
- return database.getDb();
1970
- }
1971
- /**
1972
- * Generates an idempotent SQLite CREATE TABLE IF NOT EXISTS definition
1973
- * directly from a Drizzle table schema.
1974
- */
1975
- function generateSQLiteTableDdl(table) {
1976
- const tableName = getTableName$1(table);
1977
- const columns = getTableColumns$1(table);
1978
- const colDefs = [];
1979
- for (const [, col] of Object.entries(columns)) {
1980
- let def = `"${col.name}" ${col.getSQLType().toUpperCase()}`;
1981
- if (col.primary) def += " PRIMARY KEY";
1982
- if (col.notNull) def += " NOT NULL";
1983
- if (col.isUnique) def += " UNIQUE";
1984
- if (col.hasDefault) {
1985
- if (typeof col.default === "string") def += ` DEFAULT '${col.default.replace(/'/g, "''")}'`;
1986
- else if (typeof col.default === "boolean") def += ` DEFAULT ${col.default ? 1 : 0}`;
1987
- else if (typeof col.default === "number") def += ` DEFAULT ${col.default}`;
1988
- else if (col.default !== void 0) def += ` DEFAULT ${col.default}`;
1989
- }
1990
- colDefs.push(def);
1991
- }
1992
- return `CREATE TABLE IF NOT EXISTS "${tableName}" (\n ${colDefs.join(",\n ")}\n);`;
1993
- }
1994
- /**
1995
- * Generates idempotent secondary index DDL for a Drizzle table.
1996
- * Covers owner scoping, sort columns, and exact-match filters.
1997
- * UNIQUE columns already carry an implicit index — skipped here.
1998
- * FTS/trigram indexes are handled separately by the search layer.
1999
- */
2000
- function generateSQLiteIndexDdl(table, opts = {}) {
2001
- const tableName = getTableName$1(table);
2002
- const columns = getTableColumns$1(table);
2003
- const stmts = [];
2004
- const seen = /* @__PURE__ */ new Set();
2005
- const push = (name, cols) => {
2006
- const clean = cols.filter(Boolean);
2007
- if (clean.length === 0) return;
2008
- const key = `${name}(${clean.join(",")})`;
2009
- if (seen.has(key)) return;
2010
- seen.add(key);
2011
- const colList = clean.map((c) => `"${c}"`).join(", ");
2012
- stmts.push(`CREATE INDEX IF NOT EXISTS "${name}" ON "${tableName}" (${colList});`);
2013
- };
2014
- const colNameOf = (field) => {
2015
- if (columns[field]) return columns[field].name ?? field;
2016
- for (const col of Object.values(columns)) if (col.name === field) return col.name;
2017
- };
2018
- let ownerCol;
2019
- if (opts.ownerField) {
2020
- const oc = colNameOf(opts.ownerField);
2021
- if (oc) {
2022
- ownerCol = oc;
2023
- push(`idx_${tableName}_${oc}`, [oc]);
2024
- }
2025
- }
2026
- const sorts = opts.sortFields ?? ["updated_at", "created_at"];
2027
- const sortCols = [];
2028
- for (const f of sorts) {
2029
- const c = colNameOf(f);
2030
- if (c) {
2031
- sortCols.push(c);
2032
- push(`idx_${tableName}_${c}`, [c]);
2033
- }
2034
- }
2035
- if (ownerCol && sortCols.length > 0) push(`idx_${tableName}_${ownerCol}_${sortCols[0]}`, [ownerCol, sortCols[0]]);
2036
- return stmts;
2037
- }
2038
- /**
2039
- * Ensures secondary indexes exist for a resource table.
2040
- * SQLite: B-tree indexes for owner scope + sort + composite hot path.
2041
- * Postgres: same B-trees plus pg_trgm GIN indexes for substring search.
2042
- * Best-effort: failures warn and continue (e.g. read-only replicas).
2043
- */
2044
- function ensureResourceIndexes(db, table, opts = {}) {
2045
- if (!db) return;
2046
- const isPostgres = typeof db.execute === "function" && !db.$client?.run;
2047
- const stmts = generateSQLiteIndexDdl(table, opts);
2048
- if (isPostgres && opts.searchFields && opts.searchFields.length > 0) {
2049
- const tableName = getTableName$1(table);
2050
- const columns = getTableColumns$1(table);
2051
- const colNameOf = (f) => {
2052
- if (columns[f]) return columns[f].name ?? f;
2053
- for (const col of Object.values(columns)) if (col.name === f) return col.name;
2054
- };
2055
- for (const f of opts.searchFields) {
2056
- const c = colNameOf(f);
2057
- if (c) stmts.push(`CREATE INDEX IF NOT EXISTS "idx_${tableName}_${c}_trgm" ON "${tableName}" USING gin ("${c}" gin_trgm_ops);`);
2058
- }
2059
- }
2060
- if (stmts.length === 0) return;
2061
- const run = (stmt) => {
2062
- try {
2063
- if (db.$client?.run) db.$client.run(stmt);
2064
- else if (typeof db.execute === "function") db.execute(sql$1.raw(stmt)).catch(() => {});
2065
- else if (db.run) db.run(stmt);
2066
- } catch {}
2067
- };
2068
- if (isPostgres) run(`CREATE EXTENSION IF NOT EXISTS pg_trgm;`);
2069
- for (const s of stmts) run(s);
2070
- }
2071
- /**
2072
- * SQLite FTS5 search layer for resource list (?search=).
2073
- * B-tree indexes cannot serve LIKE '%term%' (leading wildcard forces a full
2074
- * scan). FTS5 gives indexed substring/prefix search on title/slug-scale text.
2075
- * Postgres uses ilike + pg_trgm GIN indexes instead (see ensureResourceIndexes).
2076
- */
2077
- function ftsTableName(table) {
2078
- return `${getTableName$1(table)}_fts`;
2079
- }
2080
- function quoteIdent(name) {
2081
- return `"${name.replace(/"/g, "\"\"")}"`;
2082
- }
2083
- /**
2084
- * Creates the FTS5 sidecar table + sync triggers + backfills existing rows.
2085
- * Idempotent; safe to call on every resource registration.
2086
- * No-op on Postgres (relies on pg_trgm instead) and when searchCols is empty.
2087
- */
2088
- function ensureSQLiteFts(db, table, searchCols) {
2089
- if (!db || searchCols.length === 0) return;
2090
- const client = db.$client;
2091
- const runRaw = db.run;
2092
- if (!client?.run && !runRaw) return;
2093
- const run = (stmt) => {
2094
- if (client?.run) client.run(stmt);
2095
- else runRaw(stmt);
2096
- };
2097
- try {
2098
- const tableName = getTableName$1(table);
2099
- const columns = getTableColumns$1(table);
2100
- const colNameOf = (f) => {
2101
- if (columns[f]) return columns[f].name ?? f;
2102
- for (const col of Object.values(columns)) if (col.name === f) return col.name;
2103
- };
2104
- const dbCols = searchCols.map(colNameOf).filter((c) => !!c);
2105
- if (dbCols.length === 0) return;
2106
- const idCol = colNameOf("id") ?? Object.values(columns).find((c) => c.primary)?.name ?? "id";
2107
- const fts = ftsTableName(table);
2108
- const ftsCols = [`"id" UNINDEXED`, ...dbCols.map((c) => quoteIdent(c))].join(", ");
2109
- run(`CREATE VIRTUAL TABLE IF NOT EXISTS ${quoteIdent(fts)} USING fts5(${ftsCols}, tokenize='porter');`);
2110
- const colList = dbCols.map(quoteIdent).join(", ");
2111
- const newVals = dbCols.map((c) => `new.${quoteIdent(c)}`).join(", ");
2112
- run(`CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_ai`)} AFTER INSERT ON ${quoteIdent(tableName)} BEGIN INSERT INTO ${quoteIdent(fts)}("id", ${colList}) VALUES (new.${quoteIdent(idCol)}, ${newVals}); END;`);
2113
- run(`CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_ad`)} AFTER DELETE ON ${quoteIdent(tableName)} BEGIN DELETE FROM ${quoteIdent(fts)} WHERE "id" = old.${quoteIdent(idCol)}; END;`);
2114
- run(`CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_au`)} AFTER UPDATE ON ${quoteIdent(tableName)} BEGIN DELETE FROM ${quoteIdent(fts)} WHERE "id" = old.${quoteIdent(idCol)}; INSERT INTO ${quoteIdent(fts)}("id", ${colList}) VALUES (new.${quoteIdent(idCol)}, ${newVals}); END;`);
2115
- run(`INSERT INTO ${quoteIdent(fts)}("id", ${colList}) SELECT ${quoteIdent(idCol)}, ${colList} FROM ${quoteIdent(tableName)} WHERE ${quoteIdent(idCol)} NOT IN (SELECT "id" FROM ${quoteIdent(fts)});`);
2116
- } catch {}
2117
- }
2118
- /**
2119
- * Builds an FTS5 MATCH condition for a resource search term.
2120
- * Returns null when the term has no usable tokens or FTS errors.
2121
- * Caller falls back to LIKE in that case.
2122
- */
2123
- function buildFtsMatchQuery(search) {
2124
- const terms = search.split(/\s+/).map((s) => s.trim()).filter(Boolean).slice(0, 10);
2125
- if (terms.length === 0) return null;
2126
- const escaped = terms.map((term) => {
2127
- const clean = term.replace(/"/g, "").trim();
2128
- if (!clean) return null;
2129
- return `"${clean.replace(/"/g, "\"\"")}"*`;
2130
- }).filter((x) => !!x);
2131
- if (escaped.length === 0) return null;
2132
- return escaped.join(" AND ");
2133
- }
2134
- /**
2135
- * Explicit SQLite development/test schema preparation helper.
2136
- * Never called by services, resources, auth, or server startup.
2137
- * Not a migration runner; PostgreSQL schema management is caller-owned.
2138
- */
2139
- function syncSchema(tablesOrService, dbInstance) {
2140
- let db = dbInstance;
2141
- let tables = [];
2142
- if (tablesOrService && typeof tablesOrService.listActions === "function" && tablesOrService.tables) {
2143
- const service = tablesOrService;
2144
- tables = Array.from(service.tables.values());
2145
- if (!db) db = service.getDb();
2146
- } else if (tablesOrService instanceof Map) tables = Array.from(tablesOrService.values());
2147
- else if (Array.isArray(tablesOrService)) tables = tablesOrService;
2148
- else if (tablesOrService && typeof tablesOrService === "object") tables = Object.values(tablesOrService);
2149
- if (!db || tables.length === 0) return;
2150
- if (db.$client?.run || db.run) {
2151
- for (const table of tables) try {
2152
- const ddl = generateSQLiteTableDdl(table);
2153
- if (db.$client?.run) db.$client.run(ddl);
2154
- else if (db.run) db.run(sql$1.raw(ddl));
2155
- } catch (err) {
2156
- console.warn(`[Brick-TS DB] Failed to create table:`, err.message);
2157
- }
2158
- return;
2159
- }
2160
- return (async () => {
2161
- for (const table of tables) try {
2162
- getTableName$1(table);
2163
- } catch (err) {
2164
- console.warn(`[Brick-TS DB] Postgres syncSchema error:`, err.message);
2165
- }
2166
- })();
2167
- }
2168
- //#endregion
2169
- //#region src/resource.ts
2170
- /** Declares a plugin host without registering actions or changing the schema. */
2171
- function defineResource(service, config) {
2172
- const columns = getTableColumns$1(config.table);
2173
- const primary = Object.entries(columns).filter(([, column]) => column.primary);
2174
- const id = config.id ?? (primary.length === 1 ? primary[0]?.[1] : void 0);
2175
- const entry = Object.entries(columns).find(([, column]) => column === id);
2176
- if (!entry || !id) throw new Error(`Resource '${config.name}' requires an id column belonging to its table`);
2177
- if (!config.name || config.name.includes("/") || [
2178
- "__proto__",
2179
- "constructor",
2180
- "prototype"
2181
- ].includes(config.name)) throw new Error(`Invalid resource name '${config.name}'`);
2182
- service.registerTable(config.table);
2183
- const resource = {
2184
- name: config.name,
2185
- serviceName: service.name,
2186
- table: config.table,
2187
- id,
2188
- idField: entry[0],
2189
- config: Object.freeze({
2190
- ...config,
2191
- id
2192
- }),
2193
- use(plugin) {
2194
- return installPlugin(service, resource, plugin);
2195
- }
2196
- };
2197
- return resource;
2198
- }
2199
- //#endregion
2200
- //#region src/context.ts
2201
- function pickContextEnvelope(context) {
2202
- if (!context) return {};
2203
- const envelope = {};
2204
- if (context.caller !== void 0) envelope.caller = context.caller;
2205
- if (context.user !== void 0) envelope.user = context.user;
2206
- if (context.traceId !== void 0) envelope.traceId = context.traceId;
2207
- if (context.requestId !== void 0) envelope.requestId = context.requestId;
2208
- if (context.tenantId !== void 0) envelope.tenantId = context.tenantId;
2209
- return envelope;
2210
- }
2211
- //#endregion
2212
- //#region src/service.ts
2213
- const defaultLogger = {
2214
- info: (...args) => console.log("[INFO]", ...args),
2215
- warn: (...args) => console.warn("[WARN]", ...args),
2216
- error: (...args) => console.error("[ERROR]", ...args),
2217
- debug: (...args) => console.debug("[DEBUG]", ...args)
2218
- };
2219
- const DEFAULT_REQUEST = new Request("http://localhost");
2220
- const EMPTY_SERVICES = Object.freeze({});
2221
- const EMPTY_METADATA = Object.freeze({});
2222
- let _ctxSeq = 0;
2223
- const RESOLVED_SYMBOL = Symbol("resolved");
2224
- var ServiceImpl = class {
2225
- name;
2226
- options;
2227
- actions = /* @__PURE__ */ new Map();
2228
- tools = /* @__PURE__ */ new Map();
2229
- tables = /* @__PURE__ */ new Map();
2230
- resources = /* @__PURE__ */ new Map();
2231
- preparations = /* @__PURE__ */ new Map();
2232
- database;
2233
- _isBuilt = false;
2234
- constructor(name, options = {}) {
2235
- this.name = name;
2236
- this.options = options;
2237
- if (options.database !== void 0 && !isDatabaseHandle(options.database)) throw new Error("Service database must be created with defineDatabase()");
2238
- this.database = options.database;
2239
- }
2240
- use(plugin) {
2241
- return installPlugin(this, void 0, plugin);
2242
- }
2243
- get db() {
2244
- return this.getDb();
2245
- }
2246
- get isBuilt() {
2247
- return this._isBuilt;
2248
- }
2249
- /**
2250
- * Closes declarations after plugins have registered their actions and preparations.
2251
- */
2252
- build() {
2253
- if (isInstallingPlugin(this)) throw new Error("Cannot build a service during plugin setup");
2254
- if (this._isBuilt) return this;
2255
- this._isBuilt = true;
2256
- return this;
2257
- }
2258
- contributePreparation(contribution) {
2259
- if (this._isBuilt) throw new Error("Preparations must be registered before service build");
2260
- if (this.preparations.has(contribution.name)) throw new Error(`Duplicate preparation '${contribution.name}'`);
2261
- this.preparations.set(contribution.name, contribution);
2262
- getGlobalRegistry().touch();
2263
- }
2264
- listPreparations() {
2265
- return [...this.preparations.values()];
2266
- }
2267
- prepareContributions() {
2268
- for (const contribution of this.preparations.values()) contribution.prepare();
2269
- }
2270
- registerTable(table) {
2271
- try {
2272
- const tableName = getTableName(table);
2273
- this.tables.set(tableName, table);
2274
- } catch {
2275
- const fallbackName = table._?.name ?? `table_${this.tables.size + 1}`;
2276
- this.tables.set(fallbackName, table);
2277
- }
2278
- return this;
2279
- }
2280
- resource = ((config) => {
2281
- if (this._isBuilt) throw new Error("Resources must be registered before service build");
2282
- if (this.resources.has(config.name)) throw new Error(`Duplicate plugin resource: ${config.name}`);
2283
- const resourceInstance = defineResource(this, config);
2284
- this.resources.set(resourceInstance.name, resourceInstance);
2285
- getGlobalRegistry().touch();
2286
- return resourceInstance;
2287
- });
2288
- getResource(name) {
2289
- return this.resources.get(name);
2290
- }
2291
- listResources() {
2292
- return Array.from(this.resources.values());
2293
- }
2294
- action(actionOrConfig) {
2295
- let actionInstance;
2296
- const isActionFunction = typeof actionOrConfig === "function" && "config" in actionOrConfig;
2297
- if (isActionFunction) actionInstance = actionOrConfig;
2298
- else actionInstance = defineAction(actionOrConfig);
2299
- if (isInstallingPlugin(this) && this.actions.has(actionInstance.name) && this.actions.get(actionInstance.name) !== actionInstance) throw new Error(`Duplicate plugin action: ${actionInstance.name}`);
2300
- if (isTool(actionInstance)) actionInstance.config.http = true;
2301
- actionInstance.serviceName = this.name;
2302
- actionInstance.service = this;
2303
- this.actions.set(actionInstance.name, actionInstance);
2304
- getGlobalRegistry().touch();
2305
- if (isActionFunction) return this;
2306
- return actionInstance;
2307
- }
2308
- tool(toolOrConfig) {
2309
- const existing = isTool(toolOrConfig);
2310
- const tool = existing ? toolOrConfig : defineTool(toolOrConfig);
2311
- if (this.tools.has(tool.name)) throw new Error(`Duplicate tool: ${tool.name}`);
2312
- tool.serviceName = this.name;
2313
- tool.service = this;
2314
- this.tools.set(tool.name, tool);
2315
- if (tool.config.http) this.action(tool);
2316
- getGlobalRegistry().touch();
2317
- return existing ? this : tool;
2318
- }
2319
- getTool(name) {
2320
- return this.tools.get(name);
2321
- }
2322
- listTools() {
2323
- return Array.from(this.tools.values());
2324
- }
2325
- getAction(name) {
2326
- return this.actions.get(name);
2327
- }
2328
- listActions() {
2329
- return Array.from(new Set(this.actions.values()));
2330
- }
2331
- getDb() {
2332
- return this.database?.getDb();
2333
- }
2334
- setDb(database) {
2335
- if (!isDatabaseHandle(database)) throw new Error("Use defineDatabase() to set a service database");
2336
- this.database = database;
2337
- getGlobalRegistry().touch();
2338
- }
2339
- /**
2340
- * Resolves the complete service execution context once per incoming request.
2341
- * Merges framework BaseContext with the service's custom context hook.
2342
- * Always rebuilds context for this service to prevent caller context from overriding.
2343
- */
2344
- resolveContext(callCtx) {
2345
- if (callCtx?.[RESOLVED_SYMBOL] === this) return Promise.resolve(callCtx);
2346
- return this._resolveContextSlow(callCtx);
2347
- }
2348
- async _resolveContextSlow(callCtx) {
2349
- const seq = ++_ctxSeq;
2350
- const fullBaseCtx = {
2351
- request: callCtx?.request ?? DEFAULT_REQUEST,
2352
- db: this.getDb(),
2353
- logger: callCtx?.logger ?? defaultLogger,
2354
- traceId: callCtx?.traceId ?? `tr_${seq.toString(36)}`,
2355
- requestId: callCtx?.requestId ?? `req_${seq.toString(36)}`,
2356
- services: callCtx?.services ?? EMPTY_SERVICES,
2357
- metadata: callCtx?.metadata ?? EMPTY_METADATA,
2358
- ...pickContextEnvelope(callCtx)
2359
- };
2360
- const resolvedExtra = this.options.context ? await this.options.context(fullBaseCtx) : {};
2361
- return {
2362
- ...fullBaseCtx,
2363
- ...resolvedExtra,
2364
- [RESOLVED_SYMBOL]: this
2365
- };
2366
- }
2367
- introspect() {
2368
- const databaseConfig = this.database ? {
2369
- name: this.database.name,
2370
- engine: this.database.engine,
2371
- tables: Object.keys(this.database.tables)
2372
- } : void 0;
2373
- const { database: _database, ...options } = this.options;
2374
- return {
2375
- name: this.name,
2376
- options,
2377
- hasDatabase: Boolean(this.database),
2378
- databaseConfig,
2379
- actions: this.listActions().map((act) => {
2380
- const access = getActionAccess(act);
2381
- return {
2382
- name: act.name,
2383
- serviceName: this.name,
2384
- ...act.plugin ? { plugin: act.plugin } : {},
2385
- ...act.resource ? { resource: act.resource } : {},
2386
- description: act.config.description,
2387
- inputSchema: act.config.input,
2388
- outputSchema: act.config.output,
2389
- hasAuthorize: access.hasAuthorize,
2390
- hasScope: access.hasScope,
2391
- accessPolicy: access.policy,
2392
- errors: act.config.errors,
2393
- emits: act.config.emits,
2394
- tags: act.config.tags
2395
- };
2396
- }),
2397
- resources: this.listResources().map((res) => ({ name: res.name }))
2398
- };
2399
- }
2400
- };
2401
- function defineService(name, options) {
2402
- const service = new ServiceImpl(name, options);
2403
- getGlobalRegistry().register(service);
2404
- return service;
2405
- }
2406
- //#endregion
2407
- //#region src/rpc.ts
2408
- function createServiceProxy(serviceName, options = {}) {
2409
- const isMonolith = options.isMonolith ?? true;
2410
- return new Proxy({}, { get(_, actionName) {
2411
- return async (payload, callCtx) => {
2412
- if (isMonolith) {
2413
- const service = getGlobalRegistry().get(serviceName);
2414
- if (!service) throw new Error(`[Brick-TS RPC] Service '${serviceName}' is not registered in the local runtime.`);
2415
- const action = service.getAction(actionName);
2416
- if (!action) throw new Error(`[Brick-TS RPC] Action '${actionName}' does not exist on service '${serviceName}'.`);
2417
- const envelopeCtx = {
2418
- ...pickContextEnvelope(options.context),
2419
- ...pickContextEnvelope(callCtx)
2420
- };
2421
- if (!envelopeCtx.caller) envelopeCtx.caller = serviceName;
2422
- return action.execute({
2423
- input: payload,
2424
- ctx: envelopeCtx
2425
- });
2426
- } else throw new Error(`[Brick-TS RPC] Remote microservice dispatch for '${serviceName}.${actionName}' is not configured. Use createClient({ baseUrl, contract }) for HTTP calls to remote services.`);
2427
- };
2428
- } });
2429
- }
2430
- //#endregion
2431
- //#region src/mcp.ts
2432
- var UnknownToolError = class extends Error {
2433
- constructor(name) {
2434
- super(`unknown tool: ${name}`);
2435
- this.name = "UnknownToolError";
2436
- }
2437
- };
2438
- /** Collect only explicitly defined tools, without exposing ordinary actions. */
2439
- function createMcpRegistry(options) {
2440
- function toolsByName() {
2441
- const tools = /* @__PURE__ */ new Map();
2442
- for (const tool of [...options.tools ?? [], ...(options.services ?? []).flatMap((service) => service.listTools())]) {
2443
- const existing = tools.get(tool.name);
2444
- if (existing && existing !== tool) throw new Error(`Duplicate MCP tool: ${tool.name}`);
2445
- tools.set(tool.name, tool);
2446
- }
2447
- return tools;
2448
- }
2449
- toolsByName();
2450
- return {
2451
- listTools: () => Array.from(toolsByName().values(), (tool) => ({
2452
- name: tool.name,
2453
- ...tool.config.title ?? tool.config.annotations?.title ? { title: tool.config.title ?? tool.config.annotations?.title } : {},
2454
- description: tool.config.description ?? "",
2455
- inputSchema: tool.config.input ?? {
2456
- type: "object",
2457
- properties: {},
2458
- additionalProperties: false
2459
- },
2460
- annotations: tool.config.annotations ?? {}
2461
- })),
2462
- async callTool(name, args = {}, ctx) {
2463
- const tool = toolsByName().get(name);
2464
- if (!tool) throw new UnknownToolError(name);
2465
- return tool({
2466
- input: args,
2467
- ctx
2468
- });
2469
- }
2470
- };
2471
- }
2472
- function result(id, value) {
2473
- return Response.json({
2474
- jsonrpc: "2.0",
2475
- id,
2476
- result: value
2477
- });
2478
- }
2479
- function rpcError(id, code, message) {
2480
- return Response.json({
2481
- jsonrpc: "2.0",
2482
- id,
2483
- error: {
2484
- code,
2485
- message
2486
- }
2487
- });
2488
- }
2489
- function isRecord(value) {
2490
- return !!value && typeof value === "object" && !Array.isArray(value);
2491
- }
2492
- /** Stateless MCP JSON-RPC POST handler. Wrap with the app's authentication. */
2493
- function createMcpHandler(options) {
2494
- const versions = options.protocolVersions ?? ["2025-06-18"];
2495
- if (!versions.length) throw new Error("At least one MCP protocol version is required");
2496
- return async (request, ctx) => {
2497
- if (request.method !== "POST") return new Response(null, {
2498
- status: 405,
2499
- headers: { Allow: "POST" }
2500
- });
2501
- let body;
2502
- try {
2503
- body = await request.json();
2504
- } catch {
2505
- return rpcError(null, -32700, "parse error");
2506
- }
2507
- if (!isRecord(body) || body.jsonrpc !== "2.0" || typeof body.method !== "string" || body.id !== void 0 && body.id !== null && typeof body.id !== "string" && typeof body.id !== "number" || body.params !== void 0 && !isRecord(body.params)) return rpcError(null, -32600, "invalid request");
2508
- if (body.id === void 0) return new Response(null, { status: 202 });
2509
- const { id, method } = body;
2510
- const params = body.params;
2511
- switch (method) {
2512
- case "initialize": {
2513
- const requested = params?.protocolVersion;
2514
- return result(id, {
2515
- capabilities: { tools: {} },
2516
- protocolVersion: typeof requested === "string" && versions.includes(requested) ? requested : versions[0],
2517
- serverInfo: options.serverInfo
2518
- });
2519
- }
2520
- case "ping": return result(id, {});
2521
- case "tools/list": try {
2522
- return result(id, { tools: options.registry.listTools() });
2523
- } catch {
2524
- return rpcError(id, -32603, "internal error");
2525
- }
2526
- case "tools/call":
2527
- if (typeof params?.name !== "string" || params.arguments !== void 0 && !isRecord(params.arguments)) return rpcError(id, -32602, "invalid tool parameters");
2528
- try {
2529
- const value = await options.registry.callTool(params.name, params.arguments, {
2530
- ...ctx,
2531
- request
2532
- });
2533
- return result(id, { content: [{
2534
- type: "text",
2535
- text: typeof value === "string" ? value : JSON.stringify(value, null, 2) ?? "null"
2536
- }] });
2537
- } catch (error) {
2538
- if (error instanceof UnknownToolError) return rpcError(id, -32602, error.message);
2539
- return result(id, {
2540
- content: [{
2541
- type: "text",
2542
- text: error instanceof Error ? error.message : String(error)
2543
- }],
2544
- isError: true
2545
- });
2546
- }
2547
- default: return rpcError(id, -32601, `method not found: ${method}`);
2548
- }
2549
- };
2550
- }
2551
- //#endregion
2552
- export { ACTION_ACCESS_KEY, ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, UnknownToolError, ValidationError, and, asc, attachDatabase, bindCompiledApplication, blob, brick, buildErrorHelpers, buildFtsMatchQuery, compileBrickApplication, compileRoutePlan, compilerRuntime, createActionHandler, createBrickClient, createDatabase, createEndpointHandler, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, createServiceProxy, defineAction, defineDatabase, defineResource, defineResourcePlugin, defineService, defineServicePlugin, defineTool, desc, emitHandlerFactory, endpointPaths, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, executeCompiledRoute, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getCompiledCheck, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, ilike, inArray, index, integer, is, isBrickApp, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, isTool, like, listSecrets, loadCompiledBrickApp, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveEndpointDb, resolveSecrets, scalarDocsHTML, secret, setActionAccess, sql, sqliteTable, swaggerDocsHTML, syncSchema, t, text, toErrorResponse, toOpenApiPath, uniqueIndex, validateWithSchema };
367
+ export { Brick, SecretRef, envSource, isNativeBrickApp, listSecrets, overrideSecret, overrideSecrets, resetSecrets, resolveSecrets, secret };
2553
368
 
2554
369
  //# sourceMappingURL=index.js.map