@redocly/openapi-core 1.0.0-beta.86 → 1.0.0-beta.89

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.
@@ -2,10 +2,8 @@ import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import { dirname } from 'path';
4
4
  import { red, blue } from 'colorette';
5
-
6
5
  import { parseYaml, stringifyYaml } from '../js-yaml';
7
6
  import { notUndefined, slash } from '../utils';
8
-
9
7
  import {
10
8
  OasVersion,
11
9
  Oas3PreprocessorsSet,
@@ -14,11 +12,9 @@ import {
14
12
  Oas2RuleSet,
15
13
  Oas2PreprocessorsSet,
16
14
  Oas2DecoratorsSet,
17
- Oas3RuleSet
15
+ Oas3RuleSet,
18
16
  } from '../oas-types';
19
-
20
17
  import { ProblemSeverity, NormalizedProblem } from '../walk';
21
-
22
18
  import recommended from './recommended';
23
19
  import { NodeType } from '../types';
24
20
 
@@ -124,13 +120,12 @@ export type ResolveConfig = {
124
120
 
125
121
  export const DEFAULT_REGION = 'us';
126
122
  export type Region = 'us' | 'eu';
127
- export type AccessTokens = {[region in Region]?: string };
123
+ export type AccessTokens = { [region in Region]?: string };
128
124
  const REDOCLY_DOMAIN = process.env.REDOCLY_DOMAIN;
129
125
  export const DOMAINS: { [region in Region]: string } = {
130
126
  us: 'redocly.com',
131
127
  eu: 'eu.redocly.com',
132
128
  };
133
- export const AVAILABLE_REGIONS = Object.keys(DOMAINS) as Region[];
134
129
 
135
130
  // FIXME: temporary fix for our lab environments
136
131
  if (REDOCLY_DOMAIN?.endsWith('.redocly.host')) {
@@ -139,13 +134,31 @@ if (REDOCLY_DOMAIN?.endsWith('.redocly.host')) {
139
134
  if (REDOCLY_DOMAIN === 'redoc.online') {
140
135
  DOMAINS[REDOCLY_DOMAIN as Region] = REDOCLY_DOMAIN;
141
136
  }
137
+ export const AVAILABLE_REGIONS = Object.keys(DOMAINS) as Region[];
142
138
 
143
- export type RawConfig = {
144
- referenceDocs?: any;
139
+ export type DeprecatedRawConfig = {
145
140
  apiDefinitions?: Record<string, string>;
146
141
  lint?: LintRawConfig;
147
142
  resolve?: RawResolveConfig;
148
143
  region?: Region;
144
+ referenceDocs?: Record<string, any>;
145
+ };
146
+
147
+ export type Api = {
148
+ root: string;
149
+ lint?: Omit<LintRawConfig, 'plugins'>;
150
+ 'features.openapi'?: Record<string, any>;
151
+ 'features.mockServer'?: Record<string, any>;
152
+ };
153
+
154
+ export type RawConfig = {
155
+ apis?: Record<string, Api>;
156
+ lint?: LintRawConfig;
157
+ resolve?: RawResolveConfig;
158
+ region?: Region;
159
+ 'features.openapi'?: Record<string, any>;
160
+ 'features.mockServer'?: Record<string, any>;
161
+ organization?: string;
149
162
  };
150
163
 
151
164
  export class LintConfig {
@@ -201,7 +214,9 @@ export class LintConfig {
201
214
  [OasVersion.Version3_1]: { ...merged.decorators, ...merged.oas3_1Decorators },
202
215
  };
203
216
 
204
- const dir = this.configFile ? path.dirname(this.configFile) : (typeof process !== 'undefined' && process.cwd() || '');
217
+ const dir = this.configFile
218
+ ? path.dirname(this.configFile)
219
+ : (typeof process !== 'undefined' && process.cwd()) || '';
205
220
  const ignoreFile = path.join(dir, IGNORE_FILE);
206
221
 
207
222
  /* no crash when using it on the client */
@@ -229,7 +244,8 @@ export class LintConfig {
229
244
  const ignoreFile = path.join(dir, IGNORE_FILE);
230
245
  const mapped: Record<string, any> = {};
231
246
  for (const absFileName of Object.keys(this.ignore)) {
232
- const ignoredRules = (mapped[slash(path.relative(dir, absFileName))] = this.ignore[absFileName]);
247
+ const ignoredRules = (mapped[slash(path.relative(dir, absFileName))] =
248
+ this.ignore[absFileName]);
233
249
  for (const ruleId of Object.keys(ignoredRules)) {
234
250
  ignoredRules[ruleId] = Array.from(ignoredRules[ruleId]) as any;
235
251
  }
@@ -398,16 +414,19 @@ export class LintConfig {
398
414
  }
399
415
 
400
416
  export class Config {
401
- referenceDocs: any;
402
- apiDefinitions: Record<string, string>;
417
+ apis: Record<string, Api>;
403
418
  lint: LintConfig;
404
419
  resolve: ResolveConfig;
405
420
  licenseKey?: string;
406
421
  region?: Region;
422
+ 'features.openapi': Record<string, any>;
423
+ 'features.mockServer'?: Record<string, any>;
424
+ organization?: string;
407
425
  constructor(public rawConfig: RawConfig, public configFile?: string) {
408
- this.apiDefinitions = rawConfig.apiDefinitions || {};
426
+ this.apis = rawConfig.apis || {};
409
427
  this.lint = new LintConfig(rawConfig.lint || {}, configFile);
410
- this.referenceDocs = rawConfig.referenceDocs || {};
428
+ this['features.openapi'] = rawConfig['features.openapi'] || {};
429
+ this['features.mockServer'] = rawConfig['features.mockServer'] || {};
411
430
  this.resolve = {
412
431
  http: {
413
432
  headers: rawConfig?.resolve?.http?.headers ?? [],
@@ -415,13 +434,13 @@ export class Config {
415
434
  },
416
435
  };
417
436
  this.region = rawConfig.region;
437
+ this.organization = rawConfig.organization;
418
438
  }
419
439
  }
420
440
 
421
441
  function resolvePresets(presets: string[], plugins: Plugin[]) {
422
442
  return presets.map((presetName) => {
423
443
  const { pluginId, configName } = parsePresetName(presetName);
424
-
425
444
  const plugin = plugins.find((p) => p.id === pluginId);
426
445
  if (!plugin) {
427
446
  throw new Error(`Invalid config ${red(presetName)}: plugin ${pluginId} is not included.`);
@@ -624,3 +643,72 @@ function assignExisting<T>(target: Record<string, T>, obj: Record<string, T>) {
624
643
  }
625
644
  }
626
645
  }
646
+
647
+ export function getMergedConfig(config: Config, entrypointAlias?: string): Config {
648
+ return entrypointAlias
649
+ ? new Config({
650
+ ...config.rawConfig,
651
+ lint: getMergedLintConfig(config, entrypointAlias),
652
+ 'features.openapi': {
653
+ ...config['features.openapi'],
654
+ ...config.apis[entrypointAlias]?.['features.openapi'],
655
+ },
656
+ 'features.mockServer': {
657
+ ...config['features.mockServer'],
658
+ ...config.apis[entrypointAlias]?.['features.mockServer'],
659
+ },
660
+ // TODO: merge everything else here
661
+ })
662
+ : config;
663
+ }
664
+
665
+ export function getMergedLintConfig(config: Config, entrypointAlias?: string) {
666
+ const apiLint = entrypointAlias ? config.apis[entrypointAlias]?.lint : {};
667
+ const mergedLint = {
668
+ ...config.rawConfig.lint,
669
+ ...apiLint,
670
+ rules: { ...config.rawConfig.lint?.rules, ...apiLint?.rules },
671
+ preprocessors: { ...config.rawConfig.lint?.preprocessors, ...apiLint?.preprocessors },
672
+ decorators: { ...config.rawConfig.lint?.decorators, ...apiLint?.decorators },
673
+ };
674
+ return mergedLint;
675
+ }
676
+
677
+ function transformApiDefinitionsToApis(
678
+ apiDefinitions: Record<string, string> = {},
679
+ ): Record<string, Api> {
680
+ let apis: Record<string, Api> = {};
681
+ for (const [apiName, apiPath] of Object.entries(apiDefinitions)) {
682
+ apis[apiName] = { root: apiPath };
683
+ }
684
+ return apis;
685
+ }
686
+
687
+ export function transformConfig(rawConfig: DeprecatedRawConfig | RawConfig): RawConfig {
688
+ if ((rawConfig as RawConfig).apis && (rawConfig as DeprecatedRawConfig).apiDefinitions) {
689
+ throw new Error("Do not use 'apiDefinitions' field. Use 'apis' instead.\n");
690
+ }
691
+ if (
692
+ (rawConfig as RawConfig)['features.openapi'] &&
693
+ (rawConfig as DeprecatedRawConfig).referenceDocs
694
+ ) {
695
+ throw new Error("Do not use 'referenceDocs' field. Use 'features.openapi' instead.\n");
696
+ }
697
+ const { apiDefinitions, referenceDocs, ...rest } = rawConfig as DeprecatedRawConfig & RawConfig;
698
+ // TODO: put links to the changelog and uncomment this after successful release of ReferenceDocs/Redoc, Portal and Workflows
699
+ // if (apiDefinitions) {
700
+ // process.stderr.write(
701
+ // `The ${yellow('apiDefinitions')} field is deprecated. Use ${green('apis')} instead, see changelog: <link>\n`
702
+ // );
703
+ // }
704
+ // if (referenceDocs) {
705
+ // process.stderr.write(
706
+ // `The ${yellow('referenceDocs')} field is deprecated. Use ${green('features.openapi')} instead, see changelog: <link>\n`
707
+ // );
708
+ // }
709
+ return {
710
+ 'features.openapi': referenceDocs,
711
+ apis: transformApiDefinitionsToApis(apiDefinitions),
712
+ ...rest,
713
+ };
714
+ }
@@ -1,23 +1,13 @@
1
1
  import * as fs from 'fs';
2
+ import * as path from 'path';
2
3
  import { RedoclyClient } from '../redocly';
3
4
  import { loadYaml } from '../utils';
4
- import { Config, DOMAINS, RawConfig, Region } from './config';
5
-
5
+ import { Config, DOMAINS, RawConfig, Region, transformConfig } from './config';
6
6
  import { defaultPlugin } from './builtIn';
7
7
 
8
- export async function loadConfig(configPath?: string, customExtends?: string[]): Promise<Config> {
9
- if (configPath === undefined) {
10
- configPath = findConfig();
11
- }
12
- let rawConfig: RawConfig = {};
8
+ export async function loadConfig(configPath: string | undefined = findConfig(), customExtends?: string[]): Promise<Config> {
9
+ const rawConfig = await getConfig(configPath);
13
10
 
14
- if (configPath !== undefined) {
15
- try {
16
- rawConfig = (await loadYaml(configPath)) as RawConfig;
17
- } catch (e) {
18
- throw new Error(`Error parsing config file at \`${configPath}\`: ${e.message}`);
19
- }
20
- }
21
11
  if (customExtends !== undefined) {
22
12
  rawConfig.lint = rawConfig.lint || {};
23
13
  rawConfig.lint.extends = customExtends;
@@ -48,7 +38,6 @@ export async function loadConfig(configPath?: string, customExtends?: string[]):
48
38
  }] : []));
49
39
  }
50
40
  }
51
-
52
41
  return new Config(
53
42
  {
54
43
  ...rawConfig,
@@ -63,12 +52,11 @@ export async function loadConfig(configPath?: string, customExtends?: string[]):
63
52
 
64
53
  export const CONFIG_FILE_NAMES = ['redocly.yaml', 'redocly.yml', '.redocly.yaml', '.redocly.yml'];
65
54
 
66
- export function findConfig(): string | undefined {
55
+ export function findConfig(dir?: string): string | undefined {
67
56
  if (!fs.hasOwnProperty('existsSync')) return;
68
-
69
- const existingConfigFiles = CONFIG_FILE_NAMES.map((name) => fs.existsSync(name) && name).filter(
70
- Boolean,
71
- ) as Array<string | never>;
57
+ const existingConfigFiles = CONFIG_FILE_NAMES
58
+ .map(name => dir ? path.resolve(dir, name) : name)
59
+ .filter(fs.existsSync);
72
60
  if (existingConfigFiles.length > 1) {
73
61
  throw new Error(`
74
62
  Multiple configuration files are not allowed.
@@ -78,3 +66,13 @@ export function findConfig(): string | undefined {
78
66
  }
79
67
  return existingConfigFiles[0];
80
68
  }
69
+
70
+ export async function getConfig(configPath: string | undefined = findConfig()) {
71
+ if (!configPath) return {};
72
+ try {
73
+ const rawConfig = ((await loadYaml(configPath)) || {}) as RawConfig;
74
+ return transformConfig(rawConfig);
75
+ } catch (e) {
76
+ throw new Error(`Error parsing config file at '${configPath}': ${e.message}`);
77
+ }
78
+ }
@@ -183,8 +183,10 @@ export function getAstNodeByPointer(root: YAMLNode, pointer: string, reportOnKey
183
183
  for (const key of pointerSegments) {
184
184
  if (currentNode.kind === yamlAst.Kind.MAP) {
185
185
  const mapping = currentNode.mappings.find((m) => m.key.value === key);
186
- if (!mapping?.value) break;
187
- currentNode = mapping?.value as YAMLNode;
186
+ if (!mapping) break;
187
+ currentNode = mapping as YAMLNode;
188
+ if (!mapping?.value) break; // If node has value - return value, if not - return node itself
189
+ currentNode = mapping.value as YAMLNode;
188
190
  } else if (currentNode.kind === yamlAst.Kind.SEQ) {
189
191
  const elem = currentNode.items[parseInt(key, 10)] as YAMLNode;
190
192
  if (!elem) break;
package/src/index.ts CHANGED
@@ -14,16 +14,24 @@ export {
14
14
  Oas3_1Schema,
15
15
  Oas3Tag,
16
16
  Oas3_1Webhooks,
17
- Referenced
17
+ Referenced,
18
18
  } from './typings/openapi';
19
19
  export { Oas2Definition } from './typings/swagger';
20
20
  export { StatsAccumulator, StatsName } from './typings/common';
21
21
  export { normalizeTypes } from './types';
22
22
  export { Stats } from './rules/other/stats';
23
23
 
24
- export { Config, LintConfig, RawConfig, IGNORE_FILE, Region } from './config/config';
24
+ export {
25
+ Config,
26
+ LintConfig,
27
+ RawConfig,
28
+ IGNORE_FILE,
29
+ Region,
30
+ getMergedConfig,
31
+ transformConfig,
32
+ } from './config/config';
25
33
 
26
- export { loadConfig, findConfig, CONFIG_FILE_NAMES } from './config/load';
34
+ export { loadConfig, getConfig, findConfig, CONFIG_FILE_NAMES } from './config/load';
27
35
  export { RedoclyClient, isRedoclyRegistryURL } from './redocly';
28
36
 
29
37
  export {
@@ -9,6 +9,7 @@ import { isNotEmptyObject } from '../utils';
9
9
 
10
10
  const TOKEN_FILENAME = '.redocly-config.json';
11
11
 
12
+ let REDOCLY_DOMAIN: string; // workaround for the isRedoclyRegistryURL, see more below
12
13
  export class RedoclyClient {
13
14
  private accessTokens: AccessTokens = {};
14
15
  private region: Region;
@@ -22,7 +23,11 @@ export class RedoclyClient {
22
23
  ? DOMAINS[region]
23
24
  : process.env.REDOCLY_DOMAIN || DOMAINS[DEFAULT_REGION];
24
25
 
25
- process.env.REDOCLY_DOMAIN = this.domain; // isRedoclyRegistryURL depends on the value to be set
26
+ /*
27
+ * We can't use process.env here because it is replaced by a const in some client-side bundles,
28
+ * which breaks assignment.
29
+ */
30
+ REDOCLY_DOMAIN = this.domain; // isRedoclyRegistryURL depends on the value to be set
26
31
  this.registryApi = new RegistryApi(this.accessTokens, this.region);
27
32
  }
28
33
 
@@ -170,7 +175,7 @@ export class RedoclyClient {
170
175
  }
171
176
 
172
177
  export function isRedoclyRegistryURL(link: string): boolean {
173
- const domain = process.env.REDOCLY_DOMAIN || DOMAINS[DEFAULT_REGION];
178
+ const domain = REDOCLY_DOMAIN || process.env.REDOCLY_DOMAIN || DOMAINS[DEFAULT_REGION];
174
179
 
175
180
  const legacyDomain = domain === 'redocly.com' ? 'redoc.ly' : domain;
176
181
 
@@ -192,8 +192,8 @@ describe('Oas3 Structural visitor basic', () => {
192
192
  Object {
193
193
  "location": Array [
194
194
  Object {
195
- "pointer": "#/",
196
- "reportOnKey": false,
195
+ "pointer": "#/openapi",
196
+ "reportOnKey": true,
197
197
  "source": "foobar.yaml",
198
198
  },
199
199
  ],
@@ -259,8 +259,8 @@ describe('Oas3 Structural visitor basic', () => {
259
259
  Object {
260
260
  "location": Array [
261
261
  Object {
262
- "pointer": "#/",
263
- "reportOnKey": false,
262
+ "pointer": "#/openapi",
263
+ "reportOnKey": true,
264
264
  "source": "foobar.yaml",
265
265
  },
266
266
  ],
@@ -3,9 +3,10 @@ import { Oas3Rule } from '../../visitors';
3
3
  export const NoEmptyServers: Oas3Rule = () => {
4
4
  return {
5
5
  DefinitionRoot(root, { report, location }) {
6
- if (!root.servers) {
6
+ if (!root.hasOwnProperty('servers')) {
7
7
  report({
8
8
  message: 'Servers must be present.',
9
+ location: location.child(['openapi']).key()
9
10
  });
10
11
  return;
11
12
  }
package/src/types/oas2.ts CHANGED
@@ -60,6 +60,8 @@ const PathMap: NodeType = {
60
60
  const PathItem: NodeType = {
61
61
  properties: {
62
62
  $ref: { type: 'string' }, // TODO: verify special $ref handling for Path Item
63
+ parameters: listOf('Parameter'),
64
+
63
65
  get: 'Operation',
64
66
  put: 'Operation',
65
67
  post: 'Operation',
@@ -67,7 +69,6 @@ const PathItem: NodeType = {
67
69
  options: 'Operation',
68
70
  head: 'Operation',
69
71
  patch: 'Operation',
70
- parameters: listOf('Parameter'),
71
72
  },
72
73
  };
73
74
 
@@ -10,6 +10,7 @@ const ConfigRoot: NodeType = {
10
10
  },
11
11
  lint: 'ConfigLint',
12
12
  referenceDocs: 'ConfigReferenceDocs',
13
+ 'features.mockServer': 'ConfigMockServer',
13
14
  },
14
15
  };
15
16
 
@@ -552,10 +553,18 @@ const ConfigReferenceDocs: NodeType = {
552
553
  additionalProperties: { type: 'string' },
553
554
  };
554
555
 
556
+ const ConfigMockServer: NodeType = {
557
+ properties: {
558
+ strictExamples: { type: 'boolean' },
559
+ errorIfForcedExampleNotFound: { type: 'boolean' },
560
+ },
561
+ };
562
+
555
563
  export const ConfigTypes: Record<string, NodeType> = {
556
564
  ConfigRoot,
557
565
  ConfigLint,
558
566
  ConfigReferenceDocs,
567
+ ConfigMockServer,
559
568
  ConfigHTTP,
560
569
  ConfigLanguage,
561
570
  ConfigLabels,
package/src/utils.ts CHANGED
@@ -28,7 +28,6 @@ export type BundleOutputFormat = 'json' | 'yml' | 'yaml';
28
28
 
29
29
  export async function loadYaml(filename: string) {
30
30
  const contents = await fs.promises.readFile(filename, 'utf-8');
31
-
32
31
  return parseYaml(contents);
33
32
  }
34
33