@brickkit/core 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -27
- package/dist/chunks/client.d.ts +19 -12
- package/dist/chunks/client.d.ts.map +1 -1
- package/dist/chunks/client.js +5 -3
- package/dist/chunks/client.js.map +1 -1
- package/dist/client.js +1 -2
- package/dist/index.d.ts +23 -19
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +317 -239
- package/dist/index.js.map +1 -1
- package/package.json +20 -7
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as isBrickTransportError, i as isBrickServerError, n as BrickTransportError, o as ActionExecutionError, r as createBrickClient, s as ValidationError, t as BrickServerError } from "./chunks/client.js";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
|
-
import { Type } from "@sinclair/typebox";
|
|
3
|
+
import { Type, Type as t } from "@sinclair/typebox";
|
|
4
4
|
import { TypeCompiler } from "@sinclair/typebox/compiler";
|
|
5
5
|
import { Elysia } from "elysia";
|
|
6
6
|
import { blob, foreignKey, index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
@@ -185,6 +185,31 @@ function resetGlobalRegistry() {
|
|
|
185
185
|
globalRegistry = new ServiceRegistry();
|
|
186
186
|
}
|
|
187
187
|
//#endregion
|
|
188
|
+
//#region src/error-response.ts
|
|
189
|
+
/** Preserve declared failures, log and wrap unexpected throws without exposing internals. */
|
|
190
|
+
function normalizeActionError(err, { logger, requestId }) {
|
|
191
|
+
if (err instanceof ActionExecutionError || err instanceof ValidationError) return err;
|
|
192
|
+
logger.error("Unexpected action error", { requestId }, err);
|
|
193
|
+
const failure = new ActionExecutionError("INTERNAL_SERVER_ERROR", "Internal Server Error", 500, void 0, { cause: err });
|
|
194
|
+
failure.name = "InternalServerError";
|
|
195
|
+
return failure;
|
|
196
|
+
}
|
|
197
|
+
function toErrorResponse(err, context) {
|
|
198
|
+
const failure = normalizeActionError(err, context);
|
|
199
|
+
if (failure.status >= 500 && (err instanceof ActionExecutionError || err instanceof ValidationError)) context.logger.error("Server action error", { requestId: context.requestId }, err);
|
|
200
|
+
if (failure instanceof ValidationError && failure.status >= 500) return {
|
|
201
|
+
name: failure.name,
|
|
202
|
+
code: failure.code,
|
|
203
|
+
message: failure.message,
|
|
204
|
+
status: failure.status,
|
|
205
|
+
requestId: context.requestId
|
|
206
|
+
};
|
|
207
|
+
return {
|
|
208
|
+
...failure.toJSON(),
|
|
209
|
+
requestId: context.requestId
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
//#endregion
|
|
188
213
|
//#region src/typebox.ts
|
|
189
214
|
const compilerCache = /* @__PURE__ */ new WeakMap();
|
|
190
215
|
function getCompiledCheck(schema) {
|
|
@@ -272,15 +297,15 @@ function createDefaultContext(partial) {
|
|
|
272
297
|
}
|
|
273
298
|
function buildErrorHelpers(errorsDef) {
|
|
274
299
|
const helpers = {};
|
|
275
|
-
for (const [code, def] of Object.entries(standardErrorDefaults)) helpers[code] = (overrideMessage, details) => {
|
|
300
|
+
for (const [code, def] of Object.entries(standardErrorDefaults)) helpers[code] = (overrideMessage, details, options) => {
|
|
276
301
|
const message = overrideMessage || def.message;
|
|
277
302
|
const status = def.status;
|
|
278
|
-
throw new ActionExecutionError(code, message, status, details);
|
|
303
|
+
throw new ActionExecutionError(code, message, status, details, options);
|
|
279
304
|
};
|
|
280
|
-
if (errorsDef) for (const [code, def] of Object.entries(errorsDef)) helpers[code] = (overrideMessage, details) => {
|
|
305
|
+
if (errorsDef) for (const [code, def] of Object.entries(errorsDef)) helpers[code] = (overrideMessage, details, options) => {
|
|
281
306
|
const message = overrideMessage || def.message;
|
|
282
307
|
const status = def.status || 400;
|
|
283
|
-
throw new ActionExecutionError(code, message, status, details);
|
|
308
|
+
throw new ActionExecutionError(code, message, status, details, options);
|
|
284
309
|
};
|
|
285
310
|
return helpers;
|
|
286
311
|
}
|
|
@@ -313,34 +338,38 @@ function defineAction(config) {
|
|
|
313
338
|
if (params?.ctx?.[RESOLVED_SYMBOL$1] === boundService) fullCtx = params.ctx;
|
|
314
339
|
else if (boundService && typeof boundService.resolveContext === "function") fullCtx = await boundService.resolveContext(params?.ctx);
|
|
315
340
|
else fullCtx = createDefaultContext(params?.ctx);
|
|
316
|
-
|
|
317
|
-
if (
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
341
|
+
try {
|
|
342
|
+
if (!fullCtx.db) {
|
|
343
|
+
if (actionFn.service?.getDb()) fullCtx.db = actionFn.service.getDb();
|
|
344
|
+
else if (actionFn.serviceName) {
|
|
345
|
+
const s = getGlobalRegistry().get(actionFn.serviceName);
|
|
346
|
+
if (s?.getDb()) fullCtx.db = s.getDb();
|
|
347
|
+
}
|
|
321
348
|
}
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
349
|
+
if (config.input) {
|
|
350
|
+
const inputValidation = actionFn.validateInput(params?.input);
|
|
351
|
+
if (!inputValidation.success) throw new ValidationError(`Validation failed for action '${config.name}' input`, inputValidation.errors);
|
|
352
|
+
}
|
|
353
|
+
if (config.authorize) {
|
|
354
|
+
if (!await config.authorize({
|
|
355
|
+
user: fullCtx.user,
|
|
356
|
+
input: params?.input,
|
|
357
|
+
ctx: fullCtx
|
|
358
|
+
})) throw new ActionExecutionError(fullCtx.user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${config.name}'`, fullCtx.user == null ? 401 : 403);
|
|
359
|
+
}
|
|
360
|
+
const result = await config.execute({
|
|
330
361
|
input: params?.input,
|
|
331
|
-
ctx: fullCtx
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
if (!outputValidation.success) throw new ValidationError(`Validation failed for action '${config.name}' output`, outputValidation.errors, 500);
|
|
362
|
+
ctx: fullCtx,
|
|
363
|
+
error: errorHelpers
|
|
364
|
+
});
|
|
365
|
+
if (actionFn.outputValidationSchema ?? config.output) {
|
|
366
|
+
const outputValidation = actionFn.validateOutput(result);
|
|
367
|
+
if (!outputValidation.success) throw new ValidationError(`Validation failed for action '${config.name}' output`, outputValidation.errors, 500);
|
|
368
|
+
}
|
|
369
|
+
return result;
|
|
370
|
+
} catch (err) {
|
|
371
|
+
throw normalizeActionError(err, fullCtx);
|
|
342
372
|
}
|
|
343
|
-
return result;
|
|
344
373
|
};
|
|
345
374
|
return actionFn;
|
|
346
375
|
}
|
|
@@ -660,17 +689,10 @@ function validate(check, value, action, stage) {
|
|
|
660
689
|
}));
|
|
661
690
|
throw new ValidationError(`Validation failed for action '${action}' ${stage}`, errors, stage === "output" ? 500 : 400);
|
|
662
691
|
}
|
|
663
|
-
function mapError(err, set) {
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
}
|
|
668
|
-
set.status = 500;
|
|
669
|
-
return {
|
|
670
|
-
name: "InternalServerError",
|
|
671
|
-
message: err?.message || "An unexpected error occurred",
|
|
672
|
-
status: 500
|
|
673
|
-
};
|
|
692
|
+
function mapError(err, set, options) {
|
|
693
|
+
const response = toErrorResponse(err, options);
|
|
694
|
+
set.status = response.status;
|
|
695
|
+
return response;
|
|
674
696
|
}
|
|
675
697
|
const compilerRuntime = Object.freeze({
|
|
676
698
|
emptyServices: EMPTY_SERVICES$2,
|
|
@@ -681,8 +703,8 @@ const compilerRuntime = Object.freeze({
|
|
|
681
703
|
validate,
|
|
682
704
|
mapError,
|
|
683
705
|
isThenable: (value) => value != null && typeof value.then === "function",
|
|
684
|
-
deny: (action) => {
|
|
685
|
-
throw new ActionExecutionError("UNAUTHORIZED", `Access denied for action '${action}'`, 403);
|
|
706
|
+
deny: (action, user) => {
|
|
707
|
+
throw new ActionExecutionError(user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${action}'`, user == null ? 401 : 403);
|
|
686
708
|
}
|
|
687
709
|
});
|
|
688
710
|
//#endregion
|
|
@@ -837,7 +859,7 @@ async function executeCompiledRoute(plan, elysiaCtx) {
|
|
|
837
859
|
input,
|
|
838
860
|
user: ctx.user
|
|
839
861
|
});
|
|
840
|
-
if (!(authRes instanceof Promise ? await authRes : authRes)) throw new ActionExecutionError("UNAUTHORIZED", `Access denied for action '${plan.actionName}'`, 403);
|
|
862
|
+
if (!(authRes instanceof Promise ? await authRes : authRes)) throw new ActionExecutionError(ctx.user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${plan.actionName}'`, ctx.user == null ? 401 : 403);
|
|
841
863
|
}
|
|
842
864
|
const execRes = plan.execute({
|
|
843
865
|
input,
|
|
@@ -857,16 +879,12 @@ async function executeCompiledRoute(plan, elysiaCtx) {
|
|
|
857
879
|
}
|
|
858
880
|
return result;
|
|
859
881
|
} catch (err) {
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
}
|
|
864
|
-
set.status =
|
|
865
|
-
return
|
|
866
|
-
name: "InternalServerError",
|
|
867
|
-
message: err.message || "An unexpected error occurred",
|
|
868
|
-
status: 500
|
|
869
|
-
};
|
|
882
|
+
const response = toErrorResponse(err, {
|
|
883
|
+
logger: ctx.logger,
|
|
884
|
+
requestId
|
|
885
|
+
});
|
|
886
|
+
set.status = response.status;
|
|
887
|
+
return response;
|
|
870
888
|
}
|
|
871
889
|
}
|
|
872
890
|
function createActionHandler(service, action, routePath, method) {
|
|
@@ -874,58 +892,103 @@ function createActionHandler(service, action, routePath, method) {
|
|
|
874
892
|
return (elysiaCtx) => executeCompiledRoute(plan, elysiaCtx);
|
|
875
893
|
}
|
|
876
894
|
//#endregion
|
|
877
|
-
//#region src/compiler/
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
const input = ["let input;"];
|
|
883
|
-
if (route.input) {
|
|
884
|
-
input.push("let coercedQuery = query;");
|
|
885
|
-
if (route.coercions.length) {
|
|
886
|
-
input.push("if (query) {", "coercedQuery = { ...query };");
|
|
887
|
-
for (const [index, coercion] of route.coercions.entries()) {
|
|
888
|
-
const key = JSON.stringify(coercion.key);
|
|
889
|
-
input.push(`const v${index} = query[${key}];`);
|
|
890
|
-
if (coercion.type === "number") input.push(`if (v${index} !== undefined) { const n${index} = Number(v${index}); if (!Number.isNaN(n${index})) coercedQuery[${key}] = n${index}; }`);
|
|
891
|
-
else input.push(`if (v${index} === "true" || v${index} === "1") coercedQuery[${key}] = true; else if (v${index} === "false" || v${index} === "0") coercedQuery[${key}] = false;`);
|
|
892
|
-
}
|
|
893
|
-
input.push("}");
|
|
894
|
-
}
|
|
895
|
-
input.push(`input = mergeInput(${route.inputPrecedence.map((source) => source === "query" ? "coercedQuery" : source).join(", ")});`);
|
|
896
|
-
if (route.inputSchema?.type === "object") input.push("input ??= {};");
|
|
895
|
+
//#region src/compiler/handler.ts
|
|
896
|
+
function coerceQueryValue(value, type) {
|
|
897
|
+
if (type === "number" && value !== void 0) {
|
|
898
|
+
const number = Number(value);
|
|
899
|
+
return Number.isNaN(number) ? value : number;
|
|
897
900
|
}
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
const
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
if (
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
901
|
+
if (type === "boolean") {
|
|
902
|
+
if (value === "true" || value === "1") return true;
|
|
903
|
+
if (value === "false" || value === "0") return false;
|
|
904
|
+
}
|
|
905
|
+
return value;
|
|
906
|
+
}
|
|
907
|
+
/** Bind route metadata with ordinary closures; emitted factories remain build-only. */
|
|
908
|
+
function createHandlerFactory(route) {
|
|
909
|
+
return (binding, runtime) => {
|
|
910
|
+
const { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;
|
|
911
|
+
const readLike = route.inputPrecedence[0] === "query";
|
|
912
|
+
const objectInput = binding.action.config.input?.type === "object";
|
|
913
|
+
const readInput = route.input ? ({ params, body, query }) => {
|
|
914
|
+
let coercedQuery = query;
|
|
915
|
+
if (query && route.coercions.length) {
|
|
916
|
+
coercedQuery = { ...query };
|
|
917
|
+
for (const { key, type } of route.coercions) if (query[key] !== void 0) coercedQuery[key] = coerceQueryValue(query[key], type);
|
|
918
|
+
}
|
|
919
|
+
let input = readLike ? runtime.mergeInput(coercedQuery, params, body) : runtime.mergeInput(params, body, coercedQuery);
|
|
920
|
+
if (objectInput) input ??= {};
|
|
921
|
+
return input;
|
|
922
|
+
} : () => void 0;
|
|
923
|
+
const validateInput = (input) => {
|
|
924
|
+
if (inputChecker) {
|
|
925
|
+
runtime.checkDepth(input, route.action);
|
|
926
|
+
runtime.validate(inputChecker, input, route.action, "input");
|
|
927
|
+
}
|
|
928
|
+
};
|
|
929
|
+
const validateOutput = (result) => {
|
|
930
|
+
if (route.output && outputChecker) runtime.validate(outputChecker, result, route.action, "output");
|
|
931
|
+
return result;
|
|
932
|
+
};
|
|
933
|
+
const createContext = ({ headers, request, set }) => {
|
|
934
|
+
const seq = runtime.nextSequence();
|
|
935
|
+
const traceId = headers?.["x-trace-id"] || "tr_" + seq;
|
|
936
|
+
const requestId = headers?.["x-request-id"] || "req_" + seq;
|
|
937
|
+
if (set?.headers) {
|
|
938
|
+
set.headers["x-trace-id"] = traceId;
|
|
939
|
+
set.headers["x-request-id"] = requestId;
|
|
940
|
+
}
|
|
941
|
+
return {
|
|
942
|
+
request: request instanceof Request ? request : runtime.defaultRequest,
|
|
943
|
+
traceId,
|
|
944
|
+
requestId,
|
|
945
|
+
db: cachedDb ?? service.getDb(),
|
|
946
|
+
logger,
|
|
947
|
+
services: runtime.emptyServices,
|
|
948
|
+
metadata: { headers },
|
|
949
|
+
_resolved: true
|
|
950
|
+
};
|
|
951
|
+
};
|
|
952
|
+
if (contextHook || authorize) return async function brickAction(context) {
|
|
953
|
+
const input = readInput(context);
|
|
954
|
+
const ctx = createContext(context);
|
|
955
|
+
try {
|
|
956
|
+
if (contextHook) {
|
|
957
|
+
const extra = await contextHook(ctx);
|
|
958
|
+
if (extra) Object.assign(ctx, extra);
|
|
959
|
+
}
|
|
960
|
+
validateInput(input);
|
|
961
|
+
if (authorize && !await authorize({
|
|
962
|
+
ctx,
|
|
963
|
+
input,
|
|
964
|
+
user: ctx.user
|
|
965
|
+
})) runtime.deny(route.action, ctx.user);
|
|
966
|
+
return validateOutput(await execute({
|
|
967
|
+
input,
|
|
968
|
+
ctx,
|
|
969
|
+
error: errorBuilder
|
|
970
|
+
}));
|
|
971
|
+
} catch (err) {
|
|
972
|
+
return runtime.mapError(err, context.set, ctx);
|
|
973
|
+
}
|
|
974
|
+
};
|
|
975
|
+
return function brickAction(context) {
|
|
976
|
+
const input = readInput(context);
|
|
977
|
+
const ctx = createContext(context);
|
|
978
|
+
try {
|
|
979
|
+
validateInput(input);
|
|
980
|
+
const result = execute({
|
|
981
|
+
input,
|
|
982
|
+
ctx,
|
|
983
|
+
error: errorBuilder
|
|
984
|
+
});
|
|
985
|
+
if (runtime.isThenable(result)) return Promise.resolve(result).then(validateOutput).catch((err) => runtime.mapError(err, context.set, ctx));
|
|
986
|
+
return validateOutput(result);
|
|
987
|
+
} catch (err) {
|
|
988
|
+
return runtime.mapError(err, context.set, ctx);
|
|
989
|
+
}
|
|
990
|
+
};
|
|
991
|
+
};
|
|
929
992
|
}
|
|
930
993
|
//#endregion
|
|
931
994
|
//#region src/app-entry.ts
|
|
@@ -973,12 +1036,12 @@ function bindAnalyzed(ir, bindings, factories) {
|
|
|
973
1036
|
routes: Object.freeze(routes)
|
|
974
1037
|
});
|
|
975
1038
|
}
|
|
976
|
-
/** Startup compiler: analyzes once,
|
|
1039
|
+
/** Startup compiler: analyzes once, then binds live callbacks. */
|
|
977
1040
|
function compileBrickApplication(options) {
|
|
978
1041
|
const bind = buildBindings.get(applicationKey(options.services, options.prefix));
|
|
979
1042
|
if (bind && options.mode !== "generic") return bind(options.services);
|
|
980
1043
|
const { ir, bindings } = analyzeApplication(options.services, options.prefix);
|
|
981
|
-
const factories = options.mode === "generic" ? ir.routes.map(() => (plan) => (context) => executeCompiledRoute(plan, context)) : ir.routes.map(
|
|
1044
|
+
const factories = options.mode === "generic" ? ir.routes.map(() => (plan) => (context) => executeCompiledRoute(plan, context)) : ir.routes.map(createHandlerFactory);
|
|
982
1045
|
if (options.mode !== "generic") for (const service of options.services) service.prepareContributions();
|
|
983
1046
|
return bindAnalyzed(ir, bindings, factories);
|
|
984
1047
|
}
|
|
@@ -1058,57 +1121,38 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1058
1121
|
content: { "application/json": { schema: action.config.output } }
|
|
1059
1122
|
};
|
|
1060
1123
|
else responses["200"] = { description: "Successful response" };
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1124
|
+
const errorAlternatives = /* @__PURE__ */ new Set();
|
|
1125
|
+
const addError = (code, status, message) => {
|
|
1126
|
+
const key = `${status}:${code}`;
|
|
1127
|
+
if (errorAlternatives.has(key)) return;
|
|
1128
|
+
errorAlternatives.add(key);
|
|
1129
|
+
const schema = { allOf: [{ $ref: "#/components/schemas/ErrorEnvelope" }, {
|
|
1064
1130
|
type: "object",
|
|
1065
1131
|
properties: {
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
status: { type: "integer" },
|
|
1069
|
-
errors: {
|
|
1070
|
-
type: "array",
|
|
1071
|
-
items: {
|
|
1072
|
-
type: "object",
|
|
1073
|
-
properties: {
|
|
1074
|
-
path: { type: "string" },
|
|
1075
|
-
message: { type: "string" }
|
|
1076
|
-
}
|
|
1077
|
-
}
|
|
1078
|
-
}
|
|
1132
|
+
code: { const: code },
|
|
1133
|
+
status: { const: status }
|
|
1079
1134
|
}
|
|
1080
|
-
} }
|
|
1135
|
+
}] };
|
|
1136
|
+
const existing = responses[String(status)];
|
|
1137
|
+
if (existing) {
|
|
1138
|
+
existing.description += "; " + message;
|
|
1139
|
+
existing.content["application/json"].schema.oneOf.push(schema);
|
|
1140
|
+
} else responses[String(status)] = {
|
|
1141
|
+
description: message,
|
|
1142
|
+
content: { "application/json": { schema: { oneOf: [schema] } } }
|
|
1143
|
+
};
|
|
1081
1144
|
};
|
|
1082
|
-
if (
|
|
1145
|
+
if (action.config.input) addError("VALIDATION_FAILED", 400, "Validation error");
|
|
1146
|
+
if (hasAuth) {
|
|
1147
|
+
addError("UNAUTHORIZED", 401, "Authentication required");
|
|
1148
|
+
addError("FORBIDDEN", 403, "Access denied");
|
|
1149
|
+
}
|
|
1083
1150
|
if (action.config.errors) for (const [code, errorDef] of Object.entries(action.config.errors)) {
|
|
1084
1151
|
const def = errorDef;
|
|
1085
|
-
|
|
1086
|
-
responses[status] = {
|
|
1087
|
-
description: def.message || code,
|
|
1088
|
-
content: { "application/json": { schema: {
|
|
1089
|
-
type: "object",
|
|
1090
|
-
properties: {
|
|
1091
|
-
name: {
|
|
1092
|
-
type: "string",
|
|
1093
|
-
example: "ActionExecutionError"
|
|
1094
|
-
},
|
|
1095
|
-
code: {
|
|
1096
|
-
type: "string",
|
|
1097
|
-
example: code
|
|
1098
|
-
},
|
|
1099
|
-
message: {
|
|
1100
|
-
type: "string",
|
|
1101
|
-
example: def.message
|
|
1102
|
-
},
|
|
1103
|
-
status: {
|
|
1104
|
-
type: "integer",
|
|
1105
|
-
example: def.status || 400
|
|
1106
|
-
}
|
|
1107
|
-
}
|
|
1108
|
-
} } }
|
|
1109
|
-
};
|
|
1152
|
+
addError(code, def.status || 400, def.message || code);
|
|
1110
1153
|
}
|
|
1111
|
-
|
|
1154
|
+
addError("INTERNAL_SERVER_ERROR", 500, "Internal server error");
|
|
1155
|
+
if (action.config.output) addError("VALIDATION_FAILED", 500, "Output validation error");
|
|
1112
1156
|
const operation = {
|
|
1113
1157
|
operationId: `${service.name}_${action.name}_${method}`,
|
|
1114
1158
|
summary: `${service.name}.${action.name}`,
|
|
@@ -1161,12 +1205,42 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1161
1205
|
description: `Actions exposed by '${name}' service`
|
|
1162
1206
|
}))
|
|
1163
1207
|
};
|
|
1164
|
-
|
|
1208
|
+
spec.components = { schemas: { ErrorEnvelope: {
|
|
1209
|
+
type: "object",
|
|
1210
|
+
required: [
|
|
1211
|
+
"name",
|
|
1212
|
+
"code",
|
|
1213
|
+
"message",
|
|
1214
|
+
"status",
|
|
1215
|
+
"requestId"
|
|
1216
|
+
],
|
|
1217
|
+
properties: {
|
|
1218
|
+
name: { type: "string" },
|
|
1219
|
+
code: { type: "string" },
|
|
1220
|
+
message: { type: "string" },
|
|
1221
|
+
status: { type: "integer" },
|
|
1222
|
+
requestId: { type: "string" },
|
|
1223
|
+
details: {},
|
|
1224
|
+
errors: {
|
|
1225
|
+
type: "array",
|
|
1226
|
+
items: {
|
|
1227
|
+
type: "object",
|
|
1228
|
+
required: ["path", "message"],
|
|
1229
|
+
properties: {
|
|
1230
|
+
path: { type: "string" },
|
|
1231
|
+
message: { type: "string" },
|
|
1232
|
+
value: {}
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
} } };
|
|
1238
|
+
if (hasAnyAuthorizedAction) Object.assign(spec.components, { securitySchemes: { bearerAuth: {
|
|
1165
1239
|
type: "http",
|
|
1166
1240
|
scheme: "bearer",
|
|
1167
1241
|
bearerFormat: "JWT",
|
|
1168
1242
|
description: "Enter your Bearer authentication token"
|
|
1169
|
-
} } };
|
|
1243
|
+
} } });
|
|
1170
1244
|
return spec;
|
|
1171
1245
|
}
|
|
1172
1246
|
//#endregion
|
|
@@ -1485,26 +1559,12 @@ function createEndpointHandler(def, services) {
|
|
|
1485
1559
|
try {
|
|
1486
1560
|
return await def.handler(ctx);
|
|
1487
1561
|
} catch (err) {
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
}
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
return err.toJSON();
|
|
1495
|
-
}
|
|
1496
|
-
if (typeof err?.status === "number") {
|
|
1497
|
-
set.status = err.status;
|
|
1498
|
-
return {
|
|
1499
|
-
message: err.message || "Endpoint error",
|
|
1500
|
-
status: err.status
|
|
1501
|
-
};
|
|
1502
|
-
}
|
|
1503
|
-
set.status = 500;
|
|
1504
|
-
return {
|
|
1505
|
-
message: err?.message || "An unexpected error occurred",
|
|
1506
|
-
status: 500
|
|
1507
|
-
};
|
|
1562
|
+
const response = toErrorResponse(!(err instanceof ActionExecutionError || err instanceof ValidationError) && err !== null && typeof err === "object" && "status" in err && typeof err.status === "number" && Number.isInteger(err.status) && err.status >= 400 && err.status < 500 ? new ActionExecutionError("HTTP_ERROR", "message" in err && typeof err.message === "string" ? err.message : "Endpoint error", err.status, void 0, { cause: err }) : err, {
|
|
1563
|
+
logger: ctx.logger,
|
|
1564
|
+
requestId
|
|
1565
|
+
});
|
|
1566
|
+
set.status = response.status;
|
|
1567
|
+
return response;
|
|
1508
1568
|
}
|
|
1509
1569
|
};
|
|
1510
1570
|
}
|
|
@@ -1705,6 +1765,60 @@ function cachedJsonRoute(build, revision) {
|
|
|
1705
1765
|
};
|
|
1706
1766
|
}
|
|
1707
1767
|
//#endregion
|
|
1768
|
+
//#region src/compiler/emit.ts
|
|
1769
|
+
/** Emits framework code only. User callbacks remain closures bound separately. */
|
|
1770
|
+
function emitHandlerFactory(route) {
|
|
1771
|
+
const name = JSON.stringify(route.action);
|
|
1772
|
+
const fields = route.input ? "params, body, query, headers, request, set" : "headers, request, set";
|
|
1773
|
+
const input = ["let input;"];
|
|
1774
|
+
if (route.input) {
|
|
1775
|
+
input.push("let coercedQuery = query;");
|
|
1776
|
+
if (route.coercions.length) {
|
|
1777
|
+
input.push("if (query) {", "coercedQuery = { ...query };");
|
|
1778
|
+
for (const [index, coercion] of route.coercions.entries()) {
|
|
1779
|
+
const key = JSON.stringify(coercion.key);
|
|
1780
|
+
input.push(`const v${index} = query[${key}];`);
|
|
1781
|
+
if (coercion.type === "number") input.push(`if (v${index} !== undefined) { const n${index} = Number(v${index}); if (!Number.isNaN(n${index})) coercedQuery[${key}] = n${index}; }`);
|
|
1782
|
+
else input.push(`if (v${index} === "true" || v${index} === "1") coercedQuery[${key}] = true; else if (v${index} === "false" || v${index} === "0") coercedQuery[${key}] = false;`);
|
|
1783
|
+
}
|
|
1784
|
+
input.push("}");
|
|
1785
|
+
}
|
|
1786
|
+
input.push(`input = mergeInput(${route.inputPrecedence.map((source) => source === "query" ? "coercedQuery" : source).join(", ")});`);
|
|
1787
|
+
if (route.inputSchema?.type === "object") input.push("input ??= {};");
|
|
1788
|
+
}
|
|
1789
|
+
const asyncStages = route.context || route.authorize;
|
|
1790
|
+
const context = route.context ? "const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);" : "";
|
|
1791
|
+
const validation = route.input ? `checkDepth(input, ${name}); validate(inputChecker, input, ${name}, "input");` : "";
|
|
1792
|
+
const authorization = route.authorize ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name}, ctx.user);` : "";
|
|
1793
|
+
const output = route.output ? `validate(outputChecker, result, ${name}, "output");` : "";
|
|
1794
|
+
const execute = asyncStages ? `const result = await execute({ input, ctx, error: errorBuilder });\n${output}\nreturn result;` : `const result = execute({ input, ctx, error: errorBuilder });
|
|
1795
|
+
if (isThenable(result)) return Promise.resolve(result).then(value => {
|
|
1796
|
+
${route.output ? `validate(outputChecker, value, ${name}, "output");` : ""}
|
|
1797
|
+
return value;
|
|
1798
|
+
}).catch(err => mapError(err, set, ctx));
|
|
1799
|
+
${output}
|
|
1800
|
+
return result;`;
|
|
1801
|
+
return `function bindAction(binding, runtime) {
|
|
1802
|
+
const { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;
|
|
1803
|
+
const { nextSequence, defaultRequest, emptyServices, mergeInput, checkDepth, validate, deny, mapError, isThenable } = runtime;
|
|
1804
|
+
return ${asyncStages ? "async " : ""}function brickAction({ ${fields} }) {
|
|
1805
|
+
const seq = nextSequence();
|
|
1806
|
+
const traceId = (headers && headers["x-trace-id"]) || "tr_" + seq;
|
|
1807
|
+
const requestId = (headers && headers["x-request-id"]) || "req_" + seq;
|
|
1808
|
+
if (set?.headers) { set.headers["x-trace-id"] = traceId; set.headers["x-request-id"] = requestId; }
|
|
1809
|
+
${input.join("\n")}
|
|
1810
|
+
const ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,
|
|
1811
|
+
db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };
|
|
1812
|
+
try {
|
|
1813
|
+
${context}
|
|
1814
|
+
${validation}
|
|
1815
|
+
${authorization}
|
|
1816
|
+
${execute}
|
|
1817
|
+
} catch (err) { return mapError(err, set, ctx); }
|
|
1818
|
+
};
|
|
1819
|
+
}`;
|
|
1820
|
+
}
|
|
1821
|
+
//#endregion
|
|
1708
1822
|
//#region src/tool.ts
|
|
1709
1823
|
function defineTool(config) {
|
|
1710
1824
|
if (config.input && config.input.type !== "object") throw new Error(`Tool '${config.name}' input must be an object schema`);
|
|
@@ -1716,12 +1830,8 @@ function isTool(value) {
|
|
|
1716
1830
|
return typeof value === "function" && value.kind === "tool";
|
|
1717
1831
|
}
|
|
1718
1832
|
//#endregion
|
|
1719
|
-
//#region src/db/load.ts
|
|
1720
|
-
function loadDriver(id) {
|
|
1721
|
-
return (globalThis.require ?? createRequire(import.meta.url))(id);
|
|
1722
|
-
}
|
|
1723
|
-
//#endregion
|
|
1724
1833
|
//#region src/db/sqlite.ts
|
|
1834
|
+
const requireSQLite = createRequire(import.meta.url);
|
|
1725
1835
|
/**
|
|
1726
1836
|
* Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine
|
|
1727
1837
|
* and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).
|
|
@@ -1734,7 +1844,7 @@ function createSQLiteDatabase(config = {}) {
|
|
|
1734
1844
|
let Database;
|
|
1735
1845
|
let drizzle;
|
|
1736
1846
|
try {
|
|
1737
|
-
({Database} =
|
|
1847
|
+
({Database} = requireSQLite("bun:sqlite"));
|
|
1738
1848
|
({drizzle} = __require("drizzle-orm/bun-sqlite"));
|
|
1739
1849
|
} catch (err) {
|
|
1740
1850
|
throw new Error(`[Brick-TS DB] SQLite engine requires the Bun runtime ('bun:sqlite' is unavailable here). Original error: ${err?.message ?? err}`);
|
|
@@ -2087,6 +2197,18 @@ function defineResource(service, config) {
|
|
|
2087
2197
|
return resource;
|
|
2088
2198
|
}
|
|
2089
2199
|
//#endregion
|
|
2200
|
+
//#region src/context.ts
|
|
2201
|
+
function pickContextEnvelope(context) {
|
|
2202
|
+
if (!context) return {};
|
|
2203
|
+
const envelope = {};
|
|
2204
|
+
if (context.caller !== void 0) envelope.caller = context.caller;
|
|
2205
|
+
if (context.user !== void 0) envelope.user = context.user;
|
|
2206
|
+
if (context.traceId !== void 0) envelope.traceId = context.traceId;
|
|
2207
|
+
if (context.requestId !== void 0) envelope.requestId = context.requestId;
|
|
2208
|
+
if (context.tenantId !== void 0) envelope.tenantId = context.tenantId;
|
|
2209
|
+
return envelope;
|
|
2210
|
+
}
|
|
2211
|
+
//#endregion
|
|
2090
2212
|
//#region src/service.ts
|
|
2091
2213
|
const defaultLogger = {
|
|
2092
2214
|
info: (...args) => console.log("[INFO]", ...args),
|
|
@@ -2225,55 +2347,22 @@ var ServiceImpl = class {
|
|
|
2225
2347
|
}
|
|
2226
2348
|
async _resolveContextSlow(callCtx) {
|
|
2227
2349
|
const seq = ++_ctxSeq;
|
|
2228
|
-
const req = callCtx?.request ?? DEFAULT_REQUEST;
|
|
2229
|
-
const db = this.getDb();
|
|
2230
|
-
const logger = callCtx?.logger ?? defaultLogger;
|
|
2231
|
-
const traceId = callCtx?.traceId ?? `tr_${seq.toString(36)}`;
|
|
2232
|
-
const requestId = callCtx?.requestId ?? `req_${seq.toString(36)}`;
|
|
2233
|
-
const services = callCtx?.services ?? EMPTY_SERVICES;
|
|
2234
|
-
const metadata = callCtx?.metadata ?? EMPTY_METADATA;
|
|
2235
|
-
if (!this.options.context) {
|
|
2236
|
-
const finalCtx = {
|
|
2237
|
-
request: req,
|
|
2238
|
-
db,
|
|
2239
|
-
logger,
|
|
2240
|
-
traceId,
|
|
2241
|
-
requestId,
|
|
2242
|
-
services,
|
|
2243
|
-
metadata,
|
|
2244
|
-
[RESOLVED_SYMBOL]: this
|
|
2245
|
-
};
|
|
2246
|
-
if (callCtx?.user !== void 0) finalCtx.user = callCtx.user;
|
|
2247
|
-
if (callCtx?.caller !== void 0) finalCtx.caller = callCtx.caller;
|
|
2248
|
-
return finalCtx;
|
|
2249
|
-
}
|
|
2250
2350
|
const fullBaseCtx = {
|
|
2251
|
-
request:
|
|
2252
|
-
db,
|
|
2253
|
-
logger,
|
|
2254
|
-
traceId
|
|
2255
|
-
requestId
|
|
2256
|
-
services,
|
|
2257
|
-
metadata
|
|
2351
|
+
request: callCtx?.request ?? DEFAULT_REQUEST,
|
|
2352
|
+
db: this.getDb(),
|
|
2353
|
+
logger: callCtx?.logger ?? defaultLogger,
|
|
2354
|
+
traceId: callCtx?.traceId ?? `tr_${seq.toString(36)}`,
|
|
2355
|
+
requestId: callCtx?.requestId ?? `req_${seq.toString(36)}`,
|
|
2356
|
+
services: callCtx?.services ?? EMPTY_SERVICES,
|
|
2357
|
+
metadata: callCtx?.metadata ?? EMPTY_METADATA,
|
|
2358
|
+
...pickContextEnvelope(callCtx)
|
|
2258
2359
|
};
|
|
2259
|
-
const resolvedExtra = await this.options.context(fullBaseCtx);
|
|
2260
|
-
|
|
2360
|
+
const resolvedExtra = this.options.context ? await this.options.context(fullBaseCtx) : {};
|
|
2361
|
+
return {
|
|
2261
2362
|
...fullBaseCtx,
|
|
2262
2363
|
...resolvedExtra,
|
|
2263
2364
|
[RESOLVED_SYMBOL]: this
|
|
2264
2365
|
};
|
|
2265
|
-
if (callCtx) {
|
|
2266
|
-
for (const [key, value] of Object.entries(callCtx)) if (![
|
|
2267
|
-
"db",
|
|
2268
|
-
"request",
|
|
2269
|
-
"logger",
|
|
2270
|
-
"services",
|
|
2271
|
-
"metadata",
|
|
2272
|
-
"_resolved",
|
|
2273
|
-
RESOLVED_SYMBOL
|
|
2274
|
-
].includes(key)) finalCtx[key] = value;
|
|
2275
|
-
}
|
|
2276
|
-
return finalCtx;
|
|
2277
2366
|
}
|
|
2278
2367
|
introspect() {
|
|
2279
2368
|
const databaseConfig = this.database ? {
|
|
@@ -2325,27 +2414,16 @@ function createServiceProxy(serviceName, options = {}) {
|
|
|
2325
2414
|
if (!service) throw new Error(`[Brick-TS RPC] Service '${serviceName}' is not registered in the local runtime.`);
|
|
2326
2415
|
const action = service.getAction(actionName);
|
|
2327
2416
|
if (!action) throw new Error(`[Brick-TS RPC] Action '${actionName}' does not exist on service '${serviceName}'.`);
|
|
2328
|
-
const
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
"services",
|
|
2333
|
-
"metadata",
|
|
2334
|
-
"_resolved"
|
|
2335
|
-
]);
|
|
2336
|
-
const envelopeCtx = {};
|
|
2337
|
-
if (options.context) {
|
|
2338
|
-
for (const [key, value] of Object.entries(options.context)) if (!dangerousFields.has(key)) envelopeCtx[key] = value;
|
|
2339
|
-
}
|
|
2340
|
-
if (callCtx) {
|
|
2341
|
-
for (const [key, value] of Object.entries(callCtx)) if (!dangerousFields.has(key)) envelopeCtx[key] = value;
|
|
2342
|
-
}
|
|
2417
|
+
const envelopeCtx = {
|
|
2418
|
+
...pickContextEnvelope(options.context),
|
|
2419
|
+
...pickContextEnvelope(callCtx)
|
|
2420
|
+
};
|
|
2343
2421
|
if (!envelopeCtx.caller) envelopeCtx.caller = serviceName;
|
|
2344
2422
|
return action.execute({
|
|
2345
2423
|
input: payload,
|
|
2346
2424
|
ctx: envelopeCtx
|
|
2347
2425
|
});
|
|
2348
|
-
} else throw new Error(`[Brick-TS RPC] Remote microservice dispatch for '${serviceName}.${actionName}' is not
|
|
2426
|
+
} else throw new Error(`[Brick-TS RPC] Remote microservice dispatch for '${serviceName}.${actionName}' is not configured. Use createClient({ baseUrl, contract }) for HTTP calls to remote services.`);
|
|
2349
2427
|
};
|
|
2350
2428
|
} });
|
|
2351
2429
|
}
|
|
@@ -2471,6 +2549,6 @@ function createMcpHandler(options) {
|
|
|
2471
2549
|
};
|
|
2472
2550
|
}
|
|
2473
2551
|
//#endregion
|
|
2474
|
-
export { ACTION_ACCESS_KEY, ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type,
|
|
2552
|
+
export { ACTION_ACCESS_KEY, ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, UnknownToolError, ValidationError, and, asc, attachDatabase, bindCompiledApplication, blob, brick, buildErrorHelpers, buildFtsMatchQuery, compileBrickApplication, compileRoutePlan, compilerRuntime, createActionHandler, createBrickClient, createDatabase, createEndpointHandler, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, createServiceProxy, defineAction, defineDatabase, defineResource, defineResourcePlugin, defineService, defineServicePlugin, defineTool, desc, emitHandlerFactory, endpointPaths, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, executeCompiledRoute, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getCompiledCheck, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, ilike, inArray, index, integer, is, isBrickApp, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, isTool, like, listSecrets, loadCompiledBrickApp, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveEndpointDb, resolveSecrets, scalarDocsHTML, secret, setActionAccess, sql, sqliteTable, swaggerDocsHTML, syncSchema, t, text, toErrorResponse, toOpenApiPath, uniqueIndex, validateWithSchema };
|
|
2475
2553
|
|
|
2476
2554
|
//# sourceMappingURL=index.js.map
|