const normalizeLine = line => {
  if (line.startsWith('Error: ')) {
    return line.slice('Error: '.length);
  }
  if (line.startsWith('VError: ')) {
    return line.slice('VError: '.length);
  }
  return line;
};
const getCombinedMessage = (error, message) => {
  const stringifiedError = normalizeLine(`${error}`);
  if (message) {
    return `${message}: ${stringifiedError}`;
  }
  return stringifiedError;
};
const NewLine$2 = '\n';
const getNewLineIndex$1 = (string, startIndex = undefined) => {
  return string.indexOf(NewLine$2, startIndex);
};
const mergeStacks = (parent, child) => {
  if (!child) {
    return parent;
  }
  const parentNewLineIndex = getNewLineIndex$1(parent);
  const childNewLineIndex = getNewLineIndex$1(child);
  if (childNewLineIndex === -1) {
    return parent;
  }
  const parentFirstLine = parent.slice(0, parentNewLineIndex);
  const childRest = child.slice(childNewLineIndex);
  const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
  if (parentFirstLine.includes(childFirstLine)) {
    return parentFirstLine + childRest;
  }
  return child;
};
class VError extends Error {
  constructor(error, message) {
    const combinedMessage = getCombinedMessage(error, message);
    super(combinedMessage);
    this.name = 'VError';
    if (error instanceof Error) {
      this.stack = mergeStacks(this.stack, error.stack);
    }
    if (error.codeFrame) {
      // @ts-ignore
      this.codeFrame = error.codeFrame;
    }
    if (error.code) {
      // @ts-ignore
      this.code = error.code;
    }
  }
}

class AssertionError extends Error {
  constructor(message) {
    super(message);
    this.name = 'AssertionError';
  }
}
const Object$1 = 1;
const Number$1 = 2;
const Array$1 = 3;
const String$1 = 4;
const Boolean$1 = 5;
const Function = 6;
const Null = 7;
const Unknown = 8;
const getType = value => {
  switch (typeof value) {
    case 'number':
      return Number$1;
    case 'function':
      return Function;
    case 'string':
      return String$1;
    case 'object':
      if (value === null) {
        return Null;
      }
      if (Array.isArray(value)) {
        return Array$1;
      }
      return Object$1;
    case 'boolean':
      return Boolean$1;
    default:
      return Unknown;
  }
};
const number = value => {
  const type = getType(value);
  if (type !== Number$1) {
    throw new AssertionError('expected value to be of type number');
  }
};

const isMessagePort = value => {
  return value && value instanceof MessagePort;
};
const isMessagePortMain = value => {
  return value && value.constructor && value.constructor.name === 'MessagePortMain';
};
const isOffscreenCanvas = value => {
  return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
};
const isInstanceOf = (value, constructorName) => {
  return value?.constructor?.name === constructorName;
};
const isSocket = value => {
  return isInstanceOf(value, 'Socket');
};
const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
const isTransferrable = value => {
  for (const fn of transferrables) {
    if (fn(value)) {
      return true;
    }
  }
  return false;
};
const walkValue = (value, transferrables, isTransferrable) => {
  if (!value) {
    return;
  }
  if (isTransferrable(value)) {
    transferrables.push(value);
    return;
  }
  if (Array.isArray(value)) {
    for (const item of value) {
      walkValue(item, transferrables, isTransferrable);
    }
    return;
  }
  if (typeof value === 'object') {
    for (const property of Object.values(value)) {
      walkValue(property, transferrables, isTransferrable);
    }
    return;
  }
};
const getTransferrables = value => {
  const transferrables = [];
  walkValue(value, transferrables, isTransferrable);
  return transferrables;
};
const attachEvents = that => {
  const handleMessage = (...args) => {
    const data = that.getData(...args);
    that.dispatchEvent(new MessageEvent('message', {
      data
    }));
  };
  that.onMessage(handleMessage);
  const handleClose = event => {
    that.dispatchEvent(new Event('close'));
  };
  that.onClose(handleClose);
};
class Ipc extends EventTarget {
  constructor(rawIpc) {
    super();
    this._rawIpc = rawIpc;
    attachEvents(this);
  }
}
const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
const NewLine$1 = '\n';
const joinLines$1 = lines => {
  return lines.join(NewLine$1);
};
const RE_AT = /^\s+at/;
const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
const isNormalStackLine = line => {
  return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
};
const getDetails = lines => {
  const index = lines.findIndex(isNormalStackLine);
  if (index === -1) {
    return {
      actualMessage: joinLines$1(lines),
      rest: []
    };
  }
  let lastIndex = index - 1;
  while (++lastIndex < lines.length) {
    if (!isNormalStackLine(lines[lastIndex])) {
      break;
    }
  }
  return {
    actualMessage: lines[index - 1],
    rest: lines.slice(index, lastIndex)
  };
};
const splitLines$1 = lines => {
  return lines.split(NewLine$1);
};
const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
const isMessageCodeBlockStartIndex = line => {
  return RE_MESSAGE_CODE_BLOCK_START.test(line);
};
const isMessageCodeBlockEndIndex = line => {
  return RE_MESSAGE_CODE_BLOCK_END.test(line);
};
const getMessageCodeBlock = stderr => {
  const lines = splitLines$1(stderr);
  const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
  const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
  const relevantLines = lines.slice(startIndex, endIndex);
  const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
  return relevantMessage;
};
const isModuleNotFoundMessage = line => {
  return line.includes('[ERR_MODULE_NOT_FOUND]');
};
const getModuleNotFoundError = stderr => {
  const lines = splitLines$1(stderr);
  const messageIndex = lines.findIndex(isModuleNotFoundMessage);
  const message = lines[messageIndex];
  return {
    code: ERR_MODULE_NOT_FOUND,
    message
  };
};
const isModuleNotFoundError = stderr => {
  if (!stderr) {
    return false;
  }
  return stderr.includes('ERR_MODULE_NOT_FOUND');
};
const isModulesSyntaxError = stderr => {
  if (!stderr) {
    return false;
  }
  return stderr.includes('SyntaxError: Cannot use import statement outside a module');
};
const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
const isUnhelpfulNativeModuleError = stderr => {
  return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
};
const getNativeModuleErrorMessage = stderr => {
  const message = getMessageCodeBlock(stderr);
  return {
    code: E_INCOMPATIBLE_NATIVE_MODULE,
    message: `Incompatible native node module: ${message}`
  };
};
const getModuleSyntaxError = () => {
  return {
    code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON,
    message: `ES Modules are not supported in electron`
  };
};
const getHelpfulChildProcessError = (stdout, stderr) => {
  if (isUnhelpfulNativeModuleError(stderr)) {
    return getNativeModuleErrorMessage(stderr);
  }
  if (isModulesSyntaxError(stderr)) {
    return getModuleSyntaxError();
  }
  if (isModuleNotFoundError(stderr)) {
    return getModuleNotFoundError(stderr);
  }
  const lines = splitLines$1(stderr);
  const {
    actualMessage,
    rest
  } = getDetails(lines);
  return {
    code: '',
    message: actualMessage,
    stack: rest
  };
};
class IpcError extends VError {
  // @ts-ignore
  constructor(betterMessage, stdout = '', stderr = '') {
    if (stdout || stderr) {
      // @ts-ignore
      const {
        code,
        message,
        stack
      } = getHelpfulChildProcessError(stdout, stderr);
      const cause = new Error(message);
      // @ts-ignore
      cause.code = code;
      cause.stack = stack;
      super(cause, betterMessage);
    } else {
      super(betterMessage);
    }
    // @ts-ignore
    this.name = 'IpcError';
    // @ts-ignore
    this.stdout = stdout;
    // @ts-ignore
    this.stderr = stderr;
  }
}
const readyMessage = 'ready';
const getData$2 = event => {
  return event.data;
};
const listen$7 = () => {
  // @ts-ignore
  if (typeof WorkerGlobalScope === 'undefined') {
    throw new TypeError('module is not in web worker scope');
  }
  return globalThis;
};
const signal$8 = global => {
  global.postMessage(readyMessage);
};
class IpcChildWithModuleWorker extends Ipc {
  getData(event) {
    return getData$2(event);
  }
  send(message) {
    // @ts-ignore
    this._rawIpc.postMessage(message);
  }
  sendAndTransfer(message) {
    const transfer = getTransferrables(message);
    // @ts-ignore
    this._rawIpc.postMessage(message, transfer);
  }
  dispose() {
    // ignore
  }
  onClose(callback) {
    // ignore
  }
  onMessage(callback) {
    this._rawIpc.addEventListener('message', callback);
  }
}
const wrap$f = global => {
  return new IpcChildWithModuleWorker(global);
};
const waitForFirstMessage = async port => {
  const {
    promise,
    resolve
  } = Promise.withResolvers();
  port.addEventListener('message', resolve, {
    once: true
  });
  const event = await promise;
  // @ts-ignore
  return event.data;
};
const listen$6 = async () => {
  const parentIpcRaw = listen$7();
  signal$8(parentIpcRaw);
  const parentIpc = wrap$f(parentIpcRaw);
  const firstMessage = await waitForFirstMessage(parentIpc);
  if (firstMessage.method !== 'initialize') {
    throw new IpcError('unexpected first message');
  }
  const type = firstMessage.params[0];
  if (type === 'message-port') {
    parentIpc.send({
      id: firstMessage.id,
      jsonrpc: '2.0',
      result: null
    });
    parentIpc.dispose();
    const port = firstMessage.params[1];
    return port;
  }
  return globalThis;
};
class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
  getData(event) {
    return getData$2(event);
  }
  send(message) {
    this._rawIpc.postMessage(message);
  }
  sendAndTransfer(message) {
    const transfer = getTransferrables(message);
    this._rawIpc.postMessage(message, transfer);
  }
  dispose() {
    if (this._rawIpc.close) {
      this._rawIpc.close();
    }
  }
  onClose(callback) {
    // ignore
  }
  onMessage(callback) {
    this._rawIpc.addEventListener('message', callback);
    this._rawIpc.start();
  }
}
const wrap$e = port => {
  return new IpcChildWithModuleWorkerAndMessagePort(port);
};
const IpcChildWithModuleWorkerAndMessagePort$1 = {
  __proto__: null,
  listen: listen$6,
  wrap: wrap$e
};
const addListener = (emitter, type, callback) => {
  if ('addEventListener' in emitter) {
    emitter.addEventListener(type, callback);
  } else {
    emitter.on(type, callback);
  }
};
const removeListener = (emitter, type, callback) => {
  if ('removeEventListener' in emitter) {
    emitter.removeEventListener(type, callback);
  } else {
    emitter.off(type, callback);
  }
};
const getFirstEvent = (eventEmitter, eventMap) => {
  const {
    promise,
    resolve
  } = Promise.withResolvers();
  const listenerMap = Object.create(null);
  const cleanup = value => {
    for (const event of Object.keys(eventMap)) {
      removeListener(eventEmitter, event, listenerMap[event]);
    }
    resolve(value);
  };
  for (const [event, type] of Object.entries(eventMap)) {
    const listener = event => {
      cleanup({
        event,
        type
      });
    };
    addListener(eventEmitter, event, listener);
    listenerMap[event] = listener;
  }
  return promise;
};
const Message$1 = 3;
const create$5 = async ({
  isMessagePortOpen,
  messagePort
}) => {
  if (!isMessagePort(messagePort)) {
    throw new IpcError('port must be of type MessagePort');
  }
  if (isMessagePortOpen) {
    return messagePort;
  }
  const eventPromise = getFirstEvent(messagePort, {
    message: Message$1
  });
  messagePort.start();
  const {
    event,
    type
  } = await eventPromise;
  if (type !== Message$1) {
    throw new IpcError('Failed to wait for ipc message');
  }
  if (event.data !== readyMessage) {
    throw new IpcError('unexpected first message');
  }
  return messagePort;
};
const signal$1 = messagePort => {
  messagePort.start();
};
class IpcParentWithMessagePort extends Ipc {
  getData = getData$2;
  send(message) {
    this._rawIpc.postMessage(message);
  }
  sendAndTransfer(message) {
    const transfer = getTransferrables(message);
    this._rawIpc.postMessage(message, transfer);
  }
  dispose() {
    this._rawIpc.close();
  }
  onMessage(callback) {
    this._rawIpc.addEventListener('message', callback);
  }
  onClose(callback) {}
}
const wrap$5 = messagePort => {
  return new IpcParentWithMessagePort(messagePort);
};
const IpcParentWithMessagePort$1 = {
  __proto__: null,
  create: create$5,
  signal: signal$1,
  wrap: wrap$5
};

const Two$1 = '2.0';
const callbacks = Object.create(null);
const get$2 = id => {
  return callbacks[id];
};
const remove$1 = id => {
  delete callbacks[id];
};
class JsonRpcError extends Error {
  constructor(message) {
    super(message);
    this.name = 'JsonRpcError';
  }
}
const NewLine = '\n';
const DomException = 'DOMException';
const ReferenceError$1 = 'ReferenceError';
const SyntaxError$1 = 'SyntaxError';
const TypeError$1 = 'TypeError';
const getErrorConstructor = (message, type) => {
  if (type) {
    switch (type) {
      case DomException:
        return DOMException;
      case TypeError$1:
        return TypeError;
      case SyntaxError$1:
        return SyntaxError;
      case ReferenceError$1:
        return ReferenceError;
      default:
        return Error;
    }
  }
  if (message.startsWith('TypeError: ')) {
    return TypeError;
  }
  if (message.startsWith('SyntaxError: ')) {
    return SyntaxError;
  }
  if (message.startsWith('ReferenceError: ')) {
    return ReferenceError;
  }
  return Error;
};
const constructError = (message, type, name) => {
  const ErrorConstructor = getErrorConstructor(message, type);
  if (ErrorConstructor === DOMException && name) {
    return new ErrorConstructor(message, name);
  }
  if (ErrorConstructor === Error) {
    const error = new Error(message);
    if (name && name !== 'VError') {
      error.name = name;
    }
    return error;
  }
  return new ErrorConstructor(message);
};
const joinLines = lines => {
  return lines.join(NewLine);
};
const splitLines = lines => {
  return lines.split(NewLine);
};
const getCurrentStack = () => {
  const stackLinesToSkip = 3;
  const currentStack = joinLines(splitLines(new Error().stack || '').slice(stackLinesToSkip));
  return currentStack;
};
const getNewLineIndex = (string, startIndex = undefined) => {
  return string.indexOf(NewLine, startIndex);
};
const getParentStack = error => {
  let parentStack = error.stack || error.data || error.message || '';
  if (parentStack.startsWith('    at')) {
    parentStack = error.message + NewLine + parentStack;
  }
  return parentStack;
};
const MethodNotFound = -32601;
const Custom = -32001;
const restoreJsonRpcError = error => {
  const currentStack = getCurrentStack();
  if (error && error instanceof Error) {
    if (typeof error.stack === 'string') {
      error.stack = error.stack + NewLine + currentStack;
    }
    return error;
  }
  if (error && error.code && error.code === MethodNotFound) {
    const restoredError = new JsonRpcError(error.message);
    const parentStack = getParentStack(error);
    restoredError.stack = parentStack + NewLine + currentStack;
    return restoredError;
  }
  if (error && error.message) {
    const restoredError = constructError(error.message, error.type, error.name);
    if (error.data) {
      if (error.data.stack && error.data.type && error.message) {
        restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
      } else if (error.data.stack) {
        restoredError.stack = error.data.stack;
      }
      if (error.data.codeFrame) {
        // @ts-ignore
        restoredError.codeFrame = error.data.codeFrame;
      }
      if (error.data.code) {
        // @ts-ignore
        restoredError.code = error.data.code;
      }
      if (error.data.type) {
        // @ts-ignore
        restoredError.name = error.data.type;
      }
    } else {
      if (error.stack) {
        const lowerStack = restoredError.stack || '';
        // @ts-ignore
        const indexNewLine = getNewLineIndex(lowerStack);
        const parentStack = getParentStack(error);
        // @ts-ignore
        restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
      }
      if (error.codeFrame) {
        // @ts-ignore
        restoredError.codeFrame = error.codeFrame;
      }
    }
    return restoredError;
  }
  if (typeof error === 'string') {
    return new Error(`JsonRpc Error: ${error}`);
  }
  return new Error(`JsonRpc Error: ${error}`);
};
const unwrapJsonRpcResult = responseMessage => {
  if ('error' in responseMessage) {
    const restoredError = restoreJsonRpcError(responseMessage.error);
    throw restoredError;
  }
  if ('result' in responseMessage) {
    return responseMessage.result;
  }
  throw new JsonRpcError('unexpected response message');
};
const warn = (...args) => {
  console.warn(...args);
};
const resolve = (id, response) => {
  const fn = get$2(id);
  if (!fn) {
    console.log(response);
    warn(`callback ${id} may already be disposed`);
    return;
  }
  fn(response);
  remove$1(id);
};
const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
const getErrorType = prettyError => {
  if (prettyError && prettyError.type) {
    return prettyError.type;
  }
  if (prettyError && prettyError.constructor && prettyError.constructor.name) {
    return prettyError.constructor.name;
  }
  return undefined;
};
const isAlreadyStack = line => {
  return line.trim().startsWith('at ');
};
const getStack = prettyError => {
  const stackString = prettyError.stack || '';
  const newLineIndex = stackString.indexOf('\n');
  if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
    return stackString.slice(newLineIndex + 1);
  }
  return stackString;
};
const getErrorProperty = (error, prettyError) => {
  if (error && error.code === E_COMMAND_NOT_FOUND) {
    return {
      code: MethodNotFound,
      message: error.message,
      data: error.stack
    };
  }
  return {
    code: Custom,
    message: prettyError.message,
    data: {
      stack: getStack(prettyError),
      codeFrame: prettyError.codeFrame,
      type: getErrorType(prettyError),
      code: prettyError.code,
      name: prettyError.name
    }
  };
};
const create$1$2 = (id, error) => {
  return {
    jsonrpc: Two$1,
    id,
    error
  };
};
const getErrorResponse = (id, error, preparePrettyError, logError) => {
  const prettyError = preparePrettyError(error);
  logError(error, prettyError);
  const errorProperty = getErrorProperty(error, prettyError);
  return create$1$2(id, errorProperty);
};
const create$3 = (message, result) => {
  return {
    jsonrpc: Two$1,
    id: message.id,
    result: result ?? null
  };
};
const getSuccessResponse = (message, result) => {
  const resultProperty = result ?? null;
  return create$3(message, resultProperty);
};
const getErrorResponseSimple = (id, error) => {
  return {
    jsonrpc: Two$1,
    id,
    error: {
      code: Custom,
      // @ts-ignore
      message: error.message,
      data: error
    }
  };
};
const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
  try {
    const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
    return getSuccessResponse(message, result);
  } catch (error) {
    if (ipc.canUseSimpleErrorResponse) {
      return getErrorResponseSimple(message.id, error);
    }
    return getErrorResponse(message.id, error, preparePrettyError, logError);
  }
};
const defaultPreparePrettyError = error => {
  return error;
};
const defaultLogError = () => {
  // ignore
};
const defaultRequiresSocket = () => {
  return false;
};
const defaultResolve = resolve;

// TODO maybe remove this in v6 or v7, only accept options object to simplify the code
const normalizeParams = args => {
  if (args.length === 1) {
    const options = args[0];
    return {
      ipc: options.ipc,
      message: options.message,
      execute: options.execute,
      resolve: options.resolve || defaultResolve,
      preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
      logError: options.logError || defaultLogError,
      requiresSocket: options.requiresSocket || defaultRequiresSocket
    };
  }
  return {
    ipc: args[0],
    message: args[1],
    execute: args[2],
    resolve: args[3],
    preparePrettyError: args[4],
    logError: args[5],
    requiresSocket: args[6]
  };
};
const handleJsonRpcMessage = async (...args) => {
  const options = normalizeParams(args);
  const {
    message,
    ipc,
    execute,
    resolve,
    preparePrettyError,
    logError,
    requiresSocket
  } = options;
  if ('id' in message) {
    if ('method' in message) {
      const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
      try {
        ipc.send(response);
      } catch (error) {
        const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
        ipc.send(errorResponse);
      }
      return;
    }
    resolve(message.id, message);
    return;
  }
  if ('method' in message) {
    await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
    return;
  }
  throw new JsonRpcError('unexpected message');
};

class CommandNotFoundError extends Error {
  constructor(command) {
    super(`Command not found ${command}`);
    this.name = 'CommandNotFoundError';
  }
}
const commands = Object.create(null);
const register = commandMap => {
  Object.assign(commands, commandMap);
};
const getCommand = key => {
  return commands[key];
};
const execute = (command, ...args) => {
  const fn = getCommand(command);
  if (!fn) {
    throw new CommandNotFoundError(command);
  }
  return fn(...args);
};

const Two = '2.0';
const create$s = (method, params) => {
  return {
    jsonrpc: Two,
    method,
    params
  };
};
const create$r = (id, method, params) => {
  const message = {
    id,
    jsonrpc: Two,
    method,
    params
  };
  return message;
};
let id = 0;
const create$q = () => {
  return ++id;
};

/* eslint-disable n/no-unsupported-features/es-syntax */

const registerPromise = map => {
  const id = create$q();
  const {
    promise,
    resolve
  } = Promise.withResolvers();
  map[id] = resolve;
  return {
    id,
    promise
  };
};

// @ts-ignore
const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
  const {
    id,
    promise
  } = registerPromise(callbacks);
  const message = create$r(id, method, params);
  if (useSendAndTransfer && ipc.sendAndTransfer) {
    ipc.sendAndTransfer(message);
  } else {
    ipc.send(message);
  }
  const responseMessage = await promise;
  return unwrapJsonRpcResult(responseMessage);
};
const createRpc = ipc => {
  const callbacks = Object.create(null);
  ipc._resolve = (id, response) => {
    const fn = callbacks[id];
    if (!fn) {
      console.warn(`callback ${id} may already be disposed`);
      return;
    }
    fn(response);
    delete callbacks[id];
  };
  const rpc = {
    async dispose() {
      await ipc?.dispose();
    },
    invoke(method, ...params) {
      return invokeHelper(callbacks, ipc, method, params, false);
    },
    invokeAndTransfer(method, ...params) {
      return invokeHelper(callbacks, ipc, method, params, true);
    },
    // @ts-ignore
    ipc,
    /**
     * @deprecated
     */
    send(method, ...params) {
      const message = create$s(method, params);
      ipc.send(message);
    }
  };
  return rpc;
};
const requiresSocket = () => {
  return false;
};
const preparePrettyError = error => {
  return error;
};
const logError = () => {
  // handled by renderer worker
};
const handleMessage = event => {
  const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
  const actualExecute = event?.target?.execute || execute;
  return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError, actualRequiresSocket);
};
const handleIpc = ipc => {
  if ('addEventListener' in ipc) {
    ipc.addEventListener('message', handleMessage);
  } else if ('on' in ipc) {
    // deprecated
    ipc.on('message', handleMessage);
  }
};
const listen$1 = async (module, options) => {
  const rawIpc = await module.listen(options);
  if (module.signal) {
    module.signal(rawIpc);
  }
  const ipc = module.wrap(rawIpc);
  return ipc;
};
const create$4 = async ({
  commandMap,
  isMessagePortOpen = true,
  messagePort
}) => {
  // TODO create a commandMap per rpc instance
  register(commandMap);
  const rawIpc = await IpcParentWithMessagePort$1.create({
    isMessagePortOpen,
    messagePort
  });
  const ipc = IpcParentWithMessagePort$1.wrap(rawIpc);
  handleIpc(ipc);
  const rpc = createRpc(ipc);
  messagePort.start();
  return rpc;
};
const create$2$1 = async ({
  commandMap,
  isMessagePortOpen,
  send
}) => {
  const {
    port1,
    port2
  } = new MessageChannel();
  await send(port1);
  return create$4({
    commandMap,
    isMessagePortOpen,
    messagePort: port2
  });
};
const TransferMessagePortRpcParent = {
  __proto__: null,
  create: create$2$1
};
const create$1$1 = async ({
  commandMap
}) => {
  // TODO create a commandMap per rpc instance
  register(commandMap);
  const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
  handleIpc(ipc);
  const rpc = createRpc(ipc);
  return rpc;
};
const WebWorkerRpcClient = {
  __proto__: null,
  create: create$1$1
};
const createMockRpc = ({
  commandMap
}) => {
  const invocations = [];
  const invoke = (method, ...params) => {
    invocations.push([method, ...params]);
    const command = commandMap[method];
    if (!command) {
      throw new Error(`command ${method} not found`);
    }
    return command(...params);
  };
  const mockRpc = {
    invocations,
    invoke,
    invokeAndTransfer: invoke
  };
  return mockRpc;
};

const ToolBar = 'toolbar';

const Button = 1;
const Div = 4;
const Input = 6;
const Text$1 = 12;
const A = 53;
const Select$1 = 63;
const Option$1 = 64;

const Space = 9;
const PageUp = 10;
const PageDown = 11;
const End = 255;
const Home = 12;
const LeftArrow = 13;
const UpArrow = 14;
const RightArrow = 15;
const DownArrow = 16;

const ExtensionHostWorker = 44;
const FileSystemWorker = 209;
const OutputWorker = 7001;
const RendererWorker = 1;

const rpcs = Object.create(null);
const set$5 = (id, rpc) => {
  rpcs[id] = rpc;
};
const get$1 = id => {
  return rpcs[id];
};
const remove = id => {
  delete rpcs[id];
};

/* eslint-disable  @typescript-eslint/explicit-function-return-type */
const create$2 = rpcId => {
  return {
    async dispose() {
      const rpc = get$1(rpcId);
      await rpc.dispose();
    },
    // @ts-ignore
    invoke(method, ...params) {
      const rpc = get$1(rpcId);
      // @ts-ignore
      return rpc.invoke(method, ...params);
    },
    // @ts-ignore
    invokeAndTransfer(method, ...params) {
      const rpc = get$1(rpcId);
      // @ts-ignore
      return rpc.invokeAndTransfer(method, ...params);
    },
    registerMockRpc(commandMap) {
      const mockRpc = createMockRpc({
        commandMap
      });
      set$5(rpcId, mockRpc);
      // @ts-ignore
      mockRpc[Symbol.dispose] = () => {
        remove(rpcId);
      };
      // @ts-ignore
      return mockRpc;
    },
    set(rpc) {
      set$5(rpcId, rpc);
    }
  };
};

const {
  invoke: invoke$3,
  set: set$4
} = create$2(ExtensionHostWorker);

const ExtensionHost = {
  __proto__: null,
  invoke: invoke$3,
  set: set$4
};

const {
  invoke: invoke$2,
  set: set$3
} = create$2(FileSystemWorker);
const readFile = async uri => {
  return invoke$2('FileSystem.readFile', uri);
};
const writeFile = async (uri, content) => {
  return invoke$2('FileSystem.writeFile', uri, content);
};
const watchFile = async (watchId, uri, rpcId) => {
  await invoke$2('FileSystem.watchFile', watchId, uri, rpcId);
};
const unwatchFile = async watchId => {
  await invoke$2('FileSystem.unwatchFile', watchId);
};

const {
  invoke: invoke$1,
  invokeAndTransfer,
  set: set$2
} = create$2(RendererWorker);
const sendMessagePortToFileSystemWorker$1 = async (port, rpcId) => {
  const command = 'FileSystem.handleMessagePort';
  // @ts-ignore
  await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToFileSystemWorker', port, command, rpcId);
};
const sendMessagePortToExtensionHostWorker = async (port, rpcId = 0) => {
  const command = 'HandleMessagePort.handleMessagePort2';
  await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToExtensionHostWorker', port, command, rpcId);
};
const activateByEvent = (event, assetDir, platform) => {
  return invoke$1('ExtensionHostManagement.activateByEvent', event, assetDir, platform);
};
const showSaveFilePicker = async () => {
  // @ts-ignore
  return invoke$1('FilePicker.showSaveFilePicker');
};
const getLogsDir$1 = async () => {
  // @ts-ignore
  return invoke$1('PlatformPaths.getLogsDir');
};

const toCommandId = key => {
  const dotIndex = key.indexOf('.');
  return key.slice(dotIndex + 1);
};
const create$1 = () => {
  const states = Object.create(null);
  const commandMapRef = {};
  return {
    get(uid) {
      return states[uid];
    },
    set(uid, oldState, newState) {
      states[uid] = {
        oldState,
        newState
      };
    },
    dispose(uid) {
      delete states[uid];
    },
    getKeys() {
      return Object.keys(states).map(key => {
        return Number.parseInt(key);
      });
    },
    clear() {
      for (const key of Object.keys(states)) {
        delete states[key];
      }
    },
    wrapCommand(fn) {
      const wrapped = async (uid, ...args) => {
        const {
          oldState,
          newState
        } = states[uid];
        const newerState = await fn(newState, ...args);
        if (oldState === newerState || newState === newerState) {
          return;
        }
        const latest = states[uid];
        states[uid] = {
          oldState: latest.oldState,
          newState: newerState
        };
      };
      return wrapped;
    },
    wrapGetter(fn) {
      const wrapped = (uid, ...args) => {
        const {
          newState
        } = states[uid];
        return fn(newState, ...args);
      };
      return wrapped;
    },
    diff(uid, modules, numbers) {
      const {
        oldState,
        newState
      } = states[uid];
      const diffResult = [];
      for (let i = 0; i < modules.length; i++) {
        const fn = modules[i];
        if (!fn(oldState, newState)) {
          diffResult.push(numbers[i]);
        }
      }
      return diffResult;
    },
    getCommandIds() {
      const keys = Object.keys(commandMapRef);
      const ids = keys.map(toCommandId);
      return ids;
    },
    registerCommands(commandMap) {
      Object.assign(commandMapRef, commandMap);
    }
  };
};
const terminate = () => {
  globalThis.close();
};

const getTextFromParts = parts => {
  let result = '';
  for (const part of parts) {
    result += part.value;
  }
  return result;
};
const filterItems = (items, filterValue) => {
  if (!filterValue) {
    return items;
  }
  return items.filter(parts => getTextFromParts(parts).includes(filterValue));
};

const isFileNotFoundError = error => {
  return error?.message?.includes('File not found') ?? false;
};

const RE_URL = /(?:https?:\/\/\S+|file:\/\/\S+)/;
const getLinkMatch = text => {
  const match = text.match(RE_URL);
  return match ? match[0] : null;
};

const Text = 1;
const Link = 2;

const parseLine = line => {
  const parts = [];
  let rest = line;
  while (rest.length > 0) {
    const match = getLinkMatch(rest);
    if (!match) {
      if (rest) {
        parts.push({
          type: Text,
          value: rest
        });
      }
      break;
    }
    const index = rest.indexOf(match);
    if (index > 0) {
      parts.push({
        type: Text,
        value: rest.slice(0, index)
      });
    }
    parts.push({
      type: Link,
      value: match
    });
    rest = rest.slice(index + match.length);
  }
  if (parts.length === 0) {
    return [{
      type: Text,
      value: ''
    }];
  }
  return parts;
};

const loadLines = async uri => {
  try {
    // TODO use log stream, updating the output when the file is changed
    const content = await readFile(uri);
    const lines = content.split('\n').map(parseLine);
    return {
      code: 0,
      error: '',
      lines
    };
  } catch (error) {
    if (isFileNotFoundError(error)) {
      return {
        code: 1,
        error: 'log file not found',
        lines: []
      };
    }
    return {
      code: 2,
      error: String(error),
      lines: []
    };
  }
};

const clear = async state => {
  const {
    filterValue,
    options,
    selectedOption
  } = state;
  // TODO make uri a property of state to make the code simpler
  const option = options.find(option => option.id === selectedOption);
  if (!option) {
    return state;
  }
  const {
    uri
  } = option;
  await writeFile(uri, '');
  const {
    code,
    error,
    lines
  } = await loadLines(uri);
  const filteredItems = filterItems(lines, filterValue);
  return {
    ...state,
    error,
    errorCode: code,
    filteredItems,
    listItems: lines
  };
};

const closeFindWidget = async state => {
  // TODO
  return {
    ...state
  };
};

const User = 1;
const Script = 2;

const {
  get,
  getCommandIds,
  getKeys,
  registerCommands,
  set: set$1,
  wrapCommand,
  wrapGetter
} = create$1();

const create = (id, uri, x, y, width, height, platform, parentId) => {
  number(parentId);
  const state = {
    buttons: [],
    collapsedUris: [],
    error: '',
    errorCode: 0,
    filteredItems: [],
    filterValue: '',
    focusedIndex: -2,
    height,
    inputSource: User,
    itemHeight: 22,
    listItems: [],
    logLevel: 0,
    maxLineY: 0,
    message: '',
    minLineY: 0,
    options: [],
    parentId,
    platform,
    scrollLockEnabled: false,
    selectedOption: '',
    smallWidthBreakPoint: 650,
    uid: id,
    uri,
    watchId: 0,
    width,
    workspaceUri: '',
    x,
    y
  };
  set$1(id, state, state);
};

const isEqual$2 = (oldState, newState) => {
  return newState.inputSource === User || oldState.filterValue === newState.filterValue;
};

const isEqual$1 = (oldState, newState) => {
  return oldState.selectedOption === newState.selectedOption && oldState.listItems === newState.listItems && oldState.filteredItems === newState.filteredItems;
};

const isEqual = (oldState, newState) => {
  return oldState.selectedOption === newState.selectedOption;
};

const RenderItems = 1;
const RenderFilterValue = 2;
const RenderSelectedItem = 3;

const modules = [isEqual$1, isEqual$2, isEqual];
const numbers = [RenderItems, RenderFilterValue, RenderSelectedItem];

const diff = (oldState, newState) => {
  const diffResult = [];
  for (let i = 0; i < modules.length; i++) {
    const fn = modules[i];
    if (!fn(oldState, newState)) {
      diffResult.push(numbers[i]);
    }
  }
  return diffResult;
};

const diff2 = uid => {
  const {
    newState,
    oldState
  } = get(uid);
  const diffResult = diff(oldState, newState);
  return diffResult;
};

const disableScrollLock = async state => {
  const {
    scrollLockEnabled
  } = state;
  if (!scrollLockEnabled) {
    return state;
  }
  return {
    ...state,
    scrollLockEnabled: false
  };
};

const enableScrollLock = async state => {
  const {
    scrollLockEnabled
  } = state;
  if (scrollLockEnabled) {
    return state;
  }
  return {
    ...state,
    scrollLockEnabled: true
  };
};

const focusIndex = (state, index) => {
  return {
    ...state,
    focusedIndex: index
  };
};

const mergeClassNames = (...classNames) => {
  return classNames.filter(Boolean).join(' ');
};

const text = data => {
  return {
    childCount: 0,
    text: data,
    type: Text$1
  };
};

const FocusProblems = 19;

const getKeyBindings = () => {
  return [{
    command: 'Problems.focusNext',
    key: DownArrow,
    when: FocusProblems
  }, {
    command: 'Problems.focusPrevious',
    key: UpArrow,
    when: FocusProblems
  }, {
    command: 'Problems.focusFirst',
    key: Home,
    when: FocusProblems
  }, {
    command: 'Problems.focusFirst',
    key: PageUp,
    when: FocusProblems
  }, {
    command: 'Problems.focusLast',
    key: PageDown,
    when: FocusProblems
  }, {
    command: 'Problems.focusLast',
    key: End,
    when: FocusProblems
  }, {
    command: 'Problems.selectCurrent',
    key: Space,
    when: FocusProblems
  }, {
    command: 'Problems.focusFirst',
    key: Home,
    when: FocusProblems
  }, {
    command: 'Problems.focusLast',
    key: End,
    when: FocusProblems
  }, {
    command: 'Problems.handleArrowLeft',
    key: LeftArrow,
    when: FocusProblems
  }, {
    command: 'Problems.handleArrowRight',
    key: RightArrow,
    when: FocusProblems
  }];
};

const Filter$2 = 'filter';
const Output$1 = 'output';
const MainProcess = 'MainProcess';
const SharedProcess = 'SharedProcess';
const Clear = 'Clear';
const Settings$1 = 'Settings';
const ScrollLock = 'ScrollLock';

const noop = async state => {
  return state;
};
const getClickHandler = name => {
  switch (name) {
    case Clear:
      return clear;
    default:
      return noop;
  }
};

const handleButtonClick = async (state, name) => {
  const fn = getClickHandler(name);
  return fn(state);
};

const handleContextMenu = async (state, x, y, button) => {
  // TODO open context menu
  return state;
};

const handleData = async state => {
  // TODO
  return {
    ...state
  };
};

const handleError = async state => {
  // TODO
  return {
    ...state
  };
};

const handleFilterInput = async (state, value, inputSource = User) => {
  const {
    listItems
  } = state;
  const filteredItems = filterItems(listItems, value);
  return {
    ...state,
    filteredItems: filteredItems,
    filterValue: value,
    inputSource
  };
};

const createWatchId = () => {
  const watchId = Math.random();
  return watchId;
};

const handleFileChange = async watchId => {
  const keys = getKeys();
  for (const key of keys) {
    const instance = get(key);
    if (instance.newState.watchId === watchId) {
      // @ts-ignore
      await invoke$1('Output.refresh');
    }
  }
};

const watchCallbacks = Object.create(null);
const registerWatchCallback = (id, fn) => {
  watchCallbacks[id] = fn;
};
const executeWatchCallBack = id => {
  watchCallbacks[id](id);
};
const unregisterWatchCallback = id => {
  delete watchCallbacks[id];
};

const setupChangeListener = async (oldWatchId, newWatchId, uri) => {
  try {
    if (oldWatchId) {
      unregisterWatchCallback(oldWatchId);
      await unwatchFile(oldWatchId);
    }
    // TODO dispose old watcher
    const rpcId = OutputWorker;
    registerWatchCallback(newWatchId, handleFileChange);
    await watchFile(newWatchId, uri, rpcId);
  } catch {
    // ignore
  }
};

const selectChannel = async (state, id) => {
  const {
    filterValue,
    options,
    watchId
  } = state;
  const matchingOption = options.find(option => option.id === id);
  if (!matchingOption) {
    return state;
  }
  // TODO potential race condition when switching output channels fast
  const {
    code,
    error,
    lines
  } = await loadLines(matchingOption.uri);

  // TODO memory leak and race condition, need to dispose file watcher of previous uri
  const newWatchId = createWatchId();
  await setupChangeListener(watchId, newWatchId, matchingOption.uri);
  const filteredItems = filterItems(lines, filterValue);
  return {
    ...state,
    error,
    errorCode: code,
    filteredItems,
    listItems: lines,
    selectedOption: id,
    watchId: newWatchId
  };
};

const handleSelect = async (state, id) => {
  return selectChannel(state, id);
};

const sendMessagePortToExtensionHostWorker2 = async port => {
  await sendMessagePortToExtensionHostWorker(port);
};

const createExtensionHostRpc = async () => {
  try {
    const rpc = await TransferMessagePortRpcParent.create({
      commandMap: {},
      send: sendMessagePortToExtensionHostWorker2
    });
    return rpc;
  } catch (error) {
    throw new VError(error, `Failed to create extension host rpc`);
  }
};

const {
  invoke,
  set
} = ExtensionHost;

const initializeExtensionHost = async () => {
  const extensionHostRpc = await createExtensionHostRpc();
  set(extensionHostRpc);
};

const sendMessagePortToFileSystemWorker = async port => {
  await sendMessagePortToFileSystemWorker$1(port, OutputWorker);
};

const createFileSystemWorkerRpc = async () => {
  try {
    const rpc = await TransferMessagePortRpcParent.create({
      commandMap: {},
      send: sendMessagePortToFileSystemWorker
    });
    return rpc;
  } catch (error) {
    throw new VError(error, `Failed to create file system worker rpc`);
  }
};

const initializeFileSystemWorker = async () => {
  const rpc = await createFileSystemWorkerRpc();
  set$3(rpc);
};

const initialize = async () => {
  await Promise.all([initializeFileSystemWorker(), initializeExtensionHost()]);
};

const Web = 1;

const getSelectedItem = (selectedOption, platform) => {
  if (selectedOption) {
    return selectedOption;
  }
  if (platform === Web) {
    return '';
  }
  return MainProcess;
};

const emptyObject = {};
const RE_PLACEHOLDER = /\{(PH\d+)\}/g;
const i18nString = (key, placeholders = emptyObject) => {
  if (placeholders === emptyObject) {
    return key;
  }
  const replacer = (match, rest) => {
    return placeholders[rest];
  };
  return key.replaceAll(RE_PLACEHOLDER, replacer);
};

const ClearOutput = 'clear output';
const Filter$1 = 'Filter';
const LogFileNotFound$1 = 'The log file was not found.';
const Settings = 'Settings';
const TurnOffAutoScroll = 'Turn auto scrolling off';

const clearOutput = () => {
  return i18nString(ClearOutput);
};
const turnOffAutoScroll = () => {
  return i18nString(TurnOffAutoScroll);
};
const settings = () => {
  return i18nString(Settings);
};
const logFileNotFound = () => {
  return i18nString(LogFileNotFound$1);
};
const filter = () => {
  return i18nString(Filter$1);
};

const loadButtons = () => {
  return [{
    icon: 'MaskIconClearAll',
    id: Clear,
    label: clearOutput()
  }, {
    icon: 'MaskIconListFlat',
    id: ScrollLock,
    label: turnOffAutoScroll()
  }, {
    icon: 'MaskIconSettingsGear',
    id: Settings$1,
    label: settings()
  }];
};

const error = error => {
  console.error(error);
};

const getExtensionOptions = async () => {
  try {
    // TODO make api more declarative:
    // output channels are registered in extension manifest
    // only downside: it might show channels for extensions that are not active
    // @ts-ignore
    await activateByEvent('onOutput');
    // @ts-ignore
    const channels = await invoke('Output.getEnabledProviders');
    return channels;
  } catch (error$1) {
    error(error$1);
    return [];
  }
};

const getLogsDir = async () => {
  try {
    return await getLogsDir$1();
  } catch {
    return `file:///tmp`;
  }
};

const loadOptions = async platform => {
  const extensionOptions = await getExtensionOptions();
  if (platform === Web) {
    return extensionOptions;
  }
  const logsFolderUri = await getLogsDir();
  return [{
    id: MainProcess,
    label: 'Main Process',
    uri: `${logsFolderUri}/log-main-process.txt`
  }, {
    id: SharedProcess,
    label: 'Shared Process',
    uri: `${logsFolderUri}/log-shared-process.txt`
  }, ...extensionOptions];
};

const getSavedFilterValue = savedState => {
  if (savedState && typeof savedState.filterValue === 'string') {
    return savedState.filterValue;
  }
  return '';
};
const getSavedSelectedOption = savedState => {
  if (savedState && typeof savedState.selectedOption === 'string') {
    return savedState.selectedOption;
  }
  return '';
};
const getSavedScrollLockEnabled = savedState => {
  if (savedState && typeof savedState.scrollLockEnabled === 'boolean') {
    return savedState.scrollLockEnabled;
  }
  return false;
};
const restoreState = savedState => {
  const filterValue = getSavedFilterValue(savedState);
  const selectedOption = getSavedSelectedOption(savedState);
  const scrollLockEnabled = getSavedScrollLockEnabled(savedState);
  return {
    filterValue,
    scrollLockEnabled,
    selectedOption
  };
};

const isString = value => {
  return typeof value === 'string';
};
const getSavedCollapsedUris = savedState => {
  if (savedState && savedState.collapsedUris && Array.isArray(savedState.collapsedUris) && savedState.collapsedUris.every(isString)) {
    return savedState.collapsedUris;
  }
  return [];
};
const getMatchingOpen = (options, id) => {
  return options.find(option => option.id === id) || options[0];
};
const loadContent = async (state, savedState) => {
  const {
    platform,
    watchId
  } = state;
  const collapsedUris = getSavedCollapsedUris(savedState);
  const {
    filterValue,
    scrollLockEnabled,
    selectedOption
  } = restoreState(savedState);
  const selectedId = getSelectedItem(selectedOption, platform);
  const options = await loadOptions(platform);
  const option = getMatchingOpen(options, selectedId);
  if (!option) {
    throw new Error('option not found');
  }
  const {
    uri
  } = option;
  const {
    code,
    error,
    lines
  } = await loadLines(uri);
  const filteredItems = filterItems(lines, filterValue);
  const newWatchId = createWatchId();
  await setupChangeListener(watchId, newWatchId, uri);
  const buttons = loadButtons();
  return {
    ...state,
    buttons,
    collapsedUris,
    error,
    errorCode: code,
    filteredItems,
    filterValue,
    inputSource: Script,
    listItems: lines,
    options,
    scrollLockEnabled,
    selectedOption: selectedId,
    watchId: newWatchId
  };
};

const openFindWidget = async state => {
  // TODO
  return {
    ...state
  };
};

const getActions = state => {
  return [];
};

const refresh = async state => {
  const {
    filterValue,
    options,
    selectedOption
  } = state;
  const matchingOption = options.find(option => option.id === selectedOption);
  if (!matchingOption) {
    return state;
  }
  const {
    code,
    error,
    lines
  } = await loadLines(matchingOption.uri);
  const filteredItems = filterItems(lines, filterValue);
  return {
    ...state,
    error,
    errorCode: code,
    filteredItems,
    listItems: lines
  };
};

const renderFilterValue = (oldState, newState) => {
  return ['Viewlet.setValueByName', Filter$2, newState.filterValue];
};

const Filter = 'Filter';
const IconButton = 'IconButton';
const InputBox = 'InputBox';
const MaskIcon = 'MaskIcon';
const FilterInput = 'FilterInput';
const OutputContent = 'OutputContent';
const Actions = 'Actions';
const Message = 'Message';
const Viewlet = 'Viewlet';
const Output = 'Output';
const Option = 'Option';
const Select = 'Select';
const Error$1 = 'Error';
const Line = 'Line';

const parentNode = {
  childCount: 1,
  className: Line,
  type: Div
};
const getLineDom = parts => {
  const children = [];
  for (const part of parts) {
    if (part.type === Text) {
      children.push(text(part.value));
    } else {
      children.push({
        childCount: 1,
        href: part.value,
        rel: 'noopener noreferrer',
        target: '_blank',
        type: A
      }, text(part.value));
    }
  }
  const lineNode = {
    ...parentNode,
    childCount: children.length
  };
  return [lineNode, ...children];
};

const getContentDom = (lines, error) => {
  if (error) {
    return [];
  }
  return [{
    childCount: lines.length,
    className: OutputContent,
    role: 'log',
    tabIndex: 0,
    type: Div
  }, ...lines.flatMap(getLineDom)];
};

const LogFileNotFound = 1;

const getLogFileNotFoundDom = () => {
  return [{
    childCount: 1,
    className: Message,
    tabIndex: 0,
    type: Div
  }, text(logFileNotFound())];
};

const getErrorDom = (errorCode, error) => {
  if (!error) {
    return [];
  }
  if (errorCode === LogFileNotFound) {
    return getLogFileNotFoundDom();
  }
  return [{
    childCount: 1,
    className: Error$1,
    tabIndex: 0,
    type: Div
  }, text(error)];
};

const getOutputVirtualDom = (lines, errorCode, error) => {
  return [{
    childCount: 1,
    className: mergeClassNames(Viewlet, Output),
    type: Div
  }, ...getContentDom(lines, error), ...getErrorDom(errorCode, error)];
};

const renderItems = (oldState, newState) => {
  const dom = getOutputVirtualDom(newState.filteredItems, newState.errorCode, newState.error);
  return ['Viewlet.setDom2', dom];
};

const renderSelectedItem = (oldState, newState) => {
  const value = newState.selectedOption;
  const name = Output$1;
  return ['Viewlet.setValueByName', name, value];
};

const getRenderer = diffType => {
  switch (diffType) {
    case RenderFilterValue:
      return renderFilterValue;
    case RenderItems:
      return renderItems;
    case RenderSelectedItem:
      return renderSelectedItem;
    default:
      throw new Error('unknown renderer');
  }
};

const applyRender = (oldState, newState, diffResult) => {
  const commands = [];
  for (const item of diffResult) {
    const fn = getRenderer(item);
    commands.push(fn(oldState, newState));
  }
  return commands;
};

const render2 = (uid, diffResult) => {
  const {
    newState,
    oldState
  } = get(uid);
  set$1(uid, newState, newState);
  const commands = applyRender(oldState, newState, diffResult);
  return commands;
};

const HandleBlur = 'handleBlur';
const HandleClearFilterClick = 'handleClearFilterClick';
const HandleContextMenu = 'handleContextMenu';
const HandleFilterInput = 'handleFilterInput';
const HandlePointerDown = 'handlePointerDown';
const HandleSelect = 'handleSelect';
const HandleButtonClick = 'handleButtonClick';

const getActionButtonVirtualDom = button => {
  const {
    icon,
    id,
    label
  } = button;
  return [{
    childCount: 1,
    className: IconButton,
    name: id,
    onClick: HandleButtonClick,
    title: label,
    type: Button
  }, {
    className: mergeClassNames(MaskIcon, icon),
    type: Div
  }];
};

const getActionButtonsVirtualDom = buttons => {
  return buttons.flatMap(getActionButtonVirtualDom);
};

const getFilterVirtualDom = () => {
  const placeholder = filter();
  return [{
    childCount: 1,
    className: Filter,
    type: Div
  }, {
    childCount: 0,
    className: mergeClassNames(InputBox, FilterInput),
    name: Filter$2,
    onInput: HandleFilterInput,
    placeholder,
    type: Input
  }];
};

const getOptionVirtualDom = option => {
  const {
    id,
    label
  } = option;
  return [{
    childCount: 1,
    className: Option,
    type: Option$1,
    value: id
  }, text(label)];
};

const getSelectVirtualDom = options => {
  return [{
    childCount: options.length,
    className: Select,
    name: Output$1,
    onChange: HandleSelect,
    type: Select$1
  }, ...options.flatMap(getOptionVirtualDom)];
};

const getChildCount = buttonsLength => {
  const selectLength = 1;
  const filterCount = 1;
  return buttonsLength + filterCount + selectLength;
};
const getActionsVirtualDom = (options, buttons) => {
  const childCount = getChildCount(buttons.length);
  return [{
    childCount,
    className: Actions,
    role: ToolBar,
    type: Div
  }, ...getFilterVirtualDom(), ...getSelectVirtualDom(options), ...getActionButtonsVirtualDom(buttons)];
};

const renderActions = state => {
  const {
    buttons,
    options
  } = state;
  const dom = getActionsVirtualDom(options, buttons);
  return dom;
};

const renderEventListeners = () => {
  return [{
    name: HandleBlur,
    params: ['handleBlur']
  }, {
    name: HandleButtonClick,
    params: ['handleButtonClick', 'event.target.name']
  }, {
    name: HandleSelect,
    params: ['handleSelect', 'event.target.value']
  }, {
    name: HandleContextMenu,
    params: ['handleContextMenu', 'event.clientX', 'event.clientY'],
    preventDefault: true
  }, {
    name: HandleFilterInput,
    // @ts-ignore
    params: ['handleFilterInput', 'event.target.value', User]
  }, {
    name: HandleClearFilterClick,
    params: ['clearFilter']
  }, {
    name: HandlePointerDown,
    params: ['handleClickAt', 'event.clientX', 'event.clientY']
  }];
};

const resize = (state, dimensions) => {
  return {
    ...state,
    ...dimensions
  };
};

const serializeLinePart = part => {
  return part.value;
};
const serializeLineParts = parts => {
  return parts.map(serializeLinePart).join('');
};
const serializeLines = lines => {
  return lines.map(serializeLineParts).join('\n');
};

const saveOutputAs = async state => {
  const uri = await showSaveFilePicker();
  if (!uri) {
    return state;
  }
  const {
    listItems
  } = state;
  const content = serializeLines(listItems);
  await writeFile(uri, content);
  // TODO if error occurs, show error dialog
  return state;
};

const saveState = state => {
  const {
    collapsedUris,
    filterValue,
    scrollLockEnabled,
    selectedOption
  } = state;
  return {
    collapsedUris,
    filterValue,
    scrollLockEnabled,
    selectedOption
  };
};

const setLogLevel = async (state, logLevel) => {
  return {
    ...state,
    logLevel
  };
};

const setOutputChannel = async state => {
  // TODO
  return {
    ...state
  };
};

const commandMap = {
  'Output.clear': wrapCommand(clear),
  'Output.closeFindWidget': wrapCommand(closeFindWidget),
  'Output.create': create,
  'Output.diff2': diff2,
  'Output.disableScrollLock': wrapCommand(disableScrollLock),
  'Output.enableScrollLock': wrapCommand(enableScrollLock),
  'Output.executeWatchCallback': executeWatchCallBack,
  'Output.focusIndex': wrapCommand(focusIndex),
  'Output.getActions': getActions,
  'Output.getCommandIds': getCommandIds,
  'Output.getKeyBindings': getKeyBindings,
  'Output.handleButtonClick': wrapCommand(handleButtonClick),
  'Output.handleContextMenu': wrapCommand(handleContextMenu),
  'Output.handleData': wrapCommand(handleData),
  'Output.handleError': wrapCommand(handleError),
  'Output.handleFilterInput': wrapCommand(handleFilterInput),
  'Output.handleSelect': wrapCommand(handleSelect),
  'Output.initialize': initialize,
  'Output.loadContent2': wrapCommand(loadContent),
  'Output.openFindWidget': wrapCommand(openFindWidget),
  'Output.refresh': wrapCommand(refresh),
  'Output.render2': render2,
  'Output.renderActions': wrapGetter(renderActions),
  'Output.renderEventListeners': renderEventListeners,
  'Output.resize': resize,
  'Output.saveAs': wrapCommand(saveOutputAs),
  'Output.saveState': wrapGetter(saveState),
  'Output.selectChannel': wrapCommand(selectChannel),
  'Output.setLogLevel': setLogLevel,
  'Output.setOutputChannel': wrapCommand(setOutputChannel),
  'Output.terminate': terminate
};

const commandMapRef = {};

const listen = async () => {
  registerCommands(commandMap);
  Object.assign(commandMapRef, commandMap);
  const rpc = await WebWorkerRpcClient.create({
    commandMap: commandMapRef
  });
  set$2(rpc);
};

const main = async () => {
  await listen();
};

main();
