@adobe/helix-shared-config 1.7.22 → 2.0.1

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.
Files changed (46) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/package.json +10 -7
  3. package/src/config-wrapper.js +0 -6
  4. package/src/index.js +0 -12
  5. package/src/Condition.js +0 -573
  6. package/src/ConfigValidator.js +0 -95
  7. package/src/DataEmbedValidator.js +0 -51
  8. package/src/DynamicRedirect.js +0 -125
  9. package/src/HelixConfig.js +0 -133
  10. package/src/MarkupConfig.js +0 -35
  11. package/src/Origin.js +0 -159
  12. package/src/Performance.js +0 -80
  13. package/src/Redirect.js +0 -64
  14. package/src/RedirectConfig.js +0 -64
  15. package/src/RedirectRuleHandler.js +0 -46
  16. package/src/Static.js +0 -119
  17. package/src/Strain.js +0 -332
  18. package/src/Strains.js +0 -68
  19. package/src/schemas/conditions.schema.json +0 -140
  20. package/src/schemas/config.description.md +0 -7
  21. package/src/schemas/config.example.1.json +0 -26
  22. package/src/schemas/config.schema.json +0 -44
  23. package/src/schemas/data-embed-response.schema.json +0 -40
  24. package/src/schemas/giturl.schema.json +0 -62
  25. package/src/schemas/markup.schema.json +0 -22
  26. package/src/schemas/markupconfig.schema.json +0 -38
  27. package/src/schemas/markupmapping.description.md +0 -242
  28. package/src/schemas/markupmapping.schema.json +0 -122
  29. package/src/schemas/origin.description.md +0 -5
  30. package/src/schemas/origin.schema.json +0 -86
  31. package/src/schemas/performance.schema.json +0 -210
  32. package/src/schemas/proxystrain.description.md +0 -20
  33. package/src/schemas/proxystrain.schema.json +0 -87
  34. package/src/schemas/redirect.schema.json +0 -34
  35. package/src/schemas/redirectrule.schema.json +0 -46
  36. package/src/schemas/redirects.description.md +0 -1
  37. package/src/schemas/redirects.schema.json +0 -41
  38. package/src/schemas/row.schema.json +0 -23
  39. package/src/schemas/runtimestrain.schema.json +0 -144
  40. package/src/schemas/sheet.schema.json +0 -57
  41. package/src/schemas/staticgiturl.schema.json +0 -80
  42. package/src/schemas/strains.schema.json +0 -39
  43. package/src/schemas/vanity.schema.json +0 -38
  44. package/src/schemas/version-lock.description.md +0 -3
  45. package/src/schemas/version-lock.schema.json +0 -35
  46. package/src/schemas/workbook.schema.json +0 -49
@@ -1,95 +0,0 @@
1
- /*
2
- * Copyright 2018 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
-
13
- /* eslint-disable max-classes-per-file */
14
-
15
- const Ajv = require('ajv').default;
16
- const ajvFormats = require('ajv-formats');
17
- const ValidationError = require('./ValidationError.js');
18
-
19
- const schemas = [
20
- /* eslint-disable global-require */
21
- require('./schemas/config.schema.json'),
22
- require('./schemas/version-lock.schema.json'),
23
- require('./schemas/runtimestrain.schema.json'),
24
- require('./schemas/proxystrain.schema.json'),
25
- require('./schemas/strains.schema.json'),
26
- require('./schemas/giturl.schema.json'),
27
- require('./schemas/staticgiturl.schema.json'),
28
- require('./schemas/origin.schema.json'),
29
- require('./schemas/performance.schema.json'),
30
- require('./schemas/redirectrule.schema.json'),
31
- require('./schemas/conditions.schema.json'),
32
- /* eslint-enable global-require */
33
- ];
34
-
35
- class HelixConfigValidationError extends ValidationError {
36
- constructor(msg, errors = []) {
37
- super(msg, errors, HelixConfigValidationError.mapError, HelixConfigValidationError.prettyname);
38
- }
39
-
40
- static prettyname(path, schema) {
41
- if (path && path.startsWith('.strains')) {
42
- return `${schema.title || 'Invalid Strain'} ${path.replace(/\.strains(\.|\[')(.*)/, '$2').replace(/'.*/, '')}`;
43
- }
44
- return ValidationError.prettyname(path, schema);
45
- }
46
-
47
- static mapError({
48
- keyword, dataPath, message, data, params, parentSchema,
49
- }, prettyname) {
50
- if (keyword === 'required' && dataPath === '') {
51
- return 'A set of strains and a default strain are missing.';
52
- }
53
- if (keyword === 'required' && dataPath === '.strains') {
54
- return 'A default strain is missing.';
55
- }
56
- if (keyword === 'oneOf' && dataPath.startsWith('.strains')) {
57
- return `${prettyname(dataPath, parentSchema)} must be either a Runtime Strain or a Proxy Strain`;
58
- }
59
- return ValidationError.mapError(keyword, dataPath, message, data, params, parentSchema);
60
- }
61
- }
62
-
63
- class ConfigValidator {
64
- constructor() {
65
- this._ajv = new Ajv({
66
- allErrors: true,
67
- verbose: true,
68
- useDefaults: true,
69
- coerceTypes: true,
70
- strict: false,
71
- });
72
- this._ajv.addSchema(schemas);
73
- ajvFormats(this._ajv);
74
- }
75
-
76
- validate(config = {}) {
77
- this._ajv.errors = [];
78
- return this._ajv.validate('https://ns.adobe.com/helix/shared/config', config);
79
- }
80
-
81
- assetValid(config = {}) {
82
- // handle simple case for no strains. since the ajv error is a bit cryptic.
83
- if (!config.strains
84
- || ((config.strains.find && !config.strains.find((s) => s.name === 'default'))
85
- && !config.strains.default)) {
86
- throw new HelixConfigValidationError('A list of strains and a strain with the name "default" is required.');
87
- }
88
- const valid = this.validate(config);
89
- if (!valid) {
90
- throw new HelixConfigValidationError(this._ajv.errorsText(), this._ajv.errors);
91
- }
92
- }
93
- }
94
-
95
- module.exports = ConfigValidator;
@@ -1,51 +0,0 @@
1
- /*
2
- * Copyright 2018 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
-
13
- const Ajv = require('ajv').default;
14
- const ajvFormats = require('ajv-formats');
15
-
16
- const schemas = [
17
- /* eslint-disable global-require */
18
- require('./schemas/data-embed-response.schema.json'),
19
- require('./schemas/row.schema.json'),
20
- require('./schemas/sheet.schema.json'),
21
- require('./schemas/workbook.schema.json'),
22
- /* eslint-enable global-require */
23
- ];
24
-
25
- class DataEmbedValidator {
26
- constructor() {
27
- this._ajv = new Ajv({
28
- allErrors: true,
29
- verbose: true,
30
- useDefaults: false,
31
- coerceTypes: false,
32
- strict: false,
33
- });
34
- this._ajv.addSchema(schemas);
35
- ajvFormats(this._ajv);
36
- }
37
-
38
- validate(response = {}) {
39
- this._ajv.errors = [];
40
- return this._ajv.validate('https://ns.adobe.com/helix/data-embed/response', response);
41
- }
42
-
43
- assertValid(response) {
44
- const valid = this.validate(response);
45
- if (!valid) {
46
- throw new Error(this._ajv.errorsText());
47
- }
48
- }
49
- }
50
-
51
- module.exports = DataEmbedValidator;
@@ -1,125 +0,0 @@
1
- /*
2
- * Copyright 2019 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
- const { URL } = require('url');
13
- const fetchAPI = require('@adobe/helix-fetch');
14
-
15
- const { fetch } = process.env.HELIX_FETCH_FORCE_HTTP1
16
- ? fetchAPI.context({
17
- alpnProtocols: [fetchAPI.ALPN_HTTP1_1],
18
- })
19
- /* istanbul ignore next */
20
- : fetchAPI;
21
-
22
- const DEFAULT_TYPE = 'permanent';
23
- const FROM_NAMES = ['from', 'src', 'source', 'origin'];
24
- const TO_NAMES = ['to', 'target', 'dest', 'destination'];
25
- const TYPE_NAMES = ['type', 'kind'];
26
-
27
- function getProp(entry, names) {
28
- const pair = Object.entries(entry).find(([key]) => names.includes(key.toLowerCase()));
29
- return pair ? pair[1] : null;
30
- }
31
-
32
- function getPath(value) {
33
- if (value && value.startsWith('https://')) {
34
- return new URL(value).pathname;
35
- }
36
- return value;
37
- }
38
-
39
- function trim(value) {
40
- if (value && typeof value === 'string') {
41
- return value.trim();
42
- }
43
- return value;
44
- }
45
-
46
- function clean(entry) {
47
- return {
48
- from: getPath(trim(getProp(entry, FROM_NAMES))),
49
- to: trim(getProp(entry, TO_NAMES)),
50
- type: trim(getProp(entry, TYPE_NAMES)),
51
- };
52
- }
53
-
54
- class DynamicRedirect {
55
- constructor(src, logger) {
56
- this._src = src;
57
- this._data = null;
58
- this._logger = logger;
59
- this._transactionID = null;
60
- this._githubToken = null;
61
- }
62
-
63
- withTransactionID(id) {
64
- this._transactionID = id;
65
- return this;
66
- }
67
-
68
- withGithubToken(token) {
69
- this._githubToken = token;
70
- return this;
71
- }
72
-
73
- async fetch() {
74
- if (!this._data) {
75
- try {
76
- let url = new URL(this._src);
77
- if (!this._src.endsWith('.json')) {
78
- // load via universal runtime (todo: do this via a plugin)
79
- url = new URL('https://helix-pages.anywhere.run/helix-services/data-embed@v2');
80
- url.searchParams.append('src', this._src);
81
- }
82
- const res = await fetch(url.href, {
83
- headers: {
84
- ...(this._transactionID ? { 'x-request-id': this._transactionID } : {}),
85
- ...(this._githubToken ? { 'x-github-token': this._githubToken } : {}),
86
- },
87
- });
88
- const data = await res.json();
89
- if (res.ok) {
90
- this._data = data;
91
- if ('data' in this._data) {
92
- this._data = this._data.data;
93
- }
94
- this._data = this._data.map(clean);
95
- }
96
- this._logger.info(`loaded lookup table from ${this._src}`);
97
- } catch (e) {
98
- this._logger.warn(`failed to get ${this._src} ${e.message}`);
99
- }
100
- }
101
- }
102
-
103
- async match(path) {
104
- await this.fetch();
105
- if (this._data) {
106
- const hit = this._data.find((entry) => entry.from === path
107
- || entry.from === path.replace(/[ äӓ]/g, encodeURIComponent));
108
- return hit ? {
109
- url: hit.to,
110
- type: hit.type || DEFAULT_TYPE,
111
- } : null;
112
- }
113
- return null;
114
- }
115
-
116
- async all() {
117
- await this.fetch();
118
- if (this._data) {
119
- return this._data;
120
- }
121
- return [];
122
- }
123
- }
124
-
125
- module.exports = DynamicRedirect;
@@ -1,133 +0,0 @@
1
- /*
2
- * Copyright 2018 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
-
13
- const Strain = require('./Strain.js');
14
- const Strains = require('./Strains.js');
15
- const ConfigValidator = require('./ConfigValidator.js');
16
- const BaseConfig = require('./BaseConfig.js');
17
-
18
- const HELIX_CONFIG = 'helix-config.yaml';
19
-
20
- class HelixConfig extends BaseConfig {
21
- constructor() {
22
- super(HELIX_CONFIG);
23
- this._strains = new Strains();
24
- }
25
-
26
- /**
27
- * @name ResolveFn
28
- * @function
29
- * @param {Strain} left the current candidate strain (can be undefined)
30
- * @param {Strain} right the alternative candidate strain (can be undefined)
31
- */
32
-
33
- /**
34
- * Updates the current configuration with the strains of another configuration
35
- * object and a user-defined resolver function.
36
- * @param {HelixConfig} other another Helix Config to merge
37
- * @param {ResolveFn} resolvefn a resolver function that returns either a strain or undefined
38
- * @returns {HelixConfig} the merged Helix Config, i.e. `this`.
39
- */
40
- merge(other, resolvefn) {
41
- const accept = (acceptedstrains, strainname) => {
42
- const strain = resolvefn(
43
- this.strains.get(strainname),
44
- other.strains.get(strainname),
45
- ); // resolve conflict with the resolverfn
46
- if (strain) {
47
- acceptedstrains.add(strain); // add the strain (if existing) to the new list of strains
48
- }
49
- return acceptedstrains;
50
- };
51
-
52
- this._strains = [...new Set([...other.strains.keys(), ...this.strains.keys()]).keys()]
53
- .reduce(accept, new Strains());
54
-
55
- return this;
56
- }
57
-
58
- /**
59
- * Strains of this config.
60
- * @returns {Strains}
61
- */
62
- get strains() {
63
- return this._strains;
64
- }
65
-
66
- async validate() {
67
- // convert strains-map to array if needed (see https://github.com/adobe/helix-shared/issues/71)
68
- if (typeof this._cfg.strains === 'object' && !Array.isArray(this._cfg.strains)) {
69
- this._cfg.strains = Object.keys(this._cfg.strains).map((name) => {
70
- const strain = this._cfg.strains[name];
71
- strain.name = name;
72
- return strain;
73
- });
74
- // invalidate yaml document
75
- this._document = null;
76
- }
77
- new ConfigValidator().assetValid(this._cfg);
78
- }
79
-
80
- async init() {
81
- await this.loadConfig();
82
- await this.validate();
83
-
84
- this._version = this._cfg.version;
85
- if (this._document) {
86
- // create strains from document
87
- const strains = this._document.contents.items.filter((item) => item.key.value === 'strains');
88
- // strains.length is always > 0, since JSON schema mandates a strains object
89
- this._strains.fromYAML(strains[0].value);
90
- } else {
91
- this._cfg.strains.forEach((strain) => {
92
- this._strains.add(new Strain(strain));
93
- });
94
- }
95
- return this;
96
- }
97
-
98
- get preflight() {
99
- return this._cfg.preflight;
100
- }
101
-
102
- /**
103
- * Gets a list of all preflight headers used in this config
104
- * @returns String[]
105
- */
106
- get preflightHeaders() {
107
- return [...this._strains
108
- .getByFilter((s) => s.condition)
109
- .map((s) => s.condition)
110
- .reduce((s, c) => {
111
- const headers = c.preflightHeaders;
112
- if (headers && Array.isArray(headers)) {
113
- headers.forEach((h) => s.add(h));
114
- }
115
- return s;
116
- }, new Set())];
117
- }
118
-
119
- toJSON() {
120
- const retval = {
121
- version: this._version,
122
- strains: this._strains.toJSON(),
123
- };
124
-
125
- if (this.preflight) {
126
- retval.preflight = this.preflight;
127
- }
128
-
129
- return retval;
130
- }
131
- }
132
-
133
- module.exports = HelixConfig;
@@ -1,35 +0,0 @@
1
- /*
2
- * Copyright 2019 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
- const SchemaDerivedConfig = require('./SchemaDerivedConfig.js');
13
- const { NamedMapHandler } = require('./NamedMapHandler');
14
-
15
- const markupConfigSchema = require('./schemas/markupconfig.schema.json');
16
- const markupSchema = require('./schemas/markup.schema.json');
17
- const markupMappingSchema = require('./schemas/markupmapping.schema.json');
18
-
19
- class MarkupConfig extends SchemaDerivedConfig {
20
- constructor() {
21
- super({
22
- filename: 'helix-markup.yaml',
23
- schemas: {
24
- '^/$': markupConfigSchema,
25
- '^/markup$': markupSchema,
26
- '^/markup/.*$': markupMappingSchema,
27
- },
28
- handlers: {
29
- '^/markup$': NamedMapHandler(),
30
- },
31
- });
32
- }
33
- }
34
-
35
- module.exports = MarkupConfig;
package/src/Origin.js DELETED
@@ -1,159 +0,0 @@
1
- /*
2
- * Copyright 2021 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
- const URI = require('uri-js');
13
- const hash = require('object-hash');
14
- const pruneEmptyValues = require('@adobe/helix-shared-prune');
15
-
16
- class Origin {
17
- constructor(cfg) {
18
- if (typeof cfg === 'object') {
19
- this._hostname = cfg.hostname || cfg.address;
20
- this._errorThreshold = cfg.error_threshold || 0;
21
- this._firstByteTimeout = cfg.first_byte_timeout || 0;
22
- this._weight = cfg.weight || 100;
23
- this._address = cfg.address;
24
- this._connectTimeout = cfg.connect_timeout || 1000;
25
- this._name = cfg.name || `Proxy${this._hostname.replace(/[^\w]/g, '')}${hash(this._hostname).substr(0, 4)}`;
26
- this._betweenBytesTimeout = cfg.between_bytes_timeout || 10000;
27
- this._shield = cfg.shield || 'bwi-va-us';
28
- this._SSLCertHostname = cfg.ssl_cert_hostname || this._hostname;
29
- this._maxConn = cfg.max_conn || 200;
30
- this._useSSL = !(cfg.use_ssl === false);
31
- this._path = cfg.path || '/';
32
- this._overrideHost = cfg.override_host;
33
- if (cfg.port && Number.parseInt(cfg.port, 10) > 0) {
34
- this._port = cfg.port;
35
- } else {
36
- this._port = this._useSSL ? 443 : 80;
37
- }
38
- } else if (cfg && URI.parse(cfg).scheme) {
39
- const backenduri = URI.parse(cfg);
40
- this._hostname = backenduri.host;
41
- this._errorThreshold = 0;
42
- this._firstByteTimeout = 15000;
43
- this._weight = 100;
44
- this._address = backenduri.host;
45
- this._connectTimeout = 1000;
46
- this._name = `Proxy${this._hostname.replace(/[^\w]/g, '')}${hash(this._hostname).substr(0, 4)}`;
47
- this._port = backenduri.port || (backenduri.scheme === 'https' ? 443 : 80);
48
- this._betweenBytesTimeout = 10000;
49
- this._shield = 'bwi-va-us';
50
- this._SSLCertHostname = backenduri.host;
51
- this._maxConn = 200;
52
- this._useSSL = backenduri.scheme === 'https';
53
- this._path = backenduri.path;
54
- } else if (cfg) {
55
- throw new Error('Origin must be an absolute URL or an Object');
56
- } else {
57
- throw new Error('Invalid or empty configuration');
58
- }
59
- }
60
-
61
- get hostname() {
62
- return this._hostname;
63
- }
64
-
65
- get errorThreshold() {
66
- return this._errorThreshold;
67
- }
68
-
69
- get firstByteTimeout() {
70
- return this._firstByteTimeout;
71
- }
72
-
73
- get weight() {
74
- return this._weight;
75
- }
76
-
77
- get address() {
78
- return this._address;
79
- }
80
-
81
- get connectTimeout() {
82
- return Number.parseInt(this._connectTimeout, 10);
83
- }
84
-
85
- get name() {
86
- return this._name;
87
- }
88
-
89
- get port() {
90
- return Number.parseInt(this._port, 10);
91
- }
92
-
93
- get betweenBytesTimeout() {
94
- return this._betweenBytesTimeout;
95
- }
96
-
97
- get shield() {
98
- return this._shield;
99
- }
100
-
101
- get SSLCertHostname() {
102
- return this._SSLCertHostname;
103
- }
104
-
105
- get maxConn() {
106
- return this._maxConn;
107
- }
108
-
109
- get useSSL() {
110
- return this._useSSL;
111
- }
112
-
113
- get path() {
114
- return this._path;
115
- }
116
-
117
- get overrideHost() {
118
- return this._overrideHost;
119
- }
120
-
121
- /**
122
- * Returns a limited JSON representation that is compatible with the Fastly API
123
- */
124
- toFastlyJSON() {
125
- const json = {
126
- hostname: this.hostname,
127
- error_threshold: this.errorThreshold,
128
- first_byte_timeout: this.firstByteTimeout,
129
- weight: this.weight,
130
- address: this.address,
131
- connect_timeout: this.connectTimeout,
132
- name: this.name,
133
- port: this.port,
134
- between_bytes_timeout: this.betweenBytesTimeout,
135
- shield: this.shield,
136
- ssl_cert_hostname: this.SSLCertHostname,
137
- max_conn: this.maxConn,
138
- use_ssl: this.useSSL,
139
- };
140
- if (this.overrideHost) {
141
- json.override_host = this.overrideHost;
142
- }
143
- return json;
144
- }
145
-
146
- /**
147
- * Returns a full, round-trippable JSON representation
148
- */
149
- toJSON(opts) {
150
- const json = this.toFastlyJSON();
151
- json.path = this.path;
152
- if (opts && opts.minimal) {
153
- return pruneEmptyValues(json);
154
- }
155
- return json;
156
- }
157
- }
158
-
159
- module.exports = Origin;
@@ -1,80 +0,0 @@
1
- /*
2
- * Copyright 2021 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
-
13
- const YAML = require('yaml');
14
- const pruneEmptyValues = require('@adobe/helix-shared-prune');
15
-
16
- /**
17
- * Performance Definition
18
- */
19
- class Performance {
20
- constructor(cfg = {}) {
21
- this._device = cfg.device || '';
22
- this._location = cfg.location || '';
23
- this._connection = cfg.connection || '';
24
- this._thresholds = Object.keys(cfg).reduce((p, k) => {
25
- // copy all properties that are numbers
26
- if (cfg[k] && typeof cfg[k] === 'number') {
27
- // eslint-disable-next-line no-param-reassign
28
- p[k] = cfg[k];
29
- }
30
- return p;
31
- }, {});
32
- }
33
-
34
- get device() {
35
- return this._device;
36
- }
37
-
38
- get location() {
39
- return this._location;
40
- }
41
-
42
- get connection() {
43
- return this._connection;
44
- }
45
-
46
- get thresholds() {
47
- return this._thresholds;
48
- }
49
-
50
- /**
51
- * JSON Serialization of Performance
52
- * @typedef Performance~JSON
53
- * @property {String} device
54
- * @property {String} location
55
- * @property {String} connection
56
- */
57
-
58
- /**
59
- * Returns a json representation
60
- * @returns {Performance~JSON}
61
- */
62
- toJSON(opts) {
63
- const json = {
64
- device: this.device,
65
- location: this.location,
66
- connection: this.connection,
67
- ...this.thresholds,
68
- };
69
- if (opts && opts.minimal) {
70
- return pruneEmptyValues(json);
71
- }
72
- return json;
73
- }
74
-
75
- toYAMLNode() {
76
- const json = this.toJSON({ minimal: true });
77
- return json ? YAML.createNode(json) : null;
78
- }
79
- }
80
- module.exports = Performance;