Skip to content

Pr/protocol overwriting transport hooks #477

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions src/shared/protocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,22 @@ describe("protocol tests", () => {
expect(oncloseMock).toHaveBeenCalled();
});

it("should not overwrite existing hooks when connecting transports", async () => {
const oncloseMock = jest.fn();
const onerrorMock = jest.fn();
const onmessageMock = jest.fn();
transport.onclose = oncloseMock;
transport.onerror = onerrorMock;
transport.onmessage = onmessageMock;
await protocol.connect(transport);
transport.onclose();
transport.onerror(new Error());
transport.onmessage("");
expect(oncloseMock).toHaveBeenCalled();
expect(onerrorMock).toHaveBeenCalled();
expect(onmessageMock).toHaveBeenCalled();
});

describe("progress notification timeout behavior", () => {
beforeEach(() => {
jest.useFakeTimers();
Expand Down
10 changes: 9 additions & 1 deletion src/shared/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,23 +279,31 @@ export abstract class Protocol<
*/
async connect(transport: Transport): Promise<void> {
this._transport = transport;
const _onclose = this.transport?.onclose;
this._transport.onclose = () => {
_onclose?.();
this._onclose();
};

const _onerror = this.transport?.onerror;
this._transport.onerror = (error: Error) => {
_onerror?.(error);
this._onerror(error);
};

const _onmessage = this._transport?.onmessage;
this._transport.onmessage = (message, extra) => {
_onmessage?.(message, extra);
if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
this._onresponse(message);
} else if (isJSONRPCRequest(message)) {
this._onrequest(message, extra);
} else if (isJSONRPCNotification(message)) {
this._onnotification(message);
} else {
this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));
this._onerror(
new Error(`Unknown message type: ${JSON.stringify(message)}`),
);
}
};

Expand Down