"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
require("core-js/modules/es.array.iterator.js");
require("core-js/modules/es.promise.js");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.BundleUiTask = exports.BUNDLE_UI_TASK_NAME = exports.BUNDLE_UI_HASH_FILENAME = exports.BUNDLE_UI_DIR = void 0;
function _defineProperty2() {
  const data = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  _defineProperty2 = function () {
    return data;
  };
  return data;
}
function _path() {
  const data = require("path");
  _path = function () {
    return data;
  };
  return data;
}
function _fs() {
  const data = require("fs");
  _fs = function () {
    return data;
  };
  return data;
}
function _ui() {
  const data = require("@teambit/ui");
  _ui = function () {
    return data;
  };
  return data;
}
const BUNDLE_UI_TASK_NAME = 'BundleUI';
exports.BUNDLE_UI_TASK_NAME = BUNDLE_UI_TASK_NAME;
const BUNDLE_UI_DIR = 'ui-bundle';
exports.BUNDLE_UI_DIR = BUNDLE_UI_DIR;
const BUNDLE_UI_HASH_FILENAME = '.hash';
exports.BUNDLE_UI_HASH_FILENAME = BUNDLE_UI_HASH_FILENAME;
class BundleUiTask {
  constructor(ui, logger) {
    this.ui = ui;
    this.logger = logger;
    (0, _defineProperty2().default)(this, "aspectId", 'teambit.ui-foundation/ui');
    (0, _defineProperty2().default)(this, "name", BUNDLE_UI_TASK_NAME);
    (0, _defineProperty2().default)(this, "location", 'end');
  }
  async execute(context) {
    const capsule = context.capsuleNetwork.seedersCapsules.find(c => c.component.id.toStringWithoutVersion() === _ui().UIAspect.id);
    if (!capsule) {
      return {
        componentsResults: []
      };
    }
    const outputPath = (0, _path().join)(capsule.path, BundleUiTask.getArtifactDirectory());
    this.logger.info(`Generating UI bundle at ${outputPath}...`);
    try {
      await this.ui.build(undefined, outputPath);
      await this.generateHash(outputPath);
    } catch (error) {
      this.logger.error('Generating UI bundle failed');
      throw new Error('Generating UI bundle failed');
    }
    const artifacts = BundleUiTask.getArtifactDef();
    return {
      componentsResults: [],
      artifacts
    };
  }
  async generateHash(outputPath) {
    const maybeUiRoot = this.ui.getUi();
    if (!maybeUiRoot) throw new Error('no uiRoot found');
    const [, uiRoot] = maybeUiRoot;
    const hash = await this.ui.createBundleUiHash(uiRoot);
    if (!(0, _fs().existsSync)(outputPath)) (0, _fs().mkdirSync)(outputPath);
    (0, _fs().writeFileSync)((0, _path().join)(outputPath, BUNDLE_UI_HASH_FILENAME), hash);
  }
  static getArtifactDirectory() {
    return (0, _path().join)('artifacts', BUNDLE_UI_DIR);
  }
  static getArtifactDef() {
    return [{
      name: BUNDLE_UI_DIR,
      globPatterns: ['**'],
      rootDir: BundleUiTask.getArtifactDirectory()
    }];
  }
}
exports.BundleUiTask = BundleUiTask;

//# sourceMappingURL=bundle-ui.task.js.map