@backstage/config-loader 1.2.0 → 1.3.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -2,16 +2,19 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var errors = require('@backstage/errors');
6
- var yaml = require('yaml');
7
- var path = require('path');
8
5
  var Ajv = require('ajv');
9
6
  var mergeAllOf = require('json-schema-merge-allof');
10
7
  var traverse = require('json-schema-traverse');
11
8
  var config = require('@backstage/config');
12
9
  var fs = require('fs-extra');
10
+ var path = require('path');
11
+ var errors = require('@backstage/errors');
12
+ var parseArgs = require('minimist');
13
13
  var chokidar = require('chokidar');
14
+ var yaml = require('yaml');
15
+ var isEqual = require('lodash/isEqual');
14
16
  var fetch = require('node-fetch');
17
+ var cliCommon = require('@backstage/cli-common');
15
18
 
16
19
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
17
20
 
@@ -33,239 +36,16 @@ function _interopNamespace(e) {
33
36
  return Object.freeze(n);
34
37
  }
35
38
 
36
- var yaml__default = /*#__PURE__*/_interopDefaultLegacy(yaml);
37
39
  var Ajv__default = /*#__PURE__*/_interopDefaultLegacy(Ajv);
38
40
  var mergeAllOf__default = /*#__PURE__*/_interopDefaultLegacy(mergeAllOf);
39
41
  var traverse__default = /*#__PURE__*/_interopDefaultLegacy(traverse);
40
42
  var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
43
+ var parseArgs__default = /*#__PURE__*/_interopDefaultLegacy(parseArgs);
41
44
  var chokidar__default = /*#__PURE__*/_interopDefaultLegacy(chokidar);
45
+ var yaml__default = /*#__PURE__*/_interopDefaultLegacy(yaml);
46
+ var isEqual__default = /*#__PURE__*/_interopDefaultLegacy(isEqual);
42
47
  var fetch__default = /*#__PURE__*/_interopDefaultLegacy(fetch);
43
48
 
44
- const ENV_PREFIX = "APP_CONFIG_";
45
- const CONFIG_KEY_PART_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z][a-z0-9]*)*$/i;
46
- function readEnvConfig(env) {
47
- var _a;
48
- let data = void 0;
49
- for (const [name, value] of Object.entries(env)) {
50
- if (!value) {
51
- continue;
52
- }
53
- if (name.startsWith(ENV_PREFIX)) {
54
- const key = name.replace(ENV_PREFIX, "");
55
- const keyParts = key.split("_");
56
- let obj = data = data != null ? data : {};
57
- for (const [index, part] of keyParts.entries()) {
58
- if (!CONFIG_KEY_PART_PATTERN.test(part)) {
59
- throw new TypeError(`Invalid env config key '${key}'`);
60
- }
61
- if (index < keyParts.length - 1) {
62
- obj = obj[part] = (_a = obj[part]) != null ? _a : {};
63
- if (typeof obj !== "object" || Array.isArray(obj)) {
64
- const subKey = keyParts.slice(0, index + 1).join("_");
65
- throw new TypeError(
66
- `Could not nest config for key '${key}' under existing value '${subKey}'`
67
- );
68
- }
69
- } else {
70
- if (part in obj) {
71
- throw new TypeError(
72
- `Refusing to override existing config at key '${key}'`
73
- );
74
- }
75
- try {
76
- const [, parsedValue] = safeJsonParse(value);
77
- if (parsedValue === null) {
78
- throw new Error("value may not be null");
79
- }
80
- obj[part] = parsedValue;
81
- } catch (error) {
82
- throw new TypeError(
83
- `Failed to parse JSON-serialized config value for key '${key}', ${error}`
84
- );
85
- }
86
- }
87
- }
88
- }
89
- }
90
- return data ? [{ data, context: "env" }] : [];
91
- }
92
- function safeJsonParse(str) {
93
- try {
94
- return [null, JSON.parse(str)];
95
- } catch (err) {
96
- errors.assertError(err);
97
- return [err, str];
98
- }
99
- }
100
-
101
- function isObject(obj) {
102
- if (typeof obj !== "object") {
103
- return false;
104
- } else if (Array.isArray(obj)) {
105
- return false;
106
- }
107
- return obj !== null;
108
- }
109
-
110
- async function applyConfigTransforms(initialDir, input, transforms) {
111
- async function transform(inputObj, path, baseDir) {
112
- var _a;
113
- let obj = inputObj;
114
- let dir = baseDir;
115
- for (const tf of transforms) {
116
- try {
117
- const result = await tf(inputObj, baseDir);
118
- if (result.applied) {
119
- if (result.value === void 0) {
120
- return void 0;
121
- }
122
- obj = result.value;
123
- dir = (_a = result.newBaseDir) != null ? _a : dir;
124
- break;
125
- }
126
- } catch (error) {
127
- errors.assertError(error);
128
- throw new Error(`error at ${path}, ${error.message}`);
129
- }
130
- }
131
- if (typeof obj !== "object") {
132
- return obj;
133
- } else if (obj === null) {
134
- return void 0;
135
- } else if (Array.isArray(obj)) {
136
- const arr = new Array();
137
- for (const [index, value] of obj.entries()) {
138
- const out2 = await transform(value, `${path}[${index}]`, dir);
139
- if (out2 !== void 0) {
140
- arr.push(out2);
141
- }
142
- }
143
- return arr;
144
- }
145
- const out = {};
146
- for (const [key, value] of Object.entries(obj)) {
147
- if (value !== void 0) {
148
- const result = await transform(value, `${path}.${key}`, dir);
149
- if (result !== void 0) {
150
- out[key] = result;
151
- }
152
- }
153
- }
154
- return out;
155
- }
156
- const finalData = await transform(input, "", initialDir);
157
- if (!isObject(finalData)) {
158
- throw new TypeError("expected object at config root");
159
- }
160
- return finalData;
161
- }
162
-
163
- const includeFileParser = {
164
- ".json": async (content) => JSON.parse(content),
165
- ".yaml": async (content) => yaml__default["default"].parse(content),
166
- ".yml": async (content) => yaml__default["default"].parse(content)
167
- };
168
- function createIncludeTransform(env, readFile, substitute) {
169
- return async (input, baseDir) => {
170
- if (!isObject(input)) {
171
- return { applied: false };
172
- }
173
- const [includeKey] = Object.keys(input).filter((key) => key.startsWith("$"));
174
- if (includeKey) {
175
- if (Object.keys(input).length !== 1) {
176
- throw new Error(
177
- `include key ${includeKey} should not have adjacent keys`
178
- );
179
- }
180
- } else {
181
- return { applied: false };
182
- }
183
- const rawIncludedValue = input[includeKey];
184
- if (typeof rawIncludedValue !== "string") {
185
- throw new Error(`${includeKey} include value is not a string`);
186
- }
187
- const substituteResults = await substitute(rawIncludedValue, baseDir);
188
- const includeValue = substituteResults.applied ? substituteResults.value : rawIncludedValue;
189
- if (includeValue === void 0 || typeof includeValue !== "string") {
190
- throw new Error(`${includeKey} substitution value was undefined`);
191
- }
192
- switch (includeKey) {
193
- case "$file":
194
- try {
195
- const value = await readFile(path.resolve(baseDir, includeValue));
196
- return { applied: true, value: value.trimEnd() };
197
- } catch (error) {
198
- throw new Error(`failed to read file ${includeValue}, ${error}`);
199
- }
200
- case "$env":
201
- try {
202
- return { applied: true, value: await env(includeValue) };
203
- } catch (error) {
204
- throw new Error(`failed to read env ${includeValue}, ${error}`);
205
- }
206
- case "$include": {
207
- const [filePath, dataPath] = includeValue.split(/#(.*)/);
208
- const ext = path.extname(filePath);
209
- const parser = includeFileParser[ext];
210
- if (!parser) {
211
- throw new Error(
212
- `no configuration parser available for included file ${filePath}`
213
- );
214
- }
215
- const path$1 = path.resolve(baseDir, filePath);
216
- const content = await readFile(path$1);
217
- const newBaseDir = path.dirname(path$1);
218
- const parts = dataPath ? dataPath.split(".") : [];
219
- let value;
220
- try {
221
- value = await parser(content);
222
- } catch (error) {
223
- throw new Error(
224
- `failed to parse included file ${filePath}, ${error}`
225
- );
226
- }
227
- for (const [index, part] of parts.entries()) {
228
- if (!isObject(value)) {
229
- const errPath = parts.slice(0, index).join(".");
230
- throw new Error(
231
- `value at '${errPath}' in included file ${filePath} is not an object`
232
- );
233
- }
234
- value = value[part];
235
- }
236
- return {
237
- applied: true,
238
- value,
239
- newBaseDir: newBaseDir !== baseDir ? newBaseDir : void 0
240
- };
241
- }
242
- default:
243
- throw new Error(`unknown include ${includeKey}`);
244
- }
245
- };
246
- }
247
-
248
- function createSubstitutionTransform(env) {
249
- return async (input) => {
250
- if (typeof input !== "string") {
251
- return { applied: false };
252
- }
253
- const parts = input.split(/(\$?\$\{[^{}]*\})/);
254
- for (let i = 1; i < parts.length; i += 2) {
255
- const part = parts[i];
256
- if (part.startsWith("$$")) {
257
- parts[i] = part.slice(1);
258
- } else {
259
- parts[i] = await env(part.slice(2, -1).trim());
260
- }
261
- }
262
- if (parts.some((part) => part === void 0)) {
263
- return { applied: true, value: void 0 };
264
- }
265
- return { applied: true, value: parts.join("") };
266
- };
267
- }
268
-
269
49
  const CONFIG_VISIBILITIES = ["frontend", "backend", "secret"];
270
50
  const DEFAULT_CONFIG_VISIBILITY = "backend";
271
51
 
@@ -711,173 +491,1183 @@ async function loadConfigSchema(options) {
711
491
  };
712
492
  }
713
493
 
714
- function isValidUrl(url) {
715
- try {
716
- new URL(url);
717
- return true;
718
- } catch {
719
- return false;
720
- }
721
- }
722
-
723
- async function loadConfig(options) {
724
- const { configRoot, experimentalEnvFunc: envFunc, watch, remote } = options;
725
- const configPaths = options.configTargets.slice().filter((e) => e.hasOwnProperty("path")).map((configTarget) => configTarget.path);
726
- const configUrls = options.configTargets.slice().filter((e) => e.hasOwnProperty("url")).map((configTarget) => configTarget.url);
727
- if (remote === void 0) {
728
- if (configUrls.length > 0) {
729
- throw new Error(
730
- `Please make sure you are passing the remote option when loading remote configurations. See https://backstage.io/docs/conf/writing#configuration-files for detailed info.`
731
- );
732
- }
733
- } else if (remote.reloadIntervalSeconds <= 0) {
734
- throw new Error(
735
- `Remote config must be contain a non zero reloadIntervalSeconds: <seconds> value`
736
- );
494
+ class EnvConfigSource {
495
+ constructor(env) {
496
+ this.env = env;
737
497
  }
738
- if (configPaths.length === 0 && configUrls.length === 0) {
739
- configPaths.push(path.resolve(configRoot, "app-config.yaml"));
740
- const localConfig = path.resolve(configRoot, "app-config.local.yaml");
741
- if (await fs__default["default"].pathExists(localConfig)) {
742
- configPaths.push(localConfig);
743
- }
498
+ /**
499
+ * Creates a new config source that reads from the environment.
500
+ *
501
+ * @param options - Options for the config source.
502
+ * @returns A new config source that reads from the environment.
503
+ */
504
+ static create(options) {
505
+ var _a;
506
+ return new EnvConfigSource((_a = options == null ? void 0 : options.env) != null ? _a : process.env);
744
507
  }
745
- const env = envFunc != null ? envFunc : async (name) => process.env[name];
746
- const loadConfigFiles = async () => {
747
- const fileConfigs2 = [];
748
- const loadedPaths2 = /* @__PURE__ */ new Set();
749
- for (const configPath of configPaths) {
750
- if (!path.isAbsolute(configPath)) {
751
- throw new Error(`Config load path is not absolute: '${configPath}'`);
752
- }
753
- const dir = path.dirname(configPath);
754
- const readFile = (path$1) => {
755
- const fullPath = path.resolve(dir, path$1);
756
- loadedPaths2.add(fullPath);
757
- return fs__default["default"].readFile(fullPath, "utf8");
758
- };
759
- const input = yaml__default["default"].parse(await readFile(configPath));
760
- if (input !== null) {
761
- const substitutionTransform = createSubstitutionTransform(env);
762
- const data = await applyConfigTransforms(dir, input, [
763
- createIncludeTransform(env, readFile, substitutionTransform),
764
- substitutionTransform
765
- ]);
766
- fileConfigs2.push({ data, context: path.basename(configPath) });
767
- }
768
- }
769
- return { fileConfigs: fileConfigs2, loadedPaths: loadedPaths2 };
770
- };
771
- const loadRemoteConfigFiles = async () => {
772
- const configs = [];
773
- const readConfigFromUrl = async (url) => {
774
- const response = await fetch__default["default"](url);
775
- if (!response.ok) {
776
- throw new Error(`Could not read config file at ${url}`);
777
- }
778
- return await response.text();
779
- };
780
- for (let i = 0; i < configUrls.length; i++) {
781
- const configUrl = configUrls[i];
782
- if (!isValidUrl(configUrl)) {
783
- throw new Error(`Config load path is not valid: '${configUrl}'`);
784
- }
785
- const remoteConfigContent = await readConfigFromUrl(configUrl);
786
- if (!remoteConfigContent) {
787
- throw new Error(`Config is not valid`);
788
- }
789
- const configYaml = yaml__default["default"].parse(remoteConfigContent);
790
- const substitutionTransform = createSubstitutionTransform(env);
791
- const data = await applyConfigTransforms(configRoot, configYaml, [
792
- substitutionTransform
793
- ]);
794
- configs.push({ data, context: configUrl });
795
- }
796
- return configs;
797
- };
798
- let fileConfigs;
799
- let loadedPaths;
800
- try {
801
- ({ fileConfigs, loadedPaths } = await loadConfigFiles());
802
- } catch (error) {
803
- throw new errors.ForwardedError("Failed to read static configuration file", error);
508
+ async *readConfigData() {
509
+ const configs = readEnvConfig(this.env);
510
+ yield { configs };
511
+ return;
804
512
  }
805
- let remoteConfigs = [];
806
- if (remote) {
807
- try {
808
- remoteConfigs = await loadRemoteConfigFiles();
809
- } catch (error) {
810
- throw new errors.ForwardedError(
811
- `Failed to read remote configuration file`,
812
- error
813
- );
814
- }
513
+ toString() {
514
+ const keys = Object.keys(this.env).filter(
515
+ (key) => key.startsWith("APP_CONFIG_")
516
+ );
517
+ return `EnvConfigSource{count=${keys.length}}`;
815
518
  }
816
- const envConfigs = readEnvConfig(process.env);
817
- const watchConfigFile = (watchProp) => {
818
- let watchedFiles = Array.from(loadedPaths);
819
- const watcher = chokidar__default["default"].watch(watchedFiles, {
820
- usePolling: process.env.NODE_ENV === "test"
821
- });
822
- let currentSerializedConfig = JSON.stringify(fileConfigs);
823
- watcher.on("change", async () => {
824
- try {
825
- const { fileConfigs: newConfigs, loadedPaths: newLoadedPaths } = await loadConfigFiles();
826
- watcher.unwatch(watchedFiles);
827
- watchedFiles = Array.from(newLoadedPaths);
828
- watcher.add(watchedFiles);
829
- const newSerializedConfig = JSON.stringify(newConfigs);
830
- if (currentSerializedConfig === newSerializedConfig) {
831
- return;
519
+ }
520
+ const ENV_PREFIX = "APP_CONFIG_";
521
+ const CONFIG_KEY_PART_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z][a-z0-9]*)*$/i;
522
+ function readEnvConfig(env) {
523
+ var _a;
524
+ let data = void 0;
525
+ for (const [name, value] of Object.entries(env)) {
526
+ if (!value) {
527
+ continue;
528
+ }
529
+ if (name.startsWith(ENV_PREFIX)) {
530
+ const key = name.replace(ENV_PREFIX, "");
531
+ const keyParts = key.split("_");
532
+ let obj = data = data != null ? data : {};
533
+ for (const [index, part] of keyParts.entries()) {
534
+ if (!CONFIG_KEY_PART_PATTERN.test(part)) {
535
+ throw new TypeError(`Invalid env config key '${key}'`);
536
+ }
537
+ if (index < keyParts.length - 1) {
538
+ obj = obj[part] = (_a = obj[part]) != null ? _a : {};
539
+ if (typeof obj !== "object" || Array.isArray(obj)) {
540
+ const subKey = keyParts.slice(0, index + 1).join("_");
541
+ throw new TypeError(
542
+ `Could not nest config for key '${key}' under existing value '${subKey}'`
543
+ );
544
+ }
545
+ } else {
546
+ if (part in obj) {
547
+ throw new TypeError(
548
+ `Refusing to override existing config at key '${key}'`
549
+ );
550
+ }
551
+ try {
552
+ const [, parsedValue] = safeJsonParse(value);
553
+ if (parsedValue === null) {
554
+ throw new Error("value may not be null");
555
+ }
556
+ obj[part] = parsedValue;
557
+ } catch (error) {
558
+ throw new TypeError(
559
+ `Failed to parse JSON-serialized config value for key '${key}', ${error}`
560
+ );
561
+ }
832
562
  }
833
- currentSerializedConfig = newSerializedConfig;
834
- watchProp.onChange([...remoteConfigs, ...newConfigs, ...envConfigs]);
835
- } catch (error) {
836
- console.error(`Failed to reload configuration files, ${error}`);
837
563
  }
838
- });
839
- if (watchProp.stopSignal) {
840
- watchProp.stopSignal.then(() => {
841
- watcher.close();
842
- });
564
+ }
565
+ }
566
+ return data ? [{ data, context: "env" }] : [];
567
+ }
568
+ function safeJsonParse(str) {
569
+ try {
570
+ return [null, JSON.parse(str)];
571
+ } catch (err) {
572
+ errors.assertError(err);
573
+ return [err, str];
574
+ }
575
+ }
576
+
577
+ function isObject(obj) {
578
+ if (typeof obj !== "object") {
579
+ return false;
580
+ } else if (Array.isArray(obj)) {
581
+ return false;
582
+ }
583
+ return obj !== null;
584
+ }
585
+
586
+ function createSubstitutionTransform(env) {
587
+ return async (input) => {
588
+ if (typeof input !== "string") {
589
+ return { applied: false };
590
+ }
591
+ const parts = input.split(/(\$?\$\{[^{}]*\})/);
592
+ for (let i = 1; i < parts.length; i += 2) {
593
+ const part = parts[i];
594
+ if (part.startsWith("$$")) {
595
+ parts[i] = part.slice(1);
596
+ } else {
597
+ parts[i] = await env(part.slice(2, -1).trim());
598
+ }
599
+ }
600
+ if (parts.some((part) => part === void 0)) {
601
+ return { applied: true, value: void 0 };
602
+ }
603
+ return { applied: true, value: parts.join("") };
604
+ };
605
+ }
606
+
607
+ const includeFileParser = {
608
+ ".json": async (content) => JSON.parse(content),
609
+ ".yaml": async (content) => yaml__default["default"].parse(content),
610
+ ".yml": async (content) => yaml__default["default"].parse(content)
611
+ };
612
+ function createIncludeTransform(env, readFile, substitute) {
613
+ return async (input, context) => {
614
+ const { dir } = context;
615
+ if (!dir) {
616
+ throw new Error("Include transform requires a base directory");
617
+ }
618
+ if (!isObject(input)) {
619
+ return { applied: false };
620
+ }
621
+ const [includeKey] = Object.keys(input).filter((key) => key.startsWith("$"));
622
+ if (includeKey) {
623
+ if (Object.keys(input).length !== 1) {
624
+ throw new Error(
625
+ `include key ${includeKey} should not have adjacent keys`
626
+ );
627
+ }
628
+ } else {
629
+ return { applied: false };
630
+ }
631
+ const rawIncludedValue = input[includeKey];
632
+ if (typeof rawIncludedValue !== "string") {
633
+ throw new Error(`${includeKey} include value is not a string`);
634
+ }
635
+ const substituteResults = await substitute(rawIncludedValue, { dir });
636
+ const includeValue = substituteResults.applied ? substituteResults.value : rawIncludedValue;
637
+ if (includeValue === void 0 || typeof includeValue !== "string") {
638
+ throw new Error(`${includeKey} substitution value was undefined`);
639
+ }
640
+ switch (includeKey) {
641
+ case "$file":
642
+ try {
643
+ const value = await readFile(path.resolve(dir, includeValue));
644
+ return { applied: true, value: value.trimEnd() };
645
+ } catch (error) {
646
+ throw new Error(`failed to read file ${includeValue}, ${error}`);
647
+ }
648
+ case "$env":
649
+ try {
650
+ return { applied: true, value: await env(includeValue) };
651
+ } catch (error) {
652
+ throw new Error(`failed to read env ${includeValue}, ${error}`);
653
+ }
654
+ case "$include": {
655
+ const [filePath, dataPath] = includeValue.split(/#(.*)/);
656
+ const ext = path.extname(filePath);
657
+ const parser = includeFileParser[ext];
658
+ if (!parser) {
659
+ throw new Error(
660
+ `no configuration parser available for included file ${filePath}`
661
+ );
662
+ }
663
+ const path$1 = path.resolve(dir, filePath);
664
+ const content = await readFile(path$1);
665
+ const newDir = path.dirname(path$1);
666
+ const parts = dataPath ? dataPath.split(".") : [];
667
+ let value;
668
+ try {
669
+ value = await parser(content);
670
+ } catch (error) {
671
+ throw new Error(
672
+ `failed to parse included file ${filePath}, ${error}`
673
+ );
674
+ }
675
+ for (const [index, part] of parts.entries()) {
676
+ if (!isObject(value)) {
677
+ const errPath = parts.slice(0, index).join(".");
678
+ throw new Error(
679
+ `value at '${errPath}' in included file ${filePath} is not an object`
680
+ );
681
+ }
682
+ value = value[part];
683
+ }
684
+ if (typeof value === "string") {
685
+ const substituted = await substitute(value, { dir: newDir });
686
+ if (substituted.applied) {
687
+ value = substituted.value;
688
+ }
689
+ }
690
+ return {
691
+ applied: true,
692
+ value,
693
+ newDir: newDir !== dir ? newDir : void 0
694
+ };
695
+ }
696
+ default:
697
+ throw new Error(`unknown include ${includeKey}`);
843
698
  }
844
699
  };
845
- const watchRemoteConfig = (watchProp, remoteProp) => {
846
- const hasConfigChanged = async (oldRemoteConfigs, newRemoteConfigs) => {
847
- return JSON.stringify(oldRemoteConfigs) !== JSON.stringify(newRemoteConfigs);
700
+ }
701
+
702
+ async function applyConfigTransforms(input, context, transforms) {
703
+ async function transform(inputObj, path, baseDir) {
704
+ var _a;
705
+ let obj = inputObj;
706
+ let dir = baseDir;
707
+ for (const tf of transforms) {
708
+ try {
709
+ const result = await tf(inputObj, { dir });
710
+ if (result.applied) {
711
+ if (result.value === void 0) {
712
+ return void 0;
713
+ }
714
+ obj = result.value;
715
+ dir = (_a = result == null ? void 0 : result.newDir) != null ? _a : dir;
716
+ break;
717
+ }
718
+ } catch (error) {
719
+ errors.assertError(error);
720
+ throw new Error(`error at ${path}, ${error.message}`);
721
+ }
722
+ }
723
+ if (typeof obj !== "object") {
724
+ return obj;
725
+ } else if (obj === null) {
726
+ return void 0;
727
+ } else if (Array.isArray(obj)) {
728
+ const arr = new Array();
729
+ for (const [index, value] of obj.entries()) {
730
+ const out2 = await transform(value, `${path}[${index}]`, dir);
731
+ if (out2 !== void 0) {
732
+ arr.push(out2);
733
+ }
734
+ }
735
+ return arr;
736
+ }
737
+ const out = {};
738
+ for (const [key, value] of Object.entries(obj)) {
739
+ if (value !== void 0) {
740
+ const result = await transform(value, `${path}.${key}`, dir);
741
+ if (result !== void 0) {
742
+ out[key] = result;
743
+ }
744
+ }
745
+ }
746
+ return out;
747
+ }
748
+ const finalData = await transform(input, "", context == null ? void 0 : context.dir);
749
+ if (!isObject(finalData)) {
750
+ throw new TypeError("expected object at config root");
751
+ }
752
+ return finalData;
753
+ }
754
+ function createConfigTransformer(options) {
755
+ const { substitutionFunc = async (name) => process.env[name], readFile } = options;
756
+ const substitutionTransform = createSubstitutionTransform(substitutionFunc);
757
+ const transforms = [substitutionTransform];
758
+ if (readFile) {
759
+ const includeTransform = createIncludeTransform(
760
+ substitutionFunc,
761
+ readFile,
762
+ substitutionTransform
763
+ );
764
+ transforms.push(includeTransform);
765
+ }
766
+ return async (input, ctx) => applyConfigTransforms(input, ctx != null ? ctx : {}, transforms);
767
+ }
768
+
769
+ var __accessCheck$3 = (obj, member, msg) => {
770
+ if (!member.has(obj))
771
+ throw TypeError("Cannot " + msg);
772
+ };
773
+ var __privateGet$2 = (obj, member, getter) => {
774
+ __accessCheck$3(obj, member, "read from private field");
775
+ return getter ? getter.call(obj) : member.get(obj);
776
+ };
777
+ var __privateAdd$3 = (obj, member, value) => {
778
+ if (member.has(obj))
779
+ throw TypeError("Cannot add the same private member more than once");
780
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
781
+ };
782
+ var __privateSet$2 = (obj, member, value, setter) => {
783
+ __accessCheck$3(obj, member, "write to private field");
784
+ setter ? setter.call(obj, value) : member.set(obj, value);
785
+ return value;
786
+ };
787
+ var __privateMethod$2 = (obj, member, method) => {
788
+ __accessCheck$3(obj, member, "access private method");
789
+ return method;
790
+ };
791
+ var _path, _substitutionFunc, _waitForEvent, waitForEvent_fn;
792
+ async function readFile(path) {
793
+ try {
794
+ return await fs__default["default"].readFile(path, "utf8");
795
+ } catch (error) {
796
+ if (error.code === "ENOENT") {
797
+ return void 0;
798
+ }
799
+ throw error;
800
+ }
801
+ }
802
+ const _FileConfigSource = class {
803
+ constructor(options) {
804
+ __privateAdd$3(this, _waitForEvent);
805
+ __privateAdd$3(this, _path, void 0);
806
+ __privateAdd$3(this, _substitutionFunc, void 0);
807
+ __privateSet$2(this, _path, options.path);
808
+ __privateSet$2(this, _substitutionFunc, options.substitutionFunc);
809
+ }
810
+ /**
811
+ * Creates a new config source that loads configuration from the given path.
812
+ *
813
+ * @remarks
814
+ *
815
+ * The source will watch the file for changes, as well as any referenced files.
816
+ *
817
+ * @param options - Options for the config source.
818
+ * @returns A new config source that loads from the given path.
819
+ */
820
+ static create(options) {
821
+ if (!path.isAbsolute(options.path)) {
822
+ throw new Error(`Config load path is not absolute: "${options.path}"`);
823
+ }
824
+ return new _FileConfigSource(options);
825
+ }
826
+ // Work is duplicated across each read, in practice that should not
827
+ // have any impact since there won't be multiple consumers. If that
828
+ // changes it might be worth refactoring this to avoid duplicate work.
829
+ async *readConfigData(options) {
830
+ const signal = options == null ? void 0 : options.signal;
831
+ const configFileName = path.basename(__privateGet$2(this, _path));
832
+ const watchedPaths = new Array();
833
+ const watcher = chokidar__default["default"].watch(__privateGet$2(this, _path), {
834
+ usePolling: process.env.NODE_ENV === "test"
835
+ });
836
+ const dir = path.dirname(__privateGet$2(this, _path));
837
+ const transformer = createConfigTransformer({
838
+ substitutionFunc: __privateGet$2(this, _substitutionFunc),
839
+ readFile: async (path$1) => {
840
+ const fullPath = path.resolve(dir, path$1);
841
+ watcher.add(fullPath);
842
+ watchedPaths.push(fullPath);
843
+ const data = await readFile(fullPath);
844
+ if (data === void 0) {
845
+ throw new errors.NotFoundError(
846
+ `failed to include "${fullPath}", file does not exist`
847
+ );
848
+ }
849
+ return data;
850
+ }
851
+ });
852
+ const readConfigFile = async () => {
853
+ watcher.unwatch(watchedPaths);
854
+ watchedPaths.length = 0;
855
+ watcher.add(__privateGet$2(this, _path));
856
+ watchedPaths.push(__privateGet$2(this, _path));
857
+ const content = await readFile(__privateGet$2(this, _path));
858
+ if (content === void 0) {
859
+ throw new errors.NotFoundError(`Config file "${__privateGet$2(this, _path)}" does not exist`);
860
+ }
861
+ const parsed = yaml__default["default"].parse(content);
862
+ if (parsed === null) {
863
+ return [];
864
+ }
865
+ try {
866
+ const data = await transformer(parsed, { dir });
867
+ return [{ data, context: configFileName, path: __privateGet$2(this, _path) }];
868
+ } catch (error) {
869
+ throw new Error(
870
+ `Failed to read config file at "${__privateGet$2(this, _path)}", ${error.message}`
871
+ );
872
+ }
848
873
  };
849
- let handle;
850
- try {
851
- handle = setInterval(async () => {
852
- const newRemoteConfigs = await loadRemoteConfigFiles();
853
- if (await hasConfigChanged(remoteConfigs, newRemoteConfigs)) {
854
- remoteConfigs = newRemoteConfigs;
855
- watchProp.onChange([...remoteConfigs, ...fileConfigs, ...envConfigs]);
874
+ const onAbort = () => {
875
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
876
+ watcher.close();
877
+ };
878
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort);
879
+ yield { configs: await readConfigFile() };
880
+ for (; ; ) {
881
+ const event = await __privateMethod$2(this, _waitForEvent, waitForEvent_fn).call(this, watcher, signal);
882
+ if (event === "abort") {
883
+ return;
884
+ }
885
+ yield { configs: await readConfigFile() };
886
+ }
887
+ }
888
+ toString() {
889
+ return `FileConfigSource{path="${__privateGet$2(this, _path)}"}`;
890
+ }
891
+ };
892
+ let FileConfigSource = _FileConfigSource;
893
+ _path = new WeakMap();
894
+ _substitutionFunc = new WeakMap();
895
+ _waitForEvent = new WeakSet();
896
+ waitForEvent_fn = function(watcher, signal) {
897
+ return new Promise((resolve) => {
898
+ function onChange() {
899
+ resolve("change");
900
+ onDone();
901
+ }
902
+ function onAbort() {
903
+ resolve("abort");
904
+ onDone();
905
+ }
906
+ function onDone() {
907
+ watcher.removeListener("change", onChange);
908
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
909
+ }
910
+ watcher.addListener("change", onChange);
911
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort);
912
+ });
913
+ };
914
+
915
+ var __accessCheck$2 = (obj, member, msg) => {
916
+ if (!member.has(obj))
917
+ throw TypeError("Cannot " + msg);
918
+ };
919
+ var __privateAdd$2 = (obj, member, value) => {
920
+ if (member.has(obj))
921
+ throw TypeError("Cannot add the same private member more than once");
922
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
923
+ };
924
+ var __privateMethod$1 = (obj, member, method) => {
925
+ __accessCheck$2(obj, member, "access private method");
926
+ return method;
927
+ };
928
+ var _flattenSources, flattenSources_fn;
929
+ const sourcesSymbol = Symbol.for(
930
+ "@backstage/config-loader#MergedConfigSource.sources"
931
+ );
932
+ const _MergedConfigSource = class {
933
+ constructor(sources) {
934
+ this.sources = sources;
935
+ this[sourcesSymbol] = this.sources;
936
+ }
937
+ static from(sources) {
938
+ return new _MergedConfigSource(__privateMethod$1(this, _flattenSources, flattenSources_fn).call(this, sources));
939
+ }
940
+ async *readConfigData(options) {
941
+ const its = this.sources.map((source) => source.readConfigData(options));
942
+ const initialResults = await Promise.all(its.map((it) => it.next()));
943
+ const configs = initialResults.map((result, i) => {
944
+ if (result.done) {
945
+ throw new Error(
946
+ `Config source ${String(this.sources[i])} returned no data`
947
+ );
948
+ }
949
+ return result.value.configs;
950
+ });
951
+ yield { configs: configs.flat(1) };
952
+ const results = its.map((it, i) => nextWithIndex(it, i));
953
+ while (results.some(Boolean)) {
954
+ try {
955
+ const [i, result] = await Promise.race(results.filter(Boolean));
956
+ if (result.done) {
957
+ results[i] = void 0;
958
+ } else {
959
+ results[i] = nextWithIndex(its[i], i);
960
+ configs[i] = result.value.configs;
961
+ yield { configs: configs.flat(1) };
856
962
  }
857
- }, remoteProp.reloadIntervalSeconds * 1e3);
963
+ } catch (error) {
964
+ const source = this.sources[error.index];
965
+ if (source) {
966
+ throw new Error(`Config source ${String(source)} failed: ${error}`);
967
+ }
968
+ throw error;
969
+ }
970
+ }
971
+ }
972
+ toString() {
973
+ return `MergedConfigSource{${this.sources.map(String).join(", ")}}`;
974
+ }
975
+ };
976
+ let MergedConfigSource = _MergedConfigSource;
977
+ _flattenSources = new WeakSet();
978
+ flattenSources_fn = function(sources) {
979
+ return sources.flatMap((source) => {
980
+ if (sourcesSymbol in source && Array.isArray(source[sourcesSymbol])) {
981
+ return __privateMethod$1(this, _flattenSources, flattenSources_fn).call(this, source[sourcesSymbol]);
982
+ }
983
+ return source;
984
+ });
985
+ };
986
+ // An optimization to flatten nested merged sources to avid unnecessary microtasks
987
+ __privateAdd$2(MergedConfigSource, _flattenSources);
988
+ function nextWithIndex(iterator, index) {
989
+ return iterator.next().then(
990
+ (r) => [index, r],
991
+ (e) => {
992
+ throw Object.assign(e, { index });
993
+ }
994
+ );
995
+ }
996
+
997
+ var __accessCheck$1 = (obj, member, msg) => {
998
+ if (!member.has(obj))
999
+ throw TypeError("Cannot " + msg);
1000
+ };
1001
+ var __privateGet$1 = (obj, member, getter) => {
1002
+ __accessCheck$1(obj, member, "read from private field");
1003
+ return getter ? getter.call(obj) : member.get(obj);
1004
+ };
1005
+ var __privateAdd$1 = (obj, member, value) => {
1006
+ if (member.has(obj))
1007
+ throw TypeError("Cannot add the same private member more than once");
1008
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1009
+ };
1010
+ var __privateSet$1 = (obj, member, value, setter) => {
1011
+ __accessCheck$1(obj, member, "write to private field");
1012
+ setter ? setter.call(obj, value) : member.set(obj, value);
1013
+ return value;
1014
+ };
1015
+ var __privateMethod = (obj, member, method) => {
1016
+ __accessCheck$1(obj, member, "access private method");
1017
+ return method;
1018
+ };
1019
+ var _url, _reloadIntervalMs, _transformer, _load, load_fn, _wait, wait_fn;
1020
+ const DEFAULT_RELOAD_INTERVAL = { seconds: 60 };
1021
+ function durationToMs(duration) {
1022
+ const {
1023
+ years = 0,
1024
+ months = 0,
1025
+ weeks = 0,
1026
+ days = 0,
1027
+ hours = 0,
1028
+ minutes = 0,
1029
+ seconds = 0,
1030
+ milliseconds = 0
1031
+ } = duration;
1032
+ const totalDays = years * 365 + months * 30 + weeks * 7 + days;
1033
+ const totalHours = totalDays * 24 + hours;
1034
+ const totalMinutes = totalHours * 60 + minutes;
1035
+ const totalSeconds = totalMinutes * 60 + seconds;
1036
+ const totalMilliseconds = totalSeconds * 1e3 + milliseconds;
1037
+ return totalMilliseconds;
1038
+ }
1039
+ const _RemoteConfigSource = class {
1040
+ constructor(options) {
1041
+ __privateAdd$1(this, _load);
1042
+ __privateAdd$1(this, _wait);
1043
+ __privateAdd$1(this, _url, void 0);
1044
+ __privateAdd$1(this, _reloadIntervalMs, void 0);
1045
+ __privateAdd$1(this, _transformer, void 0);
1046
+ var _a;
1047
+ __privateSet$1(this, _url, options.url);
1048
+ __privateSet$1(this, _reloadIntervalMs, durationToMs(
1049
+ (_a = options.reloadInterval) != null ? _a : DEFAULT_RELOAD_INTERVAL
1050
+ ));
1051
+ __privateSet$1(this, _transformer, createConfigTransformer({
1052
+ substitutionFunc: options.substitutionFunc
1053
+ }));
1054
+ }
1055
+ /**
1056
+ * Creates a new {@link RemoteConfigSource}.
1057
+ *
1058
+ * @param options - Options for the source.
1059
+ * @returns A new remote config source.
1060
+ */
1061
+ static create(options) {
1062
+ try {
1063
+ new URL(options.url);
858
1064
  } catch (error) {
859
- console.error(`Failed to reload configuration files, ${error}`);
1065
+ throw new Error(
1066
+ `Invalid URL provided to remote config source, '${options.url}', ${error}`
1067
+ );
1068
+ }
1069
+ return new _RemoteConfigSource(options);
1070
+ }
1071
+ async *readConfigData(options) {
1072
+ var _a;
1073
+ let data = await __privateMethod(this, _load, load_fn).call(this);
1074
+ yield { configs: [{ data, context: __privateGet$1(this, _url) }] };
1075
+ for (; ; ) {
1076
+ await __privateMethod(this, _wait, wait_fn).call(this, options == null ? void 0 : options.signal);
1077
+ if ((_a = options == null ? void 0 : options.signal) == null ? void 0 : _a.aborted) {
1078
+ return;
1079
+ }
1080
+ try {
1081
+ const newData = await __privateMethod(this, _load, load_fn).call(this, options == null ? void 0 : options.signal);
1082
+ if (newData && !isEqual__default["default"](data, newData)) {
1083
+ data = newData;
1084
+ yield { configs: [{ data, context: __privateGet$1(this, _url) }] };
1085
+ }
1086
+ } catch (error) {
1087
+ if (error.name !== "AbortError") {
1088
+ console.error(`Failed to read config from ${__privateGet$1(this, _url)}, ${error}`);
1089
+ }
1090
+ }
1091
+ }
1092
+ }
1093
+ toString() {
1094
+ return `RemoteConfigSource{path="${__privateGet$1(this, _url)}"}`;
1095
+ }
1096
+ };
1097
+ let RemoteConfigSource = _RemoteConfigSource;
1098
+ _url = new WeakMap();
1099
+ _reloadIntervalMs = new WeakMap();
1100
+ _transformer = new WeakMap();
1101
+ _load = new WeakSet();
1102
+ load_fn = async function(signal) {
1103
+ const res = await fetch__default["default"](__privateGet$1(this, _url), {
1104
+ signal
1105
+ });
1106
+ if (!res.ok) {
1107
+ throw errors.ResponseError.fromResponse(res);
1108
+ }
1109
+ const content = await res.text();
1110
+ const data = await __privateGet$1(this, _transformer).call(this, yaml__default["default"].parse(content));
1111
+ if (data === null) {
1112
+ throw new Error("configuration data is null");
1113
+ } else if (typeof data !== "object") {
1114
+ throw new Error("configuration data is not an object");
1115
+ } else if (Array.isArray(data)) {
1116
+ throw new Error(
1117
+ "configuration data is an array, expected an object instead"
1118
+ );
1119
+ }
1120
+ return data;
1121
+ };
1122
+ _wait = new WeakSet();
1123
+ wait_fn = async function(signal) {
1124
+ return new Promise((resolve) => {
1125
+ const timeoutId = setTimeout(onDone, __privateGet$1(this, _reloadIntervalMs));
1126
+ signal == null ? void 0 : signal.addEventListener("abort", onDone);
1127
+ function onDone() {
1128
+ clearTimeout(timeoutId);
1129
+ signal == null ? void 0 : signal.removeEventListener("abort", onDone);
1130
+ resolve();
1131
+ }
1132
+ });
1133
+ };
1134
+
1135
+ class ObservableConfigProxy {
1136
+ constructor(parent, parentKey, abortController) {
1137
+ this.parent = parent;
1138
+ this.parentKey = parentKey;
1139
+ this.abortController = abortController;
1140
+ this.config = new config.ConfigReader({});
1141
+ this.subscribers = [];
1142
+ if (parent && !parentKey) {
1143
+ throw new Error("parentKey is required if parent is set");
1144
+ }
1145
+ }
1146
+ static create(abortController) {
1147
+ return new ObservableConfigProxy(void 0, void 0, abortController);
1148
+ }
1149
+ setConfig(config) {
1150
+ if (this.parent) {
1151
+ throw new Error("immutable");
860
1152
  }
861
- if (watchProp.stopSignal) {
862
- watchProp.stopSignal.then(() => {
863
- if (handle !== void 0) {
864
- clearInterval(handle);
865
- handle = void 0;
1153
+ this.config = config;
1154
+ for (const subscriber of this.subscribers) {
1155
+ try {
1156
+ subscriber();
1157
+ } catch (error) {
1158
+ console.error(`Config subscriber threw error, ${error}`);
1159
+ }
1160
+ }
1161
+ }
1162
+ close() {
1163
+ if (!this.abortController) {
1164
+ throw new Error("Only the root config can be closed");
1165
+ }
1166
+ this.abortController.abort();
1167
+ }
1168
+ subscribe(onChange) {
1169
+ if (this.parent) {
1170
+ return this.parent.subscribe(onChange);
1171
+ }
1172
+ this.subscribers.push(onChange);
1173
+ return {
1174
+ unsubscribe: () => {
1175
+ const index = this.subscribers.indexOf(onChange);
1176
+ if (index >= 0) {
1177
+ this.subscribers.splice(index, 1);
1178
+ }
1179
+ }
1180
+ };
1181
+ }
1182
+ select(required) {
1183
+ var _a;
1184
+ if (this.parent && this.parentKey) {
1185
+ if (required) {
1186
+ return this.parent.select(true).getConfig(this.parentKey);
1187
+ }
1188
+ return (_a = this.parent.select(false)) == null ? void 0 : _a.getOptionalConfig(this.parentKey);
1189
+ }
1190
+ return this.config;
1191
+ }
1192
+ has(key) {
1193
+ var _a, _b;
1194
+ return (_b = (_a = this.select(false)) == null ? void 0 : _a.has(key)) != null ? _b : false;
1195
+ }
1196
+ keys() {
1197
+ var _a, _b;
1198
+ return (_b = (_a = this.select(false)) == null ? void 0 : _a.keys()) != null ? _b : [];
1199
+ }
1200
+ get(key) {
1201
+ return this.select(true).get(key);
1202
+ }
1203
+ getOptional(key) {
1204
+ var _a;
1205
+ return (_a = this.select(false)) == null ? void 0 : _a.getOptional(key);
1206
+ }
1207
+ getConfig(key) {
1208
+ return new ObservableConfigProxy(this, key);
1209
+ }
1210
+ getOptionalConfig(key) {
1211
+ var _a;
1212
+ if ((_a = this.select(false)) == null ? void 0 : _a.has(key)) {
1213
+ return new ObservableConfigProxy(this, key);
1214
+ }
1215
+ return void 0;
1216
+ }
1217
+ getConfigArray(key) {
1218
+ return this.select(true).getConfigArray(key);
1219
+ }
1220
+ getOptionalConfigArray(key) {
1221
+ var _a;
1222
+ return (_a = this.select(false)) == null ? void 0 : _a.getOptionalConfigArray(key);
1223
+ }
1224
+ getNumber(key) {
1225
+ return this.select(true).getNumber(key);
1226
+ }
1227
+ getOptionalNumber(key) {
1228
+ var _a;
1229
+ return (_a = this.select(false)) == null ? void 0 : _a.getOptionalNumber(key);
1230
+ }
1231
+ getBoolean(key) {
1232
+ return this.select(true).getBoolean(key);
1233
+ }
1234
+ getOptionalBoolean(key) {
1235
+ var _a;
1236
+ return (_a = this.select(false)) == null ? void 0 : _a.getOptionalBoolean(key);
1237
+ }
1238
+ getString(key) {
1239
+ return this.select(true).getString(key);
1240
+ }
1241
+ getOptionalString(key) {
1242
+ var _a;
1243
+ return (_a = this.select(false)) == null ? void 0 : _a.getOptionalString(key);
1244
+ }
1245
+ getStringArray(key) {
1246
+ return this.select(true).getStringArray(key);
1247
+ }
1248
+ getOptionalStringArray(key) {
1249
+ var _a;
1250
+ return (_a = this.select(false)) == null ? void 0 : _a.getOptionalStringArray(key);
1251
+ }
1252
+ }
1253
+
1254
+ class ConfigSources {
1255
+ /**
1256
+ * Parses command line arguments and returns the config targets.
1257
+ *
1258
+ * @param argv - The command line arguments to parse. Defaults to `process.argv`
1259
+ * @returns A list of config targets
1260
+ */
1261
+ static parseArgs(argv = process.argv) {
1262
+ const args = [parseArgs__default["default"](argv).config].flat().filter(Boolean);
1263
+ return args.map((target) => {
1264
+ try {
1265
+ const url = new URL(target);
1266
+ if (!url.host) {
1267
+ return { type: "path", target };
866
1268
  }
1269
+ return { type: "url", target };
1270
+ } catch {
1271
+ return { type: "path", target };
1272
+ }
1273
+ });
1274
+ }
1275
+ /**
1276
+ * Creates the default config sources for the provided targets.
1277
+ *
1278
+ * @remarks
1279
+ *
1280
+ * This will create {@link FileConfigSource}s and {@link RemoteConfigSource}s
1281
+ * for the provided targets, and merge them together to a single source.
1282
+ * If no targets are provided it will fall back to `app-config.yaml` and
1283
+ * `app-config.local.yaml`.
1284
+ *
1285
+ * URL targets are only supported if the `remote` option is provided.
1286
+ *
1287
+ * @param options - Options
1288
+ * @returns A config source for the provided targets
1289
+ */
1290
+ static defaultForTargets(options) {
1291
+ var _a;
1292
+ const rootDir = (_a = options.rootDir) != null ? _a : cliCommon.findPaths(process.cwd()).targetRoot;
1293
+ const argSources = options.targets.map((arg) => {
1294
+ if (arg.type === "url") {
1295
+ if (!options.remote) {
1296
+ throw new Error(
1297
+ `Config argument "${arg.target}" looks like a URL but remote configuration is not enabled. Enable it by passing the \`remote\` option`
1298
+ );
1299
+ }
1300
+ return RemoteConfigSource.create({
1301
+ url: arg.target,
1302
+ substitutionFunc: options.substitutionFunc,
1303
+ reloadInterval: options.remote.reloadInterval
1304
+ });
1305
+ }
1306
+ return FileConfigSource.create({
1307
+ path: arg.target,
1308
+ substitutionFunc: options.substitutionFunc
867
1309
  });
1310
+ });
1311
+ if (argSources.length === 0) {
1312
+ const defaultPath = path.resolve(rootDir, "app-config.yaml");
1313
+ const localPath = path.resolve(rootDir, "app-config.local.yaml");
1314
+ argSources.push(
1315
+ FileConfigSource.create({
1316
+ path: defaultPath,
1317
+ substitutionFunc: options.substitutionFunc
1318
+ })
1319
+ );
1320
+ if (fs__default["default"].pathExistsSync(localPath)) {
1321
+ argSources.push(
1322
+ FileConfigSource.create({
1323
+ path: localPath,
1324
+ substitutionFunc: options.substitutionFunc
1325
+ })
1326
+ );
1327
+ }
868
1328
  }
869
- };
870
- if (watch) {
871
- watchConfigFile(watch);
1329
+ return this.merge(argSources);
872
1330
  }
873
- if (watch && remote) {
874
- watchRemoteConfig(watch, remote);
1331
+ /**
1332
+ * Creates the default config source for Backstage.
1333
+ *
1334
+ * @remarks
1335
+ *
1336
+ * This will read from `app-config.yaml` and `app-config.local.yaml` by
1337
+ * default, as well as environment variables prefixed with `APP_CONFIG_`.
1338
+ * If `--config <path|url>` command line arguments are passed, these will
1339
+ * override the default configuration file paths. URLs are only supported
1340
+ * if the `remote` option is provided.
1341
+ *
1342
+ * @param options - Options
1343
+ * @returns The default Backstage config source
1344
+ */
1345
+ static default(options) {
1346
+ const argSource = this.defaultForTargets({
1347
+ ...options,
1348
+ targets: this.parseArgs(options.argv)
1349
+ });
1350
+ const envSource = EnvConfigSource.create({
1351
+ env: options.env
1352
+ });
1353
+ return this.merge([argSource, envSource]);
875
1354
  }
876
- return {
877
- appConfigs: remote ? [...remoteConfigs, ...fileConfigs, ...envConfigs] : [...fileConfigs, ...envConfigs]
878
- };
1355
+ /**
1356
+ * Merges multiple config sources into a single source that reads from all
1357
+ * sources and concatenates the result.
1358
+ *
1359
+ * @param sources - The config sources to merge
1360
+ * @returns A single config source that concatenates the data from the given sources
1361
+ */
1362
+ static merge(sources) {
1363
+ return MergedConfigSource.from(sources);
1364
+ }
1365
+ /**
1366
+ * Creates an observable {@link @backstage/config#Config} implementation from a {@link ConfigSource}.
1367
+ *
1368
+ * @remarks
1369
+ *
1370
+ * If you only want to read the config once you can close the returned config immediately.
1371
+ *
1372
+ * @example
1373
+ *
1374
+ * ```ts
1375
+ * const sources = ConfigSources.default(...)
1376
+ * const config = await ConfigSources.toConfig(source)
1377
+ * config.close()
1378
+ * const example = config.getString(...)
1379
+ * ```
1380
+ *
1381
+ * @param source - The config source to read from
1382
+ * @returns A promise that resolves to a closable config
1383
+ */
1384
+ static toConfig(source) {
1385
+ return new Promise(async (resolve, reject) => {
1386
+ let config$1 = void 0;
1387
+ try {
1388
+ const abortController = new AbortController();
1389
+ for await (const { configs } of source.readConfigData({
1390
+ signal: abortController.signal
1391
+ })) {
1392
+ if (config$1) {
1393
+ config$1.setConfig(config.ConfigReader.fromConfigs(configs));
1394
+ } else {
1395
+ config$1 = ObservableConfigProxy.create(abortController);
1396
+ config$1.setConfig(config.ConfigReader.fromConfigs(configs));
1397
+ resolve(config$1);
1398
+ }
1399
+ }
1400
+ } catch (error) {
1401
+ reject(error);
1402
+ }
1403
+ });
1404
+ }
1405
+ }
1406
+
1407
+ function simpleDefer() {
1408
+ let resolve;
1409
+ const promise = new Promise((_resolve) => {
1410
+ resolve = _resolve;
1411
+ });
1412
+ return { promise, resolve };
1413
+ }
1414
+ async function waitOrAbort(promise, signal) {
1415
+ const signals = [signal].flat().filter((x) => !!x);
1416
+ return new Promise((resolve, reject) => {
1417
+ if (signals.some((s) => s.aborted)) {
1418
+ resolve([false]);
1419
+ }
1420
+ const onAbort = () => {
1421
+ resolve([false]);
1422
+ };
1423
+ promise.then(
1424
+ (value) => {
1425
+ resolve([true, value]);
1426
+ signals.forEach((s) => s.removeEventListener("abort", onAbort));
1427
+ },
1428
+ (error) => {
1429
+ reject(error);
1430
+ signals.forEach((s) => s.removeEventListener("abort", onAbort));
1431
+ }
1432
+ );
1433
+ signals.forEach((s) => s.addEventListener("abort", onAbort));
1434
+ });
1435
+ }
1436
+
1437
+ var __accessCheck = (obj, member, msg) => {
1438
+ if (!member.has(obj))
1439
+ throw TypeError("Cannot " + msg);
1440
+ };
1441
+ var __privateGet = (obj, member, getter) => {
1442
+ __accessCheck(obj, member, "read from private field");
1443
+ return getter ? getter.call(obj) : member.get(obj);
1444
+ };
1445
+ var __privateAdd = (obj, member, value) => {
1446
+ if (member.has(obj))
1447
+ throw TypeError("Cannot add the same private member more than once");
1448
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1449
+ };
1450
+ var __privateSet = (obj, member, value, setter) => {
1451
+ __accessCheck(obj, member, "write to private field");
1452
+ setter ? setter.call(obj, value) : member.set(obj, value);
1453
+ return value;
1454
+ };
1455
+ var _currentData, _deferred, _context, _abortController;
1456
+ const _MutableConfigSource = class {
1457
+ constructor(context, initialData) {
1458
+ __privateAdd(this, _currentData, void 0);
1459
+ __privateAdd(this, _deferred, void 0);
1460
+ __privateAdd(this, _context, void 0);
1461
+ __privateAdd(this, _abortController, new AbortController());
1462
+ __privateSet(this, _currentData, initialData);
1463
+ __privateSet(this, _context, context);
1464
+ __privateSet(this, _deferred, simpleDefer());
1465
+ }
1466
+ /**
1467
+ * Creates a new mutable config source.
1468
+ *
1469
+ * @param options - Options for the config source.
1470
+ * @returns A new mutable config source.
1471
+ */
1472
+ static create(options) {
1473
+ var _a;
1474
+ return new _MutableConfigSource(
1475
+ (_a = options == null ? void 0 : options.context) != null ? _a : "mutable-config",
1476
+ options == null ? void 0 : options.data
1477
+ );
1478
+ }
1479
+ async *readConfigData(options) {
1480
+ let deferredPromise = __privateGet(this, _deferred).promise;
1481
+ if (__privateGet(this, _currentData) !== void 0) {
1482
+ yield { configs: [{ data: __privateGet(this, _currentData), context: __privateGet(this, _context) }] };
1483
+ }
1484
+ for (; ; ) {
1485
+ const [ok] = await waitOrAbort(deferredPromise, [
1486
+ options == null ? void 0 : options.signal,
1487
+ __privateGet(this, _abortController).signal
1488
+ ]);
1489
+ if (!ok) {
1490
+ return;
1491
+ }
1492
+ deferredPromise = __privateGet(this, _deferred).promise;
1493
+ if (__privateGet(this, _currentData) !== void 0) {
1494
+ yield {
1495
+ configs: [{ data: __privateGet(this, _currentData), context: __privateGet(this, _context) }]
1496
+ };
1497
+ }
1498
+ }
1499
+ }
1500
+ /**
1501
+ * Set the data of the config source.
1502
+ *
1503
+ * @param data - The new data to set
1504
+ */
1505
+ setData(data) {
1506
+ if (!__privateGet(this, _abortController).signal.aborted) {
1507
+ __privateSet(this, _currentData, data);
1508
+ const oldDeferred = __privateGet(this, _deferred);
1509
+ __privateSet(this, _deferred, simpleDefer());
1510
+ oldDeferred.resolve();
1511
+ }
1512
+ }
1513
+ /**
1514
+ * Close the config source, preventing any further updates.
1515
+ */
1516
+ close() {
1517
+ __privateSet(this, _currentData, void 0);
1518
+ __privateGet(this, _abortController).abort();
1519
+ }
1520
+ toString() {
1521
+ return `MutableConfigSource{}`;
1522
+ }
1523
+ };
1524
+ let MutableConfigSource = _MutableConfigSource;
1525
+ _currentData = new WeakMap();
1526
+ _deferred = new WeakMap();
1527
+ _context = new WeakMap();
1528
+ _abortController = new WeakMap();
1529
+
1530
+ class StaticObservableConfigSource {
1531
+ constructor(data, context) {
1532
+ this.data = data;
1533
+ this.context = context;
1534
+ }
1535
+ async *readConfigData(options) {
1536
+ const queue = new Array();
1537
+ let deferred = simpleDefer();
1538
+ const sub = this.data.subscribe({
1539
+ next(value) {
1540
+ queue.push(value);
1541
+ deferred.resolve();
1542
+ deferred = simpleDefer();
1543
+ },
1544
+ complete() {
1545
+ deferred.resolve();
1546
+ }
1547
+ });
1548
+ const signal = options == null ? void 0 : options.signal;
1549
+ if (signal) {
1550
+ const onAbort = () => {
1551
+ sub.unsubscribe();
1552
+ queue.length = 0;
1553
+ deferred.resolve();
1554
+ signal.removeEventListener("abort", onAbort);
1555
+ };
1556
+ signal.addEventListener("abort", onAbort);
1557
+ }
1558
+ for (; ; ) {
1559
+ await deferred.promise;
1560
+ if (queue.length === 0) {
1561
+ return;
1562
+ }
1563
+ while (queue.length > 0) {
1564
+ yield { configs: [{ data: queue.shift(), context: this.context }] };
1565
+ }
1566
+ }
1567
+ }
1568
+ }
1569
+ function isObservable(value) {
1570
+ return "subscribe" in value && typeof value.subscribe === "function";
1571
+ }
1572
+ function isAsyncIterable(value) {
1573
+ return Symbol.asyncIterator in value;
1574
+ }
1575
+ class StaticConfigSource {
1576
+ constructor(promise, context) {
1577
+ this.promise = promise;
1578
+ this.context = context;
1579
+ }
1580
+ /**
1581
+ * Creates a new {@link StaticConfigSource}.
1582
+ *
1583
+ * @param options - Options for the config source
1584
+ * @returns A new static config source
1585
+ */
1586
+ static create(options) {
1587
+ const { data, context = "static-config" } = options;
1588
+ if (!data) {
1589
+ return {
1590
+ async *readConfigData() {
1591
+ yield { configs: [] };
1592
+ return;
1593
+ }
1594
+ };
1595
+ }
1596
+ if (isObservable(data)) {
1597
+ return new StaticObservableConfigSource(data, context);
1598
+ }
1599
+ if (isAsyncIterable(data)) {
1600
+ return {
1601
+ async *readConfigData() {
1602
+ for await (const value of data) {
1603
+ yield { configs: [{ data: value, context }] };
1604
+ }
1605
+ }
1606
+ };
1607
+ }
1608
+ return new StaticConfigSource(data, context);
1609
+ }
1610
+ async *readConfigData() {
1611
+ yield { configs: [{ data: await this.promise, context: this.context }] };
1612
+ return;
1613
+ }
1614
+ toString() {
1615
+ return `StaticConfigSource{}`;
1616
+ }
1617
+ }
1618
+
1619
+ async function loadConfig(options) {
1620
+ const source = ConfigSources.default({
1621
+ substitutionFunc: options.experimentalEnvFunc,
1622
+ remote: options.remote && {
1623
+ reloadInterval: { seconds: options.remote.reloadIntervalSeconds }
1624
+ },
1625
+ rootDir: options.configRoot,
1626
+ argv: options.configTargets.flatMap((t) => [
1627
+ "--config",
1628
+ "url" in t ? t.url : t.path
1629
+ ])
1630
+ });
1631
+ return new Promise((resolve, reject) => {
1632
+ async function loadConfigReaderLoop() {
1633
+ var _a, _b, _c, _d;
1634
+ let loaded = false;
1635
+ try {
1636
+ const abortController = new AbortController();
1637
+ (_b = (_a = options.watch) == null ? void 0 : _a.stopSignal) == null ? void 0 : _b.then(() => abortController.abort());
1638
+ for await (const { configs } of source.readConfigData({
1639
+ signal: abortController.signal
1640
+ })) {
1641
+ if (loaded) {
1642
+ (_c = options.watch) == null ? void 0 : _c.onChange(configs);
1643
+ } else {
1644
+ resolve({ appConfigs: configs });
1645
+ loaded = true;
1646
+ if (options.watch) {
1647
+ (_d = options.watch.stopSignal) == null ? void 0 : _d.then(() => abortController.abort());
1648
+ } else {
1649
+ abortController.abort();
1650
+ }
1651
+ }
1652
+ }
1653
+ } catch (error) {
1654
+ if (loaded) {
1655
+ console.error(`Failed to reload configuration, ${error}`);
1656
+ } else {
1657
+ reject(error);
1658
+ }
1659
+ }
1660
+ }
1661
+ loadConfigReaderLoop();
1662
+ });
879
1663
  }
880
1664
 
1665
+ exports.ConfigSources = ConfigSources;
1666
+ exports.EnvConfigSource = EnvConfigSource;
1667
+ exports.FileConfigSource = FileConfigSource;
1668
+ exports.MutableConfigSource = MutableConfigSource;
1669
+ exports.RemoteConfigSource = RemoteConfigSource;
1670
+ exports.StaticConfigSource = StaticConfigSource;
881
1671
  exports.loadConfig = loadConfig;
882
1672
  exports.loadConfigSchema = loadConfigSchema;
883
1673
  exports.mergeConfigSchemas = mergeConfigSchemas;