@brickkit/core 0.14.0 → 0.15.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.
@@ -1,6 +1,8 @@
1
- import { $n as EventsOptions, E as Logger, En as PluginInstance, Et as DatabaseHandle, J as ValidationErrorItem, Pn as SecretSource, R as Service, Yt as InstalledPlugin, ht as EventsHub, mt as EventsDefinition, ot as SocketBroker, rt as BrickSocketSchema, t as Action, un as ServicePort, wr as HttpMethod } from "./types.js";
1
+ import { E as Logger, J as ValidationErrorItem, Nn as PluginInstance, Nt as DatabaseHandle, R as Service, Vn as SecretSource, _n as ServicePort, ht as EventsHub, jr as HttpMethod, mt as EventsDefinition, nn as InstalledPlugin, or as EventsOptions, ot as SocketBroker, rt as BrickSocketSchema, t as Action, wt as DashboardUser } from "./types.js";
2
2
  import { Elysia } from "elysia";
3
3
  type RouteMethod = HttpMethod;
4
+ /** How a string from a query or form field becomes the schema's type; objects travel as JSON. */
5
+ type Coercion = "number" | "boolean" | "array" | "json";
4
6
  interface RouteIR {
5
7
  readonly method: RouteMethod;
6
8
  readonly path: string;
@@ -19,8 +21,12 @@ interface RouteIR {
19
21
  readonly inputSource: "query" | "body";
20
22
  readonly coercions: readonly {
21
23
  readonly key: string;
22
- readonly type: "number" | "boolean" | "array";
24
+ readonly type: Coercion;
25
+ /** How each item of an `array` field is coerced. */
26
+ readonly items?: Exclude<Coercion, "array">;
23
27
  }[];
28
+ /** The most bytes a multipart body may declare (`Content-Length`) for an input with `t.File` fields. */
29
+ readonly bodyLimit?: number;
24
30
  /** JSON projection for inspection and stale-artifact detection, not runtime validation. */
25
31
  readonly inputSchema?: unknown;
26
32
  readonly outputSchema?: unknown;
@@ -107,11 +113,20 @@ interface DashboardAuth {
107
113
  * `Response` to send instead, such as a redirect to your login page. If it
108
114
  * throws or takes longer than five seconds, the request is refused with 503.
109
115
  *
116
+ * Return `{ user: { id, name } }` to let it in and say who it is: requests
117
+ * the dashboard's pages send to the app through `/app/*` carry that user,
118
+ * signed, which the app reads with `ctx.dashboard?.user` in an action or
119
+ * `dashboardUser(request)` in an endpoint.
120
+ *
110
121
  * A request is let in when it carries a valid `token`, or when this
111
122
  * returns `true`; give both to let monitors in by token and people in by
112
123
  * sign-in.
113
124
  */
114
- authorize?: (request: Request) => boolean | Response | Promise<boolean | Response>;
125
+ authorize?: (request: Request) => boolean | Response | {
126
+ user: DashboardUser;
127
+ } | Promise<boolean | Response | {
128
+ user: DashboardUser;
129
+ }>;
115
130
  }
116
131
  /**
117
132
  * The monitoring dashboard `brick start` serves beside the app, on a port of
@@ -1,9 +1,10 @@
1
1
  import { A as byteLength, B as splitSeq, C as SOCKET_BUFFER_BYTES, D as SOCKET_PROTOCOL, E as SOCKET_MAX_BYTES, F as isSocketRoom, G as DuplicateNameError, H as GLOBAL_SYMBOL, I as isSocketSeq, K as ValidationError, L as replayFrame, M as encodeFrame, N as isControlEvent, O as SOCKET_TOKEN_PROTOCOL, P as isSocketEnvelope, R as replayHeadroom, S as actionMeta, T as SOCKET_CONTROL, U as SPAN, V as ATTR, W as ActionExecutionError, _ as pathParamNames, b as toOpenApiPath, c as DEFAULT_PREFIX, d as getActionRoute, g as ownerPath, h as joinRoute, k as STANDARD_ERRORS, l as actionOwners, m as isReadLike, p as inputSource, s as serializeSocketSchema, u as checkSegments, v as pluginRoutePath, w as SOCKET_CLOSE, x as kebabCase, y as routeKey, z as signSeq } from "./client.js";
2
2
  import { createRequire } from "node:module";
3
3
  import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
4
- import { Type, Type as t } from "@sinclair/typebox";
4
+ import { Kind, Type, TypeRegistry } from "@sinclair/typebox";
5
5
  import { TypeCompiler } from "@sinclair/typebox/compiler";
6
6
  import { formatWithOptions } from "node:util";
7
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
7
8
  import { join, resolve } from "node:path";
8
9
  import { fileURLToPath, pathToFileURL } from "node:url";
9
10
  import { and, asc, eq, inArray, isNull, lt, lte, or, sql } from "drizzle-orm";
@@ -12,7 +13,6 @@ import { bigserial, index as index$1, integer as integer$1, jsonb, pgTable, text
12
13
  import { existsSync, readFileSync } from "node:fs";
13
14
  import { AsyncLocalStorage } from "node:async_hooks";
14
15
  import { Elysia } from "elysia";
15
- import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
16
16
  import { websocket } from "elysia/websocket";
17
17
  // src/plugin-types.ts
18
18
  /** Where a plugin route mounts: under the app prefix, its service, or its resource. */
@@ -307,6 +307,59 @@ function buildErrorEnvelope(err, context) {
307
307
  };
308
308
  }
309
309
  // src/typebox.ts
310
+ /**
311
+ * Any JSON value: null, boolean, number, string, or an array or object of
312
+ * JSON values.
313
+ */
314
+ function Json(options) {
315
+ return Type.Recursive((This) => Type.Union([
316
+ Type.Null(),
317
+ Type.Boolean(),
318
+ Type.Number(),
319
+ Type.String(),
320
+ Type.Array(This),
321
+ Type.Record(Type.String(), This)
322
+ ]), options);
323
+ }
324
+ TypeRegistry.Set("File", (schema, value) => value instanceof Blob && !(value.size > (schema.maxSize ?? Infinity)));
325
+ /** A file from a `multipart/form-data` body: a `File` (a `Blob`), at most `maxSize` bytes. */
326
+ function File(options = {}) {
327
+ return Type.Unsafe({
328
+ [Kind]: "File",
329
+ type: "string",
330
+ format: "binary",
331
+ ...options
332
+ });
333
+ }
334
+ /** Several files under one form field. */
335
+ function Files(options = {}) {
336
+ const { minItems, maxItems, ...file } = options;
337
+ return Type.Array(File(file), {
338
+ minItems,
339
+ maxItems
340
+ });
341
+ }
342
+ /** TypeBox's `Type` plus Brick's `Json`, `File` and `Files`. */
343
+ const Type$1 = Object.assign({}, Type, {
344
+ Json,
345
+ File,
346
+ Files
347
+ });
348
+ function fileFields(schema) {
349
+ const fields = [];
350
+ const properties = schema?.properties;
351
+ for (const [key, prop] of Object.entries(properties ?? {})) {
352
+ const file = prop[Kind] === "File" ? prop : prop.items;
353
+ if (file?.[Kind] !== "File") continue;
354
+ const count = file === prop ? 1 : prop.maxItems;
355
+ const maxBytes = file.maxSize === void 0 || count === void 0 ? void 0 : file.maxSize * count;
356
+ fields.push({
357
+ key,
358
+ maxBytes
359
+ });
360
+ }
361
+ return fields;
362
+ }
310
363
  const compilerCache = /* @__PURE__ */ new WeakMap();
311
364
  /**
312
365
  * The compiled validator for a TypeBox schema. Compiling is slow and checking
@@ -446,6 +499,69 @@ const DEFAULT_LOG_PREFIXES = {
446
499
  error: "[ERROR]",
447
500
  debug: "[DEBUG]"
448
501
  };
502
+ // src/dashboard-identity.ts
503
+ /** The header the dashboard's `/app/*` proxy signs the identity into. */
504
+ const DASHBOARD_IDENTITY_HEADER = "x-brick-dashboard";
505
+ /** How `brick dev` hands the signing key to the app's process. */
506
+ const DASHBOARD_KEY_ENV = "BRICK_DASHBOARD_KEY";
507
+ const SIGNATURE_TTL_MS = 6e4;
508
+ const KEY = Symbol.for(GLOBAL_SYMBOL.dashboardKey);
509
+ const global = globalThis;
510
+ function hideKeyFromChildProcesses() {
511
+ const handedOver = process.env[DASHBOARD_KEY_ENV];
512
+ if (!handedOver) return;
513
+ global[KEY] = handedOver;
514
+ delete process.env[DASHBOARD_KEY_ENV];
515
+ }
516
+ hideKeyFromChildProcesses();
517
+ /**
518
+ * The key the dashboard signs identities with: random per process, or the one
519
+ * `brick dev` or the Vite plugin handed the app.
520
+ */
521
+ function dashboardKey() {
522
+ return global[KEY] ??= randomBytes(32).toString("base64url");
523
+ }
524
+ const arrivedAt = /* @__PURE__ */ new WeakMap();
525
+ /** Note when `request` arrived, before its body is read. */
526
+ function markDashboardArrival(request) {
527
+ arrivedAt.set(request, Date.now());
528
+ }
529
+ const mac = (payload) => createHmac("sha256", dashboardKey()).update(payload).digest();
530
+ /** The header value for an identity: `<base64url(json)>.<hmac>`. */
531
+ function signDashboardIdentity(identity, now = Date.now()) {
532
+ const payload = Buffer.from(JSON.stringify({
533
+ user: identity.user,
534
+ exp: now + SIGNATURE_TTL_MS
535
+ })).toString("base64url");
536
+ return `${payload}.${mac(payload).toString("base64url")}`;
537
+ }
538
+ function dashboardIdentity(request) {
539
+ const header = request?.headers.get(DASHBOARD_IDENTITY_HEADER);
540
+ if (!header) return void 0;
541
+ const dot = header.indexOf(".");
542
+ if (dot < 0) return void 0;
543
+ const payload = header.slice(0, dot);
544
+ const given = Buffer.from(header.slice(dot + 1), "base64url");
545
+ const expected = mac(payload);
546
+ if (given.length !== expected.length || !timingSafeEqual(given, expected)) return void 0;
547
+ try {
548
+ const { user, exp } = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
549
+ const now = (request && arrivedAt.get(request)) ?? Date.now();
550
+ if (typeof exp !== "number" || exp < now) return void 0;
551
+ return user === void 0 ? {} : { user };
552
+ } catch {
553
+ return;
554
+ }
555
+ }
556
+ /**
557
+ * The dashboard user a request came from, for an endpoint: the person
558
+ * `dashboard.auth.authorize` let in, when the request arrived through the
559
+ * dashboard's `/app/*` proxy. Undefined for any other request, and for one the
560
+ * dashboard let in by token. Actions read it as `ctx.dashboard?.user`.
561
+ */
562
+ function dashboardUser(request) {
563
+ return dashboardIdentity(request)?.user;
564
+ }
449
565
  // src/context.ts
450
566
  const DEFAULT_REQUEST = new Request("http://localhost");
451
567
  const EMPTY = Object.freeze({});
@@ -481,7 +597,8 @@ function baseContext(fields) {
481
597
  requestId: fields.requestId ?? newId("req"),
482
598
  services: fields.services ?? EMPTY,
483
599
  metadata: fields.metadata ?? EMPTY,
484
- deps: fields.deps ?? EMPTY
600
+ deps: fields.deps ?? EMPTY,
601
+ dashboard: fields.dashboard ?? dashboardIdentity(fields.request)
485
602
  };
486
603
  }
487
604
  function pickContextEnvelope(context) {
@@ -492,6 +609,7 @@ function pickContextEnvelope(context) {
492
609
  if (context.traceId !== void 0) envelope.traceId = context.traceId;
493
610
  if (context.requestId !== void 0) envelope.requestId = context.requestId;
494
611
  if (context.tenantId !== void 0) envelope.tenantId = context.tenantId;
612
+ if (context.dashboard !== void 0) envelope.dashboard = context.dashboard;
495
613
  return envelope;
496
614
  }
497
615
  // src/compiler/runtime.ts
@@ -508,28 +626,47 @@ function mergeInput(first, second, third) {
508
626
  if (c && !a && !b) return third;
509
627
  if (a || b || c) return Object.assign({}, first, second, third);
510
628
  }
511
- function coerceQueryValue(value, type, request, key) {
629
+ function coerceScalar(value, type) {
630
+ if (typeof value !== "string") return value;
512
631
  if (type === "number") {
513
632
  const number = Number(value);
514
633
  return Number.isNaN(number) ? value : number;
515
634
  }
516
- if (type === "array") {
517
- const values = request ? new URL(request.url).searchParams.getAll(key) : [];
518
- return values.length ? values : Array.isArray(value) ? value : [value];
635
+ if (type === "boolean") {
636
+ if (value === "true" || value === "1") return true;
637
+ if (value === "false" || value === "0") return false;
638
+ }
639
+ if (type === "json") try {
640
+ return JSON.parse(value);
641
+ } catch {
642
+ return value;
519
643
  }
520
- if (value === "true" || value === "1") return true;
521
- if (value === "false" || value === "0") return false;
522
644
  return value;
523
645
  }
646
+ function coerceQueryValue(value, { key, type, items }, request) {
647
+ if (type !== "array") return coerceScalar(value, type);
648
+ const values = request ? new URL(request.url).searchParams.getAll(key) : [];
649
+ return (values.length ? values : Array.isArray(value) ? value : [value]).map((item) => coerceScalar(item, items));
650
+ }
651
+ const BODY_TOO_LARGE = Symbol("brick.bodyTooLarge");
652
+ function bodyLimitParser(limit) {
653
+ return ({ request }) => Number(request.headers.get("content-length")) > limit ? BODY_TOO_LARGE : void 0;
654
+ }
524
655
  /** The action's input from the path, query and body, coerced by its schema. */
525
656
  function readInput(route, { params, body, query, request }) {
657
+ if (body === BODY_TOO_LARGE) throw new ActionExecutionError("PAYLOAD_TOO_LARGE", `Request body exceeds ${route.bodyLimit} bytes`, 413);
526
658
  if (!route.input) return void 0;
527
659
  let coercedQuery = query;
528
660
  let coercedParams = params;
661
+ let coercedBody = body;
529
662
  if (route.coercions.length) {
530
663
  if (query) {
531
664
  coercedQuery = { ...query };
532
- for (const { key, type } of route.coercions) if (query[key] !== void 0) coercedQuery[key] = coerceQueryValue(query[key], type, request, key);
665
+ for (const coercion of route.coercions) if (query[coercion.key] !== void 0) coercedQuery[coercion.key] = coerceQueryValue(query[coercion.key], coercion, request);
666
+ }
667
+ if (body && request?.headers.get("content-type")?.startsWith("multipart/form-data")) {
668
+ coercedBody = { ...body };
669
+ for (const coercion of route.coercions) if (body[coercion.key] !== void 0) coercedBody[coercion.key] = coerceQueryValue(body[coercion.key], coercion, void 0);
533
670
  }
534
671
  for (const { key, type } of route.coercions) {
535
672
  if (type !== "number" || typeof params?.[key] !== "string") continue;
@@ -539,7 +676,7 @@ function readInput(route, { params, body, query, request }) {
539
676
  coercedParams[key] = value;
540
677
  }
541
678
  }
542
- const input = route.readLike ? mergeInput(coercedQuery, coercedParams, body) : mergeInput(coercedParams, body, coercedQuery);
679
+ const input = route.readLike ? mergeInput(coercedQuery, coercedParams, coercedBody) : mergeInput(coercedParams, coercedBody, coercedQuery);
543
680
  return input === void 0 && route.inputSchema?.type === "object" ? {} : input;
544
681
  }
545
682
  const MAX_INPUT_DEPTH = 128;
@@ -597,6 +734,7 @@ async function authorizeCall(authorize, ctx, input, action) {
597
734
  }
598
735
  /** The stage order of every call, over HTTP and in-process: check input → authorize → execute → check output. */
599
736
  async function runStages(stages, input, ctx) {
737
+ if (stages.dashboardOnly && !ctx.dashboard) throw new ActionExecutionError("UNAUTHORIZED", `Action '${stages.name}' is only for the dashboard`, 401);
600
738
  stages.checkInput(input);
601
739
  await authorizeCall(stages.authorize, ctx, input, stages.name);
602
740
  return stages.checkOutput(await stages.execute({
@@ -628,6 +766,7 @@ function bindRoute(plan) {
628
766
  const name = route.action;
629
767
  const stages = {
630
768
  name,
769
+ dashboardOnly: plan.action.config.dashboard === true,
631
770
  checkInput: (input) => {
632
771
  if (inputChecker) validateInput(inputChecker, input, name, checkInput);
633
772
  },
@@ -639,10 +778,10 @@ function bindRoute(plan) {
639
778
  return result;
640
779
  }
641
780
  };
642
- if (contextHook || authorize) return async function brickAction(context) {
643
- const input = readInput(route, context);
781
+ if (contextHook || authorize || stages.dashboardOnly) return async function brickAction(context) {
644
782
  const ctx = requestContext(plan, context);
645
783
  try {
784
+ const input = readInput(route, context);
646
785
  if (contextHook) {
647
786
  const extra = await contextHook(ctx);
648
787
  if (extra) Object.assign(ctx, extra);
@@ -654,9 +793,9 @@ function bindRoute(plan) {
654
793
  }
655
794
  };
656
795
  return function brickAction(context) {
657
- const input = readInput(route, context);
658
796
  const ctx = requestContext(plan, context);
659
797
  try {
798
+ const input = readInput(route, context);
660
799
  stages.checkInput(input);
661
800
  const result = execute({
662
801
  input,
@@ -726,6 +865,7 @@ function defineAction(config) {
726
865
  };
727
866
  const stages = {
728
867
  name: config.name,
868
+ dashboardOnly: config.dashboard === true,
729
869
  checkInput: (input) => {
730
870
  if (!config.input) return;
731
871
  const checked = actionFn.validateInput(input);
@@ -1268,6 +1408,13 @@ function claimName(sites, label, name, site) {
1268
1408
  sites.set(name, site);
1269
1409
  }
1270
1410
  // src/compiler/ir.ts
1411
+ const FORM_FIELDS_AND_FRAMING_BYTES = 1048576;
1412
+ function coercionOf(schema) {
1413
+ if (schema?.type === "number" || schema?.type === "integer") return "number";
1414
+ if (schema?.type === "boolean") return "boolean";
1415
+ if (schema?.type === "array") return "array";
1416
+ if (schema?.type === "object") return "json";
1417
+ }
1271
1418
  function freezeIR(value) {
1272
1419
  if (value && typeof value === "object" && !Object.isFrozen(value)) {
1273
1420
  for (const child of Object.values(value)) freezeIR(child);
@@ -1356,19 +1503,22 @@ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
1356
1503
  /** What the compiler records about one action route. */
1357
1504
  function describeRoute(service, action, method, path) {
1358
1505
  const coercions = [];
1359
- for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) if (prop.type === "number" || prop.type === "integer") coercions.push({
1360
- key,
1361
- type: "number"
1362
- });
1363
- else if (prop.type === "boolean") coercions.push({
1364
- key,
1365
- type: "boolean"
1366
- });
1367
- else if (prop.type === "array") coercions.push({
1368
- key,
1369
- type: "array"
1370
- });
1506
+ for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) {
1507
+ const type = coercionOf(prop);
1508
+ if (!type) continue;
1509
+ const items = type === "array" ? coercionOf(prop.items) : void 0;
1510
+ coercions.push(items && items !== "array" ? {
1511
+ key,
1512
+ type,
1513
+ items
1514
+ } : {
1515
+ key,
1516
+ type
1517
+ });
1518
+ }
1371
1519
  const plugin = actionMeta(action).route?.plugin;
1520
+ const files = fileFields(action.config.input);
1521
+ const bodyLimit = files.length && files.every((field) => field.maxBytes !== void 0) ? files.reduce((sum, field) => sum + (field.maxBytes ?? 0), 0) + FORM_FIELDS_AND_FRAMING_BYTES : void 0;
1372
1522
  return {
1373
1523
  method,
1374
1524
  path,
@@ -1383,6 +1533,7 @@ function describeRoute(service, action, method, path) {
1383
1533
  readLike: isReadLike(method, action.name),
1384
1534
  inputSource: inputSource(method),
1385
1535
  coercions,
1536
+ ...bodyLimit === void 0 ? {} : { bodyLimit },
1386
1537
  inputSchema: schemaSnapshot(action.config.input),
1387
1538
  outputSchema: schemaSnapshot(action.config.output)
1388
1539
  };
@@ -2068,6 +2219,7 @@ function generateOpenApiSpec(options = {}) {
2068
2219
  addError("UNAUTHORIZED", 401, "Authentication required");
2069
2220
  addError("FORBIDDEN", 403, "Access denied");
2070
2221
  }
2222
+ if (action.config.dashboard === true) addError("UNAUTHORIZED", 401, "Only for the dashboard");
2071
2223
  if (action.config.errors) for (const [code, errorDef] of Object.entries(action.config.errors)) {
2072
2224
  const def = errorDef;
2073
2225
  addError(code, def.status || 400, def.message || code, def.details);
@@ -2100,14 +2252,17 @@ function generateOpenApiSpec(options = {}) {
2100
2252
  schema
2101
2253
  });
2102
2254
  }
2103
- else if (inputSchema) operation.requestBody = {
2104
- required: true,
2105
- content: { "application/json": { schema: pathParams.length && inputSchema.properties ? {
2255
+ else if (inputSchema) {
2256
+ const bodySchema = pathParams.length && inputSchema.properties ? {
2106
2257
  ...inputSchema,
2107
2258
  properties: Object.fromEntries(Object.entries(properties).filter(([key]) => !pathParams.includes(key))),
2108
2259
  required: (inputSchema.required ?? []).filter((key) => !pathParams.includes(key))
2109
- } : inputSchema } }
2110
- };
2260
+ } : inputSchema;
2261
+ operation.requestBody = {
2262
+ required: true,
2263
+ content: { [fileFields(inputSchema).length ? "multipart/form-data" : "application/json"]: { schema: bodySchema } }
2264
+ };
2265
+ }
2111
2266
  if (parameters.length) operation.parameters = parameters;
2112
2267
  if (hasAuth) operation.security = [{ bearerAuth: [] }];
2113
2268
  paths[actionPath][method] = operation;
@@ -2371,10 +2526,11 @@ function requestLoggingPlugin(opts = {}) {
2371
2526
  const markStarted = ({ request }) => {
2372
2527
  startedAt.set(request, Date.now());
2373
2528
  };
2374
- const logSuccess = ({ request, set }) => {
2529
+ const logSuccess = ({ request, set, responseValue }) => {
2375
2530
  const start = startedAt.get(request) ?? Date.now();
2376
2531
  const path = new URL(request.url).pathname;
2377
- logger(formatLog(request.method, path, set.status ?? 200, Date.now() - start));
2532
+ const status = responseValue instanceof Response ? responseValue.status : set.status ?? 200;
2533
+ logger(formatLog(request.method, path, status, Date.now() - start));
2378
2534
  };
2379
2535
  const logError = ({ request, set, error }) => {
2380
2536
  if (request) {
@@ -4060,8 +4216,8 @@ function defineServiceSocket(service, config, resolve) {
4060
4216
  if (!Number.isInteger(maxRooms) || maxRooms < 1) throw new Error("Socket maxRooms must be a positive integer");
4061
4217
  const replay = config.replay && { ...config.replay };
4062
4218
  if (replay && !(Number.isInteger(replay.keep) && replay.keep > 0 && replay.maxAgeMs > 0 && Number.isFinite(replay.maxAgeMs))) throw new Error("Socket replay needs a positive integer keep and a positive finite maxAgeMs");
4063
- for (const schema of [...Object.values(input), ...Object.values(output)]) {
4064
- serializeSocketSchema(schema);
4219
+ for (const [path, schema] of [...Object.entries(input).map(([k, v]) => [`input.${k}`, v]), ...Object.entries(output).map(([k, v]) => [`output.${k}`, v])]) {
4220
+ serializeSocketSchema(schema, path);
4065
4221
  getCompiledCheck(schema);
4066
4222
  }
4067
4223
  const typed = (socket) => socket;
@@ -4494,6 +4650,7 @@ function brick(options = {}) {
4494
4650
  if (options.secrets?.validate !== false) resolveSecrets({ source: options.secrets?.source });
4495
4651
  const services = options.services ?? getGlobalRegistry().list();
4496
4652
  const plugins = setupAppPlugins(services.flatMap((service) => installedPlugins(service)), options.plugins ?? []);
4653
+ app.onRequest(({ request }) => markDashboardArrival(request));
4497
4654
  if (options.cors) app.onRequest(corsHook(options.cors));
4498
4655
  for (const handler of plugins.middleware) app.onRequest(handler);
4499
4656
  const registeredRoutes = /* @__PURE__ */ new Map();
@@ -4563,14 +4720,15 @@ function brick(options = {}) {
4563
4720
  if (registeredRoutes.has(key) || socketRoutes.has(key)) throw new DuplicateNameError(`Brick: duplicate socket route '${socket.path}'`);
4564
4721
  socketRoutes.add(key);
4565
4722
  }
4566
- const mountRoute = (method, path, handler, plugin = false) => {
4723
+ const mountRoute = (method, path, handler, plugin = false, hook) => {
4567
4724
  const key = routeKey(method, path);
4568
4725
  if (socketRoutes.has(key)) throw new DuplicateNameError(`Brick: route '${method} ${path}' conflicts with a socket`);
4569
4726
  if (registeredRoutes.has(key)) {
4570
4727
  if (plugin || registeredRoutes.get(key)) throw new DuplicateNameError(`Brick: duplicate plugin route '${method} ${path}'`);
4571
4728
  return false;
4572
4729
  }
4573
- app.route(method, path, handler);
4730
+ if (hook) app.route(method, path, hook, handler);
4731
+ else app.route(method, path, handler);
4574
4732
  registeredRoutes.set(key, plugin);
4575
4733
  return true;
4576
4734
  };
@@ -4619,7 +4777,7 @@ function brick(options = {}) {
4619
4777
  }, () => route.handler(context)) : route.handler(context);
4620
4778
  return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
4621
4779
  };
4622
- if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke, Boolean(route.ir.plugin))) mountedRoutes.push(route.ir);
4780
+ if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke, Boolean(route.ir.plugin), route.ir.bodyLimit ? { parse: bodyLimitParser(route.ir.bodyLimit) } : void 0)) mountedRoutes.push(route.ir);
4623
4781
  }
4624
4782
  mountSockets(app, sockets, options.sockets?.broker ?? localBroker(), options.sockets?.secret);
4625
4783
  const definition = Object.freeze({
@@ -4703,6 +4861,6 @@ function cachedJsonRoute(build, revision) {
4703
4861
  return json;
4704
4862
  };
4705
4863
  }
4706
- export { segmentClaimant as $, WORKFLOW_BUNDLE as A, requireBrickApp as B, getActionAccess as C, bindCompiledApplication as D, resetGlobalRegistry as E, crudEventName as F, port as G, claimName as H, crudEventSource as I, defineServicePlugin as J, useDeps as K, eventRefs as L, defineListener as M, checkEvent as N, compileBrickApplication as O, checkPayload as P, isInstallingPlugin as Q, isCrudEvent as R, generateOpenApiSpec as S, getGlobalRegistry as T, definitionSite as U, createActionHandler as V, INTERNALS as W, hasPlugin as X, getPluginEndpoints as Y, installPlugin as Z, envSource as _, defineSchedule as a, deny as at, resetSecrets as b, runInTransaction as c, Type as ct, referencePlugin as d, traceRoute as dt, validateName as et, registerReferenceRoute as f, withCallSpan as ft, defineSecret as g, SecretRef as h, stopAllEvents as i, errorsOf as it, resolveWorkflowPaths as j, loadCompiledBrickApp as k, isOutboxTable as l, t as lt, requestLoggingPlugin as m, PLUGIN_KIND as mt, defineServiceSocket as n, buildErrorHelpers as nt, Dispatcher as o, baseContext as ot, scalarDocsHTML as p, PLUGIN_COMMIT as pt, defineResourcePlugin as q, recordingServices as r, defineAction as rt, onTransactionCommit as s, pickContextEnvelope as st, brick as t, portOf as tt, outboxTable as u, validateWithSchema as ut, listSecrets as v, setActionAccess as w, resolveSecrets as x, overrideSecret as y, isBrickApp as z };
4864
+ export { segmentClaimant as $, WORKFLOW_BUNDLE as A, requireBrickApp as B, getActionAccess as C, bindCompiledApplication as D, resetGlobalRegistry as E, crudEventName as F, port as G, claimName as H, crudEventSource as I, defineServicePlugin as J, useDeps as K, eventRefs as L, defineListener as M, checkEvent as N, compileBrickApplication as O, checkPayload as P, isInstallingPlugin as Q, isCrudEvent as R, generateOpenApiSpec as S, getGlobalRegistry as T, definitionSite as U, createActionHandler as V, INTERNALS as W, hasPlugin as X, getPluginEndpoints as Y, installPlugin as Z, envSource as _, withCallSpan as _t, defineSchedule as a, deny as at, resetSecrets as b, runInTransaction as c, DASHBOARD_IDENTITY_HEADER as ct, referencePlugin as d, dashboardUser as dt, validateName as et, registerReferenceRoute as f, signDashboardIdentity as ft, defineSecret as g, traceRoute as gt, SecretRef as h, validateWithSchema as ht, stopAllEvents as i, errorsOf as it, resolveWorkflowPaths as j, loadCompiledBrickApp as k, isOutboxTable as l, DASHBOARD_KEY_ENV as lt, requestLoggingPlugin as m, fileFields as mt, defineServiceSocket as n, buildErrorHelpers as nt, Dispatcher as o, baseContext as ot, scalarDocsHTML as p, Type$1 as pt, defineResourcePlugin as q, recordingServices as r, defineAction as rt, onTransactionCommit as s, pickContextEnvelope as st, brick as t, portOf as tt, outboxTable as u, dashboardKey as ut, listSecrets as v, PLUGIN_COMMIT as vt, setActionAccess as w, resolveSecrets as x, overrideSecret as y, PLUGIN_KIND as yt, isBrickApp as z };
4707
4865
 
4708
4866
  //# sourceMappingURL=server.js.map