@brickkit/core 0.12.0 → 0.13.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.
@@ -1,13 +1,5 @@
1
1
  import { Kind, TransformKind } from "@sinclair/typebox";
2
2
  import { Check } from "@sinclair/typebox/value";
3
- // 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
3
  // src/types.ts
12
4
  var ValidationError = class extends Error {
13
5
  code = "VALIDATION_FAILED";
@@ -50,6 +42,349 @@ var ActionExecutionError = class extends Error {
50
42
  };
51
43
  }
52
44
  };
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
+ }
53
388
  // src/socket-schema.ts
54
389
  const kinds = /* @__PURE__ */ new Set([
55
390
  "Array",
@@ -97,25 +432,6 @@ function restoreSocketSchema(value) {
97
432
  if (!schema || typeof schema !== "object" || !(Kind in schema)) throw new Error("Invalid socket contract schema");
98
433
  return schema;
99
434
  }
100
- function isSocketEnvelope(value) {
101
- return value !== null && typeof value === "object" && !Array.isArray(value) && "event" in value && typeof value.event === "string" && "data" in value && Object.keys(value).length === 2;
102
- }
103
- /** `prefix:value`, at most 200 bytes, without control characters. */
104
- function isSocketRoom(value) {
105
- return typeof value === "string" && /^[A-Za-z][\w-]*:[^\u0000-\u001f\u007f]+$/.test(value) && new TextEncoder().encode(value).byteLength <= 200;
106
- }
107
- /** A replay sequence: `<number>-<number>`, the shape of a Redis stream id, then `.` and the server's signature for its room. */
108
- function isSocketSeq(value) {
109
- return typeof value === "string" && /^\d{1,20}-\d{1,20}\.[\w-]{22}$/.test(value);
110
- }
111
- function compareSocketSeq(a, b) {
112
- const [a1, a2] = a.split(".")[0].split("-").map(BigInt);
113
- const [b1, b2] = b.split(".")[0].split("-").map(BigInt);
114
- if (a1 !== b1) return a1 > b1 ? 1 : -1;
115
- return a2 === b2 ? 0 : a2 > b2 ? 1 : -1;
116
- }
117
- const SOCKET_MAX_BYTES = 65536;
118
- const SOCKET_BUFFER_BYTES = 1048576;
119
435
  // src/socket-types.ts
120
436
  var BrickSocketError = class extends Error {
121
437
  kind;
@@ -126,21 +442,10 @@ var BrickSocketError = class extends Error {
126
442
  }
127
443
  };
128
444
  // src/socket-client.ts
129
- /** Normal close, policy and auth refusals, protocol errors: retrying would not help. */
130
- const STOP_CODES = /* @__PURE__ */ new Set([
131
- 1e3,
132
- 1003,
133
- 1007,
134
- 1008,
135
- 1009,
136
- 4e3,
137
- 4401,
138
- 4403
139
- ]);
140
445
  /** RFC 6455 subprotocols are RFC 7230 tokens. */
141
446
  const TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
142
447
  function connectSocket(baseUrl, contract, options) {
143
- const url = new URL(`${baseUrl.replace(/\/$/, "")}${contract.config.path}`);
448
+ const url = new URL(`${baseUrl}${contract.config.path}`);
144
449
  if (![
145
450
  "http:",
146
451
  "https:",
@@ -203,7 +508,6 @@ function connectSocket(baseUrl, contract, options) {
203
508
  ws.onmessage = null;
204
509
  ws.onclose = null;
205
510
  };
206
- /** Ends the client for good. */
207
511
  const finish = (info, error) => {
208
512
  if (status === "closed") return;
209
513
  detach();
@@ -229,7 +533,7 @@ function connectSocket(baseUrl, contract, options) {
229
533
  ]) listeners.clear();
230
534
  }
231
535
  };
232
- const stop = (error, code = 1e3, reason = "") => {
536
+ const stop = (error, code = SOCKET_CLOSE.normal, reason = "") => {
233
537
  if (status === "closed") return;
234
538
  try {
235
539
  if (error instanceof BrickSocketError) report(error);
@@ -250,7 +554,7 @@ function connectSocket(baseUrl, contract, options) {
250
554
  detach();
251
555
  ws = void 0;
252
556
  if (error) report(error);
253
- if (!backoff || STOP_CODES.has(info.code)) return finish(info, error);
557
+ if (!backoff || SOCKET_STOP_CODES.has(info.code)) return finish(info, error);
254
558
  settleJoins(new BrickSocketError("connection", "Socket closed before joining"));
255
559
  if (openedAt && Date.now() - openedAt >= 1e4) attempts = 0;
256
560
  openedAt = 0;
@@ -284,20 +588,20 @@ function connectSocket(baseUrl, contract, options) {
284
588
  } catch (cause) {
285
589
  attempting = false;
286
590
  return dropped({
287
- code: 1006,
591
+ code: SOCKET_CLOSE.abnormal,
288
592
  reason: ""
289
593
  }, new BrickSocketError("connection", "Socket token failed", { cause }));
290
594
  }
291
595
  if (status === "closed") return;
292
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"));
293
- protocols = ["brick.v1", `brick.token.${token}`];
597
+ protocols = [SOCKET_PROTOCOL, SOCKET_TOKEN_PROTOCOL + token];
294
598
  }
295
599
  try {
296
600
  ws = protocols ? new WebSocket(url, protocols) : new WebSocket(url);
297
601
  } catch (cause) {
298
602
  attempting = false;
299
603
  return dropped({
300
- code: 1006,
604
+ code: SOCKET_CLOSE.abnormal,
301
605
  reason: ""
302
606
  }, new BrickSocketError("connection", "Socket connection failed", { cause }));
303
607
  }
@@ -307,7 +611,7 @@ function connectSocket(baseUrl, contract, options) {
307
611
  const failed = (message) => {
308
612
  const socket = ws;
309
613
  dropped({
310
- code: 1006,
614
+ code: SOCKET_CLOSE.abnormal,
311
615
  reason: ""
312
616
  }, new BrickSocketError("connection", message));
313
617
  socket?.close();
@@ -336,15 +640,13 @@ function connectSocket(baseUrl, contract, options) {
336
640
  ws.onmessage = receive;
337
641
  if (options.timeoutMs !== void 0) timer = setTimeout(() => failed("Socket connection timed out"), options.timeoutMs);
338
642
  };
339
- const write = (event, data) => {
643
+ const assertOpen = () => {
340
644
  if (!ws || status !== "open" || ws.readyState !== 1) throw new BrickSocketError("connection", "Socket is not open");
341
- ws.send(JSON.stringify({
342
- event,
343
- data
344
- }));
645
+ return ws;
345
646
  };
647
+ const write = (event, data) => assertOpen().send(encodeFrame(event, data));
346
648
  const request = (room, since) => new Promise((resolve, reject) => {
347
- write("$join", since === void 0 ? { room } : {
649
+ write(SOCKET_CONTROL.join, since === void 0 ? { room } : {
348
650
  room,
349
651
  since
350
652
  });
@@ -360,7 +662,7 @@ function connectSocket(baseUrl, contract, options) {
360
662
  /** Checks a room acknowledgement or removal; returns the work to run once it passed. */
361
663
  const control = (event, data) => {
362
664
  const fields = data ?? {};
363
- if (event === "$error") {
665
+ if (event === SOCKET_CONTROL.error) {
364
666
  const { event: input, code, message, status, details } = fields;
365
667
  if (typeof input !== "string" || typeof code !== "string" || typeof message !== "string" || typeof status !== "number") throw new Error("Invalid control message");
366
668
  return () => {
@@ -370,7 +672,7 @@ function connectSocket(baseUrl, contract, options) {
370
672
  }
371
673
  const { room, seq } = fields;
372
674
  if (!isSocketRoom(room) || seq !== void 0 && !isSocketSeq(seq)) throw new Error("Invalid control message");
373
- if (event === "$join" && typeof fields.ok === "boolean") {
675
+ if (event === SOCKET_CONTROL.join && typeof fields.ok === "boolean") {
374
676
  const ok = fields.ok;
375
677
  return () => {
376
678
  const pending = joins.get(room);
@@ -382,51 +684,44 @@ function connectSocket(baseUrl, contract, options) {
382
684
  for (const settle of pending) settle(ok);
383
685
  };
384
686
  }
385
- if (event === "$left") {
687
+ if (event === SOCKET_CONTROL.left) {
386
688
  const reason = typeof fields.reason === "string" ? fields.reason : void 0;
387
689
  return () => {
388
690
  rooms.delete(room);
389
691
  notifyLeave(room, reason);
390
692
  };
391
693
  }
392
- if (event === "$gap" && seq !== void 0) return () => {
694
+ if (event === SOCKET_CONTROL.gap && seq !== void 0) return () => {
393
695
  seqs.set(room, seq);
394
696
  notifyGap(room);
395
697
  };
396
- if (event === "$leave") return () => {};
698
+ if (event === SOCKET_CONTROL.leave) return () => {};
397
699
  throw new Error("Unknown control message");
398
700
  };
399
701
  const receive = ({ data }) => {
400
702
  let message;
401
703
  let action;
402
- let room;
403
- let seq;
404
704
  try {
405
- if (typeof data !== "string" || new TextEncoder().encode(data).byteLength > 65536) throw new Error("Expected JSON text under 64 KiB");
406
- const parsed = JSON.parse(data);
407
- const fields = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
408
- ({room, seq} = fields);
409
- message = Object.fromEntries(Object.entries(fields).filter(([key]) => key !== "room" && key !== "seq"));
410
- if ((room !== void 0 || seq !== void 0) && !(isSocketRoom(room) && isSocketSeq(seq))) throw new Error("Invalid socket sequence");
411
- if (!isSocketEnvelope(message)) throw new Error("Invalid socket envelope");
412
- if (message.event.startsWith("$")) {
413
- 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");
414
708
  action = control(message.event, message.data);
415
709
  } else {
416
710
  const schema = schemas.get(message.event);
417
711
  if (!schema || !Check(schema, message.data)) throw new Error("Invalid socket output");
418
712
  }
419
713
  } catch (cause) {
420
- 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");
421
715
  return;
422
716
  }
423
717
  if (action) return action();
424
- if (isSocketRoom(room) && isSocketSeq(seq)) {
718
+ const { room, seq } = message;
719
+ if (room !== void 0 && seq !== void 0) {
425
720
  const last = seqs.get(room);
426
721
  if (last !== void 0 && compareSocketSeq(seq, last) <= 0) return;
427
722
  seqs.set(room, seq);
428
723
  }
429
- 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);
430
725
  };
431
726
  function abort() {
432
727
  stop(signal?.reason ?? new DOMException("Aborted", "AbortError"));
@@ -451,20 +746,17 @@ function connectSocket(baseUrl, contract, options) {
451
746
  seqs.delete(room);
452
747
  for (const settle of joins.get(room) ?? []) settle(new BrickSocketError("refused", `Left before joining: ${room}`));
453
748
  joins.delete(room);
454
- 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 });
455
750
  },
456
751
  send(event, data) {
457
- if (!ws || status !== "open" || ws.readyState !== 1) throw new BrickSocketError("connection", "Socket is not open");
458
- if (event.startsWith("$")) throw new BrickSocketError("protocol", "Reserved socket event");
459
- const frame = JSON.stringify({
460
- event,
461
- data
462
- });
463
- const bytes = new TextEncoder().encode(frame).byteLength;
464
- 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`);
465
757
  if (ws.bufferedAmount + bytes > 1048576) {
466
758
  const error = new BrickSocketError("backpressure", "Socket buffer full");
467
- stop(error, 4001, "Socket buffer full");
759
+ stop(error, SOCKET_CLOSE.clientBufferFull, "Socket buffer full");
468
760
  throw error;
469
761
  }
470
762
  ws.send(frame);
@@ -568,7 +860,7 @@ function normalizeBaseUrl(baseUrl) {
568
860
  return trimmed;
569
861
  }
570
862
  function normalizePrefix(prefix) {
571
- if (!prefix) return "/api";
863
+ if (!prefix) return DEFAULT_PREFIX;
572
864
  const withLeading = prefix.startsWith("/") ? prefix : `/${prefix}`;
573
865
  return withLeading.length > 1 ? withLeading.replace(/\/+$/, "") : withLeading;
574
866
  }
@@ -600,8 +892,10 @@ function planRequest(path, target, input, baseUrl, prefix) {
600
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)\`.`);
601
893
  const service = typeof actionTarget?.serviceName === "string" && actionTarget.serviceName ? actionTarget.serviceName : path[0];
602
894
  const action = typeof actionTarget?.name === "string" && actionTarget.name ? actionTarget.name : path.slice(1).join(".");
603
- const method = actionConfig?.method ?? "POST";
604
- 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;
605
899
  let actionPath = configuredPath ?? `${prefix}/${encodeURIComponent(kebabCase(service))}/${action.split(".").map((part) => encodeURIComponent(kebabCase(part))).join(".")}`;
606
900
  let remaining = input;
607
901
  if (configuredPath !== void 0) {
@@ -616,7 +910,7 @@ function planRequest(path, target, input, baseUrl, prefix) {
616
910
  });
617
911
  remaining = input === void 0 ? void 0 : record;
618
912
  }
619
- const queryOnly = method === "GET" || method === "DELETE";
913
+ const queryOnly = inputSource(method) === "query";
620
914
  return {
621
915
  method,
622
916
  url: `${baseUrl}${actionPath}${queryOnly ? toQueryString(remaining) : ""}`,
@@ -625,11 +919,8 @@ function planRequest(path, target, input, baseUrl, prefix) {
625
919
  };
626
920
  }
627
921
  function toActionError(status, body, url) {
628
- if (body !== null && typeof body === "object") {
629
- const record = body;
630
- 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);
631
- 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);
632
- }
922
+ const decoded = decodeError(body, status);
923
+ if (decoded) return decoded;
633
924
  if (status >= 500) return new BrickServerError(`Unexpected server error (status ${status}) for ${url}.`, {
634
925
  status,
635
926
  url,
@@ -725,6 +1016,6 @@ function createBrickClient(options) {
725
1016
  timeoutMs: options.timeoutMs
726
1017
  }, [], options.contract);
727
1018
  }
728
- 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 };
729
1020
 
730
1021
  //# sourceMappingURL=client.js.map