@geekmidas/constructs 10.0.0-alpha.154 → 10.0.0-alpha.155

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,1122 +1,25 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_shutdown = require("./shutdown-BMJmAhSt.cjs");
3
- const require_construct_interface = require("./construct-interface.cjs");
4
- const require_surfaceEnv = require("./surfaceEnv-CNimK76p.cjs");
5
- let _geekmidas_manifest = require("@geekmidas/manifest");
6
- let _geekmidas_logger_console = require("@geekmidas/logger/console");
7
- let node_crypto = require("node:crypto");
8
- let _geekmidas_services = require("@geekmidas/services");
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
- }
176
- //#endregion
177
- //#region src/websocket/publisher.ts
178
- /** A message sent on an action the surface does not declare. */
179
- var UnknownWebSocketMessage = class extends Error {
180
- surface;
181
- action;
182
- declared;
183
- constructor(surface, action, declared) {
184
- super(`${surface} sends no '${action}' message. It declares ${declared.map((a) => `'${a}'`).join(", ")} — send one of them, or add '${action}' to its messages.`);
185
- this.surface = surface;
186
- this.action = action;
187
- this.declared = declared;
188
- this.name = "UnknownWebSocketMessage";
189
- }
190
- };
191
- /** A message whose data its action's schema refused. */
192
- var InvalidWebSocketMessage = class extends Error {
193
- surface;
194
- action;
195
- issues;
196
- constructor(surface, action, issues) {
197
- super(`${surface}'s '${action}' message was refused by its schema: ${issues.map((issue) => issue.message).join("; ")}. Nothing was sent.`);
198
- this.surface = surface;
199
- this.action = action;
200
- this.issues = issues;
201
- this.name = "InvalidWebSocketMessage";
202
- }
203
- };
204
- /**
205
- * How anything reaches a socket — `services.realtime` in an endpoint, and
206
- * `sockets` in a route of the surface itself.
207
- *
208
- * A message is `{ action, data }`, the shape a client's frames arrive in —
209
- * or, where the surface names a `frame.discriminator`, flat: `{ [key]: action,
210
- * ...data }`.
211
- * Where the surface declares its messages, `action` is one of them and
212
- * `data` is typed and checked by its schema before anything is sent; where it
213
- * declares none, any action and any JSON value go. A message is serialised
214
- * once, whatever the number of sockets it goes to. An id whose process has
215
- * gone is dropped silently, as API Gateway's `postToConnection` to a closed
216
- * connection is a no-op the sender rarely wants to handle.
217
- */
218
- var WebSocketPublisher = class {
219
- sink;
220
- declared;
221
- frame;
222
- constructor(sink, declared, frame = new FrameShape(declared?.surface ?? "")) {
223
- this.sink = sink;
224
- this.declared = declared;
225
- this.frame = frame;
226
- }
227
- /** Send `action`'s message to each connection. */
228
- async send(ids, action, data) {
229
- const payload = await this.payload(action, data);
230
- await this.sink.send(listOf(ids), payload);
231
- }
232
- /** Send `action`'s message to every open connection, on every process. */
233
- async broadcast(action, data, options = {}) {
234
- const payload = await this.payload(action, data);
235
- await this.sink.broadcast(payload, options.except?.length ? options.except : void 0);
236
- }
237
- /** Close each connection, with a close code and reason its client sees. */
238
- async close(ids, code = 1e3, reason = "") {
239
- await this.sink.close(listOf(ids), code, reason);
240
- }
241
- /**
242
- * The frame, checked by the action's schema where the surface declares
243
- * its messages.
244
- *
245
- * @throws {UnknownWebSocketMessage}, {InvalidWebSocketMessage}, and for a
246
- * flat frame {WebSocketDataNotAnObject}, {WebSocketDataHasDiscriminator}
247
- */
248
- async payload(action, data) {
249
- if (!this.declared) return this.frame.encode(action, data);
250
- const { surface, messages } = this.declared;
251
- const schema = messages[action];
252
- if (!schema) throw new UnknownWebSocketMessage(surface, action, Object.keys(messages));
253
- const result = await schema["~standard"].validate(data);
254
- if (result.issues) throw new InvalidWebSocketMessage(surface, action, result.issues);
255
- return this.frame.encode(action, result.value);
256
- }
257
- };
258
- function listOf(ids) {
259
- return typeof ids === "string" ? [ids] : ids;
260
- }
261
- //#endregion
262
- //#region src/websocket/core.ts
263
- /** Two routes answer one action. */
264
- var DuplicateWebSocketRoute = class extends Error {
265
- surface;
266
- action;
267
- constructor(surface, action) {
268
- super(`Two routes on ${surface} answer '${action}'. Each action has one handler — rename one of them.`);
269
- this.surface = surface;
270
- this.action = action;
271
- this.name = "DuplicateWebSocketRoute";
272
- }
273
- };
274
- var WebSocketCore = class {
275
- options;
276
- surface;
277
- /** How frames are read and written — what an adaptor decodes replies by. */
278
- frame;
279
- /** `sockets` in every handler. */
280
- sockets;
281
- routes = /* @__PURE__ */ new Map();
282
- lifecycle = {};
283
- /**
284
- * @throws {DuplicateWebSocketRoute} when two routes answer one action, and
285
- * the frame checks of `FrameShape.check` for declared messages.
286
- */
287
- constructor(options) {
288
- this.options = options;
289
- this.surface = options.surface;
290
- for (const route of options.routes) {
291
- if (route.surface.id !== options.surface) continue;
292
- if (route.kind === "message") {
293
- if (this.routes.has(route.action)) throw new DuplicateWebSocketRoute(options.surface, route.action);
294
- this.routes.set(route.action, route);
295
- } else {
296
- if (this.lifecycle[route.kind]) throw new DuplicateWebSocketRoute(options.surface, route.action);
297
- this.lifecycle[route.kind] = route;
298
- }
299
- }
300
- this.frame = new FrameShape(options.surface, options.frame?.discriminator);
301
- if (options.messages) this.frame.check(options.messages);
302
- this.sockets = new WebSocketPublisher(options.sink, options.messages ? {
303
- surface: options.surface,
304
- messages: options.messages
305
- } : void 0, this.frame);
306
- }
307
- /**
308
- * Run the connect handler for a handshake: accepted with the connection's
309
- * `data` (what the handler returned, `{}` for nothing), or refused with
310
- * the status of the `HttpError` it threw — 500 for anything else. A surface
311
- * with no connect handler accepts every handshake, and verifies no session.
312
- */
313
- async connect(request, options = {}) {
314
- const { connectionId, headers, query } = request;
315
- const route = this.lifecycle.connect;
316
- if (!route) return {
317
- accepted: true,
318
- connection: {
319
- id: connectionId,
320
- data: {}
321
- }
322
- };
323
- try {
324
- const session = "session" in request ? request.session : this.options.authenticator ? await this.options.authenticator.verify(headers, this.options.envParser) : null;
325
- const returned = await this.run(route, connectionId, (base) => ({
326
- ...base,
327
- connectionId,
328
- headers,
329
- query,
330
- session
331
- }), options);
332
- return {
333
- accepted: true,
334
- connection: {
335
- id: connectionId,
336
- data: returned && typeof returned === "object" ? returned : {}
337
- }
338
- };
339
- } catch (error) {
340
- if (error instanceof _geekmidas_errors.HttpError) return {
341
- accepted: false,
342
- status: error.statusCode,
343
- statusText: error.statusMessage,
344
- error
345
- };
346
- this.options.logger.error({
347
- err: error,
348
- connectionId
349
- }, "WebSocket connect handler failed");
350
- return {
351
- accepted: false,
352
- status: 500,
353
- statusText: "Internal Server Error",
354
- error
355
- };
356
- }
357
- }
358
- /**
359
- * Parse, validate and run one inbound frame. The reply — the handler's
360
- * return, encoded — and every `$error` are written with `write`; an error
361
- * is a frame, never a close. A binary frame is refused: frames are text.
362
- */
363
- async message(connection, raw, write, options = {}) {
364
- if (typeof raw !== "string") return this.error(write, {}, "Frames are JSON text.");
365
- let parsed;
366
- try {
367
- parsed = JSON.parse(raw);
368
- } catch {
369
- return this.error(write, {}, "Frames are JSON.");
370
- }
371
- const frame = this.frame.decode(parsed);
372
- if (!frame) return this.error(write, { id: this.frame.idOf(parsed) }, `A frame names its \`${this.frame.key}\`.`);
373
- const { action, id } = frame;
374
- const route = this.routes.get(action) ?? this.routes.get("$default");
375
- if (!route) return this.error(write, {
376
- action,
377
- id
378
- }, `No route answers '${action}'.`);
379
- let body = frame.data;
380
- if (route.schema) {
381
- const result = await route.schema["~standard"].validate(frame.data);
382
- if (result.issues) return this.error(write, {
383
- action,
384
- id
385
- }, "The frame was invalid.", result.issues);
386
- body = result.value;
387
- }
388
- try {
389
- const returned = await this.run(route, connection.id, (base) => ({
390
- ...base,
391
- connection,
392
- body,
393
- reply: (message) => write(JSON.stringify(message))
394
- }), options);
395
- if (returned !== void 0) write(this.frame.encode(action, returned, id));
396
- return {
397
- ok: true,
398
- action,
399
- ...id !== void 0 ? { id } : {},
400
- returned
401
- };
402
- } catch (error) {
403
- if (error instanceof _geekmidas_errors.HttpError) return this.error(write, {
404
- action,
405
- id
406
- }, error.message, void 0, error);
407
- this.options.logger.error({
408
- err: error,
409
- connectionId: connection.id,
410
- action
411
- }, "WebSocket route failed");
412
- return this.error(write, {
413
- action,
414
- id
415
- }, "The route failed.", void 0, error);
416
- }
417
- }
418
- /**
419
- * Run the disconnect handler for a connection that has closed. What it
420
- * throws is logged and returned, never thrown: the socket is gone either
421
- * way.
422
- */
423
- async disconnect(connection, close, options = {}) {
424
- const route = this.lifecycle.disconnect;
425
- if (!route) return { ok: true };
426
- try {
427
- await this.run(route, connection.id, (base) => ({
428
- ...base,
429
- connection,
430
- ...close
431
- }), options);
432
- return { ok: true };
433
- } catch (error) {
434
- this.options.logger.error({
435
- err: error,
436
- connectionId: connection.id
437
- }, "WebSocket disconnect handler failed");
438
- return {
439
- ok: false,
440
- error
441
- };
442
- }
443
- }
444
- /** Run a handler with its services, inside a request context of its own. */
445
- async run(route, connectionId, context, options) {
446
- const logger = this.options.logger.child({
447
- connectionId,
448
- action: route.action
449
- });
450
- return (0, _geekmidas_services.runWithRequestContext)({
451
- logger,
452
- requestId: connectionId,
453
- startTime: Date.now(),
454
- operation: `ws ${route.action}`
455
- }, async () => {
456
- const services = await this.services(route, options.services);
457
- return route.handler(context({
458
- services,
459
- logger,
460
- sockets: this.sockets
461
- }));
462
- });
463
- }
464
- /** The route's services: the overrides it names, the rest registered. */
465
- async services(route, overrides = {}) {
466
- const given = {};
467
- const wanted = route.services.filter((service) => {
468
- if (!Object.hasOwn(overrides, service.serviceName)) return true;
469
- given[service.serviceName] = overrides[service.serviceName];
470
- return false;
471
- });
472
- return {
473
- ...wanted.length ? await _geekmidas_services.ServiceDiscovery.getInstance(this.options.envParser).register([...wanted]) : {},
474
- ...given
475
- };
476
- }
477
- error(write, at, message, issues, error) {
478
- write(this.frame.encode("$error", {
479
- message,
480
- ...issues ? { issues } : {}
481
- }, at.id));
482
- return {
483
- ok: false,
484
- ...at.action !== void 0 ? { action: at.action } : {},
485
- ...at.id !== void 0 ? { id: at.id } : {},
486
- message,
487
- ...issues ? { issues } : {},
488
- ...error !== void 0 ? { error } : {}
489
- };
490
- }
491
- };
492
- //#endregion
493
- //#region src/websocket/route.ts
494
- /**
495
- * A handler bound to a WebSocket surface — what `realtime.route('chat.send')
496
- * …handle()` returns, and what a file exports.
497
- *
498
- * Carries `surface` and `constructs` the way an endpoint does, so discovery
499
- * records what its process reaches without knowing what a route is.
500
- */
501
- var WebSocketRoute = class {
502
- kind;
503
- action;
504
- surface;
505
- services;
506
- constructs;
507
- handler;
508
- schema;
509
- __IS_WEBSOCKET_ROUTE__ = true;
510
- static isRoute(value) {
511
- return Boolean(value && value.__IS_WEBSOCKET_ROUTE__ === true);
512
- }
513
- constructor(kind, action, surface, services, constructs, handler, schema) {
514
- this.kind = kind;
515
- this.action = action;
516
- this.surface = surface;
517
- this.services = services;
518
- this.constructs = constructs;
519
- this.handler = handler;
520
- this.schema = schema;
521
- }
522
- };
523
- /** The builder `connect()`, `disconnect()` and `route()` start. */
524
- var WebSocketRouteBuilder = class WebSocketRouteBuilder {
525
- kind;
526
- action;
527
- surface;
528
- _services;
529
- _constructs;
530
- schema;
531
- constructor(kind, action, surface, _services = [], _constructs = [], schema) {
532
- this.kind = kind;
533
- this.action = action;
534
- this.surface = surface;
535
- this._services = _services;
536
- this._constructs = _constructs;
537
- this.schema = schema;
538
- }
539
- /** The schema a frame's `data` must satisfy before the handler runs. */
540
- body(schema) {
541
- return new WebSocketRouteBuilder(this.kind, this.action, this.surface, this._services, this._constructs, schema);
542
- }
543
- /** What the handler reaches, as `services.<id>` — per route, as an endpoint's. */
544
- dependsOn(constructs) {
545
- return new WebSocketRouteBuilder(this.kind, this.action, this.surface, [...this._services, ...require_construct_interface.servicesOf(constructs)], require_construct_interface.idsOf(constructs, this._constructs), this.schema);
546
- }
547
- /**
548
- * The handler. A message handler's return value, when there is one, is
549
- * sent back to the connection as the reply to that frame; a connect
550
- * handler's is kept as the connection's `data`.
551
- */
552
- handle(handler) {
553
- return new WebSocketRoute(this.kind, this.action, this.surface, this._services, this._constructs, handler, this.schema);
554
- }
555
- };
556
- /** The instance a connection id was issued by: everything before its dot. */
557
- function instanceOf(connectionId) {
558
- const dot = connectionId.indexOf(".");
559
- return dot > 0 ? connectionId.slice(0, dot) : void 0;
560
- }
561
- /**
562
- * A publisher's sink over a transport: a send goes to the instance each
563
- * connection id names, a broadcast to every instance. What `services.<id>`
564
- * sends through, and what the Node adaptor's own `sockets` do.
565
- */
566
- var TransportSink = class {
567
- transport;
568
- local;
569
- constructor(transport, local) {
570
- this.transport = transport;
571
- this.local = local;
572
- }
573
- send(ids, payload) {
574
- return this.each(ids, (group) => ({
575
- kind: "send",
576
- ids: group,
577
- payload
578
- }));
579
- }
580
- async broadcast(payload, except) {
581
- await this.transport.publish("*", {
582
- kind: "broadcast",
583
- payload,
584
- ...except?.length ? { except } : {}
585
- });
586
- }
587
- close(ids, code, reason) {
588
- return this.each(ids, (group) => ({
589
- kind: "close",
590
- ids: group,
591
- code,
592
- reason
593
- }));
594
- }
595
- /** One delivery per process that holds any of `ids`. */
596
- async each(ids, delivery) {
597
- const byInstance = /* @__PURE__ */ new Map();
598
- for (const id of ids) {
599
- const instance = instanceOf(id);
600
- if (!instance) continue;
601
- const group = byInstance.get(instance) ?? [];
602
- group.push(id);
603
- byInstance.set(instance, group);
604
- }
605
- await Promise.all([...byInstance].map(([instance, group]) => this.local?.instance === instance ? this.local.deliver(delivery(group)) : this.transport.publish(instance, delivery(group))));
606
- }
607
- };
608
- /** A connection string names no transport this package knows. */
609
- var UnsupportedWebSocketTransport = class extends Error {
610
- connectionString;
611
- constructor(connectionString) {
612
- super(`'${redact(connectionString)}' is not a WebSocket publisher connection string. Use redis://, rediss:// or memory:// — gkm composes it as <ID>_PUBLISHER_CONNECTION_STRING.`);
613
- this.connectionString = connectionString;
614
- this.name = "UnsupportedWebSocketTransport";
615
- }
616
- };
617
- /** The scheme alone, so an error never prints a password. */
618
- function redact(connectionString) {
619
- const scheme = connectionString.split("://")[0];
620
- return scheme && scheme !== connectionString ? `${scheme}://…` : connectionString.slice(0, 12);
621
- }
622
- const key = Symbol.for("@geekmidas/constructs/websocket/memory");
623
- const registry = globalThis;
624
- registry[key] ??= /* @__PURE__ */ new Map();
625
- const channels = registry[key];
626
- /**
627
- * In one process: the server and whoever sends meet in a map, keyed by the
628
- * channel the connection string names.
629
- */
630
- var MemoryTransport = class {
631
- channel;
632
- subscribed = /* @__PURE__ */ new Set();
633
- constructor(channel) {
634
- this.channel = channel;
635
- }
636
- async publish(instance, delivery) {
637
- const instances = channels.get(this.channel);
638
- if (!instances) return;
639
- if (instance === "*") {
640
- for (const receive of instances.values()) receive(delivery);
641
- return;
642
- }
643
- instances.get(instance)?.(delivery);
644
- }
645
- async subscribe(instance, receive) {
646
- let instances = channels.get(this.channel);
647
- if (!instances) {
648
- instances = /* @__PURE__ */ new Map();
649
- channels.set(this.channel, instances);
650
- }
651
- instances.set(instance, receive);
652
- this.subscribed.add(instance);
653
- }
654
- async close() {
655
- const instances = channels.get(this.channel);
656
- for (const instance of this.subscribed) instances?.delete(instance);
657
- this.subscribed.clear();
658
- }
659
- };
660
- /**
661
- * Over Redis pub/sub: one channel per instance and one for broadcasts, under
662
- * a prefix that keeps two surfaces — or two projects on one Redis — apart.
663
- * Channels are not scoped by database index, so the prefix is what does it.
664
- *
665
- * Publishing and subscribing take separate connections, because a connection
666
- * that has subscribed can do nothing else.
667
- */
668
- var RedisTransport = class {
669
- client;
670
- prefix;
671
- subscriber;
672
- closed;
673
- constructor(client, prefix) {
674
- this.client = client;
675
- this.prefix = prefix;
676
- }
677
- channel(instance) {
678
- return `${this.prefix}:${instance}`;
679
- }
680
- async publish(instance, delivery) {
681
- await this.client.publish(this.channel(instance), JSON.stringify(delivery));
682
- }
683
- async subscribe(instance, receive) {
684
- const subscriber = this.client.duplicate();
685
- this.subscriber = subscriber;
686
- const own = this.channel(instance);
687
- const every = this.channel("*");
688
- subscriber.on("message", (channel, message) => {
689
- if (channel !== own && channel !== every) return;
690
- receive(JSON.parse(message));
691
- });
692
- await subscriber.subscribe(own, every);
693
- }
694
- /** Idempotent: the server and a shutdown hook may both close it. */
695
- close() {
696
- this.closed ??= Promise.all([this.subscriber?.quit(), this.client.quit()]).then(() => void 0);
697
- return this.closed;
698
- }
699
- };
700
- /**
701
- * The transport a connection string names.
702
- *
703
- * `redis://` and `rediss://` take an optional `channel` query parameter, the
704
- * prefix every channel is named under; `memory://<channel>` is in-process.
705
- * Absent, the channel is `fallback` — the surface's own.
706
- */
707
- async function transportFromConnectionString(connectionString, fallback) {
708
- if (connectionString.startsWith("memory://")) return new MemoryTransport(connectionString.slice(9) || fallback);
709
- const url = URL.canParse(connectionString) ? new URL(connectionString) : void 0;
710
- if (!url) throw new UnsupportedWebSocketTransport(connectionString);
711
- if (url.protocol === "redis:" || url.protocol === "rediss:") {
712
- const channel = url.searchParams.get("channel") || fallback;
713
- url.searchParams.delete("channel");
714
- const { Redis } = await import("ioredis");
715
- return new RedisTransport(new Redis(url.toString(), {
716
- maxRetriesPerRequest: null,
717
- lazyConnect: false
718
- }), channel);
719
- }
720
- throw new UnsupportedWebSocketTransport(connectionString);
721
- }
722
- //#endregion
723
- //#region src/websocket/server.ts
724
- /**
725
- * The Node adaptor: the process that holds a WebSocket surface's sockets.
726
- *
727
- * Node's own `http` server and `ws`, nothing between them. This owns what
728
- * only a real socket has — the upgrade, the Origin check, connection ids,
729
- * the heartbeat, backpressure — and hands the rest to the surface's
730
- * `WebSocketCore`: a handshake to `connect()`, each frame to `message()`, a
731
- * close to `disconnect()`. The HTTP server is whatever the entry started —
732
- * the generated one serves `/health` on the same port — and this attaches to
733
- * its `upgrade` event.
734
- */
735
- /** Close codes a client sees. */
736
- const CLOSE = {
737
- normal: 1e3,
738
- /** The process is stopping; reconnect and land on another. */
739
- serviceRestart: 1012,
740
- /** It stopped reading, and what was queued for it passed the limit. */
741
- tooSlow: 1013
742
- };
743
- var WebSocketSurfaceServer = class WebSocketSurfaceServer {
744
- wss;
745
- options;
746
- /** This process, as connection ids name it. */
747
- instance = (0, node_crypto.randomBytes)(6).toString("hex");
748
- /** Where each handshake, frame and close is handed. */
749
- core;
750
- held = /* @__PURE__ */ new Map();
751
- heartbeat;
752
- trusted;
753
- next = 0;
754
- closing = false;
755
- constructor(wss, options) {
756
- this.wss = wss;
757
- this.options = options;
758
- this.core = options.core(new TransportSink(options.transport, {
759
- instance: this.instance,
760
- deliver: (delivery) => this.deliver(delivery)
761
- }));
762
- this.trusted = [...options.trustedOrigins, ...ownOrigins(options.url)];
763
- this.heartbeat = setInterval(() => this.beat(), options.heartbeatMs ?? 3e4);
764
- this.heartbeat.unref();
765
- }
766
- static async start(options) {
767
- const { WebSocketServer } = await import("ws");
768
- const wss = new WebSocketServer({
769
- noServer: true,
770
- maxPayload: options.maxPayload ?? 1048576,
771
- perMessageDeflate: false,
772
- clientTracking: false
773
- });
774
- const server = new WebSocketSurfaceServer(wss, options);
775
- await options.transport.subscribe(server.instance, (delivery) => server.deliver(delivery));
776
- return server;
777
- }
778
- /** `sockets` in a route: local sends skip the transport. */
779
- get publisher() {
780
- return this.core.sockets;
781
- }
782
- /** How many sockets this process holds. */
783
- get size() {
784
- return this.held.size;
785
- }
786
- /** Take over `server`'s upgrades. */
787
- attach(server) {
788
- server.on("upgrade", (request, socket, head) => {
789
- this.upgrade(request, socket, head);
790
- });
791
- }
792
- /** Upgrade one request, or refuse it with a status line. */
793
- async upgrade(request, socket, head) {
794
- if (this.closing) return refuse(socket, 503, "Service Unavailable");
795
- const origin = request.headers.origin;
796
- if (origin && !(0, _geekmidas_manifest.trustsOrigin)(origin, this.trusted)) return refuse(socket, 403, "Forbidden");
797
- const outcome = await this.core.connect({
798
- connectionId: `${this.instance}.${(this.next++).toString(36)}`,
799
- headers: headersOf(request),
800
- query: new URL(request.url ?? "/", "http://localhost").searchParams
801
- });
802
- if (!outcome.accepted) return refuse(socket, outcome.status, outcome.statusText);
803
- if (socket.destroyed) return;
804
- this.wss.handleUpgrade(request, socket, head, (ws) => this.open(ws, outcome.connection));
805
- }
806
- open(socket, connection) {
807
- const held = {
808
- socket,
809
- connection,
810
- alive: true
811
- };
812
- this.held.set(connection.id, held);
813
- const write = (payload) => this.write(held, payload);
814
- socket.on("pong", () => {
815
- held.alive = true;
816
- });
817
- socket.on("message", (raw, isBinary) => {
818
- held.alive = true;
819
- this.core.message(connection, isBinary ? bytesOf(raw) : raw.toString(), write);
820
- });
821
- socket.on("error", () => socket.terminate());
822
- socket.on("close", (code, reason) => {
823
- this.held.delete(connection.id);
824
- this.core.disconnect(connection, {
825
- code,
826
- reason: reason.toString()
827
- });
828
- });
829
- }
830
- /** Write, unless the socket has stopped reading and its queue is full. */
831
- write(held, payload) {
832
- const { socket } = held;
833
- if (socket.readyState !== socket.OPEN) return;
834
- if (socket.bufferedAmount > (this.options.maxBufferedBytes ?? 4194304)) {
835
- socket.close(CLOSE.tooSlow, "Too slow");
836
- return;
837
- }
838
- socket.send(payload);
839
- }
840
- /** What the transport, or a local publisher, asked of this process. */
841
- deliver(delivery) {
842
- switch (delivery.kind) {
843
- case "send":
844
- for (const id of delivery.ids) {
845
- const held = this.held.get(id);
846
- if (held) this.write(held, delivery.payload);
847
- }
848
- return;
849
- case "broadcast": {
850
- const except = delivery.except ? new Set(delivery.except) : void 0;
851
- for (const [id, held] of this.held) if (!except?.has(id)) this.write(held, delivery.payload);
852
- return;
853
- }
854
- case "close":
855
- for (const id of delivery.ids) this.held.get(id)?.socket.close(delivery.code, delivery.reason);
856
- return;
857
- }
858
- }
859
- /** Drop every socket that missed the last ping, and ping the rest. */
860
- beat() {
861
- for (const [id, held] of this.held) {
862
- if (!held.alive) {
863
- held.socket.terminate();
864
- this.held.delete(id);
865
- continue;
866
- }
867
- held.alive = false;
868
- held.socket.ping();
869
- }
870
- }
871
- /**
872
- * Stop: refuse new upgrades, close every socket with `code` — 1012 tells
873
- * a client to reconnect, and it lands on a process that is still up — and
874
- * leave the transport.
875
- */
876
- async close(code = CLOSE.serviceRestart, reason = "Restarting") {
877
- if (this.closing) return;
878
- this.closing = true;
879
- clearInterval(this.heartbeat);
880
- const closed = [...this.held.values()].map(({ socket }) => new Promise((resolve) => {
881
- if (socket.readyState === socket.CLOSED) return resolve();
882
- socket.once("close", () => resolve());
883
- socket.close(code, reason);
884
- setTimeout(() => {
885
- socket.terminate();
886
- resolve();
887
- }, 2e3).unref();
888
- }));
889
- await Promise.all(closed);
890
- await this.options.transport.close();
891
- this.wss.close();
892
- }
893
- };
894
- /**
895
- * The origins a client of the surface's own address sends: the `https://`
896
- * one a native socket derives from `wss://`, and the address's own.
897
- */
898
- function ownOrigins(url) {
899
- if (!url || !URL.canParse(url)) return [];
900
- const own = new URL(url);
901
- const web = new URL(url.replace(/^ws(s?):/i, "http$1:"));
902
- return [.../* @__PURE__ */ new Set([`${own.protocol}//${own.host}`, web.origin])];
903
- }
904
- /** A binary frame's bytes, however `ws` delivered them. */
905
- function bytesOf(raw) {
906
- if (Array.isArray(raw)) return Buffer.concat(raw);
907
- return raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw;
908
- }
909
- function headersOf(request) {
910
- const headers = new Headers();
911
- for (const [name, value] of Object.entries(request.headers)) {
912
- if (value === void 0) continue;
913
- for (const one of Array.isArray(value) ? value : [value]) headers.append(name, one);
914
- }
915
- return headers;
916
- }
917
- function refuse(socket, status, message) {
918
- if (!socket.destroyed) socket.end(`HTTP/1.1 ${status} ${message}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
919
- }
920
- //#endregion
921
- //#region src/websocket-api.ts
922
- /** A replica count that is not a whole number of at least one. */
923
- var InvalidReplicaCount = class extends Error {
924
- id;
925
- replicas;
926
- constructor(id, replicas) {
927
- super(`${id} asks for ${replicas} replicas. A surface runs on at least one process — give a whole number of 1 or more.`);
928
- this.id = id;
929
- this.replicas = replicas;
930
- this.name = "InvalidReplicaCount";
931
- }
932
- };
933
- var WebSocketApi = class WebSocketApi {
934
- config;
935
- authenticator;
936
- id;
937
- keys;
938
- logger;
939
- envParser;
940
- telemetry;
941
- /**
942
- * The shape its frames take — `{ action, data }`, or flat under
943
- * `discriminator`. What a client of the surface decodes by.
944
- */
945
- frame;
946
- /**
947
- * The surface as a dependency: `services.<id>` is its publisher, so an
948
- * endpoint sends to a socket the way a route beside it does.
949
- */
950
- service;
951
- constructor(id, config, authenticator) {
952
- this.config = config;
953
- this.authenticator = authenticator;
954
- const canonical = (0, _geekmidas_manifest.canonicalId)(id);
955
- this.id = canonical;
956
- const replicas = config.replicas ?? 1;
957
- if (!Number.isInteger(replicas) || replicas < 1) throw new InvalidReplicaCount(canonical, replicas);
958
- const frame = new FrameShape(canonical, config.frame?.discriminator);
959
- if (config.messages) frame.check(config.messages);
960
- this.frame = config.frame ? { discriminator: config.frame.discriminator } : {};
961
- this.keys = {
962
- url: (0, _geekmidas_manifest.provideKey)(canonical, "url"),
963
- trustedOrigins: (0, _geekmidas_manifest.provideKey)(canonical, "trustedOrigins"),
964
- publisherConnectionString: (0, _geekmidas_manifest.provideKey)(canonical, "publisherConnectionString")
965
- };
966
- this.logger = config.logger ?? _geekmidas_logger_console.DEFAULT_LOGGER;
967
- this.telemetry = config.telemetry;
968
- this.envParser = require_surfaceEnv.envParserFor(config.envParser ? {
969
- id: canonical,
970
- envParser: config.envParser
971
- } : void 0);
972
- const envVar = this.keys.publisherConnectionString;
973
- const channel = channelOf(canonical);
974
- const declared = this.declared;
975
- this.service = {
976
- serviceName: (0, _geekmidas_manifest.serviceKey)(canonical),
977
- async register({ envParser }) {
978
- const { connectionString } = envParser.create((get) => ({ connectionString: get(envVar).string() })).parse();
979
- const transport = await transportFromConnectionString(connectionString, channel);
980
- require_shutdown.onShutdown(() => transport.close());
981
- return new WebSocketPublisher(new TransportSink(transport), declared, frame);
982
- }
983
- };
984
- }
985
- /** The handler a connection's upgrade runs: refuse it, or say who it is. */
986
- connect() {
987
- return new WebSocketRouteBuilder("connect", "$connect", { id: this.id });
988
- }
989
- /** The handler a closed connection runs. */
990
- disconnect() {
991
- return new WebSocketRouteBuilder("disconnect", "$disconnect", { id: this.id });
992
- }
993
- /**
994
- * The handler for frames whose `action` — or, for flat frames, whose
995
- * discriminator — is `action`. `$default` answers
996
- * any action nothing else does.
997
- */
998
- route(action) {
999
- return new WebSocketRouteBuilder("message", action, { id: this.id });
1000
- }
1001
- /** What authenticates a connection — its session reaches `connect()`. */
1002
- auth(construct) {
1003
- return new WebSocketApi(this.id, this.config, construct);
1004
- }
1005
- /**
1006
- * Serve it: the routes exported by `modules` that were built from this
1007
- * surface, on whatever HTTP server `attach` is handed.
1008
- *
1009
- * `app` answers plain HTTP — the generated entry puts `/health` in front
1010
- * of it — and `attach` takes over the server's upgrades. The sockets are
1011
- * closed with 1012 when the server shuts down.
1012
- */
1013
- async server(options) {
1014
- const { Hono } = await import("hono");
1015
- const { connectionString, origins, url } = options.envParser.create((get) => ({
1016
- connectionString: get(this.keys.publisherConnectionString).string().default(`memory://${channelOf(this.id)}`),
1017
- origins: get(this.keys.trustedOrigins).string().default("").transform((value) => value.split(",").map((origin) => origin.trim()).filter(Boolean)),
1018
- url: get(this.keys.url).string().optional()
1019
- })).parse();
1020
- const server = await WebSocketSurfaceServer.start({
1021
- core: (sink) => this.core({
1022
- envParser: options.envParser,
1023
- sink,
1024
- ...options.modules ? { modules: options.modules } : {}
1025
- }),
1026
- transport: await transportFromConnectionString(connectionString, channelOf(this.id)),
1027
- trustedOrigins: origins,
1028
- ...url ? { url } : {},
1029
- ...this.config.heartbeat ? { heartbeatMs: this.config.heartbeat * 1e3 } : {},
1030
- ...this.config.maxPayload ? { maxPayload: this.config.maxPayload } : {}
1031
- });
1032
- require_shutdown.onShutdown(() => server.close());
1033
- const app = new Hono();
1034
- app.get("/health", (c) => c.json({
1035
- status: "ok",
1036
- connections: server.size
1037
- }));
1038
- app.get("/", (c) => c.json({
1039
- surface: this.id,
1040
- connections: server.size
1041
- }, 426, { Upgrade: "websocket" }));
1042
- return {
1043
- app,
1044
- attach: (http) => server.attach(http),
1045
- release: () => server.close(),
1046
- server
1047
- };
1048
- }
1049
- /**
1050
- * The surface with no socket in it — what every runtime serves. The
1051
- * routes exported by `modules` that were built from this surface answer
1052
- * its frames; `sink` is where its handlers' `sockets` send.
1053
- *
1054
- * `server()` is the Node adaptor over it. Another runtime (a Lambda
1055
- * behind API Gateway, a test) builds one with a sink of its own and
1056
- * calls `connect()`, `message()` and `disconnect()` per connection id.
1057
- *
1058
- * @throws {DuplicateWebSocketRoute} when two routes answer one action.
1059
- */
1060
- core(options) {
1061
- return new WebSocketCore({
1062
- surface: this.id,
1063
- routes: (options.modules ?? []).flatMap((module) => Object.values(module).filter(WebSocketRoute.isRoute)),
1064
- sink: options.sink,
1065
- envParser: options.envParser,
1066
- logger: this.logger,
1067
- ...this.config.frame ? { frame: this.config.frame } : {},
1068
- ...this.declared ? { messages: this.declared.messages } : {},
1069
- ...this.authenticator ? { authenticator: this.authenticator } : {}
1070
- });
1071
- }
1072
- /** The declared messages, with the surface they are checked for. */
1073
- get declared() {
1074
- return this.config.messages ? {
1075
- surface: this.id,
1076
- messages: this.config.messages
1077
- } : void 0;
1078
- }
1079
- declare() {
1080
- return [{
1081
- kind: "websocket-api",
1082
- id: this.id,
1083
- path: this.config.path,
1084
- ...this.config.subdomain ? { subdomain: this.config.subdomain } : {},
1085
- ...this.authenticator ? { auth: require_construct_interface.edgeTo(this.authenticator) } : {},
1086
- ...this.config.telemetry ? { telemetry: this.config.telemetry.id } : {},
1087
- ...this.config.replicas && this.config.replicas > 1 ? { replicas: this.config.replicas } : {},
1088
- provides: [
1089
- this.keys.url,
1090
- this.keys.trustedOrigins,
1091
- this.keys.publisherConnectionString
1092
- ]
1093
- }];
1094
- }
1095
- };
1096
- /** The prefix a surface's channels are named under. */
1097
- function channelOf(id) {
1098
- return `gkm:ws:${id}`;
1099
- }
1100
- //#endregion
1101
- exports.CLOSE = CLOSE;
1102
- exports.DuplicateWebSocketRoute = DuplicateWebSocketRoute;
1103
- exports.InvalidReplicaCount = InvalidReplicaCount;
1104
- exports.InvalidWebSocketMessage = InvalidWebSocketMessage;
1105
- exports.MemoryTransport = MemoryTransport;
1106
- exports.RedisTransport = RedisTransport;
1107
- exports.TransportSink = TransportSink;
1108
- exports.UnknownWebSocketMessage = UnknownWebSocketMessage;
1109
- exports.UnsupportedWebSocketTransport = UnsupportedWebSocketTransport;
1110
- exports.WebSocketApi = WebSocketApi;
1111
- exports.WebSocketCore = WebSocketCore;
1112
- exports.WebSocketDataHasDiscriminator = WebSocketDataHasDiscriminator;
1113
- exports.WebSocketDataNotAnObject = WebSocketDataNotAnObject;
1114
- exports.WebSocketMessageDeclaresDiscriminator = WebSocketMessageDeclaresDiscriminator;
1115
- exports.WebSocketMessageNotAnObject = WebSocketMessageNotAnObject;
1116
- exports.WebSocketPublisher = WebSocketPublisher;
1117
- exports.WebSocketRoute = WebSocketRoute;
1118
- exports.WebSocketRouteBuilder = WebSocketRouteBuilder;
1119
- exports.WebSocketSurfaceServer = WebSocketSurfaceServer;
1120
- exports.transportFromConnectionString = transportFromConnectionString;
1121
-
1122
- //# sourceMappingURL=websocket-api.cjs.map
2
+ const require_websocket_api = require("./websocket-api-9bXfgrqd.cjs");
3
+ exports.CLOSE = require_websocket_api.CLOSE;
4
+ exports.DuplicateWebSocketRoute = require_websocket_api.DuplicateWebSocketRoute;
5
+ exports.InvalidReplicaCount = require_websocket_api.InvalidReplicaCount;
6
+ exports.InvalidWebSocketMessage = require_websocket_api.InvalidWebSocketMessage;
7
+ exports.InvalidWebSocketRequest = require_websocket_api.InvalidWebSocketRequest;
8
+ exports.MemoryTransport = require_websocket_api.MemoryTransport;
9
+ exports.RecordingSink = require_websocket_api.RecordingSink;
10
+ exports.RedisTransport = require_websocket_api.RedisTransport;
11
+ exports.TestWebSocketPublisher = require_websocket_api.TestWebSocketPublisher;
12
+ exports.TransportSink = require_websocket_api.TransportSink;
13
+ exports.UnknownWebSocketMessage = require_websocket_api.UnknownWebSocketMessage;
14
+ exports.UnsupportedWebSocketTransport = require_websocket_api.UnsupportedWebSocketTransport;
15
+ exports.WebSocketApi = require_websocket_api.WebSocketApi;
16
+ exports.WebSocketCore = require_websocket_api.WebSocketCore;
17
+ exports.WebSocketDataHasDiscriminator = require_websocket_api.WebSocketDataHasDiscriminator;
18
+ exports.WebSocketDataNotAnObject = require_websocket_api.WebSocketDataNotAnObject;
19
+ exports.WebSocketMessageDeclaresDiscriminator = require_websocket_api.WebSocketMessageDeclaresDiscriminator;
20
+ exports.WebSocketMessageNotAnObject = require_websocket_api.WebSocketMessageNotAnObject;
21
+ exports.WebSocketPublisher = require_websocket_api.WebSocketPublisher;
22
+ exports.WebSocketRoute = require_websocket_api.WebSocketRoute;
23
+ exports.WebSocketRouteBuilder = require_websocket_api.WebSocketRouteBuilder;
24
+ exports.WebSocketSurfaceServer = require_websocket_api.WebSocketSurfaceServer;
25
+ exports.transportFromConnectionString = require_websocket_api.transportFromConnectionString;