'use strict';

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

const Asset = require('../Asset');
const localRequire = require('../utils/localRequire');

class TypeScriptAsset extends Asset {
  constructor(name, pkg, options) {
    super(name, pkg, options);
    this.type = 'js';
  }

  generate() {
    var _this = this;

    return _asyncToGenerator(function* () {
      // require typescript, installed locally in the app
      let typescript = yield localRequire('typescript', _this.name);
      let transpilerOptions = {
        compilerOptions: {
          module: typescript.ModuleKind.CommonJS,
          jsx: typescript.JsxEmit.Preserve,

          // it brings the generated output from TypeScript closer to that generated by Babel
          // see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html
          esModuleInterop: true
        },
        fileName: _this.relativeName
      };

      let tsconfig = yield _this.getConfig(['tsconfig.json']);

      // Overwrite default if config is found
      if (tsconfig) {
        transpilerOptions.compilerOptions = Object.assign(transpilerOptions.compilerOptions, tsconfig.compilerOptions);
      }
      transpilerOptions.compilerOptions.noEmit = false;
      transpilerOptions.compilerOptions.sourceMap = _this.options.sourceMaps;

      // Transpile Module using TypeScript and parse result as ast format through babylon
      let transpiled = typescript.transpileModule(_this.contents, transpilerOptions);
      let sourceMap = transpiled.sourceMapText;

      if (sourceMap) {
        sourceMap = JSON.parse(sourceMap);
        sourceMap.sources = [_this.relativeName];
        sourceMap.sourcesContent = [_this.contents];

        // Remove the source map URL
        let content = transpiled.outputText;
        transpiled.outputText = content.substring(0, content.lastIndexOf('//# sourceMappingURL'));
      }

      return [{
        type: 'js',
        value: transpiled.outputText,
        sourceMap
      }];
    })();
  }
}

module.exports = TypeScriptAsset;