@geekmidas/constructs 10.0.0-alpha.145 → 10.0.0-alpha.147

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.
@@ -7,6 +7,172 @@ let _geekmidas_logger_console = require("@geekmidas/logger/console");
7
7
  let node_crypto = require("node:crypto");
8
8
  let _geekmidas_services = require("@geekmidas/services");
9
9
  let _geekmidas_errors = require("@geekmidas/errors");
10
+ let _geekmidas_schema_conversion = require("@geekmidas/schema/conversion");
11
+ //#region src/websocket/frame.ts
12
+ /**
13
+ * The shape a surface's frames take on the wire.
14
+ *
15
+ * By default a frame is `{ "action": …, "id"?: …, "data": … }` — API
16
+ * Gateway's shape. A surface that names a discriminator — `frame: {
17
+ * discriminator: 'type' }` — sends and reads flat frames instead: the action
18
+ * under that key, and the data's own fields beside it.
19
+ *
20
+ * ```json
21
+ * {"type":"chat.message.created","chatId":"c1","message":{…}}
22
+ * ```
23
+ *
24
+ * A flat frame has no `id` of its own: every field but the discriminator is
25
+ * the data, so a reply is paired by its action, not an echoed id.
26
+ */
27
+ /** A declared message whose schema does not describe an object. */
28
+ var WebSocketMessageNotAnObject = class extends Error {
29
+ surface;
30
+ action;
31
+ discriminator;
32
+ constructor(surface, action, discriminator) {
33
+ super(`${surface} sends flat frames, keyed by '${discriminator}', so each message's fields sit beside it — but '${action}' is not an object schema. Declare it as an object (z.object({ … })), or drop \`frame\` to send { action, data }.`);
34
+ this.surface = surface;
35
+ this.action = action;
36
+ this.discriminator = discriminator;
37
+ this.name = "WebSocketMessageNotAnObject";
38
+ }
39
+ };
40
+ /** A declared message whose schema has a field named the discriminator. */
41
+ var WebSocketMessageDeclaresDiscriminator = class extends Error {
42
+ surface;
43
+ action;
44
+ discriminator;
45
+ constructor(surface, action, discriminator) {
46
+ super(`${surface}'s '${action}' message declares a '${discriminator}' field, which is where its flat frames keep the action. Rename the field, or give \`frame.discriminator\` a key no message uses.`);
47
+ this.surface = surface;
48
+ this.action = action;
49
+ this.discriminator = discriminator;
50
+ this.name = "WebSocketMessageDeclaresDiscriminator";
51
+ }
52
+ };
53
+ /** Data sent in a flat frame that is not an object. */
54
+ var WebSocketDataNotAnObject = class extends Error {
55
+ surface;
56
+ action;
57
+ discriminator;
58
+ constructor(surface, action, discriminator) {
59
+ super(`${surface} sends flat frames, keyed by '${discriminator}', and '${action}''s data is not an object, so it has no fields to put beside it. Send an object. Nothing was sent.`);
60
+ this.surface = surface;
61
+ this.action = action;
62
+ this.discriminator = discriminator;
63
+ this.name = "WebSocketDataNotAnObject";
64
+ }
65
+ };
66
+ /** Data sent in a flat frame that carries the discriminator itself. */
67
+ var WebSocketDataHasDiscriminator = class extends Error {
68
+ surface;
69
+ action;
70
+ discriminator;
71
+ constructor(surface, action, discriminator) {
72
+ super(`'${action}''s data on ${surface} has a '${discriminator}' field, which is where its flat frames keep the action. Rename the field. Nothing was sent.`);
73
+ this.surface = surface;
74
+ this.action = action;
75
+ this.discriminator = discriminator;
76
+ this.name = "WebSocketDataHasDiscriminator";
77
+ }
78
+ };
79
+ /** How one surface writes and reads its frames. */
80
+ var FrameShape = class {
81
+ surface;
82
+ discriminator;
83
+ constructor(surface, discriminator) {
84
+ this.surface = surface;
85
+ this.discriminator = discriminator;
86
+ }
87
+ /** The key an inbound frame names its action under. */
88
+ get key() {
89
+ return this.discriminator ?? "action";
90
+ }
91
+ /**
92
+ * The frame for `action`'s `data`, serialised.
93
+ *
94
+ * @throws {WebSocketDataNotAnObject}, {WebSocketDataHasDiscriminator} for
95
+ * a flat frame whose data cannot sit beside the discriminator.
96
+ */
97
+ encode(action, data, id) {
98
+ const { discriminator } = this;
99
+ if (discriminator === void 0) return JSON.stringify({
100
+ action,
101
+ ...id !== void 0 ? { id } : {},
102
+ data
103
+ });
104
+ if (!isRecord(data)) throw new WebSocketDataNotAnObject(this.surface, action, discriminator);
105
+ if (Object.hasOwn(data, discriminator)) throw new WebSocketDataHasDiscriminator(this.surface, action, discriminator);
106
+ return JSON.stringify({
107
+ [discriminator]: action,
108
+ ...data
109
+ });
110
+ }
111
+ /** A parsed frame's action, id and data — `undefined` when it names none. */
112
+ decode(frame) {
113
+ if (!isRecord(frame)) return void 0;
114
+ const { discriminator } = this;
115
+ if (discriminator === void 0) {
116
+ if (typeof frame.action !== "string") return void 0;
117
+ return {
118
+ action: frame.action,
119
+ ...isId(frame.id) ? { id: frame.id } : {},
120
+ data: frame.data
121
+ };
122
+ }
123
+ const { [discriminator]: action, ...data } = frame;
124
+ if (typeof action !== "string") return void 0;
125
+ return {
126
+ action,
127
+ data
128
+ };
129
+ }
130
+ /** The id a frame that names no action carried, to echo on its error. */
131
+ idOf(frame) {
132
+ if (this.discriminator !== void 0 || !isRecord(frame)) return void 0;
133
+ return isId(frame.id) ? frame.id : void 0;
134
+ }
135
+ /**
136
+ * Refuse a declared message a flat frame cannot carry: one that is not an
137
+ * object, or that has a field named the discriminator.
138
+ *
139
+ * @throws {WebSocketMessageNotAnObject}, {WebSocketMessageDeclaresDiscriminator}
140
+ */
141
+ check(messages) {
142
+ const { discriminator } = this;
143
+ if (discriminator === void 0) return;
144
+ for (const [action, schema] of Object.entries(messages)) {
145
+ const shape = objectShape((0, _geekmidas_schema_conversion.toJsonSchema)(schema));
146
+ if (!shape) throw new WebSocketMessageNotAnObject(this.surface, action, discriminator);
147
+ if (shape.has(discriminator)) throw new WebSocketMessageDeclaresDiscriminator(this.surface, action, discriminator);
148
+ }
149
+ }
150
+ };
151
+ /**
152
+ * The fields a JSON Schema's object declares, or `undefined` when it is not
153
+ * an object. A union or intersection is one when each of its members is.
154
+ */
155
+ function objectShape(schema) {
156
+ if (!isRecord(schema)) return void 0;
157
+ const members = schema.anyOf ?? schema.oneOf ?? schema.allOf;
158
+ if (Array.isArray(members) && members.length > 0) {
159
+ const fields = /* @__PURE__ */ new Set();
160
+ for (const member of members) {
161
+ const shape = objectShape(member);
162
+ if (!shape) return void 0;
163
+ for (const field of shape) fields.add(field);
164
+ }
165
+ return fields;
166
+ }
167
+ if (schema.type !== "object") return void 0;
168
+ return new Set(isRecord(schema.properties) ? Object.keys(schema.properties) : []);
169
+ }
170
+ function isRecord(value) {
171
+ return typeof value === "object" && value !== null && !Array.isArray(value);
172
+ }
173
+ function isId(value) {
174
+ return typeof value === "string" || typeof value === "number";
175
+ }
10
176
  /** A connection string names no transport this package knows. */
11
177
  var UnsupportedWebSocketTransport = class extends Error {
12
178
  connectionString;
@@ -158,7 +324,9 @@ var InvalidWebSocketMessage = class extends Error {
158
324
  * How anything reaches a socket — `services.realtime` in an endpoint, and
159
325
  * `sockets` in a route of the surface itself.
160
326
  *
161
- * A message is `{ action, data }`, the shape a client's frames arrive in.
327
+ * A message is `{ action, data }`, the shape a client's frames arrive in —
328
+ * or, where the surface names a `frame.discriminator`, flat: `{ [key]: action,
329
+ * ...data }`.
162
330
  * Where the surface declares its messages, `action` is one of them and
163
331
  * `data` is typed and checked by its schema before anything is sent; where it
164
332
  * declares none, any action and any JSON value go. A message is serialised
@@ -170,10 +338,12 @@ var WebSocketPublisher = class {
170
338
  transport;
171
339
  local;
172
340
  declared;
173
- constructor(transport, local, declared) {
341
+ frame;
342
+ constructor(transport, local, declared, frame = new FrameShape(declared?.surface ?? "")) {
174
343
  this.transport = transport;
175
344
  this.local = local;
176
345
  this.declared = declared;
346
+ this.frame = frame;
177
347
  }
178
348
  /** Send `action`'s message to each connection. */
179
349
  async send(ids, action, data) {
@@ -206,22 +376,17 @@ var WebSocketPublisher = class {
206
376
  * The frame, checked by the action's schema where the surface declares
207
377
  * its messages.
208
378
  *
209
- * @throws {UnknownWebSocketMessage}, {InvalidWebSocketMessage}
379
+ * @throws {UnknownWebSocketMessage}, {InvalidWebSocketMessage}, and for a
380
+ * flat frame {WebSocketDataNotAnObject}, {WebSocketDataHasDiscriminator}
210
381
  */
211
382
  async payload(action, data) {
212
- if (!this.declared) return JSON.stringify({
213
- action,
214
- data
215
- });
383
+ if (!this.declared) return this.frame.encode(action, data);
216
384
  const { surface, messages } = this.declared;
217
385
  const schema = messages[action];
218
386
  if (!schema) throw new UnknownWebSocketMessage(surface, action, Object.keys(messages));
219
387
  const result = await schema["~standard"].validate(data);
220
388
  if (result.issues) throw new InvalidWebSocketMessage(surface, action, result.issues);
221
- return JSON.stringify({
222
- action,
223
- data: result.value
224
- });
389
+ return this.frame.encode(action, result.value);
225
390
  }
226
391
  /** One delivery per process that holds any of `ids`. */
227
392
  async each(ids, delivery) {
@@ -340,6 +505,8 @@ var WebSocketSurfaceServer = class WebSocketSurfaceServer {
340
505
  routes = /* @__PURE__ */ new Map();
341
506
  lifecycle = {};
342
507
  heartbeat;
508
+ frame;
509
+ trusted;
343
510
  next = 0;
344
511
  closing = false;
345
512
  constructor(wss, options) {
@@ -355,13 +522,16 @@ var WebSocketSurfaceServer = class WebSocketSurfaceServer {
355
522
  this.lifecycle[route.kind] = route;
356
523
  }
357
524
  }
525
+ this.frame = new FrameShape(options.surface, options.frame?.discriminator);
526
+ if (options.messages) this.frame.check(options.messages);
527
+ this.trusted = [...options.trustedOrigins, ...ownOrigins(options.url)];
358
528
  this.publisher = new WebSocketPublisher(options.transport, {
359
529
  instance: this.instance,
360
530
  deliver: (delivery) => this.deliver(delivery)
361
531
  }, options.messages ? {
362
532
  surface: options.surface,
363
533
  messages: options.messages
364
- } : void 0);
534
+ } : void 0, this.frame);
365
535
  this.heartbeat = setInterval(() => this.beat(), options.heartbeatMs ?? 3e4);
366
536
  this.heartbeat.unref();
367
537
  }
@@ -391,7 +561,7 @@ var WebSocketSurfaceServer = class WebSocketSurfaceServer {
391
561
  async upgrade(request, socket, head) {
392
562
  if (this.closing) return refuse(socket, 503, "Service Unavailable");
393
563
  const origin = request.headers.origin;
394
- if (origin && !(0, _geekmidas_manifest.trustsOrigin)(origin, this.options.trustedOrigins)) return refuse(socket, 403, "Forbidden");
564
+ if (origin && !(0, _geekmidas_manifest.trustsOrigin)(origin, this.trusted)) return refuse(socket, 403, "Forbidden");
395
565
  const connectionId = `${this.instance}.${(this.next++).toString(36)}`;
396
566
  const headers = headersOf(request);
397
567
  let data = {};
@@ -453,13 +623,14 @@ var WebSocketSurfaceServer = class WebSocketSurfaceServer {
453
623
  }
454
624
  /** Parse, validate and run one frame. Errors go back as frames, not closes. */
455
625
  async dispatch(held, text) {
456
- let frame;
626
+ let parsed;
457
627
  try {
458
- frame = JSON.parse(text);
628
+ parsed = JSON.parse(text);
459
629
  } catch {
460
630
  return this.error(held, void 0, "Frames are JSON.");
461
631
  }
462
- if (!frame || typeof frame.action !== "string") return this.error(held, frame?.id, "A frame names its `action`.");
632
+ const frame = this.frame.decode(parsed);
633
+ if (!frame) return this.error(held, this.frame.idOf(parsed), `A frame names its \`${this.frame.key}\`.`);
463
634
  const route = this.routes.get(frame.action) ?? this.routes.get("$default");
464
635
  if (!route) return this.error(held, frame.id, `No route answers '${frame.action}'.`);
465
636
  let body = frame.data;
@@ -475,11 +646,7 @@ var WebSocketSurfaceServer = class WebSocketSurfaceServer {
475
646
  body,
476
647
  reply: (message) => this.write(held, JSON.stringify(message))
477
648
  }));
478
- if (returned !== void 0) this.write(held, JSON.stringify({
479
- action: frame.action,
480
- ...frame.id !== void 0 ? { id: frame.id } : {},
481
- data: returned
482
- }));
649
+ if (returned !== void 0) this.write(held, this.frame.encode(frame.action, returned, frame.id));
483
650
  } catch (error) {
484
651
  if (error instanceof _geekmidas_errors.HttpError) return this.error(held, frame.id, error.message);
485
652
  this.options.logger.error({
@@ -511,14 +678,10 @@ var WebSocketSurfaceServer = class WebSocketSurfaceServer {
511
678
  });
512
679
  }
513
680
  error(held, id, message, issues) {
514
- this.write(held, JSON.stringify({
515
- action: "$error",
516
- ...id !== void 0 ? { id } : {},
517
- data: {
518
- message,
519
- ...issues ? { issues } : {}
520
- }
521
- }));
681
+ this.write(held, this.frame.encode("$error", {
682
+ message,
683
+ ...issues ? { issues } : {}
684
+ }, id));
522
685
  }
523
686
  /** Write, unless the socket has stopped reading and its queue is full. */
524
687
  write(held, payload) {
@@ -584,6 +747,16 @@ var WebSocketSurfaceServer = class WebSocketSurfaceServer {
584
747
  this.wss.close();
585
748
  }
586
749
  };
750
+ /**
751
+ * The origins a client of the surface's own address sends: the `https://`
752
+ * one a native socket derives from `wss://`, and the address's own.
753
+ */
754
+ function ownOrigins(url) {
755
+ if (!url || !URL.canParse(url)) return [];
756
+ const own = new URL(url);
757
+ const web = new URL(url.replace(/^ws(s?):/i, "http$1:"));
758
+ return [.../* @__PURE__ */ new Set([`${own.protocol}//${own.host}`, web.origin])];
759
+ }
587
760
  function headersOf(request) {
588
761
  const headers = new Headers();
589
762
  for (const [name, value] of Object.entries(request.headers)) {
@@ -617,6 +790,11 @@ var WebSocketApi = class WebSocketApi {
617
790
  envParser;
618
791
  telemetry;
619
792
  /**
793
+ * The shape its frames take — `{ action, data }`, or flat under
794
+ * `discriminator`. What a client of the surface decodes by.
795
+ */
796
+ frame;
797
+ /**
620
798
  * The surface as a dependency: `services.<id>` is its publisher, so an
621
799
  * endpoint sends to a socket the way a route beside it does.
622
800
  */
@@ -628,6 +806,9 @@ var WebSocketApi = class WebSocketApi {
628
806
  this.id = canonical;
629
807
  const replicas = config.replicas ?? 1;
630
808
  if (!Number.isInteger(replicas) || replicas < 1) throw new InvalidReplicaCount(canonical, replicas);
809
+ const frame = new FrameShape(canonical, config.frame?.discriminator);
810
+ if (config.messages) frame.check(config.messages);
811
+ this.frame = config.frame ? { discriminator: config.frame.discriminator } : {};
631
812
  this.keys = {
632
813
  url: (0, _geekmidas_manifest.provideKey)(canonical, "url"),
633
814
  trustedOrigins: (0, _geekmidas_manifest.provideKey)(canonical, "trustedOrigins"),
@@ -648,7 +829,7 @@ var WebSocketApi = class WebSocketApi {
648
829
  const { connectionString } = envParser.create((get) => ({ connectionString: get(envVar).string() })).parse();
649
830
  const transport = await transportFromConnectionString(connectionString, channel);
650
831
  require_shutdown.onShutdown(() => transport.close());
651
- return new WebSocketPublisher(transport, void 0, declared);
832
+ return new WebSocketPublisher(transport, void 0, declared, frame);
652
833
  }
653
834
  };
654
835
  }
@@ -661,7 +842,8 @@ var WebSocketApi = class WebSocketApi {
661
842
  return new WebSocketRouteBuilder("disconnect", "$disconnect", { id: this.id });
662
843
  }
663
844
  /**
664
- * The handler for frames whose `action` is `action`. `$default` answers
845
+ * The handler for frames whose `action` — or, for flat frames, whose
846
+ * discriminator — is `action`. `$default` answers
665
847
  * any action nothing else does.
666
848
  */
667
849
  route(action) {
@@ -682,9 +864,10 @@ var WebSocketApi = class WebSocketApi {
682
864
  async server(options) {
683
865
  const { Hono } = await import("hono");
684
866
  const routes = (options.modules ?? []).flatMap((module) => Object.values(module).filter(WebSocketRoute.isRoute));
685
- const { connectionString, origins } = options.envParser.create((get) => ({
867
+ const { connectionString, origins, url } = options.envParser.create((get) => ({
686
868
  connectionString: get(this.keys.publisherConnectionString).string().default(`memory://${channelOf(this.id)}`),
687
- origins: get(this.keys.trustedOrigins).string().default("").transform((value) => value.split(",").map((origin) => origin.trim()).filter(Boolean))
869
+ origins: get(this.keys.trustedOrigins).string().default("").transform((value) => value.split(",").map((origin) => origin.trim()).filter(Boolean)),
870
+ url: get(this.keys.url).string().optional()
688
871
  })).parse();
689
872
  const server = await WebSocketSurfaceServer.start({
690
873
  surface: this.id,
@@ -693,6 +876,8 @@ var WebSocketApi = class WebSocketApi {
693
876
  envParser: options.envParser,
694
877
  logger: this.logger,
695
878
  trustedOrigins: origins,
879
+ ...url ? { url } : {},
880
+ ...this.config.frame ? { frame: this.config.frame } : {},
696
881
  ...this.declared ? { messages: this.declared.messages } : {},
697
882
  ...this.authenticator ? { authenticator: this.authenticator } : {},
698
883
  ...this.config.heartbeat ? { heartbeatMs: this.config.heartbeat * 1e3 } : {},
@@ -753,6 +938,10 @@ exports.RedisTransport = RedisTransport;
753
938
  exports.UnknownWebSocketMessage = UnknownWebSocketMessage;
754
939
  exports.UnsupportedWebSocketTransport = UnsupportedWebSocketTransport;
755
940
  exports.WebSocketApi = WebSocketApi;
941
+ exports.WebSocketDataHasDiscriminator = WebSocketDataHasDiscriminator;
942
+ exports.WebSocketDataNotAnObject = WebSocketDataNotAnObject;
943
+ exports.WebSocketMessageDeclaresDiscriminator = WebSocketMessageDeclaresDiscriminator;
944
+ exports.WebSocketMessageNotAnObject = WebSocketMessageNotAnObject;
756
945
  exports.WebSocketPublisher = WebSocketPublisher;
757
946
  exports.WebSocketRoute = WebSocketRoute;
758
947
  exports.WebSocketRouteBuilder = WebSocketRouteBuilder;