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