inMemory.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * In-memory transport for creating clients and servers that talk to each other within the same process.
  3. */
  4. export class InMemoryTransport {
  5. constructor() {
  6. this._messageQueue = [];
  7. }
  8. /**
  9. * 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.
  10. */
  11. static createLinkedPair() {
  12. const clientTransport = new InMemoryTransport();
  13. const serverTransport = new InMemoryTransport();
  14. clientTransport._otherTransport = serverTransport;
  15. serverTransport._otherTransport = clientTransport;
  16. return [clientTransport, serverTransport];
  17. }
  18. async start() {
  19. // Process any messages that were queued before start was called
  20. while (this._messageQueue.length > 0) {
  21. const queuedMessage = this._messageQueue.shift();
  22. this.onmessage?.(queuedMessage.message, queuedMessage.extra);
  23. }
  24. }
  25. async close() {
  26. const other = this._otherTransport;
  27. this._otherTransport = undefined;
  28. await other?.close();
  29. this.onclose?.();
  30. }
  31. /**
  32. * Sends a message with optional auth info.
  33. * This is useful for testing authentication scenarios.
  34. */
  35. async send(message, options) {
  36. if (!this._otherTransport) {
  37. throw new Error('Not connected');
  38. }
  39. if (this._otherTransport.onmessage) {
  40. this._otherTransport.onmessage(message, { authInfo: options?.authInfo });
  41. }
  42. else {
  43. this._otherTransport._messageQueue.push({ message, extra: { authInfo: options?.authInfo } });
  44. }
  45. }
  46. }
  47. //# sourceMappingURL=inMemory.js.map