Path: blob/main/src/vs/base/parts/ipc/common/ipc.mp.ts
4780 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import { VSBuffer } from '../../../common/buffer.js';6import { Event } from '../../../common/event.js';7import { IDisposable } from '../../../common/lifecycle.js';8import { IMessagePassingProtocol, IPCClient } from './ipc.js';910/**11* Declare minimal `MessageEvent` and `MessagePort` interfaces here12* so that this utility can be used both from `browser` and13* `electron-main` namespace where message ports are available.14*/1516export interface MessageEvent {1718/**19* For our use we only consider `Uint8Array` a valid data transfer20* via message ports because our protocol implementation is buffer based.21*/22data: Uint8Array;23}2425export interface MessagePort {2627addEventListener(type: 'message', listener: (this: MessagePort, e: MessageEvent) => unknown): void;28removeEventListener(type: 'message', listener: (this: MessagePort, e: MessageEvent) => unknown): void;2930postMessage(message: Uint8Array): void;3132start(): void;33close(): void;34}3536/**37* The MessagePort `Protocol` leverages MessagePort style IPC communication38* for the implementation of the `IMessagePassingProtocol`. That style of API39* is a simple `onmessage` / `postMessage` pattern.40*/41export class Protocol implements IMessagePassingProtocol {4243readonly onMessage;4445constructor(private port: MessagePort) {46this.onMessage = Event.fromDOMEventEmitter<VSBuffer>(this.port, 'message', (e: MessageEvent) => {47if (e.data) {48return VSBuffer.wrap(e.data);49}50return VSBuffer.alloc(0);51});52// we must call start() to ensure messages are flowing53port.start();54}5556send(message: VSBuffer): void {57this.port.postMessage(message.buffer);58}5960disconnect(): void {61this.port.close();62}63}6465/**66* An implementation of a `IPCClient` on top of MessagePort style IPC communication.67*/68export class Client extends IPCClient implements IDisposable {6970private protocol: Protocol;7172constructor(port: MessagePort, clientId: string) {73const protocol = new Protocol(port);74super(protocol, clientId);7576this.protocol = protocol;77}7879override dispose(): void {80this.protocol.disconnect();8182super.dispose();83}84}858687