All files / cli/src app.ts

0% Statements 0/43
0% Branches 0/6
0% Functions 0/17
0% Lines 0/43

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                                                                                                                                                                                                                                                                                                                                                                     
import '@metamask/kernel-shims/endoify-node';
import { Logger } from '@metamask/logger';
import type { LogEntry } from '@metamask/logger';
import path from 'node:path';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
 
import { bundleSource } from './commands/bundle.ts';
import { getServer } from './commands/serve.ts';
import { watchDir } from './commands/watch.ts';
import { defaultConfig } from './config.ts';
import type { Config } from './config.ts';
import { startRelay } from './relay.ts';
import { withTimeout } from './utils.ts';
 
/**
 * Console transport that omits tags from output.
 *
 * @param entry - The log entry to write.
 */
function consoleTransport(entry: LogEntry): void {
  const args = [
    ...(entry.message ? [entry.message] : []),
    ...(entry.data ?? []),
  ];
  // eslint-disable-next-line no-console
  console[entry.level](...args);
}
 
const logger = new Logger({ tags: ['cli'], transports: [consoleTransport] });
 
const yargsInstance = yargs(hideBin(process.argv))
  .scriptName('ocap')
  .usage('$0 <command> [options]')
  .demandCommand(1)
  .strict()
  .command(
    'bundle <targets..>',
    'Bundle user code to be used in a vat',
    (_yargs) =>
      _yargs.option('targets', {
        type: 'string',
        file: true,
        dir: true,
        array: true,
        demandOption: true,
        describe: 'The files or directories of files to bundle',
      }),
    async (args) => {
      await Promise.all(
        args.targets.map(async (target) => bundleSource(target, logger)),
      );
    },
  )
  .command(
    'serve <dir> [options]',
    'Serve bundled user code by filename',
    (_yargs) =>
      _yargs
        .option('dir', {
          type: 'string',
          dir: true,
          required: true,
          describe: 'A directory containing bundle files to serve',
        })
        .option('port', {
          alias: 'p',
          type: 'number',
          default: defaultConfig.server.port,
        }),
    async (args) => {
      const appName = 'bundle server';
      const url = `http://localhost:${args.port}`;
      const resolvedDir = path.resolve(args.dir);
      const config: Config = {
        server: {
          port: args.port,
        },
        dir: resolvedDir,
      };
      logger.info(`Starting ${appName} in ${resolvedDir} on ${url}`);
      const server = getServer(config, logger);
      await server.listen();
    },
  )
  .command(
    'watch <dir>',
    'Bundle all .js files in the target dirs and rebundle on change.',
    (_yargs) =>
      _yargs.option('dir', {
        type: 'string',
        dir: true,
        required: true,
        describe: 'The directory to watch',
      }),
    (args) => {
      const { ready, error } = watchDir(args.dir, logger);
      let handleClose: undefined | (() => Promise<void>);
 
      ready
        .then((close) => {
          handleClose = close;
          logger.info(`Watching ${args.dir}...`);
          return undefined;
        })
        .catch(logger.error);
 
      error.catch(async (reason) => {
        logger.error(reason);
        // If watching started, close the watcher.
        return handleClose ? withTimeout(handleClose(), 400) : undefined;
      });
    },
  )
  .command(
    'start <dir> [-p port]',
    'Watch the target directory and serve from it on the given port.',
    (_yargs) =>
      _yargs
        .option('dir', {
          type: 'string',
          dir: true,
          required: true,
          describe: 'A directory containing source files to bundle and serve',
        })
        .option('port', {
          alias: 'p',
          type: 'number',
          default: defaultConfig.server.port,
        }),
    async (args) => {
      const closeHandlers: (() => Promise<void>)[] = [];
      const resolvedDir = path.resolve(args.dir);
 
      const handleClose = async (): Promise<void> => {
        await Promise.all(
          closeHandlers.map(async (close) => withTimeout(close(), 400)),
        );
      };
 
      const { ready: watchReady, error: watchError } = watchDir(
        resolvedDir,
        logger,
      );
 
      watchError.catch(async (reason) => {
        logger.error(reason);
        await handleClose();
      });
 
      const closeWatcher = await watchReady;
      closeHandlers.push(closeWatcher);
 
      const server = getServer(
        {
          server: {
            port: args.port,
          },
          dir: resolvedDir,
        },
        logger,
      );
      const { close: closeServer, port } = await server.listen();
      closeHandlers.push(closeServer);
 
      logger.info(`Bundling and serving ${resolvedDir} on localhost:${port}`);
    },
  )
  .command(
    'relay',
    'Start a relay server',
    (_yargs) => _yargs,
    async () => {
      await startRelay(logger);
    },
  );
 
await yargsInstance.help('help').parse();