"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _path = _interopRequireDefault(require("path"));

var _fs = _interopRequireDefault(require("fs"));

var _worker = require("threads/worker");

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

var babel = require('@babel/core');

function getCustomConfig() {
  var customConfigFile = _path.default.resolve(process.cwd(), '.builder');

  if (_fs.default.existsSync(customConfigFile)) {
    try {
      return JSON.parse(_fs.default.readFileSync(customConfigFile, 'utf-8'));
    } catch (error) {
      console.log(`Error while parsing custom config > ${error}`);
      return null;
    }
  }
}

function getBabelConfig() {
  var config = {
    presets: [[require.resolve('@babel/preset-typescript'), {}], [require.resolve('@babel/preset-env'), {
      targets: {
        node: 6
      }
    }]],
    plugins: [require.resolve('@babel/plugin-transform-runtime'), require.resolve('@babel/plugin-proposal-export-default-from'), require.resolve('@babel/plugin-proposal-do-expressions'), require.resolve('@babel/plugin-proposal-class-properties')]
  };
  var customConfig = getCustomConfig();

  if (customConfig) {
    config = _objectSpread(_objectSpread({}, config), customConfig);
  }

  return config;
}

(0, _worker.expose)({
  transform: function transform(content, filename) {
    return new Promise(function (resolve, reject) {
      var babelConfig = getBabelConfig();
      babel.transform(content, _objectSpread(_objectSpread({}, babelConfig), {}, {
        filename: filename
      }), function (err, res) {
        if (err) {
          return reject(err);
        }

        return resolve(res);
      });
    });
  }
});