@backstage/config-loader 0.9.3 → 0.9.4

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @backstage/config-loader
2
2
 
3
+ ## 0.9.4
4
+
5
+ ### Patch Changes
6
+
7
+ - 1ed305728b: Bump `node-fetch` to version 2.6.7 and `cross-fetch` to version 3.1.5
8
+ - c77c5c7eb6: Added `backstage.role` to `package.json`
9
+ - Updated dependencies
10
+ - @backstage/errors@0.2.1
11
+ - @backstage/cli-common@0.1.7
12
+ - @backstage/config@0.1.14
13
+ - @backstage/types@0.1.2
14
+
3
15
  ## 0.9.3
4
16
 
5
17
  ### Patch Changes
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@backstage/config-loader",
3
3
  "description": "Config loading functionality used by Backstage backend, and CLI",
4
- "version": "0.9.3",
4
+ "version": "0.9.4",
5
5
  "private": false,
6
6
  "publishConfig": {
7
7
  "access": "public",
@@ -9,6 +9,9 @@
9
9
  "module": "dist/index.esm.js",
10
10
  "types": "dist/index.d.ts"
11
11
  },
12
+ "backstage": {
13
+ "role": "node-library"
14
+ },
12
15
  "homepage": "https://backstage.io",
13
16
  "repository": {
14
17
  "type": "git",
@@ -22,18 +25,19 @@
22
25
  "main": "dist/index.cjs.js",
23
26
  "types": "dist/index.d.ts",
24
27
  "scripts": {
25
- "build": "backstage-cli build",
26
- "lint": "backstage-cli lint",
27
- "test": "backstage-cli test",
28
- "prepack": "backstage-cli prepack",
29
- "postpack": "backstage-cli postpack",
30
- "clean": "backstage-cli clean"
28
+ "build": "backstage-cli package build",
29
+ "lint": "backstage-cli package lint",
30
+ "test": "backstage-cli package test",
31
+ "prepack": "backstage-cli package prepack",
32
+ "postpack": "backstage-cli package postpack",
33
+ "clean": "backstage-cli package clean",
34
+ "start": "backstage-cli package start"
31
35
  },
32
36
  "dependencies": {
33
- "@backstage/cli-common": "^0.1.6",
34
- "@backstage/config": "^0.1.13",
35
- "@backstage/errors": "^0.2.0",
36
- "@backstage/types": "^0.1.1",
37
+ "@backstage/cli-common": "^0.1.7",
38
+ "@backstage/config": "^0.1.14",
39
+ "@backstage/errors": "^0.2.1",
40
+ "@backstage/types": "^0.1.2",
37
41
  "@types/json-schema": "^7.0.6",
38
42
  "ajv": "^7.0.3",
39
43
  "chokidar": "^3.5.2",
@@ -41,7 +45,7 @@
41
45
  "json-schema": "^0.4.0",
42
46
  "json-schema-merge-allof": "^0.8.1",
43
47
  "json-schema-traverse": "^1.0.0",
44
- "node-fetch": "^2.6.1",
48
+ "node-fetch": "^2.6.7",
45
49
  "typescript-json-schema": "^0.52.0",
46
50
  "yaml": "^1.9.2",
47
51
  "yup": "^0.32.9"
@@ -58,6 +62,6 @@
58
62
  "files": [
59
63
  "dist"
60
64
  ],
61
- "gitHead": "600d6e3c854bbfb12a0078ca6f726d1c0d1fea0b",
65
+ "gitHead": "4805c3d13ce9bfc369e53c271b1b95e722b3b4dc",
62
66
  "module": "dist/index.esm.js"
63
67
  }
package/dist/index.d.ts DELETED
@@ -1,174 +0,0 @@
1
- import { AppConfig } from '@backstage/config';
2
- import { JSONSchema7 } from 'json-schema';
3
- import { JsonObject } from '@backstage/types';
4
-
5
- /**
6
- * Read runtime configuration from the environment.
7
- *
8
- * Only environment variables prefixed with APP_CONFIG_ will be considered.
9
- *
10
- * For each variable, the prefix will be removed, and rest of the key will
11
- * be split by '_'. Each part will then be used as keys to build up a nested
12
- * config object structure. The treatment of the entire environment variable
13
- * is case-sensitive.
14
- *
15
- * The value of the variable should be JSON serialized, as it will be parsed
16
- * and the type will be kept intact. For example "true" and true are treated
17
- * differently, as well as "42" and 42.
18
- *
19
- * For example, to set the config app.title to "My Title", use the following:
20
- *
21
- * APP_CONFIG_app_title='"My Title"'
22
- *
23
- * @public
24
- */
25
- declare function readEnvConfig(env: {
26
- [name: string]: string | undefined;
27
- }): AppConfig[];
28
-
29
- /**
30
- * A type representing the possible configuration value visibilities
31
- *
32
- * @public
33
- */
34
- declare type ConfigVisibility = 'frontend' | 'backend' | 'secret';
35
- /**
36
- * A function used to transform primitive configuration values.
37
- *
38
- * @public
39
- */
40
- declare type TransformFunc<T extends number | string | boolean> = (value: T, context: {
41
- visibility: ConfigVisibility;
42
- }) => T | undefined;
43
- /**
44
- * Options used to process configuration data with a schema.
45
- *
46
- * @public
47
- */
48
- declare type ConfigSchemaProcessingOptions = {
49
- /**
50
- * The visibilities that should be included in the output data.
51
- * If omitted, the data will not be filtered by visibility.
52
- */
53
- visibility?: ConfigVisibility[];
54
- /**
55
- * A transform function that can be used to transform primitive configuration values
56
- * during validation. The value returned from the transform function will be used
57
- * instead of the original value. If the transform returns `undefined`, the value
58
- * will be omitted.
59
- */
60
- valueTransform?: TransformFunc<any>;
61
- /**
62
- * Whether or not to include the `filteredKeys` property in the output `AppConfig`s.
63
- *
64
- * Default: `false`.
65
- */
66
- withFilteredKeys?: boolean;
67
- /**
68
- * Whether or not to include the `deprecatedKeys` property in the output `AppConfig`s.
69
- *
70
- * Default: `true`.
71
- */
72
- withDeprecatedKeys?: boolean;
73
- };
74
- /**
75
- * A loaded configuration schema that is ready to process configuration data.
76
- *
77
- * @public
78
- */
79
- declare type ConfigSchema = {
80
- process(appConfigs: AppConfig[], options?: ConfigSchemaProcessingOptions): AppConfig[];
81
- serialize(): JsonObject;
82
- };
83
-
84
- /**
85
- * Given a list of configuration schemas from packages, merge them
86
- * into a single json schema.
87
- *
88
- * @public
89
- */
90
- declare function mergeConfigSchemas(schemas: JSONSchema7[]): JSONSchema7;
91
-
92
- /**
93
- * Options that control the loading of configuration schema files in the backend.
94
- *
95
- * @public
96
- */
97
- declare type LoadConfigSchemaOptions = {
98
- dependencies: string[];
99
- packagePaths?: string[];
100
- } | {
101
- serialized: JsonObject;
102
- };
103
- /**
104
- * Loads config schema for a Backstage instance.
105
- *
106
- * @public
107
- */
108
- declare function loadConfigSchema(options: LoadConfigSchemaOptions): Promise<ConfigSchema>;
109
-
110
- /** @public */
111
- declare type ConfigTarget = {
112
- path: string;
113
- } | {
114
- url: string;
115
- };
116
- /** @public */
117
- declare type LoadConfigOptionsWatch = {
118
- /**
119
- * A listener that is called when a config file is changed.
120
- */
121
- onChange: (configs: AppConfig[]) => void;
122
- /**
123
- * An optional signal that stops the watcher once the promise resolves.
124
- */
125
- stopSignal?: Promise<void>;
126
- };
127
- /** @public */
128
- declare type LoadConfigOptionsRemote = {
129
- /**
130
- * A remote config reloading period, in seconds
131
- */
132
- reloadIntervalSeconds: number;
133
- };
134
- /**
135
- * Options that control the loading of configuration files in the backend.
136
- *
137
- * @public
138
- */
139
- declare type LoadConfigOptions = {
140
- configRoot: string;
141
- configTargets: ConfigTarget[];
142
- /**
143
- * Custom environment variable loading function
144
- *
145
- * @experimental This API is not stable and may change at any point
146
- */
147
- experimentalEnvFunc?: (name: string) => Promise<string | undefined>;
148
- /**
149
- * An optional remote config
150
- */
151
- remote?: LoadConfigOptionsRemote;
152
- /**
153
- * An optional configuration that enables watching of config files.
154
- */
155
- watch?: LoadConfigOptionsWatch;
156
- };
157
- /**
158
- * Results of loading configuration files.
159
- * @public
160
- */
161
- declare type LoadConfigResult = {
162
- /**
163
- * Array of all loaded configs.
164
- */
165
- appConfigs: AppConfig[];
166
- };
167
- /**
168
- * Load configuration data.
169
- *
170
- * @public
171
- */
172
- declare function loadConfig(options: LoadConfigOptions): Promise<LoadConfigResult>;
173
-
174
- export { ConfigSchema, ConfigSchemaProcessingOptions, ConfigTarget, ConfigVisibility, LoadConfigOptions, LoadConfigOptionsRemote, LoadConfigOptionsWatch, LoadConfigResult, LoadConfigSchemaOptions, TransformFunc, loadConfig, loadConfigSchema, mergeConfigSchemas, readEnvConfig };
package/dist/index.esm.js DELETED
@@ -1,737 +0,0 @@
1
- import { assertError, ForwardedError } from '@backstage/errors';
2
- import yaml from 'yaml';
3
- import { extname, resolve, dirname, sep, relative, isAbsolute, basename } from 'path';
4
- import Ajv from 'ajv';
5
- import mergeAllOf from 'json-schema-merge-allof';
6
- import traverse from 'json-schema-traverse';
7
- import { ConfigReader } from '@backstage/config';
8
- import fs from 'fs-extra';
9
- import { getProgramFromFiles, generateSchema } from 'typescript-json-schema';
10
- import chokidar from 'chokidar';
11
- import fetch from 'node-fetch';
12
-
13
- const ENV_PREFIX = "APP_CONFIG_";
14
- const CONFIG_KEY_PART_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z][a-z0-9]*)*$/i;
15
- function readEnvConfig(env) {
16
- var _a;
17
- let data = void 0;
18
- for (const [name, value] of Object.entries(env)) {
19
- if (!value) {
20
- continue;
21
- }
22
- if (name.startsWith(ENV_PREFIX)) {
23
- const key = name.replace(ENV_PREFIX, "");
24
- const keyParts = key.split("_");
25
- let obj = data = data != null ? data : {};
26
- for (const [index, part] of keyParts.entries()) {
27
- if (!CONFIG_KEY_PART_PATTERN.test(part)) {
28
- throw new TypeError(`Invalid env config key '${key}'`);
29
- }
30
- if (index < keyParts.length - 1) {
31
- obj = obj[part] = (_a = obj[part]) != null ? _a : {};
32
- if (typeof obj !== "object" || Array.isArray(obj)) {
33
- const subKey = keyParts.slice(0, index + 1).join("_");
34
- throw new TypeError(`Could not nest config for key '${key}' under existing value '${subKey}'`);
35
- }
36
- } else {
37
- if (part in obj) {
38
- throw new TypeError(`Refusing to override existing config at key '${key}'`);
39
- }
40
- try {
41
- const [, parsedValue] = safeJsonParse(value);
42
- if (parsedValue === null) {
43
- throw new Error("value may not be null");
44
- }
45
- obj[part] = parsedValue;
46
- } catch (error) {
47
- throw new TypeError(`Failed to parse JSON-serialized config value for key '${key}', ${error}`);
48
- }
49
- }
50
- }
51
- }
52
- }
53
- return data ? [{ data, context: "env" }] : [];
54
- }
55
- function safeJsonParse(str) {
56
- try {
57
- return [null, JSON.parse(str)];
58
- } catch (err) {
59
- assertError(err);
60
- return [err, str];
61
- }
62
- }
63
-
64
- function isObject(obj) {
65
- if (typeof obj !== "object") {
66
- return false;
67
- } else if (Array.isArray(obj)) {
68
- return false;
69
- }
70
- return obj !== null;
71
- }
72
-
73
- async function applyConfigTransforms(initialDir, input, transforms) {
74
- async function transform(inputObj, path, baseDir) {
75
- var _a;
76
- let obj = inputObj;
77
- let dir = baseDir;
78
- for (const tf of transforms) {
79
- try {
80
- const result = await tf(inputObj, baseDir);
81
- if (result.applied) {
82
- if (result.value === void 0) {
83
- return void 0;
84
- }
85
- obj = result.value;
86
- dir = (_a = result.newBaseDir) != null ? _a : dir;
87
- break;
88
- }
89
- } catch (error) {
90
- assertError(error);
91
- throw new Error(`error at ${path}, ${error.message}`);
92
- }
93
- }
94
- if (typeof obj !== "object") {
95
- return obj;
96
- } else if (obj === null) {
97
- return void 0;
98
- } else if (Array.isArray(obj)) {
99
- const arr = new Array();
100
- for (const [index, value] of obj.entries()) {
101
- const out2 = await transform(value, `${path}[${index}]`, dir);
102
- if (out2 !== void 0) {
103
- arr.push(out2);
104
- }
105
- }
106
- return arr;
107
- }
108
- const out = {};
109
- for (const [key, value] of Object.entries(obj)) {
110
- if (value !== void 0) {
111
- const result = await transform(value, `${path}.${key}`, dir);
112
- if (result !== void 0) {
113
- out[key] = result;
114
- }
115
- }
116
- }
117
- return out;
118
- }
119
- const finalData = await transform(input, "", initialDir);
120
- if (!isObject(finalData)) {
121
- throw new TypeError("expected object at config root");
122
- }
123
- return finalData;
124
- }
125
-
126
- const includeFileParser = {
127
- ".json": async (content) => JSON.parse(content),
128
- ".yaml": async (content) => yaml.parse(content),
129
- ".yml": async (content) => yaml.parse(content)
130
- };
131
- function createIncludeTransform(env, readFile, substitute) {
132
- return async (input, baseDir) => {
133
- if (!isObject(input)) {
134
- return { applied: false };
135
- }
136
- const [includeKey] = Object.keys(input).filter((key) => key.startsWith("$"));
137
- if (includeKey) {
138
- if (Object.keys(input).length !== 1) {
139
- throw new Error(`include key ${includeKey} should not have adjacent keys`);
140
- }
141
- } else {
142
- return { applied: false };
143
- }
144
- const rawIncludedValue = input[includeKey];
145
- if (typeof rawIncludedValue !== "string") {
146
- throw new Error(`${includeKey} include value is not a string`);
147
- }
148
- const substituteResults = await substitute(rawIncludedValue, baseDir);
149
- const includeValue = substituteResults.applied ? substituteResults.value : rawIncludedValue;
150
- if (includeValue === void 0 || typeof includeValue !== "string") {
151
- throw new Error(`${includeKey} substitution value was undefined`);
152
- }
153
- switch (includeKey) {
154
- case "$file":
155
- try {
156
- const value = await readFile(resolve(baseDir, includeValue));
157
- return { applied: true, value };
158
- } catch (error) {
159
- throw new Error(`failed to read file ${includeValue}, ${error}`);
160
- }
161
- case "$env":
162
- try {
163
- return { applied: true, value: await env(includeValue) };
164
- } catch (error) {
165
- throw new Error(`failed to read env ${includeValue}, ${error}`);
166
- }
167
- case "$include": {
168
- const [filePath, dataPath] = includeValue.split(/#(.*)/);
169
- const ext = extname(filePath);
170
- const parser = includeFileParser[ext];
171
- if (!parser) {
172
- throw new Error(`no configuration parser available for included file ${filePath}`);
173
- }
174
- const path = resolve(baseDir, filePath);
175
- const content = await readFile(path);
176
- const newBaseDir = dirname(path);
177
- const parts = dataPath ? dataPath.split(".") : [];
178
- let value;
179
- try {
180
- value = await parser(content);
181
- } catch (error) {
182
- throw new Error(`failed to parse included file ${filePath}, ${error}`);
183
- }
184
- for (const [index, part] of parts.entries()) {
185
- if (!isObject(value)) {
186
- const errPath = parts.slice(0, index).join(".");
187
- throw new Error(`value at '${errPath}' in included file ${filePath} is not an object`);
188
- }
189
- value = value[part];
190
- }
191
- return {
192
- applied: true,
193
- value,
194
- newBaseDir: newBaseDir !== baseDir ? newBaseDir : void 0
195
- };
196
- }
197
- default:
198
- throw new Error(`unknown include ${includeKey}`);
199
- }
200
- };
201
- }
202
-
203
- function createSubstitutionTransform(env) {
204
- return async (input) => {
205
- if (typeof input !== "string") {
206
- return { applied: false };
207
- }
208
- const parts = input.split(/(\$?\$\{[^{}]*\})/);
209
- for (let i = 1; i < parts.length; i += 2) {
210
- const part = parts[i];
211
- if (part.startsWith("$$")) {
212
- parts[i] = part.slice(1);
213
- } else {
214
- parts[i] = await env(part.slice(2, -1).trim());
215
- }
216
- }
217
- if (parts.some((part) => part === void 0)) {
218
- return { applied: true, value: void 0 };
219
- }
220
- return { applied: true, value: parts.join("") };
221
- };
222
- }
223
-
224
- const CONFIG_VISIBILITIES = ["frontend", "backend", "secret"];
225
- const DEFAULT_CONFIG_VISIBILITY = "backend";
226
-
227
- function compileConfigSchemas(schemas) {
228
- const visibilityByDataPath = /* @__PURE__ */ new Map();
229
- const deprecationByDataPath = /* @__PURE__ */ new Map();
230
- const ajv = new Ajv({
231
- allErrors: true,
232
- allowUnionTypes: true,
233
- schemas: {
234
- "https://backstage.io/schema/config-v1": true
235
- }
236
- }).addKeyword({
237
- keyword: "visibility",
238
- metaSchema: {
239
- type: "string",
240
- enum: CONFIG_VISIBILITIES
241
- },
242
- compile(visibility) {
243
- return (_data, context) => {
244
- if ((context == null ? void 0 : context.dataPath) === void 0) {
245
- return false;
246
- }
247
- if (visibility && visibility !== "backend") {
248
- const normalizedPath = context.dataPath.replace(/\['?(.*?)'?\]/g, (_, segment) => `/${segment}`);
249
- visibilityByDataPath.set(normalizedPath, visibility);
250
- }
251
- return true;
252
- };
253
- }
254
- }).removeKeyword("deprecated").addKeyword({
255
- keyword: "deprecated",
256
- metaSchema: { type: "string" },
257
- compile(deprecationDescription) {
258
- return (_data, context) => {
259
- if ((context == null ? void 0 : context.dataPath) === void 0) {
260
- return false;
261
- }
262
- const normalizedPath = context.dataPath.replace(/\['?(.*?)'?\]/g, (_, segment) => `/${segment}`);
263
- deprecationByDataPath.set(normalizedPath, deprecationDescription);
264
- return true;
265
- };
266
- }
267
- });
268
- for (const schema of schemas) {
269
- try {
270
- ajv.compile(schema.value);
271
- } catch (error) {
272
- throw new Error(`Schema at ${schema.path} is invalid, ${error}`);
273
- }
274
- }
275
- const merged = mergeConfigSchemas(schemas.map((_) => _.value));
276
- const validate = ajv.compile(merged);
277
- const visibilityBySchemaPath = /* @__PURE__ */ new Map();
278
- traverse(merged, (schema, path) => {
279
- if (schema.visibility && schema.visibility !== "backend") {
280
- visibilityBySchemaPath.set(path, schema.visibility);
281
- }
282
- });
283
- return (configs) => {
284
- var _a;
285
- const config = ConfigReader.fromConfigs(configs).get();
286
- visibilityByDataPath.clear();
287
- const valid = validate(config);
288
- if (!valid) {
289
- return {
290
- errors: (_a = validate.errors) != null ? _a : [],
291
- visibilityByDataPath: new Map(visibilityByDataPath),
292
- visibilityBySchemaPath,
293
- deprecationByDataPath
294
- };
295
- }
296
- return {
297
- visibilityByDataPath: new Map(visibilityByDataPath),
298
- visibilityBySchemaPath,
299
- deprecationByDataPath
300
- };
301
- };
302
- }
303
- function mergeConfigSchemas(schemas) {
304
- const merged = mergeAllOf({ allOf: schemas }, {
305
- ignoreAdditionalProperties: true,
306
- resolvers: {
307
- visibility(values, path) {
308
- const hasFrontend = values.some((_) => _ === "frontend");
309
- const hasSecret = values.some((_) => _ === "secret");
310
- if (hasFrontend && hasSecret) {
311
- throw new Error(`Config schema visibility is both 'frontend' and 'secret' for ${path.join("/")}`);
312
- } else if (hasFrontend) {
313
- return "frontend";
314
- } else if (hasSecret) {
315
- return "secret";
316
- }
317
- return "backend";
318
- }
319
- }
320
- });
321
- return merged;
322
- }
323
-
324
- const req = typeof __non_webpack_require__ === "undefined" ? require : __non_webpack_require__;
325
- async function collectConfigSchemas(packageNames, packagePaths) {
326
- const schemas = new Array();
327
- const tsSchemaPaths = new Array();
328
- const visitedPackageVersions = /* @__PURE__ */ new Map();
329
- const currentDir = await fs.realpath(process.cwd());
330
- async function processItem(item) {
331
- var _a, _b, _c, _d;
332
- let pkgPath = item.packagePath;
333
- if (pkgPath) {
334
- const pkgExists = await fs.pathExists(pkgPath);
335
- if (!pkgExists) {
336
- return;
337
- }
338
- } else if (item.name) {
339
- const { name, parentPath } = item;
340
- try {
341
- pkgPath = req.resolve(`${name}/package.json`, parentPath && {
342
- paths: [parentPath]
343
- });
344
- } catch {
345
- }
346
- }
347
- if (!pkgPath) {
348
- return;
349
- }
350
- const pkg = await fs.readJson(pkgPath);
351
- let versions = visitedPackageVersions.get(pkg.name);
352
- if (versions == null ? void 0 : versions.has(pkg.version)) {
353
- return;
354
- }
355
- if (!versions) {
356
- versions = /* @__PURE__ */ new Set();
357
- visitedPackageVersions.set(pkg.name, versions);
358
- }
359
- versions.add(pkg.version);
360
- const depNames = [
361
- ...Object.keys((_a = pkg.dependencies) != null ? _a : {}),
362
- ...Object.keys((_b = pkg.devDependencies) != null ? _b : {}),
363
- ...Object.keys((_c = pkg.optionalDependencies) != null ? _c : {}),
364
- ...Object.keys((_d = pkg.peerDependencies) != null ? _d : {})
365
- ];
366
- const hasSchema = "configSchema" in pkg;
367
- const hasBackstageDep = depNames.some((_) => _.startsWith("@backstage/"));
368
- if (!hasSchema && !hasBackstageDep) {
369
- return;
370
- }
371
- if (hasSchema) {
372
- if (typeof pkg.configSchema === "string") {
373
- const isJson = pkg.configSchema.endsWith(".json");
374
- const isDts = pkg.configSchema.endsWith(".d.ts");
375
- if (!isJson && !isDts) {
376
- throw new Error(`Config schema files must be .json or .d.ts, got ${pkg.configSchema}`);
377
- }
378
- if (isDts) {
379
- tsSchemaPaths.push(relative(currentDir, resolve(dirname(pkgPath), pkg.configSchema)));
380
- } else {
381
- const path = resolve(dirname(pkgPath), pkg.configSchema);
382
- const value = await fs.readJson(path);
383
- schemas.push({
384
- value,
385
- path: relative(currentDir, path)
386
- });
387
- }
388
- } else {
389
- schemas.push({
390
- value: pkg.configSchema,
391
- path: relative(currentDir, pkgPath)
392
- });
393
- }
394
- }
395
- await Promise.all(depNames.map((depName) => processItem({ name: depName, parentPath: pkgPath })));
396
- }
397
- await Promise.all([
398
- ...packageNames.map((name) => processItem({ name, parentPath: currentDir })),
399
- ...packagePaths.map((path) => processItem({ name: path, packagePath: path }))
400
- ]);
401
- const tsSchemas = compileTsSchemas(tsSchemaPaths);
402
- return schemas.concat(tsSchemas);
403
- }
404
- function compileTsSchemas(paths) {
405
- if (paths.length === 0) {
406
- return [];
407
- }
408
- const program = getProgramFromFiles(paths, {
409
- incremental: false,
410
- isolatedModules: true,
411
- lib: ["ES5"],
412
- noEmit: true,
413
- noResolve: true,
414
- skipLibCheck: true,
415
- skipDefaultLibCheck: true,
416
- strict: true,
417
- typeRoots: [],
418
- types: []
419
- });
420
- const tsSchemas = paths.map((path) => {
421
- let value;
422
- try {
423
- value = generateSchema(program, "Config", {
424
- required: true,
425
- validationKeywords: ["visibility", "deprecated"]
426
- }, [path.split(sep).join("/")]);
427
- } catch (error) {
428
- assertError(error);
429
- if (error.message !== "type Config not found") {
430
- throw error;
431
- }
432
- }
433
- if (!value) {
434
- throw new Error(`Invalid schema in ${path}, missing Config export`);
435
- }
436
- return { path, value };
437
- });
438
- return tsSchemas;
439
- }
440
-
441
- function filterByVisibility(data, includeVisibilities, visibilityByDataPath, deprecationByDataPath, transformFunc, withFilteredKeys, withDeprecatedKeys) {
442
- var _a;
443
- const filteredKeys = new Array();
444
- const deprecatedKeys = new Array();
445
- function transform(jsonVal, visibilityPath, filterPath) {
446
- var _a2;
447
- const visibility = (_a2 = visibilityByDataPath.get(visibilityPath)) != null ? _a2 : DEFAULT_CONFIG_VISIBILITY;
448
- const isVisible = includeVisibilities.includes(visibility);
449
- const deprecation = deprecationByDataPath.get(visibilityPath);
450
- if (deprecation) {
451
- deprecatedKeys.push({ key: filterPath, description: deprecation });
452
- }
453
- if (typeof jsonVal !== "object") {
454
- if (isVisible) {
455
- if (transformFunc) {
456
- return transformFunc(jsonVal, { visibility });
457
- }
458
- return jsonVal;
459
- }
460
- if (withFilteredKeys) {
461
- filteredKeys.push(filterPath);
462
- }
463
- return void 0;
464
- } else if (jsonVal === null) {
465
- return void 0;
466
- } else if (Array.isArray(jsonVal)) {
467
- const arr = new Array();
468
- for (const [index, value] of jsonVal.entries()) {
469
- let path = visibilityPath;
470
- const hasVisibilityInIndex = visibilityByDataPath.get(`${visibilityPath}/${index}`);
471
- if (hasVisibilityInIndex || typeof value === "object") {
472
- path = `${visibilityPath}/${index}`;
473
- }
474
- const out = transform(value, path, `${filterPath}[${index}]`);
475
- if (out !== void 0) {
476
- arr.push(out);
477
- }
478
- }
479
- if (arr.length > 0 || isVisible) {
480
- return arr;
481
- }
482
- return void 0;
483
- }
484
- const outObj = {};
485
- let hasOutput = false;
486
- for (const [key, value] of Object.entries(jsonVal)) {
487
- if (value === void 0) {
488
- continue;
489
- }
490
- const out = transform(value, `${visibilityPath}/${key}`, filterPath ? `${filterPath}.${key}` : key);
491
- if (out !== void 0) {
492
- outObj[key] = out;
493
- hasOutput = true;
494
- }
495
- }
496
- if (hasOutput || isVisible) {
497
- return outObj;
498
- }
499
- return void 0;
500
- }
501
- return {
502
- filteredKeys: withFilteredKeys ? filteredKeys : void 0,
503
- deprecatedKeys: withDeprecatedKeys ? deprecatedKeys : void 0,
504
- data: (_a = transform(data, "", "")) != null ? _a : {}
505
- };
506
- }
507
- function filterErrorsByVisibility(errors, includeVisibilities, visibilityByDataPath, visibilityBySchemaPath) {
508
- if (!errors) {
509
- return [];
510
- }
511
- if (!includeVisibilities) {
512
- return errors;
513
- }
514
- const visibleSchemaPaths = Array.from(visibilityBySchemaPath).filter(([, v]) => includeVisibilities.includes(v)).map(([k]) => k);
515
- return errors.filter((error) => {
516
- var _a;
517
- if (error.keyword === "type" && ["object", "array"].includes(error.params.type)) {
518
- return true;
519
- }
520
- if (error.keyword === "required") {
521
- const trimmedPath = error.schemaPath.slice(1, -"/required".length);
522
- const fullPath = `${trimmedPath}/properties/${error.params.missingProperty}`;
523
- if (visibleSchemaPaths.some((visiblePath) => visiblePath.startsWith(fullPath))) {
524
- return true;
525
- }
526
- }
527
- const vis = (_a = visibilityByDataPath.get(error.dataPath)) != null ? _a : DEFAULT_CONFIG_VISIBILITY;
528
- return vis && includeVisibilities.includes(vis);
529
- });
530
- }
531
-
532
- function errorsToError(errors) {
533
- const messages = errors.map(({ dataPath, message, params }) => {
534
- const paramStr = Object.entries(params).map(([name, value]) => `${name}=${value}`).join(" ");
535
- return `Config ${message || ""} { ${paramStr} } at ${dataPath}`;
536
- });
537
- const error = new Error(`Config validation failed, ${messages.join("; ")}`);
538
- error.messages = messages;
539
- return error;
540
- }
541
- async function loadConfigSchema(options) {
542
- var _a;
543
- let schemas;
544
- if ("dependencies" in options) {
545
- schemas = await collectConfigSchemas(options.dependencies, (_a = options.packagePaths) != null ? _a : []);
546
- } else {
547
- const { serialized } = options;
548
- if ((serialized == null ? void 0 : serialized.backstageConfigSchemaVersion) !== 1) {
549
- throw new Error("Serialized configuration schema is invalid or has an invalid version number");
550
- }
551
- schemas = serialized.schemas;
552
- }
553
- const validate = compileConfigSchemas(schemas);
554
- return {
555
- process(configs, { visibility, valueTransform, withFilteredKeys, withDeprecatedKeys } = {}) {
556
- const result = validate(configs);
557
- const visibleErrors = filterErrorsByVisibility(result.errors, visibility, result.visibilityByDataPath, result.visibilityBySchemaPath);
558
- if (visibleErrors.length > 0) {
559
- throw errorsToError(visibleErrors);
560
- }
561
- let processedConfigs = configs;
562
- if (visibility) {
563
- processedConfigs = processedConfigs.map(({ data, context }) => ({
564
- context,
565
- ...filterByVisibility(data, visibility, result.visibilityByDataPath, result.deprecationByDataPath, valueTransform, withFilteredKeys, withDeprecatedKeys)
566
- }));
567
- } else if (valueTransform) {
568
- processedConfigs = processedConfigs.map(({ data, context }) => ({
569
- context,
570
- ...filterByVisibility(data, Array.from(CONFIG_VISIBILITIES), result.visibilityByDataPath, result.deprecationByDataPath, valueTransform, withFilteredKeys, withDeprecatedKeys)
571
- }));
572
- }
573
- return processedConfigs;
574
- },
575
- serialize() {
576
- return {
577
- schemas,
578
- backstageConfigSchemaVersion: 1
579
- };
580
- }
581
- };
582
- }
583
-
584
- function isValidUrl(url) {
585
- try {
586
- new URL(url);
587
- return true;
588
- } catch {
589
- return false;
590
- }
591
- }
592
-
593
- async function loadConfig(options) {
594
- const { configRoot, experimentalEnvFunc: envFunc, watch, remote } = options;
595
- const configPaths = options.configTargets.slice().filter((e) => e.hasOwnProperty("path")).map((configTarget) => configTarget.path);
596
- const configUrls = options.configTargets.slice().filter((e) => e.hasOwnProperty("url")).map((configTarget) => configTarget.url);
597
- if (remote === void 0) {
598
- if (configUrls.length > 0) {
599
- throw new Error(`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.`);
600
- }
601
- } else if (remote.reloadIntervalSeconds <= 0) {
602
- throw new Error(`Remote config must be contain a non zero reloadIntervalSeconds: <seconds> value`);
603
- }
604
- if (configPaths.length === 0 && configUrls.length === 0) {
605
- configPaths.push(resolve(configRoot, "app-config.yaml"));
606
- const localConfig = resolve(configRoot, "app-config.local.yaml");
607
- if (await fs.pathExists(localConfig)) {
608
- configPaths.push(localConfig);
609
- }
610
- }
611
- const env = envFunc != null ? envFunc : async (name) => process.env[name];
612
- const loadConfigFiles = async () => {
613
- const configs = [];
614
- for (const configPath of configPaths) {
615
- if (!isAbsolute(configPath)) {
616
- throw new Error(`Config load path is not absolute: '${configPath}'`);
617
- }
618
- const dir = dirname(configPath);
619
- const readFile = (path) => fs.readFile(resolve(dir, path), "utf8");
620
- const input = yaml.parse(await readFile(configPath));
621
- const substitutionTransform = createSubstitutionTransform(env);
622
- const data = await applyConfigTransforms(dir, input, [
623
- createIncludeTransform(env, readFile, substitutionTransform),
624
- substitutionTransform
625
- ]);
626
- configs.push({ data, context: basename(configPath) });
627
- }
628
- return configs;
629
- };
630
- const loadRemoteConfigFiles = async () => {
631
- const configs = [];
632
- const readConfigFromUrl = async (url) => {
633
- const response = await fetch(url);
634
- if (!response.ok) {
635
- throw new Error(`Could not read config file at ${url}`);
636
- }
637
- return await response.text();
638
- };
639
- for (let i = 0; i < configUrls.length; i++) {
640
- const configUrl = configUrls[i];
641
- if (!isValidUrl(configUrl)) {
642
- throw new Error(`Config load path is not valid: '${configUrl}'`);
643
- }
644
- const remoteConfigContent = await readConfigFromUrl(configUrl);
645
- if (!remoteConfigContent) {
646
- throw new Error(`Config is not valid`);
647
- }
648
- const configYaml = yaml.parse(remoteConfigContent);
649
- const substitutionTransform = createSubstitutionTransform(env);
650
- const data = await applyConfigTransforms(configRoot, configYaml, [
651
- substitutionTransform
652
- ]);
653
- configs.push({ data, context: configUrl });
654
- }
655
- return configs;
656
- };
657
- let fileConfigs;
658
- try {
659
- fileConfigs = await loadConfigFiles();
660
- } catch (error) {
661
- throw new ForwardedError("Failed to read static configuration file", error);
662
- }
663
- let remoteConfigs = [];
664
- if (remote) {
665
- try {
666
- remoteConfigs = await loadRemoteConfigFiles();
667
- } catch (error) {
668
- throw new ForwardedError(`Failed to read remote configuration file`, error);
669
- }
670
- }
671
- const envConfigs = await readEnvConfig(process.env);
672
- const watchConfigFile = (watchProp) => {
673
- const watcher = chokidar.watch(configPaths, {
674
- usePolling: process.env.NODE_ENV === "test"
675
- });
676
- let currentSerializedConfig = JSON.stringify(fileConfigs);
677
- watcher.on("change", async () => {
678
- try {
679
- const newConfigs = await loadConfigFiles();
680
- const newSerializedConfig = JSON.stringify(newConfigs);
681
- if (currentSerializedConfig === newSerializedConfig) {
682
- return;
683
- }
684
- currentSerializedConfig = newSerializedConfig;
685
- watchProp.onChange([...remoteConfigs, ...newConfigs, ...envConfigs]);
686
- } catch (error) {
687
- console.error(`Failed to reload configuration files, ${error}`);
688
- }
689
- });
690
- if (watchProp.stopSignal) {
691
- watchProp.stopSignal.then(() => {
692
- watcher.close();
693
- });
694
- }
695
- };
696
- const watchRemoteConfig = (watchProp, remoteProp) => {
697
- const hasConfigChanged = async (oldRemoteConfigs, newRemoteConfigs) => {
698
- return JSON.stringify(oldRemoteConfigs) !== JSON.stringify(newRemoteConfigs);
699
- };
700
- let handle;
701
- try {
702
- handle = setInterval(async () => {
703
- console.info(`Checking for config update`);
704
- const newRemoteConfigs = await loadRemoteConfigFiles();
705
- if (await hasConfigChanged(remoteConfigs, newRemoteConfigs)) {
706
- remoteConfigs = newRemoteConfigs;
707
- console.info(`Remote config change, reloading config ...`);
708
- watchProp.onChange([...remoteConfigs, ...fileConfigs, ...envConfigs]);
709
- console.info(`Remote config reloaded`);
710
- }
711
- }, remoteProp.reloadIntervalSeconds * 1e3);
712
- } catch (error) {
713
- console.error(`Failed to reload configuration files, ${error}`);
714
- }
715
- if (watchProp.stopSignal) {
716
- watchProp.stopSignal.then(() => {
717
- if (handle !== void 0) {
718
- console.info(`Stopping remote config watch`);
719
- clearInterval(handle);
720
- handle = void 0;
721
- }
722
- });
723
- }
724
- };
725
- if (watch) {
726
- watchConfigFile(watch);
727
- }
728
- if (watch && remote) {
729
- watchRemoteConfig(watch, remote);
730
- }
731
- return {
732
- appConfigs: remote ? [...remoteConfigs, ...fileConfigs, ...envConfigs] : [...fileConfigs, ...envConfigs]
733
- };
734
- }
735
-
736
- export { loadConfig, loadConfigSchema, mergeConfigSchemas, readEnvConfig };
737
- //# sourceMappingURL=index.esm.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.esm.js","sources":["../src/lib/env.ts","../src/lib/transform/utils.ts","../src/lib/transform/apply.ts","../src/lib/transform/include.ts","../src/lib/transform/substitution.ts","../src/lib/schema/types.ts","../src/lib/schema/compile.ts","../src/lib/schema/collect.ts","../src/lib/schema/filtering.ts","../src/lib/schema/load.ts","../src/lib/urls.ts","../src/loader.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppConfig } from '@backstage/config';\nimport { JsonObject } from '@backstage/types';\nimport { assertError } from '@backstage/errors';\n\nconst ENV_PREFIX = 'APP_CONFIG_';\n\n// Update the same pattern in config package if this is changed\nconst CONFIG_KEY_PART_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z][a-z0-9]*)*$/i;\n\n/**\n * Read runtime configuration from the environment.\n *\n * Only environment variables prefixed with APP_CONFIG_ will be considered.\n *\n * For each variable, the prefix will be removed, and rest of the key will\n * be split by '_'. Each part will then be used as keys to build up a nested\n * config object structure. The treatment of the entire environment variable\n * is case-sensitive.\n *\n * The value of the variable should be JSON serialized, as it will be parsed\n * and the type will be kept intact. For example \"true\" and true are treated\n * differently, as well as \"42\" and 42.\n *\n * For example, to set the config app.title to \"My Title\", use the following:\n *\n * APP_CONFIG_app_title='\"My Title\"'\n *\n * @public\n */\nexport function readEnvConfig(env: {\n [name: string]: string | undefined;\n}): AppConfig[] {\n let data: JsonObject | undefined = undefined;\n\n for (const [name, value] of Object.entries(env)) {\n if (!value) {\n continue;\n }\n if (name.startsWith(ENV_PREFIX)) {\n const key = name.replace(ENV_PREFIX, '');\n const keyParts = key.split('_');\n\n let obj = (data = data ?? {});\n for (const [index, part] of keyParts.entries()) {\n if (!CONFIG_KEY_PART_PATTERN.test(part)) {\n throw new TypeError(`Invalid env config key '${key}'`);\n }\n if (index < keyParts.length - 1) {\n obj = (obj[part] = obj[part] ?? {}) as JsonObject;\n if (typeof obj !== 'object' || Array.isArray(obj)) {\n const subKey = keyParts.slice(0, index + 1).join('_');\n throw new TypeError(\n `Could not nest config for key '${key}' under existing value '${subKey}'`,\n );\n }\n } else {\n if (part in obj) {\n throw new TypeError(\n `Refusing to override existing config at key '${key}'`,\n );\n }\n try {\n const [, parsedValue] = safeJsonParse(value);\n if (parsedValue === null) {\n throw new Error('value may not be null');\n }\n obj[part] = parsedValue;\n } catch (error) {\n throw new TypeError(\n `Failed to parse JSON-serialized config value for key '${key}', ${error}`,\n );\n }\n }\n }\n }\n }\n\n return data ? [{ data, context: 'env' }] : [];\n}\n\nfunction safeJsonParse(str: string): [Error | null, any] {\n try {\n return [null, JSON.parse(str)];\n } catch (err) {\n assertError(err);\n return [err, str];\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JsonValue, JsonObject } from '@backstage/types';\n\nexport function isObject(obj: JsonValue | undefined): obj is JsonObject {\n if (typeof obj !== 'object') {\n return false;\n } else if (Array.isArray(obj)) {\n return false;\n }\n return obj !== null;\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JsonObject, JsonValue } from '@backstage/types';\nimport { assertError } from '@backstage/errors';\nimport { TransformFunc } from './types';\nimport { isObject } from './utils';\n\n/**\n * Applies a set of transforms to raw configuration data.\n */\nexport async function applyConfigTransforms(\n initialDir: string,\n input: JsonValue,\n transforms: TransformFunc[],\n): Promise<JsonObject> {\n async function transform(\n inputObj: JsonValue,\n path: string,\n baseDir: string,\n ): Promise<JsonValue | undefined> {\n let obj = inputObj;\n let dir = baseDir;\n\n for (const tf of transforms) {\n try {\n const result = await tf(inputObj, baseDir);\n if (result.applied) {\n if (result.value === undefined) {\n return undefined;\n }\n obj = result.value;\n dir = result.newBaseDir ?? dir;\n break;\n }\n } catch (error) {\n assertError(error);\n throw new Error(`error at ${path}, ${error.message}`);\n }\n }\n\n if (typeof obj !== 'object') {\n return obj;\n } else if (obj === null) {\n return undefined;\n } else if (Array.isArray(obj)) {\n const arr = new Array<JsonValue>();\n\n for (const [index, value] of obj.entries()) {\n const out = await transform(value, `${path}[${index}]`, dir);\n if (out !== undefined) {\n arr.push(out);\n }\n }\n\n return arr;\n }\n\n const out: JsonObject = {};\n\n for (const [key, value] of Object.entries(obj)) {\n // undefined covers optional fields\n if (value !== undefined) {\n const result = await transform(value, `${path}.${key}`, dir);\n if (result !== undefined) {\n out[key] = result;\n }\n }\n }\n\n return out;\n }\n\n const finalData = await transform(input, '', initialDir);\n if (!isObject(finalData)) {\n throw new TypeError('expected object at config root');\n }\n return finalData;\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport yaml from 'yaml';\nimport { extname, dirname, resolve as resolvePath } from 'path';\nimport { JsonObject, JsonValue } from '@backstage/types';\nimport { isObject } from './utils';\nimport { TransformFunc, EnvFunc, ReadFileFunc } from './types';\n\n// Parsers for each type of included file\nconst includeFileParser: {\n [ext in string]: (content: string) => Promise<JsonObject>;\n} = {\n '.json': async content => JSON.parse(content),\n '.yaml': async content => yaml.parse(content),\n '.yml': async content => yaml.parse(content),\n};\n\n/**\n * Transforms a include description into the actual included value.\n */\nexport function createIncludeTransform(\n env: EnvFunc,\n readFile: ReadFileFunc,\n substitute: TransformFunc,\n): TransformFunc {\n return async (input: JsonValue, baseDir: string) => {\n if (!isObject(input)) {\n return { applied: false };\n }\n // Check if there's any key that starts with a '$', in that case we treat\n // this entire object as an include description.\n const [includeKey] = Object.keys(input).filter(key => key.startsWith('$'));\n if (includeKey) {\n if (Object.keys(input).length !== 1) {\n throw new Error(\n `include key ${includeKey} should not have adjacent keys`,\n );\n }\n } else {\n return { applied: false };\n }\n\n const rawIncludedValue = input[includeKey];\n if (typeof rawIncludedValue !== 'string') {\n throw new Error(`${includeKey} include value is not a string`);\n }\n\n const substituteResults = await substitute(rawIncludedValue, baseDir);\n const includeValue = substituteResults.applied\n ? substituteResults.value\n : rawIncludedValue;\n\n // The second string check is needed for Typescript to know this is a string.\n if (includeValue === undefined || typeof includeValue !== 'string') {\n throw new Error(`${includeKey} substitution value was undefined`);\n }\n\n switch (includeKey) {\n case '$file':\n try {\n const value = await readFile(resolvePath(baseDir, includeValue));\n return { applied: true, value };\n } catch (error) {\n throw new Error(`failed to read file ${includeValue}, ${error}`);\n }\n case '$env':\n try {\n return { applied: true, value: await env(includeValue) };\n } catch (error) {\n throw new Error(`failed to read env ${includeValue}, ${error}`);\n }\n\n case '$include': {\n const [filePath, dataPath] = includeValue.split(/#(.*)/);\n\n const ext = extname(filePath);\n const parser = includeFileParser[ext];\n if (!parser) {\n throw new Error(\n `no configuration parser available for included file ${filePath}`,\n );\n }\n\n const path = resolvePath(baseDir, filePath);\n const content = await readFile(path);\n const newBaseDir = dirname(path);\n\n const parts = dataPath ? dataPath.split('.') : [];\n\n let value: JsonValue | undefined;\n try {\n value = await parser(content);\n } catch (error) {\n throw new Error(\n `failed to parse included file ${filePath}, ${error}`,\n );\n }\n\n // This bit handles selecting a subtree in the included file, if a path was provided after a #\n for (const [index, part] of parts.entries()) {\n if (!isObject(value)) {\n const errPath = parts.slice(0, index).join('.');\n throw new Error(\n `value at '${errPath}' in included file ${filePath} is not an object`,\n );\n }\n value = value[part];\n }\n\n return {\n applied: true,\n value,\n newBaseDir: newBaseDir !== baseDir ? newBaseDir : undefined,\n };\n }\n\n default:\n throw new Error(`unknown include ${includeKey}`);\n }\n };\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JsonValue } from '@backstage/types';\nimport { TransformFunc, EnvFunc } from './types';\n\n/**\n * A environment variable substitution transform that transforms e.g. 'token ${MY_TOKEN}'\n * to 'token abc' if MY_TOKEN is 'abc'. If any of the substituted variables are undefined,\n * the entire expression ends up undefined.\n */\nexport function createSubstitutionTransform(env: EnvFunc): TransformFunc {\n return async (input: JsonValue) => {\n if (typeof input !== 'string') {\n return { applied: false };\n }\n\n const parts: (string | undefined)[] = input.split(/(\\$?\\$\\{[^{}]*\\})/);\n for (let i = 1; i < parts.length; i += 2) {\n const part = parts[i]!;\n if (part.startsWith('$$')) {\n parts[i] = part.slice(1);\n } else {\n parts[i] = await env(part.slice(2, -1).trim());\n }\n }\n\n if (parts.some(part => part === undefined)) {\n return { applied: true, value: undefined };\n }\n return { applied: true, value: parts.join('') };\n };\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppConfig } from '@backstage/config';\nimport { JsonObject } from '@backstage/types';\n\n/**\n * An sub-set of configuration schema.\n */\nexport type ConfigSchemaPackageEntry = {\n /**\n * The configuration schema itself.\n */\n value: JsonObject;\n /**\n * The relative path that the configuration schema was discovered at.\n */\n path: string;\n};\n\n/**\n * A list of all possible configuration value visibilities.\n */\nexport const CONFIG_VISIBILITIES = ['frontend', 'backend', 'secret'] as const;\n\n/**\n * A type representing the possible configuration value visibilities\n *\n * @public\n */\nexport type ConfigVisibility = 'frontend' | 'backend' | 'secret';\n\n/**\n * The default configuration visibility if no other values is given.\n */\nexport const DEFAULT_CONFIG_VISIBILITY: ConfigVisibility = 'backend';\n\n/**\n * An explanation of a configuration validation error.\n */\nexport type ValidationError = {\n keyword: string;\n dataPath: string;\n schemaPath: string;\n params: Record<string, any>;\n propertyName?: string;\n message?: string;\n};\n\n/**\n * The result of validating configuration data using a schema.\n */\ntype ValidationResult = {\n /**\n * Errors that where emitted during validation, if any.\n */\n errors?: ValidationError[];\n /**\n * The configuration visibilities that were discovered during validation.\n *\n * The path in the key uses the form `/<key>/<sub-key>/<array-index>/<leaf-key>`\n */\n visibilityByDataPath: Map<string, ConfigVisibility>;\n\n /**\n * The configuration visibilities that were discovered during validation.\n *\n * The path in the key uses the form `/properties/<key>/items/additionalProperties/<leaf-key>`\n */\n visibilityBySchemaPath: Map<string, ConfigVisibility>;\n\n /**\n * The deprecated options that were discovered during validation.\n *\n * The path in the key uses the form `/<key>/<sub-key>/<array-index>/<leaf-key>`\n */\n deprecationByDataPath: Map<string, string>;\n};\n\n/**\n * A function used validate configuration data.\n */\nexport type ValidationFunc = (configs: AppConfig[]) => ValidationResult;\n\n/**\n * A function used to transform primitive configuration values.\n *\n * @public\n */\nexport type TransformFunc<T extends number | string | boolean> = (\n value: T,\n context: { visibility: ConfigVisibility },\n) => T | undefined;\n\n/**\n * Options used to process configuration data with a schema.\n *\n * @public\n */\nexport type ConfigSchemaProcessingOptions = {\n /**\n * The visibilities that should be included in the output data.\n * If omitted, the data will not be filtered by visibility.\n */\n visibility?: ConfigVisibility[];\n\n /**\n * A transform function that can be used to transform primitive configuration values\n * during validation. The value returned from the transform function will be used\n * instead of the original value. If the transform returns `undefined`, the value\n * will be omitted.\n */\n valueTransform?: TransformFunc<any>;\n\n /**\n * Whether or not to include the `filteredKeys` property in the output `AppConfig`s.\n *\n * Default: `false`.\n */\n withFilteredKeys?: boolean;\n\n /**\n * Whether or not to include the `deprecatedKeys` property in the output `AppConfig`s.\n *\n * Default: `true`.\n */\n withDeprecatedKeys?: boolean;\n};\n\n/**\n * A loaded configuration schema that is ready to process configuration data.\n *\n * @public\n */\nexport type ConfigSchema = {\n process(\n appConfigs: AppConfig[],\n options?: ConfigSchemaProcessingOptions,\n ): AppConfig[];\n\n serialize(): JsonObject;\n};\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport Ajv from 'ajv';\nimport { JSONSchema7 as JSONSchema } from 'json-schema';\nimport mergeAllOf, { Resolvers } from 'json-schema-merge-allof';\nimport traverse from 'json-schema-traverse';\nimport { ConfigReader } from '@backstage/config';\nimport {\n ConfigSchemaPackageEntry,\n ValidationFunc,\n CONFIG_VISIBILITIES,\n ConfigVisibility,\n} from './types';\n\n/**\n * This takes a collection of Backstage configuration schemas from various\n * sources and compiles them down into a single schema validation function.\n *\n * It also handles the implementation of the custom \"visibility\" keyword used\n * to specify the scope of different config paths.\n */\nexport function compileConfigSchemas(\n schemas: ConfigSchemaPackageEntry[],\n): ValidationFunc {\n // The ajv instance below is stateful and doesn't really allow for additional\n // output during validation. We work around this by having this extra piece\n // of state that we reset before each validation.\n const visibilityByDataPath = new Map<string, ConfigVisibility>();\n const deprecationByDataPath = new Map<string, string>();\n\n const ajv = new Ajv({\n allErrors: true,\n allowUnionTypes: true,\n schemas: {\n 'https://backstage.io/schema/config-v1': true,\n },\n })\n .addKeyword({\n keyword: 'visibility',\n metaSchema: {\n type: 'string',\n enum: CONFIG_VISIBILITIES,\n },\n compile(visibility: ConfigVisibility) {\n return (_data, context) => {\n if (context?.dataPath === undefined) {\n return false;\n }\n if (visibility && visibility !== 'backend') {\n const normalizedPath = context.dataPath.replace(\n /\\['?(.*?)'?\\]/g,\n (_, segment) => `/${segment}`,\n );\n visibilityByDataPath.set(normalizedPath, visibility);\n }\n return true;\n };\n },\n })\n .removeKeyword('deprecated') // remove `deprecated` keyword so that we can implement our own compiler\n .addKeyword({\n keyword: 'deprecated',\n metaSchema: { type: 'string' },\n compile(deprecationDescription: string) {\n return (_data, context) => {\n if (context?.dataPath === undefined) {\n return false;\n }\n const normalizedPath = context.dataPath.replace(\n /\\['?(.*?)'?\\]/g,\n (_, segment) => `/${segment}`,\n );\n // create mapping of deprecation description and data path of property\n deprecationByDataPath.set(normalizedPath, deprecationDescription);\n return true;\n };\n },\n });\n\n for (const schema of schemas) {\n try {\n ajv.compile(schema.value);\n } catch (error) {\n throw new Error(`Schema at ${schema.path} is invalid, ${error}`);\n }\n }\n\n const merged = mergeConfigSchemas(schemas.map(_ => _.value));\n\n const validate = ajv.compile(merged);\n\n const visibilityBySchemaPath = new Map<string, ConfigVisibility>();\n traverse(merged, (schema, path) => {\n if (schema.visibility && schema.visibility !== 'backend') {\n visibilityBySchemaPath.set(path, schema.visibility);\n }\n });\n\n return configs => {\n const config = ConfigReader.fromConfigs(configs).get();\n\n visibilityByDataPath.clear();\n\n const valid = validate(config);\n\n if (!valid) {\n return {\n errors: validate.errors ?? [],\n visibilityByDataPath: new Map(visibilityByDataPath),\n visibilityBySchemaPath,\n deprecationByDataPath,\n };\n }\n\n return {\n visibilityByDataPath: new Map(visibilityByDataPath),\n visibilityBySchemaPath,\n deprecationByDataPath,\n };\n };\n}\n\n/**\n * Given a list of configuration schemas from packages, merge them\n * into a single json schema.\n *\n * @public\n */\nexport function mergeConfigSchemas(schemas: JSONSchema[]): JSONSchema {\n const merged = mergeAllOf(\n { allOf: schemas },\n {\n // JSONSchema is typically subtractive, as in it always reduces the set of allowed\n // inputs through constraints. This changes the object property merging to be additive\n // rather than subtractive.\n ignoreAdditionalProperties: true,\n resolvers: {\n // This ensures that the visibilities across different schemas are sound, and\n // selects the most specific visibility for each path.\n visibility(values: string[], path: string[]) {\n const hasFrontend = values.some(_ => _ === 'frontend');\n const hasSecret = values.some(_ => _ === 'secret');\n if (hasFrontend && hasSecret) {\n throw new Error(\n `Config schema visibility is both 'frontend' and 'secret' for ${path.join(\n '/',\n )}`,\n );\n } else if (hasFrontend) {\n return 'frontend';\n } else if (hasSecret) {\n return 'secret';\n }\n\n return 'backend';\n },\n } as Partial<Resolvers<JSONSchema>>,\n },\n );\n return merged;\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport {\n resolve as resolvePath,\n relative as relativePath,\n dirname,\n sep,\n} from 'path';\nimport { ConfigSchemaPackageEntry } from './types';\nimport { getProgramFromFiles, generateSchema } from 'typescript-json-schema';\nimport { JsonObject } from '@backstage/types';\nimport { assertError } from '@backstage/errors';\n\ntype Item = {\n name?: string;\n parentPath?: string;\n packagePath?: string;\n};\n\nconst req =\n typeof __non_webpack_require__ === 'undefined'\n ? require\n : __non_webpack_require__;\n\n/**\n * This collects all known config schemas across all dependencies of the app.\n */\nexport async function collectConfigSchemas(\n packageNames: string[],\n packagePaths: string[],\n): Promise<ConfigSchemaPackageEntry[]> {\n const schemas = new Array<ConfigSchemaPackageEntry>();\n const tsSchemaPaths = new Array<string>();\n const visitedPackageVersions = new Map<string, Set<string>>(); // pkgName: [versions...]\n\n const currentDir = await fs.realpath(process.cwd());\n\n async function processItem(item: Item) {\n let pkgPath = item.packagePath;\n\n if (pkgPath) {\n const pkgExists = await fs.pathExists(pkgPath);\n if (!pkgExists) {\n return;\n }\n } else if (item.name) {\n const { name, parentPath } = item;\n\n try {\n pkgPath = req.resolve(\n `${name}/package.json`,\n parentPath && {\n paths: [parentPath],\n },\n );\n } catch {\n // We can somewhat safely ignore packages that don't export package.json,\n // as they are likely not part of the Backstage ecosystem anyway.\n }\n }\n if (!pkgPath) {\n return;\n }\n\n const pkg = await fs.readJson(pkgPath);\n\n // Ensures that we only process the same version of each package once.\n let versions = visitedPackageVersions.get(pkg.name);\n if (versions?.has(pkg.version)) {\n return;\n }\n if (!versions) {\n versions = new Set();\n visitedPackageVersions.set(pkg.name, versions);\n }\n versions.add(pkg.version);\n\n const depNames = [\n ...Object.keys(pkg.dependencies ?? {}),\n ...Object.keys(pkg.devDependencies ?? {}),\n ...Object.keys(pkg.optionalDependencies ?? {}),\n ...Object.keys(pkg.peerDependencies ?? {}),\n ];\n\n // TODO(Rugvip): Trying this out to avoid having to traverse the full dependency graph,\n // since that's pretty slow. We probably need a better way to determine when\n // we've left the Backstage ecosystem, but this will do for now.\n const hasSchema = 'configSchema' in pkg;\n const hasBackstageDep = depNames.some(_ => _.startsWith('@backstage/'));\n if (!hasSchema && !hasBackstageDep) {\n return;\n }\n if (hasSchema) {\n if (typeof pkg.configSchema === 'string') {\n const isJson = pkg.configSchema.endsWith('.json');\n const isDts = pkg.configSchema.endsWith('.d.ts');\n if (!isJson && !isDts) {\n throw new Error(\n `Config schema files must be .json or .d.ts, got ${pkg.configSchema}`,\n );\n }\n if (isDts) {\n tsSchemaPaths.push(\n relativePath(\n currentDir,\n resolvePath(dirname(pkgPath), pkg.configSchema),\n ),\n );\n } else {\n const path = resolvePath(dirname(pkgPath), pkg.configSchema);\n const value = await fs.readJson(path);\n schemas.push({\n value,\n path: relativePath(currentDir, path),\n });\n }\n } else {\n schemas.push({\n value: pkg.configSchema,\n path: relativePath(currentDir, pkgPath),\n });\n }\n }\n\n await Promise.all(\n depNames.map(depName =>\n processItem({ name: depName, parentPath: pkgPath }),\n ),\n );\n }\n\n await Promise.all([\n ...packageNames.map(name => processItem({ name, parentPath: currentDir })),\n ...packagePaths.map(path => processItem({ name: path, packagePath: path })),\n ]);\n\n const tsSchemas = compileTsSchemas(tsSchemaPaths);\n\n return schemas.concat(tsSchemas);\n}\n\n// This handles the support of TypeScript .d.ts config schema declarations.\n// We collect all typescript schema definition and compile them all in one go.\n// This is much faster than compiling them separately.\nfunction compileTsSchemas(paths: string[]) {\n if (paths.length === 0) {\n return [];\n }\n\n const program = getProgramFromFiles(paths, {\n incremental: false,\n isolatedModules: true,\n lib: ['ES5'], // Skipping most libs speeds processing up a lot, we just need the primitive types anyway\n noEmit: true,\n noResolve: true,\n skipLibCheck: true, // Skipping lib checks speeds things up\n skipDefaultLibCheck: true,\n strict: true,\n typeRoots: [], // Do not include any additional types\n types: [],\n });\n\n const tsSchemas = paths.map(path => {\n let value;\n try {\n value = generateSchema(\n program,\n // All schemas should export a `Config` symbol\n 'Config',\n // This enables usage of @visibility and @deprecated in doc comments\n {\n required: true,\n validationKeywords: ['visibility', 'deprecated'],\n },\n [path.split(sep).join('/')], // Unix paths are expected for all OSes here\n ) as JsonObject | null;\n } catch (error) {\n assertError(error);\n if (error.message !== 'type Config not found') {\n throw error;\n }\n }\n\n if (!value) {\n throw new Error(`Invalid schema in ${path}, missing Config export`);\n }\n return { path, value };\n });\n\n return tsSchemas;\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JsonObject, JsonValue } from '@backstage/types';\nimport {\n ConfigVisibility,\n DEFAULT_CONFIG_VISIBILITY,\n TransformFunc,\n ValidationError,\n} from './types';\n\n/**\n * This filters data by visibility by discovering the visibility of each\n * value, and then only keeping the ones that are specified in `includeVisibilities`.\n */\nexport function filterByVisibility(\n data: JsonObject,\n includeVisibilities: ConfigVisibility[],\n visibilityByDataPath: Map<string, ConfigVisibility>,\n deprecationByDataPath: Map<string, string>,\n transformFunc?: TransformFunc<number | string | boolean>,\n withFilteredKeys?: boolean,\n withDeprecatedKeys?: boolean,\n): {\n data: JsonObject;\n filteredKeys?: string[];\n deprecatedKeys?: { key: string; description: string }[];\n} {\n const filteredKeys = new Array<string>();\n const deprecatedKeys = new Array<{ key: string; description: string }>();\n\n function transform(\n jsonVal: JsonValue,\n visibilityPath: string, // Matches the format we get from ajv\n filterPath: string, // Matches the format of the ConfigReader\n ): JsonValue | undefined {\n const visibility =\n visibilityByDataPath.get(visibilityPath) ?? DEFAULT_CONFIG_VISIBILITY;\n const isVisible = includeVisibilities.includes(visibility);\n\n // deprecated keys are added regardless of visibility indicator\n const deprecation = deprecationByDataPath.get(visibilityPath);\n if (deprecation) {\n deprecatedKeys.push({ key: filterPath, description: deprecation });\n }\n\n if (typeof jsonVal !== 'object') {\n if (isVisible) {\n if (transformFunc) {\n return transformFunc(jsonVal, { visibility });\n }\n return jsonVal;\n }\n if (withFilteredKeys) {\n filteredKeys.push(filterPath);\n }\n return undefined;\n } else if (jsonVal === null) {\n return undefined;\n } else if (Array.isArray(jsonVal)) {\n const arr = new Array<JsonValue>();\n\n for (const [index, value] of jsonVal.entries()) {\n let path = visibilityPath;\n const hasVisibilityInIndex = visibilityByDataPath.get(\n `${visibilityPath}/${index}`,\n );\n\n if (hasVisibilityInIndex || typeof value === 'object') {\n path = `${visibilityPath}/${index}`;\n }\n\n const out = transform(value, path, `${filterPath}[${index}]`);\n\n if (out !== undefined) {\n arr.push(out);\n }\n }\n\n if (arr.length > 0 || isVisible) {\n return arr;\n }\n return undefined;\n }\n\n const outObj: JsonObject = {};\n let hasOutput = false;\n\n for (const [key, value] of Object.entries(jsonVal)) {\n if (value === undefined) {\n continue;\n }\n const out = transform(\n value,\n `${visibilityPath}/${key}`,\n filterPath ? `${filterPath}.${key}` : key,\n );\n if (out !== undefined) {\n outObj[key] = out;\n hasOutput = true;\n }\n }\n\n if (hasOutput || isVisible) {\n return outObj;\n }\n return undefined;\n }\n\n return {\n filteredKeys: withFilteredKeys ? filteredKeys : undefined,\n deprecatedKeys: withDeprecatedKeys ? deprecatedKeys : undefined,\n data: (transform(data, '', '') as JsonObject) ?? {},\n };\n}\n\nexport function filterErrorsByVisibility(\n errors: ValidationError[] | undefined,\n includeVisibilities: ConfigVisibility[] | undefined,\n visibilityByDataPath: Map<string, ConfigVisibility>,\n visibilityBySchemaPath: Map<string, ConfigVisibility>,\n): ValidationError[] {\n if (!errors) {\n return [];\n }\n if (!includeVisibilities) {\n return errors;\n }\n\n const visibleSchemaPaths = Array.from(visibilityBySchemaPath)\n .filter(([, v]) => includeVisibilities.includes(v))\n .map(([k]) => k);\n\n // If we're filtering by visibility we only care about the errors that happened\n // in a visible path.\n return errors.filter(error => {\n // We always include structural errors as we don't know whether there are\n // any visible paths within the structures.\n if (\n error.keyword === 'type' &&\n ['object', 'array'].includes(error.params.type)\n ) {\n return true;\n }\n\n // For fields that were required we use the schema path to determine whether\n // it was visible in addition to the data path. This is because the data path\n // visibilities are only populated for values that we reached, which we won't\n // if the value is missing.\n // We don't use this method for all the errors as the data path is more robust\n // and doesn't require us to properly trim the schema path.\n if (error.keyword === 'required') {\n const trimmedPath = error.schemaPath.slice(1, -'/required'.length);\n const fullPath = `${trimmedPath}/properties/${error.params.missingProperty}`;\n if (\n visibleSchemaPaths.some(visiblePath => visiblePath.startsWith(fullPath))\n ) {\n return true;\n }\n }\n\n const vis =\n visibilityByDataPath.get(error.dataPath) ?? DEFAULT_CONFIG_VISIBILITY;\n return vis && includeVisibilities.includes(vis);\n });\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppConfig } from '@backstage/config';\nimport { JsonObject } from '@backstage/types';\nimport { compileConfigSchemas } from './compile';\nimport { collectConfigSchemas } from './collect';\nimport { filterByVisibility, filterErrorsByVisibility } from './filtering';\nimport {\n ValidationError,\n ConfigSchema,\n ConfigSchemaPackageEntry,\n CONFIG_VISIBILITIES,\n} from './types';\n\n/**\n * Options that control the loading of configuration schema files in the backend.\n *\n * @public\n */\nexport type LoadConfigSchemaOptions =\n | {\n dependencies: string[];\n packagePaths?: string[];\n }\n | {\n serialized: JsonObject;\n };\n\nfunction errorsToError(errors: ValidationError[]): Error {\n const messages = errors.map(({ dataPath, message, params }) => {\n const paramStr = Object.entries(params)\n .map(([name, value]) => `${name}=${value}`)\n .join(' ');\n return `Config ${message || ''} { ${paramStr} } at ${dataPath}`;\n });\n const error = new Error(`Config validation failed, ${messages.join('; ')}`);\n (error as any).messages = messages;\n return error;\n}\n\n/**\n * Loads config schema for a Backstage instance.\n *\n * @public\n */\nexport async function loadConfigSchema(\n options: LoadConfigSchemaOptions,\n): Promise<ConfigSchema> {\n let schemas: ConfigSchemaPackageEntry[];\n\n if ('dependencies' in options) {\n schemas = await collectConfigSchemas(\n options.dependencies,\n options.packagePaths ?? [],\n );\n } else {\n const { serialized } = options;\n if (serialized?.backstageConfigSchemaVersion !== 1) {\n throw new Error(\n 'Serialized configuration schema is invalid or has an invalid version number',\n );\n }\n schemas = serialized.schemas as ConfigSchemaPackageEntry[];\n }\n\n const validate = compileConfigSchemas(schemas);\n\n return {\n process(\n configs: AppConfig[],\n { visibility, valueTransform, withFilteredKeys, withDeprecatedKeys } = {},\n ): AppConfig[] {\n const result = validate(configs);\n\n const visibleErrors = filterErrorsByVisibility(\n result.errors,\n visibility,\n result.visibilityByDataPath,\n result.visibilityBySchemaPath,\n );\n if (visibleErrors.length > 0) {\n throw errorsToError(visibleErrors);\n }\n\n let processedConfigs = configs;\n\n if (visibility) {\n processedConfigs = processedConfigs.map(({ data, context }) => ({\n context,\n ...filterByVisibility(\n data,\n visibility,\n result.visibilityByDataPath,\n result.deprecationByDataPath,\n valueTransform,\n withFilteredKeys,\n withDeprecatedKeys,\n ),\n }));\n } else if (valueTransform) {\n processedConfigs = processedConfigs.map(({ data, context }) => ({\n context,\n ...filterByVisibility(\n data,\n Array.from(CONFIG_VISIBILITIES),\n result.visibilityByDataPath,\n result.deprecationByDataPath,\n valueTransform,\n withFilteredKeys,\n withDeprecatedKeys,\n ),\n }));\n }\n\n return processedConfigs;\n },\n serialize(): JsonObject {\n return {\n schemas,\n backstageConfigSchemaVersion: 1,\n };\n },\n };\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function isValidUrl(url: string): boolean {\n try {\n // eslint-disable-next-line no-new\n new URL(url);\n return true;\n } catch {\n return false;\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport yaml from 'yaml';\nimport chokidar from 'chokidar';\nimport { basename, dirname, isAbsolute, resolve as resolvePath } from 'path';\nimport { AppConfig } from '@backstage/config';\nimport { ForwardedError } from '@backstage/errors';\nimport {\n applyConfigTransforms,\n createIncludeTransform,\n createSubstitutionTransform,\n isValidUrl,\n readEnvConfig,\n} from './lib';\nimport fetch from 'node-fetch';\n\n/** @public */\nexport type ConfigTarget = { path: string } | { url: string };\n\n/** @public */\nexport type LoadConfigOptionsWatch = {\n /**\n * A listener that is called when a config file is changed.\n */\n onChange: (configs: AppConfig[]) => void;\n\n /**\n * An optional signal that stops the watcher once the promise resolves.\n */\n stopSignal?: Promise<void>;\n};\n\n/** @public */\nexport type LoadConfigOptionsRemote = {\n /**\n * A remote config reloading period, in seconds\n */\n reloadIntervalSeconds: number;\n};\n\n/**\n * Options that control the loading of configuration files in the backend.\n *\n * @public\n */\nexport type LoadConfigOptions = {\n // The root directory of the config loading context. Used to find default configs.\n configRoot: string;\n\n // Paths to load config files from. Configs from earlier paths have lower priority.\n configTargets: ConfigTarget[];\n\n /**\n * Custom environment variable loading function\n *\n * @experimental This API is not stable and may change at any point\n */\n experimentalEnvFunc?: (name: string) => Promise<string | undefined>;\n\n /**\n * An optional remote config\n */\n remote?: LoadConfigOptionsRemote;\n\n /**\n * An optional configuration that enables watching of config files.\n */\n watch?: LoadConfigOptionsWatch;\n};\n\n/**\n * Results of loading configuration files.\n * @public\n */\nexport type LoadConfigResult = {\n /**\n * Array of all loaded configs.\n */\n appConfigs: AppConfig[];\n};\n\n/**\n * Load configuration data.\n *\n * @public\n */\nexport async function loadConfig(\n options: LoadConfigOptions,\n): Promise<LoadConfigResult> {\n const { configRoot, experimentalEnvFunc: envFunc, watch, remote } = options;\n\n const configPaths: string[] = options.configTargets\n .slice()\n .filter((e): e is { path: string } => e.hasOwnProperty('path'))\n .map(configTarget => configTarget.path);\n\n const configUrls: string[] = options.configTargets\n .slice()\n .filter((e): e is { url: string } => e.hasOwnProperty('url'))\n .map(configTarget => configTarget.url);\n\n if (remote === undefined) {\n if (configUrls.length > 0) {\n throw new Error(\n `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.`,\n );\n }\n } else if (remote.reloadIntervalSeconds <= 0) {\n throw new Error(\n `Remote config must be contain a non zero reloadIntervalSeconds: <seconds> value`,\n );\n }\n\n // If no paths are provided, we default to reading\n // `app-config.yaml` and, if it exists, `app-config.local.yaml`\n if (configPaths.length === 0 && configUrls.length === 0) {\n configPaths.push(resolvePath(configRoot, 'app-config.yaml'));\n\n const localConfig = resolvePath(configRoot, 'app-config.local.yaml');\n if (await fs.pathExists(localConfig)) {\n configPaths.push(localConfig);\n }\n }\n\n const env = envFunc ?? (async (name: string) => process.env[name]);\n\n const loadConfigFiles = async () => {\n const configs = [];\n\n for (const configPath of configPaths) {\n if (!isAbsolute(configPath)) {\n throw new Error(`Config load path is not absolute: '${configPath}'`);\n }\n\n const dir = dirname(configPath);\n const readFile = (path: string) =>\n fs.readFile(resolvePath(dir, path), 'utf8');\n\n const input = yaml.parse(await readFile(configPath));\n const substitutionTransform = createSubstitutionTransform(env);\n const data = await applyConfigTransforms(dir, input, [\n createIncludeTransform(env, readFile, substitutionTransform),\n substitutionTransform,\n ]);\n\n configs.push({ data, context: basename(configPath) });\n }\n\n return configs;\n };\n\n const loadRemoteConfigFiles = async () => {\n const configs: AppConfig[] = [];\n\n const readConfigFromUrl = async (url: string) => {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`Could not read config file at ${url}`);\n }\n\n return await response.text();\n };\n\n for (let i = 0; i < configUrls.length; i++) {\n const configUrl = configUrls[i];\n if (!isValidUrl(configUrl)) {\n throw new Error(`Config load path is not valid: '${configUrl}'`);\n }\n\n const remoteConfigContent = await readConfigFromUrl(configUrl);\n if (!remoteConfigContent) {\n throw new Error(`Config is not valid`);\n }\n const configYaml = yaml.parse(remoteConfigContent);\n const substitutionTransform = createSubstitutionTransform(env);\n const data = await applyConfigTransforms(configRoot, configYaml, [\n substitutionTransform,\n ]);\n\n configs.push({ data, context: configUrl });\n }\n\n return configs;\n };\n\n let fileConfigs: AppConfig[];\n try {\n fileConfigs = await loadConfigFiles();\n } catch (error) {\n throw new ForwardedError('Failed to read static configuration file', error);\n }\n\n let remoteConfigs: AppConfig[] = [];\n if (remote) {\n try {\n remoteConfigs = await loadRemoteConfigFiles();\n } catch (error) {\n throw new ForwardedError(\n `Failed to read remote configuration file`,\n error,\n );\n }\n }\n\n const envConfigs = await readEnvConfig(process.env);\n\n const watchConfigFile = (watchProp: LoadConfigOptionsWatch) => {\n const watcher = chokidar.watch(configPaths, {\n usePolling: process.env.NODE_ENV === 'test',\n });\n\n let currentSerializedConfig = JSON.stringify(fileConfigs);\n watcher.on('change', async () => {\n try {\n const newConfigs = await loadConfigFiles();\n const newSerializedConfig = JSON.stringify(newConfigs);\n\n if (currentSerializedConfig === newSerializedConfig) {\n return;\n }\n currentSerializedConfig = newSerializedConfig;\n\n watchProp.onChange([...remoteConfigs, ...newConfigs, ...envConfigs]);\n } catch (error) {\n console.error(`Failed to reload configuration files, ${error}`);\n }\n });\n\n if (watchProp.stopSignal) {\n watchProp.stopSignal.then(() => {\n watcher.close();\n });\n }\n };\n\n const watchRemoteConfig = (\n watchProp: LoadConfigOptionsWatch,\n remoteProp: LoadConfigOptionsRemote,\n ) => {\n const hasConfigChanged = async (\n oldRemoteConfigs: AppConfig[],\n newRemoteConfigs: AppConfig[],\n ) => {\n return (\n JSON.stringify(oldRemoteConfigs) !== JSON.stringify(newRemoteConfigs)\n );\n };\n\n let handle: NodeJS.Timeout | undefined;\n try {\n handle = setInterval(async () => {\n console.info(`Checking for config update`);\n const newRemoteConfigs = await loadRemoteConfigFiles();\n if (await hasConfigChanged(remoteConfigs, newRemoteConfigs)) {\n remoteConfigs = newRemoteConfigs;\n console.info(`Remote config change, reloading config ...`);\n watchProp.onChange([...remoteConfigs, ...fileConfigs, ...envConfigs]);\n console.info(`Remote config reloaded`);\n }\n }, remoteProp.reloadIntervalSeconds * 1000);\n } catch (error) {\n console.error(`Failed to reload configuration files, ${error}`);\n }\n\n if (watchProp.stopSignal) {\n watchProp.stopSignal.then(() => {\n if (handle !== undefined) {\n console.info(`Stopping remote config watch`);\n clearInterval(handle);\n handle = undefined;\n }\n });\n }\n };\n\n // Set up config file watching if requested by the caller\n if (watch) {\n watchConfigFile(watch);\n }\n\n if (watch && remote) {\n watchRemoteConfig(watch, remote);\n }\n\n return {\n appConfigs: remote\n ? [...remoteConfigs, ...fileConfigs, ...envConfigs]\n : [...fileConfigs, ...envConfigs],\n };\n}\n"],"names":["resolvePath","relativePath"],"mappings":";;;;;;;;;;;;AAoBA,MAAM,aAAa;AAGnB,MAAM,0BAA0B;uBAsBF,KAEd;AA/ChB;AAgDE,MAAI,OAA+B;AAEnC,aAAW,CAAC,MAAM,UAAU,OAAO,QAAQ,MAAM;AAC/C,QAAI,CAAC,OAAO;AACV;AAAA;AAEF,QAAI,KAAK,WAAW,aAAa;AAC/B,YAAM,MAAM,KAAK,QAAQ,YAAY;AACrC,YAAM,WAAW,IAAI,MAAM;AAE3B,UAAI,MAAO,OAAO,sBAAQ;AAC1B,iBAAW,CAAC,OAAO,SAAS,SAAS,WAAW;AAC9C,YAAI,CAAC,wBAAwB,KAAK,OAAO;AACvC,gBAAM,IAAI,UAAU,2BAA2B;AAAA;AAEjD,YAAI,QAAQ,SAAS,SAAS,GAAG;AAC/B,gBAAO,IAAI,QAAQ,UAAI,UAAJ,YAAa;AAChC,cAAI,OAAO,QAAQ,YAAY,MAAM,QAAQ,MAAM;AACjD,kBAAM,SAAS,SAAS,MAAM,GAAG,QAAQ,GAAG,KAAK;AACjD,kBAAM,IAAI,UACR,kCAAkC,8BAA8B;AAAA;AAAA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