Add an InMemoryTransport
This commit is contained in:
parent
c82d633d8d
commit
852ebb9ec0
1 changed files with 148 additions and 0 deletions
54
src/inMemory.ts
Normal file
54
src/inMemory.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import { Transport } from "./shared/transport.js";
|
||||
import { JSONRPCMessage } from "./types.js";
|
||||
|
||||
/**
|
||||
* In-memory transport for creating clients and servers that talk to each other within the same process.
|
||||
*/
|
||||
export class InMemoryTransport implements Transport {
|
||||
private _otherTransport?: InMemoryTransport;
|
||||
private _messageQueue: JSONRPCMessage[] = [];
|
||||
|
||||
onclose?: () => void;
|
||||
onerror?: (error: Error) => void;
|
||||
onmessage?: (message: JSONRPCMessage) => void;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
static createLinkedPair(): [InMemoryTransport, InMemoryTransport] {
|
||||
const clientTransport = new InMemoryTransport();
|
||||
const serverTransport = new InMemoryTransport();
|
||||
clientTransport._otherTransport = serverTransport;
|
||||
serverTransport._otherTransport = clientTransport;
|
||||
return [clientTransport, serverTransport];
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
// Process any messages that were queued before start was called
|
||||
while (this._messageQueue.length > 0) {
|
||||
const message = this._messageQueue.shift();
|
||||
if (message) {
|
||||
this.onmessage?.(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
const other = this._otherTransport;
|
||||
this._otherTransport = undefined;
|
||||
await other?.close();
|
||||
this.onclose?.();
|
||||
}
|
||||
|
||||
async send(message: JSONRPCMessage): Promise<void> {
|
||||
if (!this._otherTransport) {
|
||||
throw new Error("Not connected");
|
||||
}
|
||||
|
||||
if (this._otherTransport.onmessage) {
|
||||
this._otherTransport.onmessage(message);
|
||||
} else {
|
||||
this._otherTransport._messageQueue.push(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue