All files / kernel-browser-runtime/src makeIframeVatWorker.ts

7.69% Statements 1/13
0% Branches 0/3
0% Functions 0/4
7.69% Lines 1/13

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                                                    2x                                                                    
import { Logger } from '@metamask/logger';
import type { VatId, VatConfig } from '@metamask/ocap-kernel';
import { createWindow } from '@metamask/snaps-utils';
import type { initializeMessageChannel } from '@metamask/streams/browser';
 
import type { VatWorker } from './PlatformServicesServer.ts';
 
type Options = {
  id: VatId;
  getPort: typeof initializeMessageChannel;
  logger: Logger;
  iframeUri: string;
  testId?: string;
};
 
/**
 * Create a vat worker that launches a new window with an iframe.
 *
 * @param options - The options for the vat worker.
 * @param options.id - The id of the vat.
 * @param options.getPort - The function to get the port for the vat.
 * @param options.logger - The logger for the vat.
 * @param options.iframeUri - The uri of the iframe.
 * @param options.testId - The test id of the iframe element, for use in e2e tests.
 * @returns The vat worker.
 */
export const makeIframeVatWorker = ({
  id,
  getPort,
  logger,
  iframeUri,
  testId = 'ocap-iframe',
}: Options): VatWorker => {
  const vatHtmlId = `ocap-iframe-${id}`;
  return {
    launch: async (_vatConfig: VatConfig) => {
      const newWindow = await createWindow({
        uri: `${iframeUri}?vatId=${id}`,
        id: vatHtmlId,
        testId,
      });
      const port = await getPort((message, transfer) =>
        newWindow.postMessage(message, '*', transfer),
      );
 
      return [port, newWindow];
    },
    terminate: async (): Promise<null> => {
      const iframe = document.getElementById(vatHtmlId);
      if (iframe === null) {
        logger.error(
          `iframe of vat with id "${id}" already removed from DOM (#${vatHtmlId})`,
        );
        return null;
      }
      iframe.remove();
      return null;
    },
  };
};