inMemory.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.InMemoryTransport = void 0;
  4. /**
  5. * In-memory transport for creating clients and servers that talk to each other within the same process.
  6. */
  7. class InMemoryTransport {
  8. constructor() {
  9. this._messageQueue = [];
  10. }
  11. /**
  12. * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a Client and one to a Server.
  13. */
  14. static createLinkedPair() {
  15. const clientTransport = new InMemoryTransport();
  16. const serverTransport = new InMemoryTransport();
  17. clientTransport._otherTransport = serverTransport;
  18. serverTransport._otherTransport = clientTransport;
  19. return [clientTransport, serverTransport];
  20. }
  21. async start() {
  22. // Process any messages that were queued before start was called
  23. while (this._messageQueue.length > 0) {
  24. const queuedMessage = this._messageQueue.shift();
  25. this.onmessage?.(queuedMessage.message, queuedMessage.extra);
  26. }
  27. }
  28. async close() {
  29. const other = this._otherTransport;
  30. this._otherTransport = undefined;
  31. await other?.close();
  32. this.onclose?.();
  33. }
  34. /**
  35. * Sends a message with optional auth info.
  36. * This is useful for testing authentication scenarios.
  37. */
  38. async send(message, options) {
  39. if (!this._otherTransport) {
  40. throw new Error('Not connected');
  41. }
  42. if (this._otherTransport.onmessage) {
  43. this._otherTransport.onmessage(message, { authInfo: options?.authInfo });
  44. }
  45. else {
  46. this._otherTransport._messageQueue.push({ message, extra: { authInfo: options?.authInfo } });
  47. }
  48. }
  49. }
  50. exports.InMemoryTransport = InMemoryTransport;
  51. //# sourceMappingURL=inMemory.js.map