MCPcopy
hub / github.com/cloudflare/capnweb / BunWebSocketTransport

Class BunWebSocketTransport

src/bun.ts:58–135  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

56}
57
58export class BunWebSocketTransport<T = undefined> implements RpcTransport {
59 constructor (ws: ServerWebSocket<T>) {
60 this.#ws = ws;
61 }
62
63 #ws: ServerWebSocket<T>;
64 #receiveResolver?: (message: string) => void;
65 #receiveRejecter?: (err: any) => void;
66 #receiveQueue: string[] = [];
67 #error?: any;
68
69 async send(message: string): Promise<void> {
70 this.#ws.send(message);
71 }
72
73 async receive(): Promise<string> {
74 if (this.#receiveQueue.length > 0) {
75 return this.#receiveQueue.shift()!;
76 } else if (this.#error) {
77 throw this.#error;
78 } else {
79 return new Promise<string>((resolve, reject) => {
80 this.#receiveResolver = resolve;
81 this.#receiveRejecter = reject;
82 });
83 }
84 }
85
86 abort?(reason: any): void {
87 let message: string;
88 if (reason instanceof Error) {
89 message = reason.message;
90 } else {
91 message = `${reason}`;
92 }
93 this.#ws.close(3000, message);
94
95 if (!this.#error) {
96 this.#error = reason;
97 // No need to call receiveRejecter(); RPC implementation will stop listening anyway.
98 }
99 }
100
101 dispatchMessage(data: string | Buffer): void {
102 if (this.#error) {
103 return;
104 }
105
106 let strData = typeof data === "string" ? data : data.toString("utf-8");
107
108 if (this.#receiveResolver) {
109 this.#receiveResolver(strData);
110 this.#receiveResolver = undefined;
111 this.#receiveRejecter = undefined;
112 } else {
113 this.#receiveQueue.push(strData);
114 }
115 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…