"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = start;

function _react() {
  const data = _interopRequireDefault(require("react"));

  _react = function _react() {
    return data;
  };

  return data;
}

function _child_process() {
  const data = require("child_process");

  _child_process = function _child_process() {
    return data;
  };

  return data;
}

var _send = _interopRequireWildcard(require("./send"));

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const usedPorts = [];
let CURRENT_PORT = undefined;

function start(scriptPath, opts = {}) {
  const onMessage = opts.onMessage;
  const execArgv = process.execArgv.slice(0);
  const inspectArgvIndex = execArgv.findIndex(argv => argv.includes('--inspect-brk'));

  if (inspectArgvIndex > -1) {
    const inspectArgv = execArgv[inspectArgvIndex];
    execArgv.splice(inspectArgvIndex, 1, inspectArgv.replace(/--inspect-brk=(.*)/, (match, s1) => {
      let port;

      try {
        port = parseInt(s1) + 1;
      } catch (e) {
        port = 9230; // node default inspect port plus 1.
      }

      if (usedPorts.includes(port)) {
        port += 1;
      }

      usedPorts.push(port);
      return `--inspect-brk=${port}`;
    }));
  } // set port to env when current port has value


  if (CURRENT_PORT) {
    process.env.PORT = CURRENT_PORT;
  }

  const child = (0, _child_process().fork)(scriptPath, process.argv.slice(2), {
    execArgv
  });
  child.on('message', data => {
    const type = data && data.type || null;

    if (type === _send.RESTART) {
      child.kill();
      start(scriptPath);
    } else if (type === 'UPDATE_PORT') {
      // set current used port
      CURRENT_PORT = data.port;
    }

    if (onMessage) {
      onMessage(data);
    }

    (0, _send.default)(data);
  });
  return child;
}