"use strict";

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

var _debug = _interopRequireDefault(require("debug"));

var _path = require("./path");

var _capabilities = require("../core/capabilities");

var _commandTree = require("../core/command-tree");

var _badges = require("../webapp/views/registrar/badges");

var _modes = require("../webapp/views/registrar/modes");

var _registrar = require("../session/registrar");

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

/*
 * Copyright 2017-2020 IBM Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var __awaiter = void 0 && (void 0).__awaiter || function (thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function (resolve) {
      resolve(value);
    });
  }

  return new (P || (P = Promise))(function (resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }

    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }

    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }

    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};

const debug = (0, _debug.default)('core/plugins/preloader');
debug('loading');

class PreloaderRegistrarImpl extends _commandTree.ImplForPlugins {
  // why does eslint consider this to be a useless constructor??
  // eslint-disable-next-line no-useless-constructor
  constructor(plugin) {
    super(plugin);
  }

  registerMode(registration) {
    (0, _modes.registerSidecarMode)(registration);
  }

  registerModes(...registrations) {
    registrations.forEach(_ => this.registerMode(_));
  }

  registerBadge(registration) {
    (0, _badges.registerSidecarBadge)(registration);
  }

  registerBadges(...registrations) {
    registrations.forEach(_ => this.registerBadge(_));
  }
  /** session initializers */


  registerSessionInitializer(init) {
    (0, _registrar.registerSessionInitializer)(init);
  }

}
/**
 * This module allows for plugins to register themselves to be
 * preloaded at startup, rather than in response to a user command
 *
 */


var _default = prescan => __awaiter(void 0, void 0, void 0, function* () {
  debug('init');
  const jobs = Promise.all(prescan.preloads.map(module => __awaiter(void 0, void 0, void 0, function* () {
    // extends the capabilities of Kui
    try {
      debug('preloading capabilities.1 %s', module.path);
      const registrationRef = module.path.charAt(0) === '/' ? yield Promise.resolve().then(() => require(`${
      /* webpackIgnore: true */
      module.path}`)) : (0, _capabilities.isHeadless)() ? yield Promise.resolve().then(() => require(`${
      /* webpackIgnore: true */
      (0, _path.mainPath)(module.path)}`)) : module.route === 'client' ? require(
      /* webpackMode: "lazy" */
      '@kui-shell/client/' + 'mdist/preload') : yield Promise.resolve().then(() => require(`${
      /* webpackMode: "lazy" */
      '@kui-shell/plugin-' + (0, _path.webpackPath)(module.route) + '/mdist/preload'}`));
      debug('preloading capabilities.2 %s', module.path);
      const registration = registrationRef.registerCapability;

      if (registration && typeof registration === 'function') {
        yield registration(new PreloaderRegistrarImpl(module.route));
        debug('registered capabilities %s', module.path);
      } else {
        debug('no registered capabilities %s', module.path);
      }
    } catch (err) {
      debug('error registering capabilities', module.path, err);
      console.error(err);
    }
  }))).then(() => __awaiter(void 0, void 0, void 0, function* () {
    yield Promise.resolve().then(() => require('../core/events')).then(({
      eventBus
    }) => {
      eventBus.once('/tab/new', tab => {
        if (tab._kui_session === undefined) {
          tab._kui_session = Promise.resolve();
        }
      });
    });
  })).then(() => Promise.all(prescan.preloads.map(module => __awaiter(void 0, void 0, void 0, function* () {
    // FIXME to support field-installed plugin paths
    try {
      debug('preloading misc %s', module.path); // NOTE ON @kui-shell relativization: this is important so that
      // webpack can be isntructed to pull in the plugins into the
      // build see the corresponding NOTE in ./assembler.ts and
      // ./plugins.ts

      const registrationRef = module.path.charAt(0) === '/' ? yield Promise.resolve().then(() => require(`${
      /* webpackIgnore: true */
      module.path}`)) : (0, _capabilities.isHeadless)() ? yield Promise.resolve().then(() => require(`${
      /* webpackIgnore: true */
      (0, _path.mainPath)(module.path)}`)) : module.route === 'client' ? require(
      /* webpackMode: "lazy" */
      '@kui-shell/client/' + 'mdist/preload') : yield Promise.resolve().then(() => require(`${
      /* webpackMode: "lazy" */
      '@kui-shell/plugin-' + (0, _path.webpackPath)(module.route) + '/mdist/preload'}`));
      const registration = registrationRef.default || registrationRef;

      if (registration && typeof registration === 'function') {
        yield registration(new PreloaderRegistrarImpl(module.route));
      }

      debug('done preloading %s', module.path);
    } catch (err) {
      debug('error invoking preload', module.path, err);
      console.error(err);
    }
  }))));

  try {
    yield jobs;
  } catch (err) {
    console.error(err);
  }

  debug('done');
});

exports.default = _default;