@brickkit/core 0.11.0 → 0.13.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,15 +1,6 @@
1
1
  import { Kind, TransformKind } from "@sinclair/typebox";
2
2
  import { Check } from "@sinclair/typebox/value";
3
- //#region src/kebab.ts
4
- /**
5
- * The URL segment for a declared name: `orderBilling` becomes `order-billing`,
6
- * `importCSV` becomes `import-csv`. Dots and existing dashes stay.
7
- */
8
- function kebabCase(name) {
9
- return name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").toLowerCase();
10
- }
11
- //#endregion
12
- //#region src/types.ts
3
+ // src/types.ts
13
4
  var ValidationError = class extends Error {
14
5
  code = "VALIDATION_FAILED";
15
6
  status;
@@ -51,8 +42,350 @@ var ActionExecutionError = class extends Error {
51
42
  };
52
43
  }
53
44
  };
54
- //#endregion
55
- //#region src/socket-schema.ts
45
+ /**
46
+ * Two declarations claim one name or URL segment. Startup throws it; `brick lint`
47
+ * reports it as `unique-names`. Compare `name`, since a second copy of core
48
+ * throws its own class.
49
+ */
50
+ var DuplicateNameError = class extends Error {
51
+ constructor(message) {
52
+ super(message);
53
+ this.name = "DuplicateNameError";
54
+ }
55
+ };
56
+ // src/telemetry-names.ts
57
+ const SPAN = {
58
+ /** `action <service>.<action>` */
59
+ actionPrefix: "action ",
60
+ /** `rpc <service>.<action>` */
61
+ rpcPrefix: "rpc ",
62
+ exceptionEvent: "exception",
63
+ /** The span event a `ctx.logger` line becomes. */
64
+ logEvent: "log"
65
+ };
66
+ const ATTR = {
67
+ httpMethod: "http.request.method",
68
+ httpRoute: "http.route",
69
+ httpStatus: "http.response.status_code",
70
+ urlPath: "url.path",
71
+ service: "brick.service",
72
+ action: "brick.action",
73
+ traceId: "brick.trace_id",
74
+ errorCode: "brick.error.code",
75
+ errorMessage: "brick.error.message",
76
+ errorStatus: "brick.error.status",
77
+ logsDropped: "brick.logs.dropped",
78
+ dbStatement: "db.statement",
79
+ dbSystem: "db.system",
80
+ dbOperation: "db.operation",
81
+ exceptionMessage: "exception.message",
82
+ exceptionStack: "exception.stacktrace",
83
+ logLevel: "log.level",
84
+ logMessage: "log.message"
85
+ };
86
+ /**
87
+ * `Symbol.for` names shared through globalThis, because the CLI and the app may
88
+ * each hold their own copy of core.
89
+ */
90
+ const GLOBAL_SYMBOL = {
91
+ /** Set by the CLI while a dashboard collects logs. */
92
+ logsCapture: "brickkit.logs.capture",
93
+ /** Core's function that records a log line on the running span. */
94
+ logsRecord: "brickkit.logs.record",
95
+ /** The set of running event hubs, so the CLI can stop them all. */
96
+ eventsStarted: "brickkit.events.started"
97
+ };
98
+ // src/protocol.ts
99
+ /** The codes every action, listener and socket handler can raise, with their status and default message. */
100
+ const STANDARD_ERRORS = {
101
+ BAD_REQUEST: {
102
+ status: 400,
103
+ message: "Bad Request"
104
+ },
105
+ UNAUTHORIZED: {
106
+ status: 401,
107
+ message: "Unauthorized"
108
+ },
109
+ FORBIDDEN: {
110
+ status: 403,
111
+ message: "Forbidden"
112
+ },
113
+ NOT_FOUND: {
114
+ status: 404,
115
+ message: "Not Found"
116
+ },
117
+ CONFLICT: {
118
+ status: 409,
119
+ message: "Conflict"
120
+ },
121
+ INTERNAL_SERVER_ERROR: {
122
+ status: 500,
123
+ message: "Internal Server Error"
124
+ }
125
+ };
126
+ /** Rebuild the error a server sent; `undefined` when the body is not a Brick error. */
127
+ function decodeError(body, status) {
128
+ if (body === null || typeof body !== "object") return void 0;
129
+ const record = body;
130
+ if (record.name === "ValidationError") return new ValidationError(typeof record.message === "string" ? record.message : "Validation failed", Array.isArray(record.errors) ? record.errors : [], typeof record.status === "number" ? record.status : status);
131
+ if (typeof record.code !== "string") return void 0;
132
+ return new ActionExecutionError(record.code, typeof record.message === "string" ? record.message : record.code, typeof record.status === "number" ? record.status : status, record.details ?? void 0);
133
+ }
134
+ /** The subprotocol a Brick socket client offers and the server echoes. */
135
+ const SOCKET_PROTOCOL = "brick.v1";
136
+ /** `brick.token.<token>`: a bearer token carried as a subprotocol, since browsers can't set headers on a WebSocket. */
137
+ const SOCKET_TOKEN_PROTOCOL = "brick.token.";
138
+ /** Control messages, sent as frames whose event starts with `$`. */
139
+ const SOCKET_CONTROL = {
140
+ /** Client: `{room, since?}`. Server ack: `{room, ok, seq?}`. */
141
+ join: "$join",
142
+ /** Client: `{room}`. Server ack: `{room}`. */
143
+ leave: "$leave",
144
+ /** Server: `{room, reason?}`, the client was removed from a room. */
145
+ left: "$left",
146
+ /** Server: `{room, seq}`, history was lost; resume from `seq`. */
147
+ gap: "$gap",
148
+ /** Server: `{event, ...WireError}`, a handler raised a declared error. */
149
+ error: "$error"
150
+ };
151
+ /** Event names starting with `$` are reserved for control messages. */
152
+ const isControlEvent = (event) => event.startsWith("$");
153
+ const SOCKET_CLOSE = {
154
+ normal: 1e3,
155
+ unsupportedData: 1003,
156
+ abnormal: 1006,
157
+ invalidPayload: 1007,
158
+ policy: 1008,
159
+ tooLarge: 1009,
160
+ serverError: 1011,
161
+ tryAgainLater: 1013,
162
+ /** Client: the server sent an invalid message. */
163
+ invalidServerMessage: 4e3,
164
+ /** Client: its send buffer is full. */
165
+ clientBufferFull: 4001,
166
+ /** Not sent by Brick: for proxies or custom servers refusing auth after the upgrade. */
167
+ unauthorized: 4401,
168
+ forbidden: 4403
169
+ };
170
+ /** Close codes after which the client does not reconnect: retrying would not help. */
171
+ const SOCKET_STOP_CODES = /* @__PURE__ */ new Set([
172
+ SOCKET_CLOSE.normal,
173
+ SOCKET_CLOSE.unsupportedData,
174
+ SOCKET_CLOSE.invalidPayload,
175
+ SOCKET_CLOSE.policy,
176
+ SOCKET_CLOSE.tooLarge,
177
+ SOCKET_CLOSE.invalidServerMessage,
178
+ SOCKET_CLOSE.unauthorized,
179
+ SOCKET_CLOSE.forbidden
180
+ ]);
181
+ const SOCKET_MAX_BYTES = 65536;
182
+ const SOCKET_BUFFER_BYTES = 1048576;
183
+ const ROOM_MAX_BYTES = 200;
184
+ const byteLength = (value) => new TextEncoder().encode(value).byteLength;
185
+ const encodeFrame = (event, data) => JSON.stringify({
186
+ event,
187
+ data
188
+ });
189
+ /** Adds the room and signed sequence to an encoded frame of a socket with replay. */
190
+ const replayFrame = (frame, room, seq) => `${frame.slice(0, -1)},"room":${JSON.stringify(room)},"seq":${JSON.stringify(seq)}}`;
191
+ /** The longest signed sequence: two 20-digit numbers and a signature. */
192
+ const LONGEST_SEQ = `${"9".repeat(20)}-${"9".repeat(20)}.${"x".repeat(22)}`;
193
+ /** Bytes an emit to `room` gains when replay adds its `room` and signed `seq` on delivery. */
194
+ const replayHeadroom = (room) => byteLength(replayFrame("{}", room, LONGEST_SEQ)) - 2;
195
+ function isSocketEnvelope(value) {
196
+ return value !== null && typeof value === "object" && !Array.isArray(value) && "event" in value && typeof value.event === "string" && "data" in value && Object.keys(value).length === 2;
197
+ }
198
+ /** Parses a server frame: an envelope, plus `room` and `seq` on a replayed emit. Throws on anything else. */
199
+ function decodeFrame(text) {
200
+ if (typeof text !== "string" || byteLength(text) > 65536) throw new Error(`Expected JSON text under ${SOCKET_MAX_BYTES / 1024} KiB`);
201
+ const parsed = JSON.parse(text);
202
+ const { room, seq, ...message } = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
203
+ if ((room !== void 0 || seq !== void 0) && !(isSocketRoom(room) && isSocketSeq(seq))) throw new Error("Invalid socket sequence");
204
+ if (!isSocketEnvelope(message)) throw new Error("Invalid socket envelope");
205
+ return room === void 0 ? message : {
206
+ ...message,
207
+ room,
208
+ seq
209
+ };
210
+ }
211
+ /** `prefix:value`, at most 200 bytes, without control characters. */
212
+ function isSocketRoom(value) {
213
+ return typeof value === "string" && /^[A-Za-z][\w-]*:[^\u0000-\u001f\u007f]+$/.test(value) && byteLength(value) <= ROOM_MAX_BYTES;
214
+ }
215
+ /** A replay sequence: `<number>-<number>`, the shape of a Redis stream id, then `.` and the server's signature for its room. */
216
+ const SIGNED_SEQ = new RegExp(`^\\d{1,20}-\\d{1,20}\\.[\\w-]{22}$`);
217
+ const isSocketSeq = (value) => typeof value === "string" && SIGNED_SEQ.test(value);
218
+ const signSeq = (seq, signature) => `${seq}.${signature}`;
219
+ /** The sequence and signature of a signed sequence. */
220
+ const splitSeq = (signed) => signed.split(".");
221
+ /** Orders two sequences, signed or not. */
222
+ function compareSocketSeq(a, b) {
223
+ const [a1, a2] = splitSeq(a)[0].split("-").map(BigInt);
224
+ const [b1, b2] = splitSeq(b)[0].split("-").map(BigInt);
225
+ if (a1 !== b1) return a1 > b1 ? 1 : -1;
226
+ return a2 === b2 ? 0 : a2 > b2 ? 1 : -1;
227
+ }
228
+ // src/action-meta.ts
229
+ /**
230
+ * The slot that holds an action's `ActionMeta`. Process-global, so a second copy
231
+ * of core (bundler SSR, Vitest) reads what the first wrote on the same action.
232
+ */
233
+ const ACTION_META = Symbol.for("brickkit.action.meta");
234
+ /** An action's metadata, created empty on first use. */
235
+ function actionMeta(action) {
236
+ return action[ACTION_META] ??= {};
237
+ }
238
+ // src/kebab.ts
239
+ /**
240
+ * The URL segment for a declared name: `orderBilling` becomes `order-billing`,
241
+ * `importCSV` becomes `import-csv`. Dots and existing dashes stay.
242
+ */
243
+ function kebabCase(name) {
244
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").toLowerCase();
245
+ }
246
+ // src/routes.ts
247
+ /** The route prefix of actions when the app sets none. */
248
+ const DEFAULT_PREFIX = "/api";
249
+ const PATH_PARAM = /:([^/]+)/g;
250
+ /** `/p/:slug` → `/p/{slug}` for OpenAPI. */
251
+ function toOpenApiPath(path) {
252
+ return path.replace(PATH_PARAM, "{$1}");
253
+ }
254
+ /** The parameter names of a route path: `/p/:slug` → `["slug"]`. */
255
+ function pathParamNames(path) {
256
+ return [...path.matchAll(PATH_PARAM)].map((match) => match[1]);
257
+ }
258
+ /**
259
+ * The route every name of an owner mounts under: `${prefix}`,
260
+ * `${prefix}/${service}`, or `${prefix}/${service}/${resource}`, in kebab-case.
261
+ */
262
+ function ownerPath(prefix, service, resource) {
263
+ let path = prefix.replace(/\/$/, "");
264
+ if (service !== void 0) path += `/${kebabCase(service)}`;
265
+ if (resource !== void 0) path += `/${kebabCase(resource)}`;
266
+ return path;
267
+ }
268
+ /** Joins a path relative to its owner. `/` is the owner's own route. */
269
+ function joinRoute(base, path) {
270
+ return `${base}${path === "/" ? "" : path}` || "/";
271
+ }
272
+ /** Where a plugin route mounts: under the app prefix, its service, or its resource. */
273
+ function pluginRoutePath(binding, prefix) {
274
+ return joinRoute(binding.scope === "app" ? ownerPath(prefix) : ownerPath(prefix, binding.service, binding.scope === "resource" ? binding.resource : void 0), binding.path);
275
+ }
276
+ /**
277
+ * Where a plugin mounted an action over HTTP, for the OpenAPI generator, the
278
+ * compiler, and the typed client.
279
+ *
280
+ * @param action - An action.
281
+ * @param prefix - The application's route prefix (default `/api`).
282
+ * @returns `undefined` when no plugin bound the action (it uses its own route),
283
+ * `false` when the plugin's route was switched off, otherwise the route's
284
+ * `path`, `method`, the `clientPath` the typed client uses, and the owning
285
+ * `plugin` and `resource`.
286
+ */
287
+ function getPluginActionRoute(action, prefix = DEFAULT_PREFIX) {
288
+ const binding = actionMeta(action).route;
289
+ if (!binding) return void 0;
290
+ if (!binding.enabled) return false;
291
+ return {
292
+ path: pluginRoutePath(binding, prefix),
293
+ method: binding.method,
294
+ clientPath: binding.clientPath,
295
+ plugin: binding.plugin,
296
+ resource: binding.resource
297
+ };
298
+ }
299
+ /**
300
+ * Where an action is served over HTTP: its method and its path under the owner
301
+ * tree (`${prefix}/${service}/${action}`, a plugin's route, or a resource
302
+ * action's `${prefix}/${service}/${resource}[/:id]/${action}`).
303
+ *
304
+ * @param action - An action registered on a service.
305
+ * @param prefix - The application's route prefix (default `/api`).
306
+ * @returns `false` when a plugin switched the route off, otherwise the route.
307
+ */
308
+ function getActionRoute(action, prefix = DEFAULT_PREFIX) {
309
+ return actionRoute(action, action.serviceName ?? "", prefix);
310
+ }
311
+ /** `getActionRoute` for an action that may not be registered yet, under `service`. */
312
+ function actionRoute(action, service, prefix) {
313
+ const plugin = getPluginActionRoute(action, prefix);
314
+ if (plugin === false) return false;
315
+ if (plugin) return {
316
+ method: plugin.method,
317
+ path: plugin.path
318
+ };
319
+ const method = action.config.method ?? "POST";
320
+ const { resourceAction } = actionMeta(action);
321
+ if (resourceAction) {
322
+ const base = ownerPath(prefix, service, resourceAction.resource);
323
+ return {
324
+ method,
325
+ path: action.config.path !== void 0 ? joinRoute(base, action.config.path) : `${base}${resourceAction.record ? "/:id" : ""}/${kebabCase(resourceAction.name)}`
326
+ };
327
+ }
328
+ const base = ownerPath(prefix, service);
329
+ return {
330
+ method,
331
+ path: action.config.path !== void 0 ? joinRoute(base, action.config.path) : `${base}/${kebabCase(action.name)}`
332
+ };
333
+ }
334
+ /** The owning plugin and resource of an action, for OpenAPI, introspection and the client contract. */
335
+ function actionOwners(action) {
336
+ const { route, resourceAction } = actionMeta(action);
337
+ const resource = route?.resource ?? resourceAction?.resource;
338
+ return {
339
+ ...route ? { plugin: route.plugin } : {},
340
+ ...resource ? { resource } : {}
341
+ };
342
+ }
343
+ /** Read-like actions read their input from the query first. */
344
+ function isReadLike(method, name) {
345
+ return method === "GET" || name.startsWith("get") || name.endsWith(".get") || name.startsWith("list") || name.endsWith(".list") || name.startsWith("find") || name.startsWith("read");
346
+ }
347
+ /** Where a caller sends an action's input (the server merges all sources). */
348
+ function inputSource(method) {
349
+ return method === "GET" || method === "DELETE" ? "query" : "body";
350
+ }
351
+ /** Two routes collide when their keys are equal: the same method and path, whatever the parameter names. */
352
+ function routeKey(method, path) {
353
+ return `${method} ${path.replace(/:[^/]+/g, ":param")}`;
354
+ }
355
+ /**
356
+ * The URL segments after the service that its resources, sockets and actions
357
+ * claim, in that order. An explicit path, a resource action or a plugin route
358
+ * claims none. Two claims of one segment collide.
359
+ */
360
+ function claimedSegments(service) {
361
+ return [
362
+ ...service.listResources().map((resource) => ({
363
+ segment: kebabCase(resource.name),
364
+ owner: `resource "${resource.name}"`
365
+ })),
366
+ ...service.listSockets().filter((socket) => socket.schema.path === void 0).map((socket) => ({
367
+ segment: kebabCase(socket.schema.name),
368
+ owner: `socket "${socket.schema.name}"`
369
+ })),
370
+ ...service.listActions().filter((action) => {
371
+ const meta = actionMeta(action);
372
+ return action.config.path === void 0 && !meta.resourceAction && !meta.route;
373
+ }).map((action) => ({
374
+ segment: kebabCase(action.name),
375
+ owner: `action "${action.name}"`
376
+ }))
377
+ ];
378
+ }
379
+ /** @throws When two of a service's declarations claim the same URL segment. */
380
+ function checkSegments(service) {
381
+ const owners = /* @__PURE__ */ new Map();
382
+ for (const { segment, owner } of claimedSegments(service)) {
383
+ const previous = owners.get(segment);
384
+ if (previous) throw new DuplicateNameError(`Brick: duplicate name "${segment}" in service "${service.name}": ${previous} and ${owner} share the URL segment`);
385
+ owners.set(segment, owner);
386
+ }
387
+ }
388
+ // src/socket-schema.ts
56
389
  const kinds = /* @__PURE__ */ new Set([
57
390
  "Array",
58
391
  "Boolean",
@@ -99,27 +432,7 @@ function restoreSocketSchema(value) {
99
432
  if (!schema || typeof schema !== "object" || !(Kind in schema)) throw new Error("Invalid socket contract schema");
100
433
  return schema;
101
434
  }
102
- function isSocketEnvelope(value) {
103
- return value !== null && typeof value === "object" && !Array.isArray(value) && "event" in value && typeof value.event === "string" && "data" in value && Object.keys(value).length === 2;
104
- }
105
- /** `prefix:value`, at most 200 bytes, without control characters. */
106
- function isSocketRoom(value) {
107
- return typeof value === "string" && /^[A-Za-z][\w-]*:[^\u0000-\u001f\u007f]+$/.test(value) && new TextEncoder().encode(value).byteLength <= 200;
108
- }
109
- /** A replay sequence: `<number>-<number>`, the shape of a Redis stream id, then `.` and the server's signature for its room. */
110
- function isSocketSeq(value) {
111
- return typeof value === "string" && /^\d{1,20}-\d{1,20}\.[\w-]{22}$/.test(value);
112
- }
113
- function compareSocketSeq(a, b) {
114
- const [a1, a2] = a.split(".")[0].split("-").map(BigInt);
115
- const [b1, b2] = b.split(".")[0].split("-").map(BigInt);
116
- if (a1 !== b1) return a1 > b1 ? 1 : -1;
117
- return a2 === b2 ? 0 : a2 > b2 ? 1 : -1;
118
- }
119
- const SOCKET_MAX_BYTES = 65536;
120
- const SOCKET_BUFFER_BYTES = 1048576;
121
- //#endregion
122
- //#region src/socket-types.ts
435
+ // src/socket-types.ts
123
436
  var BrickSocketError = class extends Error {
124
437
  kind;
125
438
  constructor(kind, message, options) {
@@ -128,23 +441,11 @@ var BrickSocketError = class extends Error {
128
441
  this.name = "BrickSocketError";
129
442
  }
130
443
  };
131
- //#endregion
132
- //#region src/socket-client.ts
133
- /** Normal close, policy and auth refusals, protocol errors: retrying would not help. */
134
- const STOP_CODES = /* @__PURE__ */ new Set([
135
- 1e3,
136
- 1003,
137
- 1007,
138
- 1008,
139
- 1009,
140
- 4e3,
141
- 4401,
142
- 4403
143
- ]);
444
+ // src/socket-client.ts
144
445
  /** RFC 6455 subprotocols are RFC 7230 tokens. */
145
446
  const TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
146
447
  function connectSocket(baseUrl, contract, options) {
147
- const url = new URL(`${baseUrl.replace(/\/$/, "")}${contract.config.path}`);
448
+ const url = new URL(`${baseUrl}${contract.config.path}`);
148
449
  if (![
149
450
  "http:",
150
451
  "https:",
@@ -164,6 +465,7 @@ function connectSocket(baseUrl, contract, options) {
164
465
  const schemas = new Map(Object.entries(contract.output).map(([name, schema]) => [name, restoreSocketSchema(schema)]));
165
466
  const events = /* @__PURE__ */ new Map();
166
467
  const errors = /* @__PURE__ */ new Set();
468
+ const failures = /* @__PURE__ */ new Set();
167
469
  const closes = /* @__PURE__ */ new Set();
168
470
  const leaves = /* @__PURE__ */ new Set();
169
471
  const statuses = /* @__PURE__ */ new Set();
@@ -206,7 +508,6 @@ function connectSocket(baseUrl, contract, options) {
206
508
  ws.onmessage = null;
207
509
  ws.onclose = null;
208
510
  };
209
- /** Ends the client for good. */
210
511
  const finish = (info, error) => {
211
512
  if (status === "closed") return;
212
513
  detach();
@@ -223,6 +524,7 @@ function connectSocket(baseUrl, contract, options) {
223
524
  events.clear();
224
525
  for (const listeners of [
225
526
  errors,
527
+ failures,
226
528
  closes,
227
529
  leaves,
228
530
  statuses,
@@ -231,7 +533,7 @@ function connectSocket(baseUrl, contract, options) {
231
533
  ]) listeners.clear();
232
534
  }
233
535
  };
234
- const stop = (error, code = 1e3, reason = "") => {
536
+ const stop = (error, code = SOCKET_CLOSE.normal, reason = "") => {
235
537
  if (status === "closed") return;
236
538
  try {
237
539
  if (error instanceof BrickSocketError) report(error);
@@ -252,7 +554,7 @@ function connectSocket(baseUrl, contract, options) {
252
554
  detach();
253
555
  ws = void 0;
254
556
  if (error) report(error);
255
- if (!backoff || STOP_CODES.has(info.code)) return finish(info, error);
557
+ if (!backoff || SOCKET_STOP_CODES.has(info.code)) return finish(info, error);
256
558
  settleJoins(new BrickSocketError("connection", "Socket closed before joining"));
257
559
  if (openedAt && Date.now() - openedAt >= 1e4) attempts = 0;
258
560
  openedAt = 0;
@@ -286,20 +588,20 @@ function connectSocket(baseUrl, contract, options) {
286
588
  } catch (cause) {
287
589
  attempting = false;
288
590
  return dropped({
289
- code: 1006,
591
+ code: SOCKET_CLOSE.abnormal,
290
592
  reason: ""
291
593
  }, new BrickSocketError("connection", "Socket token failed", { cause }));
292
594
  }
293
595
  if (status === "closed") return;
294
596
  if (typeof token !== "string" || !TOKEN.test(token)) return stop(new BrickSocketError("protocol", "Socket token must use RFC 6455 token characters, such as a JWT or base64url without = padding"));
295
- protocols = ["brick.v1", `brick.token.${token}`];
597
+ protocols = [SOCKET_PROTOCOL, SOCKET_TOKEN_PROTOCOL + token];
296
598
  }
297
599
  try {
298
600
  ws = protocols ? new WebSocket(url, protocols) : new WebSocket(url);
299
601
  } catch (cause) {
300
602
  attempting = false;
301
603
  return dropped({
302
- code: 1006,
604
+ code: SOCKET_CLOSE.abnormal,
303
605
  reason: ""
304
606
  }, new BrickSocketError("connection", "Socket connection failed", { cause }));
305
607
  }
@@ -309,7 +611,7 @@ function connectSocket(baseUrl, contract, options) {
309
611
  const failed = (message) => {
310
612
  const socket = ws;
311
613
  dropped({
312
- code: 1006,
614
+ code: SOCKET_CLOSE.abnormal,
313
615
  reason: ""
314
616
  }, new BrickSocketError("connection", message));
315
617
  socket?.close();
@@ -338,15 +640,13 @@ function connectSocket(baseUrl, contract, options) {
338
640
  ws.onmessage = receive;
339
641
  if (options.timeoutMs !== void 0) timer = setTimeout(() => failed("Socket connection timed out"), options.timeoutMs);
340
642
  };
341
- const write = (event, data) => {
643
+ const assertOpen = () => {
342
644
  if (!ws || status !== "open" || ws.readyState !== 1) throw new BrickSocketError("connection", "Socket is not open");
343
- ws.send(JSON.stringify({
344
- event,
345
- data
346
- }));
645
+ return ws;
347
646
  };
647
+ const write = (event, data) => assertOpen().send(encodeFrame(event, data));
348
648
  const request = (room, since) => new Promise((resolve, reject) => {
349
- write("$join", since === void 0 ? { room } : {
649
+ write(SOCKET_CONTROL.join, since === void 0 ? { room } : {
350
650
  room,
351
651
  since
352
652
  });
@@ -362,9 +662,17 @@ function connectSocket(baseUrl, contract, options) {
362
662
  /** Checks a room acknowledgement or removal; returns the work to run once it passed. */
363
663
  const control = (event, data) => {
364
664
  const fields = data ?? {};
665
+ if (event === SOCKET_CONTROL.error) {
666
+ const { event: input, code, message, status, details } = fields;
667
+ if (typeof input !== "string" || typeof code !== "string" || typeof message !== "string" || typeof status !== "number") throw new Error("Invalid control message");
668
+ return () => {
669
+ const failure = Object.assign(new ActionExecutionError(code, message, status, details), { event: input });
670
+ for (const listener of failures) listener(failure);
671
+ };
672
+ }
365
673
  const { room, seq } = fields;
366
674
  if (!isSocketRoom(room) || seq !== void 0 && !isSocketSeq(seq)) throw new Error("Invalid control message");
367
- if (event === "$join" && typeof fields.ok === "boolean") {
675
+ if (event === SOCKET_CONTROL.join && typeof fields.ok === "boolean") {
368
676
  const ok = fields.ok;
369
677
  return () => {
370
678
  const pending = joins.get(room);
@@ -376,51 +684,44 @@ function connectSocket(baseUrl, contract, options) {
376
684
  for (const settle of pending) settle(ok);
377
685
  };
378
686
  }
379
- if (event === "$left") {
687
+ if (event === SOCKET_CONTROL.left) {
380
688
  const reason = typeof fields.reason === "string" ? fields.reason : void 0;
381
689
  return () => {
382
690
  rooms.delete(room);
383
691
  notifyLeave(room, reason);
384
692
  };
385
693
  }
386
- if (event === "$gap" && seq !== void 0) return () => {
694
+ if (event === SOCKET_CONTROL.gap && seq !== void 0) return () => {
387
695
  seqs.set(room, seq);
388
696
  notifyGap(room);
389
697
  };
390
- if (event === "$leave") return () => {};
698
+ if (event === SOCKET_CONTROL.leave) return () => {};
391
699
  throw new Error("Unknown control message");
392
700
  };
393
701
  const receive = ({ data }) => {
394
702
  let message;
395
703
  let action;
396
- let room;
397
- let seq;
398
704
  try {
399
- if (typeof data !== "string" || new TextEncoder().encode(data).byteLength > 65536) throw new Error("Expected JSON text under 64 KiB");
400
- const parsed = JSON.parse(data);
401
- const fields = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
402
- ({room, seq} = fields);
403
- message = Object.fromEntries(Object.entries(fields).filter(([key]) => key !== "room" && key !== "seq"));
404
- if ((room !== void 0 || seq !== void 0) && !(isSocketRoom(room) && isSocketSeq(seq))) throw new Error("Invalid socket sequence");
405
- if (!isSocketEnvelope(message)) throw new Error("Invalid socket envelope");
406
- if (message.event.startsWith("$")) {
407
- if (seq !== void 0) throw new Error("Invalid control message");
705
+ message = decodeFrame(data);
706
+ if (isControlEvent(message.event)) {
707
+ if (message.seq !== void 0) throw new Error("Invalid control message");
408
708
  action = control(message.event, message.data);
409
709
  } else {
410
710
  const schema = schemas.get(message.event);
411
711
  if (!schema || !Check(schema, message.data)) throw new Error("Invalid socket output");
412
712
  }
413
713
  } catch (cause) {
414
- stop(new BrickSocketError("protocol", "Server sent an invalid socket message", { cause }), 4e3, "Invalid server message");
714
+ stop(new BrickSocketError("protocol", "Server sent an invalid socket message", { cause }), SOCKET_CLOSE.invalidServerMessage, "Invalid server message");
415
715
  return;
416
716
  }
417
717
  if (action) return action();
418
- if (isSocketRoom(room) && isSocketSeq(seq)) {
718
+ const { room, seq } = message;
719
+ if (room !== void 0 && seq !== void 0) {
419
720
  const last = seqs.get(room);
420
721
  if (last !== void 0 && compareSocketSeq(seq, last) <= 0) return;
421
722
  seqs.set(room, seq);
422
723
  }
423
- if (isSocketEnvelope(message)) for (const listener of events.get(message.event) ?? []) listener(message.data);
724
+ for (const listener of events.get(message.event) ?? []) listener(message.data);
424
725
  };
425
726
  function abort() {
426
727
  stop(signal?.reason ?? new DOMException("Aborted", "AbortError"));
@@ -445,20 +746,17 @@ function connectSocket(baseUrl, contract, options) {
445
746
  seqs.delete(room);
446
747
  for (const settle of joins.get(room) ?? []) settle(new BrickSocketError("refused", `Left before joining: ${room}`));
447
748
  joins.delete(room);
448
- if (isSocketRoom(room) && status === "open" && ws?.readyState === 1) write("$leave", { room });
749
+ if (isSocketRoom(room) && status === "open" && ws?.readyState === 1) write(SOCKET_CONTROL.leave, { room });
449
750
  },
450
751
  send(event, data) {
451
- if (!ws || status !== "open" || ws.readyState !== 1) throw new BrickSocketError("connection", "Socket is not open");
452
- if (event.startsWith("$")) throw new BrickSocketError("protocol", "Reserved socket event");
453
- const frame = JSON.stringify({
454
- event,
455
- data
456
- });
457
- const bytes = new TextEncoder().encode(frame).byteLength;
458
- if (!isSocketEnvelope(JSON.parse(frame)) || bytes > 65536) throw new BrickSocketError("protocol", "Message must be a JSON payload under 64 KiB");
752
+ const ws = assertOpen();
753
+ if (isControlEvent(event)) throw new BrickSocketError("protocol", "Reserved socket event");
754
+ const frame = encodeFrame(event, data);
755
+ const bytes = byteLength(frame);
756
+ if (!isSocketEnvelope(JSON.parse(frame)) || bytes > 65536) throw new BrickSocketError("protocol", `Message must be a JSON payload under ${SOCKET_MAX_BYTES / 1024} KiB`);
459
757
  if (ws.bufferedAmount + bytes > 1048576) {
460
758
  const error = new BrickSocketError("backpressure", "Socket buffer full");
461
- stop(error, 4001, "Socket buffer full");
759
+ stop(error, SOCKET_CLOSE.clientBufferFull, "Socket buffer full");
462
760
  throw error;
463
761
  }
464
762
  ws.send(frame);
@@ -481,6 +779,7 @@ function connectSocket(baseUrl, contract, options) {
481
779
  onStatus: (listener) => listen(statuses, listener),
482
780
  onReconnect: (listener) => listen(reconnects, listener),
483
781
  onError: (listener) => listen(errors, listener),
782
+ onHandlerError: (listener) => listen(failures, listener),
484
783
  onClose: (listener) => listen(closes, listener)
485
784
  };
486
785
  if (signal?.aborted) {
@@ -495,8 +794,7 @@ function connectSocket(baseUrl, contract, options) {
495
794
  attempt();
496
795
  return api;
497
796
  }
498
- //#endregion
499
- //#region src/client.ts
797
+ // src/client.ts
500
798
  /**
501
799
  * The request never received a meaningful server answer: DNS / connection
502
800
  * failure, a malformed body, or a 4xx response outside the declared contract
@@ -562,7 +860,7 @@ function normalizeBaseUrl(baseUrl) {
562
860
  return trimmed;
563
861
  }
564
862
  function normalizePrefix(prefix) {
565
- if (!prefix) return "/api";
863
+ if (!prefix) return DEFAULT_PREFIX;
566
864
  const withLeading = prefix.startsWith("/") ? prefix : `/${prefix}`;
567
865
  return withLeading.length > 1 ? withLeading.replace(/\/+$/, "") : withLeading;
568
866
  }
@@ -594,8 +892,10 @@ function planRequest(path, target, input, baseUrl, prefix) {
594
892
  if (path.length < 2) throw new Error(`[Brick-TS client] Cannot address '${path.join(".")}': custom actions need a service segment, e.g. \`api.${path[0]}.<action>(input)\`.`);
595
893
  const service = typeof actionTarget?.serviceName === "string" && actionTarget.serviceName ? actionTarget.serviceName : path[0];
596
894
  const action = typeof actionTarget?.name === "string" && actionTarget.name ? actionTarget.name : path.slice(1).join(".");
597
- const method = actionConfig?.method ?? "POST";
598
- const configuredPath = actionConfig?.path;
895
+ const route = isActionValue(actionTarget) ? actionRoute(actionTarget, service, prefix) : actionConfig;
896
+ if (route === false) throw new Error(`[Brick-TS client] '${path.join(".")}' has no HTTP route: its plugin switched it off.`);
897
+ const method = route?.method ?? "POST";
898
+ const configuredPath = route?.path;
599
899
  let actionPath = configuredPath ?? `${prefix}/${encodeURIComponent(kebabCase(service))}/${action.split(".").map((part) => encodeURIComponent(kebabCase(part))).join(".")}`;
600
900
  let remaining = input;
601
901
  if (configuredPath !== void 0) {
@@ -610,7 +910,7 @@ function planRequest(path, target, input, baseUrl, prefix) {
610
910
  });
611
911
  remaining = input === void 0 ? void 0 : record;
612
912
  }
613
- const queryOnly = method === "GET" || method === "DELETE";
913
+ const queryOnly = inputSource(method) === "query";
614
914
  return {
615
915
  method,
616
916
  url: `${baseUrl}${actionPath}${queryOnly ? toQueryString(remaining) : ""}`,
@@ -619,11 +919,8 @@ function planRequest(path, target, input, baseUrl, prefix) {
619
919
  };
620
920
  }
621
921
  function toActionError(status, body, url) {
622
- if (body !== null && typeof body === "object") {
623
- const record = body;
624
- if (record.name === "ValidationError") return new ValidationError(typeof record.message === "string" ? record.message : "Validation failed", Array.isArray(record.errors) ? record.errors : [], typeof record.status === "number" ? record.status : status);
625
- if (typeof record.code === "string") return new ActionExecutionError(record.code, typeof record.message === "string" ? record.message : record.code, typeof record.status === "number" ? record.status : status, record.details ?? void 0);
626
- }
922
+ const decoded = decodeError(body, status);
923
+ if (decoded) return decoded;
627
924
  if (status >= 500) return new BrickServerError(`Unexpected server error (status ${status}) for ${url}.`, {
628
925
  status,
629
926
  url,
@@ -719,7 +1016,6 @@ function createBrickClient(options) {
719
1016
  timeoutMs: options.timeoutMs
720
1017
  }, [], options.contract);
721
1018
  }
722
- //#endregion
723
- export { isBrickTransportError as a, SOCKET_MAX_BYTES as c, isSocketRoom as d, isSocketSeq as f, kebabCase as g, ValidationError as h, isBrickServerError as i, compareSocketSeq as l, ActionExecutionError as m, BrickTransportError as n, BrickSocketError as o, serializeSocketSchema as p, createBrickClient as r, SOCKET_BUFFER_BYTES as s, BrickServerError as t, isSocketEnvelope as u };
1019
+ export { byteLength as A, splitSeq as B, SOCKET_BUFFER_BYTES as C, SOCKET_PROTOCOL as D, SOCKET_MAX_BYTES as E, isSocketRoom as F, DuplicateNameError as G, GLOBAL_SYMBOL as H, isSocketSeq as I, ValidationError as K, replayFrame as L, encodeFrame as M, isControlEvent as N, SOCKET_TOKEN_PROTOCOL as O, isSocketEnvelope as P, replayHeadroom as R, actionMeta as S, SOCKET_CONTROL as T, SPAN as U, ATTR as V, ActionExecutionError as W, pathParamNames as _, isBrickTransportError as a, toOpenApiPath as b, DEFAULT_PREFIX as c, getActionRoute as d, getPluginActionRoute as f, ownerPath as g, joinRoute as h, isBrickServerError as i, compareSocketSeq as j, STANDARD_ERRORS as k, actionOwners as l, isReadLike as m, BrickTransportError as n, BrickSocketError as o, inputSource as p, createBrickClient as r, serializeSocketSchema as s, BrickServerError as t, checkSegments as u, pluginRoutePath as v, SOCKET_CLOSE as w, kebabCase as x, routeKey as y, signSeq as z };
724
1020
 
725
1021
  //# sourceMappingURL=client.js.map