All files / streams/src/browser ChromeRuntimeStream.ts

100% Statements 39/39
100% Branches 17/17
100% Functions 11/11
100% Lines 39/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284                                                                                  2x     17x                                                                                             14x     6x 6x       14x 14x 14x 14x   14x   14x   14x                   18x 1x     17x     1x         1x     16x     1x         1x     15x 2x       2x                                                       7x     13x               7x     2x                                                                     4x               2x       4x             2x       4x 4x                                   5x 1x     4x           4x 4x     2x  
/**
 * This module provides a pair of classes for creating readable and writable streams
 * over the Chrome Extension Runtime messaging API.
 *
 * These streams utilize `chrome.runtime.sendMessage` for sending data and
 * `chrome.runtime.onMessage.addListener` for receiving data. This allows for
 * communication between different parts of a Chrome extension (e.g., background scripts,
 * content scripts, and popup pages).
 *
 * Note that unlike e.g. the `MessagePort` API, the Chrome Extension Runtime messaging API
 * doesn't have a built-in way to close the connection. The streams will continue to operate
 * as long as the extension is running, unless manually ended.
 *
 * @module ChromeRuntime streams
 */
 
import { stringify } from '@metamask/kernel-utils';
import type { Json } from '@metamask/utils';
 
import type { ChromeRuntime, ChromeMessageSender } from './chrome.d.ts';
import {
  BaseDuplexStream,
  makeDuplexStreamInputValidator,
} from '../BaseDuplexStream.ts';
import type {
  BaseReaderArgs,
  ValidateInput,
  BaseWriterArgs,
  ReceiveInput,
} from '../BaseStream.ts';
import { BaseReader, BaseWriter } from '../BaseStream.ts';
import type { Dispatchable } from '../utils.ts';
 
export type ChromeRuntimeTarget = 'background' | 'offscreen' | 'popup';
 
export type MessageEnvelope<Payload> = {
  target: ChromeRuntimeTarget;
  source: ChromeRuntimeTarget;
  payload: Payload;
};
 
const isMessageEnvelope = (
  message: unknown,
): message is MessageEnvelope<unknown> =>
  typeof message === 'object' &&
  message !== null &&
  'target' in message &&
  'source' in message &&
  'payload' in message;
 
/**
 * A readable stream over the Chrome Extension Runtime messaging API.
 *
 * This class is a naive passthrough mechanism for data using `chrome.runtime.onMessage`.
 * Expects exclusive read access to the messaging API.
 *
 * @see
 * - {@link ChromeRuntimeWriter} for the corresponding writable stream.
 * - The module-level documentation for more details.
 */
export class ChromeRuntimeReader<Read extends Json> extends BaseReader<Read> {
  readonly #receiveInput: ReceiveInput;
 
  readonly #target: ChromeRuntimeTarget;
 
  readonly #source: ChromeRuntimeTarget;
 
  readonly #extensionId: string;
 
  /**
   * Constructs a new {@link ChromeRuntimeReader}.
   *
   * @param runtime - The Chrome runtime API object.
   * @param target - The target context (e.g., 'background', 'offscreen', 'popup').
   * @param source - The source context that messages are expected from.
   * @param options - Options bag for configuring the reader.
   * @param options.validateInput - A function that validates input from the transport.
   * @param options.onEnd - A function that is called when the stream ends.
   */
  constructor(
    runtime: ChromeRuntime,
    target: ChromeRuntimeTarget,
    source: ChromeRuntimeTarget,
    { validateInput, onEnd }: BaseReaderArgs<Read> = {},
  ) {
    // eslint-disable-next-line prefer-const
    let messageListener: (
      message: unknown,
      sender: ChromeMessageSender,
    ) => void;
 
    super({
      validateInput,
      onEnd: async (error) => {
        runtime.onMessage.removeListener(messageListener);
        await onEnd?.(error);
      },
    });
 
    this.#receiveInput = super.getReceiveInput();
    this.#target = target;
    this.#source = source;
    this.#extensionId = runtime.id;
 
    messageListener = this.#onMessage.bind(this);
    // Begin listening for messages from the Chrome runtime.
    runtime.onMessage.addListener(messageListener);
 
    harden(this);
  }
 
  /**
   * Handles incoming messages from the Chrome runtime.
   *
   * @param message - The message received from the Chrome runtime.
   * @param sender - The sender information for the message.
   */
  #onMessage(message: unknown, sender: ChromeMessageSender): void {
    if (sender.id !== this.#extensionId) {
      return;
    }
 
    if (!isMessageEnvelope(message)) {
      // TODO(#562): Use logger instead.
      // eslint-disable-next-line no-console
      console.debug(
        `ChromeRuntimeReader received unexpected message: ${stringify(
          message,
        )}`,
      );
      return;
    }
 
    if (message.target !== this.#target || message.source !== this.#source) {
      // TODO(#562): Use logger instead.
      // eslint-disable-next-line no-console
      console.debug(
        `ChromeRuntimeReader received message with incorrect target or source: ${stringify(message)}`,
        `Expected target: ${this.#target}`,
        `Expected source: ${this.#source}`,
      );
      return;
    }
 
    this.#receiveInput(message.payload).catch(async (error) =>
      this.throw(error),
    );
  }
}
harden(ChromeRuntimeReader);
 
/**
 * A writable stream over the Chrome Extension Runtime messaging API.
 *
 * This class is a naive passthrough mechanism for data using `chrome.runtime.sendMessage`.
 *
 * @see
 * - {@link ChromeRuntimeReader} for the corresponding readable stream.
 * - The module-level documentation for more details.
 */
export class ChromeRuntimeWriter<Write extends Json> extends BaseWriter<Write> {
  /**
   * Constructs a new {@link ChromeRuntimeWriter}.
   *
   * @param runtime - The Chrome runtime API object.
   * @param target - The target context to send messages to.
   * @param source - The source context identifying where messages originate.
   * @param options - Options bag for configuring the writer.
   * @param options.name - The name of the stream, for logging purposes.
   * @param options.onEnd - A function that is called when the stream ends.
   */
  constructor(
    runtime: ChromeRuntime,
    target: ChromeRuntimeTarget,
    source: ChromeRuntimeTarget,
    { name, onEnd }: Omit<BaseWriterArgs<Write>, 'onDispatch'> = {},
  ) {
    super({
      name,
      onDispatch: async (value: Dispatchable<Write>) => {
        await runtime.sendMessage({
          target,
          source,
          payload: value,
        });
      },
      onEnd,
    });
    harden(this);
  }
}
harden(ChromeRuntimeWriter);
 
/**
 * A duplex stream over the Chrome Extension Runtime messaging API.
 *
 * This class is a naive passthrough mechanism for data using `chrome.runtime.onMessage`.
 *
 * @see
 * - {@link ChromeRuntimeReader} for the corresponding readable stream.
 * - {@link ChromeRuntimeWriter} for the corresponding writable stream.
 */
export class ChromeRuntimeDuplexStream<
  Read extends Json,
  Write extends Json = Read,
> extends BaseDuplexStream<
  Read,
  ChromeRuntimeReader<Read>,
  Write,
  ChromeRuntimeWriter<Write>
> {
  /**
   * Constructs a new {@link ChromeRuntimeDuplexStream}.
   *
   * @param runtime - The Chrome runtime API object.
   * @param localTarget - The local target context for this stream.
   * @param remoteTarget - The remote target context to communicate with.
   * @param validateInput - A function that validates input from the transport.
   */
  constructor(
    runtime: ChromeRuntime,
    localTarget: ChromeRuntimeTarget,
    remoteTarget: ChromeRuntimeTarget,
    validateInput?: ValidateInput<Read>,
  ) {
    let writer: ChromeRuntimeWriter<Write>; // eslint-disable-line prefer-const
    const reader = new ChromeRuntimeReader<Read>(
      runtime,
      localTarget,
      remoteTarget,
      {
        name: 'ChromeRuntimeDuplexStream',
        validateInput: makeDuplexStreamInputValidator(validateInput),
        onEnd: async () => {
          await writer.return();
        },
      },
    );
    writer = new ChromeRuntimeWriter<Write>(
      runtime,
      remoteTarget,
      localTarget,
      {
        name: 'ChromeRuntimeDuplexStream',
        onEnd: async () => {
          await reader.return();
        },
      },
    );
    super(reader, writer);
    harden(this);
  }
 
  /**
   * Creates and synchronizes a new {@link ChromeRuntimeDuplexStream}.
   *
   * @param runtime - The Chrome runtime API object.
   * @param localTarget - The local target context for this stream.
   * @param remoteTarget - The remote target context to communicate with.
   * @param validateInput - A function that validates input from the transport.
   * @returns A synchronized duplex stream.
   */
  static async make<Read extends Json, Write extends Json = Read>(
    runtime: ChromeRuntime,
    localTarget: ChromeRuntimeTarget,
    remoteTarget: ChromeRuntimeTarget,
    validateInput?: ValidateInput<Read>,
  ): Promise<ChromeRuntimeDuplexStream<Read, Write>> {
    if (localTarget === remoteTarget) {
      throw new Error('localTarget and remoteTarget must be different');
    }
 
    const stream = new ChromeRuntimeDuplexStream<Read, Write>(
      runtime,
      localTarget,
      remoteTarget,
      validateInput,
    );
    await stream.synchronize();
    return stream;
  }
}
harden(ChromeRuntimeDuplexStream);