'use strict';

var ConfigSources = require('./sources/ConfigSources.cjs.js');
require('@backstage/errors');
require('chokidar');
require('fs-extra');
require('path');
require('yaml');
require('@backstage/types');
require('lodash/isEqual');

async function loadConfig(options) {
  const source = ConfigSources.ConfigSources.default({
    substitutionFunc: options.experimentalEnvFunc,
    remote: options.remote && {
      reloadInterval: { seconds: options.remote.reloadIntervalSeconds }
    },
    watch: Boolean(options.watch),
    rootDir: options.configRoot,
    argv: options.configTargets.flatMap((t) => [
      "--config",
      "url" in t ? t.url : t.path
    ])
  });
  return new Promise((resolve, reject) => {
    async function loadConfigReaderLoop() {
      let loaded = false;
      try {
        const abortController = new AbortController();
        options.watch?.stopSignal?.then(() => abortController.abort());
        for await (const { configs } of source.readConfigData({
          signal: abortController.signal
        })) {
          if (loaded) {
            options.watch?.onChange(configs);
          } else {
            resolve({ appConfigs: configs });
            loaded = true;
            if (options.watch) {
              options.watch.stopSignal?.then(() => abortController.abort());
            } else {
              abortController.abort();
            }
          }
        }
      } catch (error) {
        if (loaded) {
          console.error(`Failed to reload configuration, ${error}`);
        } else {
          reject(error);
        }
      }
    }
    loadConfigReaderLoop();
  });
}

exports.loadConfig = loadConfig;
//# sourceMappingURL=loader.cjs.js.map
