@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.
@@ -4,6 +4,7 @@ const require_construct_interface = require("../construct-interface.cjs");
4
4
  const require_auth = require("../auth.cjs");
5
5
  const require_functions = require("../functions-DLF6-IK8.cjs");
6
6
  const require_Endpoint = require("../Endpoint-52z1P0Ue.cjs");
7
+ const require_websocket_api = require("../websocket-api-9bXfgrqd.cjs");
7
8
  const require_Queue = require("../Queue-D4Iaidrs.cjs");
8
9
  const require_email = require("../email.cjs");
9
10
  const require_Topic = require("../Topic-Dp9Q7Lj2.cjs");
@@ -710,6 +711,7 @@ function featureTest(options = {}) {
710
711
  auth: /* @__PURE__ */ new Map(),
711
712
  addresses: /* @__PURE__ */ new Set(),
712
713
  published: /* @__PURE__ */ new Map(),
714
+ sockets: /* @__PURE__ */ new Map(),
713
715
  pending: [],
714
716
  delivering: false
715
717
  };
@@ -720,6 +722,7 @@ function featureTest(options = {}) {
720
722
  };
721
723
  contexts.set(id, state);
722
724
  await state.discovery.register(recorders(app.channels, state));
725
+ await state.discovery.register(socketRecorders(app.surfaces, state));
723
726
  await state.discovery.register(watchers(app, state));
724
727
  try {
725
728
  await (0, _geekmidas_testkit_context.runInTestContext)(id, async () => {
@@ -763,6 +766,11 @@ function featureTest(options = {}) {
763
766
  await deliver(app, state, id);
764
767
  } }),
765
768
  published: (channel) => [...state.published.get(channel.id) ?? []],
769
+ sockets: (surface) => {
770
+ const recorder = state.sockets.get(surface.id);
771
+ if (!recorder) throw new UnknownWebSocketApi(surface.id, [...state.sockets.keys()]);
772
+ return recorder;
773
+ },
766
774
  services: { get: (name) => resolveService(app, state, name) },
767
775
  subscriber: (subscriber) => thenDeliver(new TestSubscriberAdaptor(subscriber, state.discovery), () => deliver(app, state, id)),
768
776
  queue: (queue) => thenDeliver(new TestQueueAdaptor(queue, state.discovery), () => deliver(app, state, id)),
@@ -829,6 +837,7 @@ async function load(manifest, modules) {
829
837
  const channels = unique(constructs.filter((value) => value instanceof require_Topic.Topic || value instanceof require_Queue.Queue));
830
838
  const watched = unique(constructs.filter((value) => isBucket(value) && subscribers.some(({ subscriber }) => subscriber.bucketName === value.id)));
831
839
  const inboxes = unique(constructs.filter(isInboxConstruct));
840
+ const surfaces = unique(constructs.filter((value) => value instanceof require_websocket_api.WebSocketApi));
832
841
  const inbox = emails.map((email) => manifest.env[(0, _geekmidas_manifest.provideKey)(email.id, "inboxUrl")]).find(Boolean);
833
842
  return {
834
843
  envParser,
@@ -839,6 +848,7 @@ async function load(manifest, modules) {
839
848
  channels,
840
849
  watched,
841
850
  inboxes,
851
+ surfaces,
842
852
  env: manifest.env,
843
853
  consumables,
844
854
  subscribers,
@@ -870,6 +880,20 @@ function recorders(channels, state) {
870
880
  });
871
881
  }
872
882
  /**
883
+ * A WebSocket surface's publisher that records rather than sends, under the
884
+ * name `.dependsOn([realtime])` injects it by — one per surface per test.
885
+ */
886
+ function socketRecorders(surfaces, state) {
887
+ return surfaces.map((surface) => {
888
+ const recorder = surface.testPublisher();
889
+ state.sockets.set(surface.id, recorder);
890
+ return {
891
+ serviceName: surface.service.serviceName,
892
+ register: () => recorder
893
+ };
894
+ });
895
+ }
896
+ /**
873
897
  * The databases a test is handed: the app's own. A schema tenant an auth server
874
898
  * owns is reached through that server, as the app reaches it, and a reader is
875
899
  * the same database through a read-only role — neither is another database to
@@ -1032,6 +1056,17 @@ function isBucket(value) {
1032
1056
  return typeof declare === "function" && declare.call(value)[0]?.kind === "objects";
1033
1057
  }
1034
1058
  /** `objects(bucket)` named a bucket no subscriber in the app is bound to. */
1059
+ /** `sockets(surface)` for a surface the test manifest does not declare. */
1060
+ var UnknownWebSocketApi = class extends Error {
1061
+ surface;
1062
+ declared;
1063
+ constructor(surface, declared) {
1064
+ super(`The test manifest declares no WebSocketApi '${surface}'` + (declared.length ? ` — it declares ${declared.map((id) => `'${id}'`).join(", ")}.` : ", and no WebSocketApi at all.") + " Export the surface from the app so `gkm test` records it.");
1065
+ this.surface = surface;
1066
+ this.declared = declared;
1067
+ this.name = "UnknownWebSocketApi";
1068
+ }
1069
+ };
1035
1070
  var BucketNotWatched = class extends Error {
1036
1071
  bucket;
1037
1072
  constructor(bucket) {
@@ -1308,28 +1343,199 @@ var UnknownService = class extends Error {
1308
1343
  }
1309
1344
  };
1310
1345
  //#endregion
1346
+ //#region src/websocket/msw.ts
1347
+ /**
1348
+ * The MSW adaptor: a surface's real routes behind MSW's `ws.link()`, so code
1349
+ * that holds a `WebSocket` — a client, its reconnects, its decoding — runs
1350
+ * unchanged against them, in one process, with no server.
1351
+ *
1352
+ * MSW intercepts the client's `WebSocket` and hands each connection here.
1353
+ * The adaptor gives it an id, runs `connect()`, then each frame the client
1354
+ * sends through `message()`, and `disconnect()` when either side closes.
1355
+ * What reaches a socket from elsewhere — an endpoint's `services.<surface>` —
1356
+ * goes over an in-process `memory://` channel, as it does between a route
1357
+ * and the Node adaptor in one dev process, and is written to MSW's `client`.
1358
+ *
1359
+ * ```ts
1360
+ * const realtime = createMswWebSocketHandlers(surface, [routes], {
1361
+ * url: 'wss://realtime.test',
1362
+ * });
1363
+ * server.use(...realtime.handlers);
1364
+ *
1365
+ * realtime.registerContext(id, { session, services: { database: trx } });
1366
+ * const socket = new WebSocket(`wss://realtime.test/?${TEST_CONTEXT_PARAM}=${id}`);
1367
+ * await sendMessage.request({ services: { realtime: realtime.publisher }, … });
1368
+ * ```
1369
+ *
1370
+ * There is no handshake to see: a browser-style `WebSocket` sends no headers
1371
+ * a test can set, so the session comes from the registered context (no
1372
+ * context is no session). The Origin check, the heartbeat and close codes
1373
+ * on a real upgrade stay the Node adaptor's.
1374
+ */
1375
+ /**
1376
+ * The query parameter that names a connection's test context. Read and
1377
+ * removed before `connect()` sees `query`, so the handler never does.
1378
+ */
1379
+ const TEST_CONTEXT_PARAM = "__gkm_test_context";
1380
+ /**
1381
+ * The close code a refused connection gets: `4000 + status`, so a 401 is
1382
+ * 4401. MSW cannot answer an upgrade with a status line, as a server does.
1383
+ */
1384
+ const REFUSED_CLOSE_BASE = 4e3;
1385
+ /** A connection whose query names a context no test registered. */
1386
+ var UnknownWebSocketTestContext = class extends Error {
1387
+ id;
1388
+ constructor(id) {
1389
+ super(`No test registered the WebSocket context '${id}'. Call registerContext('${id}', …) before opening the socket, and keep it until it closes.`);
1390
+ this.id = id;
1391
+ this.name = "UnknownWebSocketTestContext";
1392
+ }
1393
+ };
1394
+ /** The close code a connection with an unknown context is closed with. */
1395
+ const UNKNOWN_CONTEXT_CLOSE = 1011;
1396
+ function createMswWebSocketHandlers(surface, modules, options) {
1397
+ const instance = `msw${(0, node_crypto.randomUUID)().slice(0, 8)}`;
1398
+ const channel = options.channel ?? `gkm:ws:${surface.id}:${instance}`;
1399
+ const transport = new require_websocket_api.MemoryTransport(channel);
1400
+ const contexts = /* @__PURE__ */ new Map();
1401
+ const open = /* @__PURE__ */ new Map();
1402
+ const deliver = (delivery) => {
1403
+ if (delivery.kind === "broadcast") {
1404
+ const except = new Set(delivery.except ?? []);
1405
+ for (const [id, { client }] of open) if (!except.has(id)) client.send(delivery.payload);
1406
+ return;
1407
+ }
1408
+ for (const id of delivery.ids) {
1409
+ const client = open.get(id)?.client;
1410
+ if (!client) continue;
1411
+ if (delivery.kind === "send") client.send(delivery.payload);
1412
+ else client.close(delivery.code, delivery.reason);
1413
+ }
1414
+ };
1415
+ const subscribed = transport.subscribe(instance, deliver);
1416
+ const sink = new require_websocket_api.TransportSink(transport, {
1417
+ instance,
1418
+ deliver
1419
+ });
1420
+ const core = surface.core({
1421
+ envParser: options.envParser ?? surface.envParser,
1422
+ sink,
1423
+ modules
1424
+ });
1425
+ let issued = 0;
1426
+ async function accept(client) {
1427
+ const query = new URLSearchParams(client.url.searchParams);
1428
+ const contextId = query.get(TEST_CONTEXT_PARAM);
1429
+ query.delete(TEST_CONTEXT_PARAM);
1430
+ const context = contextId ? contexts.get(contextId) : {};
1431
+ issued += 1;
1432
+ const connectionId = `${instance}.${issued}`;
1433
+ let accepted = Promise.resolve(void 0);
1434
+ let queue = Promise.resolve();
1435
+ let closed = false;
1436
+ const call = context?.services ? { services: context.services } : {};
1437
+ client.addEventListener("message", (event) => {
1438
+ queue = queue.then(async () => {
1439
+ const connection = await accepted;
1440
+ if (!connection) return;
1441
+ await core.message(connection, await textOrBytes(event.data), (payload) => client.send(payload), call);
1442
+ });
1443
+ });
1444
+ client.addEventListener("close", (event) => {
1445
+ if (closed) return;
1446
+ closed = true;
1447
+ queue = queue.then(async () => {
1448
+ const connection = await accepted;
1449
+ if (!connection) return;
1450
+ open.delete(connection.id);
1451
+ await core.disconnect(connection, {
1452
+ code: event.code,
1453
+ reason: event.reason
1454
+ }, call);
1455
+ });
1456
+ });
1457
+ if (!context) {
1458
+ const error = new UnknownWebSocketTestContext(contextId);
1459
+ client.close(UNKNOWN_CONTEXT_CLOSE, error.message.slice(0, 123));
1460
+ return;
1461
+ }
1462
+ accepted = (async () => {
1463
+ await subscribed;
1464
+ const outcome = await core.connect({
1465
+ connectionId,
1466
+ headers: new Headers(),
1467
+ query,
1468
+ session: context.session ?? null
1469
+ }, call);
1470
+ if (!outcome.accepted) {
1471
+ client.close(REFUSED_CLOSE_BASE + outcome.status, outcome.statusText);
1472
+ return;
1473
+ }
1474
+ if (closed) return void 0;
1475
+ open.set(connectionId, {
1476
+ connection: outcome.connection,
1477
+ client
1478
+ });
1479
+ return outcome.connection;
1480
+ })();
1481
+ await accepted;
1482
+ }
1483
+ return {
1484
+ handlers: [msw.ws.link(options.url).addEventListener("connection", ({ client }) => {
1485
+ accept(client);
1486
+ })],
1487
+ registerContext: (id, context) => {
1488
+ contexts.set(id, context);
1489
+ },
1490
+ removeContext: (id) => {
1491
+ contexts.delete(id);
1492
+ },
1493
+ publisher: surface.publisher(new require_websocket_api.TransportSink(new require_websocket_api.MemoryTransport(channel))),
1494
+ connectionString: `memory://${channel}`,
1495
+ get connections() {
1496
+ return [...open.values()].map(({ connection }) => connection);
1497
+ },
1498
+ close: () => transport.close()
1499
+ };
1500
+ }
1501
+ /** A frame as the core takes it: text, or the bytes it refuses. */
1502
+ async function textOrBytes(data) {
1503
+ if (typeof data === "string") return data;
1504
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
1505
+ if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
1506
+ if (data instanceof Blob) return new Uint8Array(await data.arrayBuffer());
1507
+ return String(data);
1508
+ }
1509
+ //#endregion
1311
1510
  exports.DeliveryDidNotSettle = DeliveryDidNotSettle;
1312
1511
  exports.DeliveryFailed = DeliveryFailed;
1313
1512
  exports.IN_PROCESS_PEER_ADDRESS = IN_PROCESS_PEER_ADDRESS;
1314
1513
  exports.InboxNotLocal = InboxNotLocal;
1514
+ exports.InvalidWebSocketRequest = require_websocket_api.InvalidWebSocketRequest;
1315
1515
  exports.MessageRejected = MessageRejected;
1316
1516
  exports.NoInbox = NoInbox;
1317
1517
  exports.NoInboxForAddress = NoInboxForAddress;
1318
1518
  exports.NoTestManifest = NoTestManifest;
1519
+ exports.REFUSED_CLOSE_BASE = REFUSED_CLOSE_BASE;
1319
1520
  exports.ReceiveFieldsOrRaw = ReceiveFieldsOrRaw;
1320
1521
  exports.ReceiveNeedsRecipient = ReceiveNeedsRecipient;
1321
1522
  exports.SignInFailed = SignInFailed;
1322
1523
  exports.TEST_CONTEXT_HEADER = _geekmidas_testkit_context.TEST_CONTEXT_HEADER;
1524
+ exports.TEST_CONTEXT_PARAM = TEST_CONTEXT_PARAM;
1323
1525
  exports.TEST_MANIFEST_ENV = TEST_MANIFEST_ENV;
1324
1526
  exports.TestEndpointAdaptor = TestEndpointAdaptor;
1325
1527
  exports.TestFunctionAdaptor = TestFunctionAdaptor;
1326
1528
  exports.TestQueueAdaptor = TestQueueAdaptor;
1327
1529
  exports.TestSubscriberAdaptor = TestSubscriberAdaptor;
1530
+ exports.TestWebSocketPublisher = require_websocket_api.TestWebSocketPublisher;
1328
1531
  exports.UnknownDatabase = UnknownDatabase;
1329
1532
  exports.UnknownFactory = UnknownFactory;
1330
1533
  exports.UnknownService = UnknownService;
1331
1534
  exports.UnknownTestContext = UnknownTestContext;
1535
+ exports.UnknownWebSocketApi = UnknownWebSocketApi;
1536
+ exports.UnknownWebSocketTestContext = UnknownWebSocketTestContext;
1332
1537
  exports.createMswHandlers = createMswHandlers;
1538
+ exports.createMswWebSocketHandlers = createMswWebSocketHandlers;
1333
1539
  exports.featureTest = featureTest;
1334
1540
  exports.inProcessBindings = inProcessBindings;
1335
1541
  exports.loadTestManifest = loadTestManifest;