@redocly/cli 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/lib/__mocks__/@redocly/openapi-core.d.ts +1 -0
  3. package/lib/__mocks__/@redocly/openapi-core.js +4 -3
  4. package/lib/__mocks__/utils.d.ts +2 -0
  5. package/lib/__mocks__/utils.js +3 -1
  6. package/lib/__tests__/commands/build-docs.test.js +2 -2
  7. package/lib/__tests__/commands/bundle.test.js +7 -7
  8. package/lib/__tests__/commands/join.test.js +25 -18
  9. package/lib/__tests__/commands/lint.test.js +15 -15
  10. package/lib/__tests__/commands/push-region.test.js +2 -2
  11. package/lib/__tests__/commands/push.test.js +30 -30
  12. package/lib/__tests__/fetch-with-timeout.test.js +2 -2
  13. package/lib/__tests__/utils.test.js +63 -32
  14. package/lib/__tests__/wrapper.test.js +3 -3
  15. package/lib/assert-node-version.js +1 -1
  16. package/lib/commands/build-docs/index.js +9 -9
  17. package/lib/commands/build-docs/types.d.ts +2 -2
  18. package/lib/commands/build-docs/utils.js +10 -10
  19. package/lib/commands/bundle.d.ts +1 -1
  20. package/lib/commands/bundle.js +25 -25
  21. package/lib/commands/join.d.ts +1 -1
  22. package/lib/commands/join.js +49 -48
  23. package/lib/commands/lint.d.ts +1 -1
  24. package/lib/commands/lint.js +22 -22
  25. package/lib/commands/login.d.ts +1 -1
  26. package/lib/commands/login.js +3 -3
  27. package/lib/commands/preview-docs/index.d.ts +1 -1
  28. package/lib/commands/preview-docs/index.js +7 -7
  29. package/lib/commands/preview-docs/preview-server/hot.js +19 -2
  30. package/lib/commands/preview-docs/preview-server/preview-server.js +15 -14
  31. package/lib/commands/preview-docs/preview-server/server.d.ts +3 -1
  32. package/lib/commands/preview-docs/preview-server/server.js +2 -2
  33. package/lib/commands/push.d.ts +2 -2
  34. package/lib/commands/push.js +31 -31
  35. package/lib/commands/split/__tests__/index.test.js +9 -9
  36. package/lib/commands/split/index.d.ts +2 -2
  37. package/lib/commands/split/index.js +41 -40
  38. package/lib/commands/split/types.d.ts +2 -2
  39. package/lib/commands/split/types.js +2 -2
  40. package/lib/commands/stats.d.ts +1 -1
  41. package/lib/commands/stats.js +9 -9
  42. package/lib/fetch-with-timeout.js +5 -2
  43. package/lib/index.js +11 -12
  44. package/lib/types.d.ts +6 -6
  45. package/lib/update-version-notifier.js +18 -18
  46. package/lib/utils.d.ts +6 -3
  47. package/lib/utils.js +66 -38
  48. package/lib/wrapper.js +5 -5
  49. package/package.json +3 -3
  50. package/src/__mocks__/@redocly/openapi-core.ts +1 -0
  51. package/src/__mocks__/utils.ts +2 -0
  52. package/src/__tests__/commands/join.test.ts +37 -7
  53. package/src/__tests__/utils.test.ts +45 -1
  54. package/src/commands/join.ts +8 -3
  55. package/src/commands/preview-docs/preview-server/hot.js +19 -2
  56. package/src/commands/preview-docs/preview-server/preview-server.ts +6 -4
  57. package/src/commands/preview-docs/preview-server/server.ts +2 -2
  58. package/src/commands/split/__tests__/index.test.ts +14 -5
  59. package/src/commands/split/index.ts +25 -17
  60. package/src/fetch-with-timeout.ts +3 -0
  61. package/src/index.ts +0 -1
  62. package/src/utils.ts +40 -1
  63. package/tsconfig.tsbuildinfo +1 -1
@@ -1,4 +1,6 @@
1
1
  /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ /// <reference types="node" />
2
4
  import * as http from 'http';
3
5
  import { ReadStream } from 'fs';
4
6
  export declare const mimeTypes: {
@@ -20,4 +22,4 @@ export declare const mimeTypes: {
20
22
  };
21
23
  export declare function respondWithGzip(contents: string | Buffer | ReadStream, request: http.IncomingMessage, response: http.ServerResponse, headers?: {}, code?: number): void;
22
24
  export declare function startHttpServer(port: number, host: string, handler: http.RequestListener): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
23
- export declare function startWsServer(port: number): any;
25
+ export declare function startWsServer(port: number, host: string): any;
@@ -58,8 +58,8 @@ function startHttpServer(port, host, handler) {
58
58
  return http.createServer(handler).listen(port, host);
59
59
  }
60
60
  exports.startHttpServer = startHttpServer;
61
- function startWsServer(port) {
62
- const socketServer = new SocketServer({ port, clientTracking: true });
61
+ function startWsServer(port, host) {
62
+ const socketServer = new SocketServer({ port, host, clientTracking: true });
63
63
  socketServer.on('connection', (socket) => {
64
64
  socket.on('data', (data) => {
65
65
  const message = JSON.parse(data);
@@ -1,6 +1,6 @@
1
1
  import { Config, Region } from '@redocly/openapi-core';
2
2
  export declare const DESTINATION_REGEX: RegExp;
3
- export declare type PushOptions = {
3
+ export type PushOptions = {
4
4
  api?: string;
5
5
  destination?: string;
6
6
  branchName?: string;
@@ -20,7 +20,7 @@ export declare function getDestinationProps(destination: string | undefined, org
20
20
  name: string | undefined;
21
21
  version: string | undefined;
22
22
  };
23
- declare type BarePushArgs = Omit<PushOptions, 'destination' | 'branchName'> & {
23
+ type BarePushArgs = Omit<PushOptions, 'destination' | 'branchName'> & {
24
24
  maybeDestination?: string;
25
25
  maybeBranchName?: string;
26
26
  branch?: string;
@@ -37,7 +37,7 @@ function handlePush(argv, config) {
37
37
  const client = new openapi_core_1.RedoclyClient(config.region);
38
38
  const isAuthorized = yield client.isAuthorizedWithRedoclyByRegion();
39
39
  if (!isAuthorized) {
40
- const clientToken = yield login_1.promptClientToken(client.domain);
40
+ const clientToken = yield (0, login_1.promptClientToken)(client.domain);
41
41
  yield client.login(clientToken);
42
42
  }
43
43
  const startedAt = perf_hooks_1.performance.now();
@@ -45,34 +45,34 @@ function handlePush(argv, config) {
45
45
  const jobId = argv['job-id'];
46
46
  const batchSize = argv['batch-size'];
47
47
  if (destination && !exports.DESTINATION_REGEX.test(destination)) {
48
- utils_1.exitWithError(`Destination argument value is not valid, please use the right format: ${colorette_1.yellow('<api-name@api-version>')}`);
48
+ (0, utils_1.exitWithError)(`Destination argument value is not valid, please use the right format: ${(0, colorette_1.yellow)('<api-name@api-version>')}`);
49
49
  }
50
50
  const destinationProps = getDestinationProps(destination, config.organization);
51
51
  const organizationId = argv.organization || destinationProps.organizationId;
52
52
  const { name, version } = destinationProps;
53
53
  if (!organizationId) {
54
- return utils_1.exitWithError(`No organization provided, please use --organization option or specify the 'organization' field in the config file.`);
54
+ return (0, utils_1.exitWithError)(`No organization provided, please use --organization option or specify the 'organization' field in the config file.`);
55
55
  }
56
56
  const api = argv.api || (name && version && getApiRoot({ name, version, config }));
57
57
  if (name && version && !api) {
58
- utils_1.exitWithError(`No api found that matches ${colorette_1.blue(`${name}@${version}`)}. Please make sure you have provided the correct data in the config file.`);
58
+ (0, utils_1.exitWithError)(`No api found that matches ${(0, colorette_1.blue)(`${name}@${version}`)}. Please make sure you have provided the correct data in the config file.`);
59
59
  }
60
60
  // Ensure that a destination for the api is provided.
61
61
  if (!name && api) {
62
- return utils_1.exitWithError(`No destination provided, please use --destination option to provide destination.`);
62
+ return (0, utils_1.exitWithError)(`No destination provided, please use --destination option to provide destination.`);
63
63
  }
64
64
  if (jobId && !jobId.trim()) {
65
- utils_1.exitWithError(`The ${colorette_1.blue(`job-id`)} option value is not valid, please avoid using an empty string.`);
65
+ (0, utils_1.exitWithError)(`The ${(0, colorette_1.blue)(`job-id`)} option value is not valid, please avoid using an empty string.`);
66
66
  }
67
67
  if (batchSize && batchSize < 2) {
68
- utils_1.exitWithError(`The ${colorette_1.blue(`batch-size`)} option value is not valid, please use the integer bigger than 1.`);
68
+ (0, utils_1.exitWithError)(`The ${(0, colorette_1.blue)(`batch-size`)} option value is not valid, please use the integer bigger than 1.`);
69
69
  }
70
70
  const apis = api ? { [`${name}@${version}`]: { root: api } } : config.apis;
71
71
  if (!Object.keys(apis).length) {
72
- utils_1.exitWithError(`Api not found. Please make sure you have provided the correct data in the config file.`);
72
+ (0, utils_1.exitWithError)(`Api not found. Please make sure you have provided the correct data in the config file.`);
73
73
  }
74
74
  for (const [apiNameAndVersion, { root: api }] of Object.entries(apis)) {
75
- const resolvedConfig = openapi_core_1.getMergedConfig(config, apiNameAndVersion);
75
+ const resolvedConfig = (0, openapi_core_1.getMergedConfig)(config, apiNameAndVersion);
76
76
  resolvedConfig.styleguide.skipDecorators(argv['skip-decorator']);
77
77
  const [name, version = DEFAULT_VERSION] = apiNameAndVersion.split('@');
78
78
  const encodedName = encodeURIComponent(name);
@@ -81,7 +81,7 @@ function handlePush(argv, config) {
81
81
  const filePaths = [];
82
82
  const filesToUpload = yield collectFilesToUpload(api, resolvedConfig);
83
83
  const filesHash = hashFiles(filesToUpload.files);
84
- process.stdout.write(`Uploading ${filesToUpload.files.length} ${utils_1.pluralize('file', filesToUpload.files.length)}:\n`);
84
+ process.stdout.write(`Uploading ${filesToUpload.files.length} ${(0, utils_1.pluralize)('file', filesToUpload.files.length)}:\n`);
85
85
  let uploaded = 0;
86
86
  for (const file of filesToUpload.files) {
87
87
  const { signedUploadUrl, filePath } = yield client.registryApi.prepareFileUpload({
@@ -96,13 +96,13 @@ function handlePush(argv, config) {
96
96
  rootFilePath = filePath;
97
97
  }
98
98
  filePaths.push(filePath);
99
- process.stdout.write(`Uploading ${file.contents ? 'bundle for ' : ''}${colorette_1.blue(file.filePath)}...`);
99
+ process.stdout.write(`Uploading ${file.contents ? 'bundle for ' : ''}${(0, colorette_1.blue)(file.filePath)}...`);
100
100
  const uploadResponse = yield uploadFileToS3(signedUploadUrl, file.contents || file.filePath);
101
101
  const fileCounter = `(${++uploaded}/${filesToUpload.files.length})`;
102
102
  if (!uploadResponse.ok) {
103
- utils_1.exitWithError(`✗ ${fileCounter}\nFile upload failed\n`);
103
+ (0, utils_1.exitWithError)(`✗ ${fileCounter}\nFile upload failed\n`);
104
104
  }
105
- process.stdout.write(colorette_1.green(`✓ ${fileCounter}\n`));
105
+ process.stdout.write((0, colorette_1.green)(`✓ ${fileCounter}\n`));
106
106
  }
107
107
  process.stdout.write('\n');
108
108
  yield client.registryApi.pushApi({
@@ -120,16 +120,16 @@ function handlePush(argv, config) {
120
120
  }
121
121
  catch (error) {
122
122
  if (error.message === 'ORGANIZATION_NOT_FOUND') {
123
- utils_1.exitWithError(`Organization ${colorette_1.blue(organizationId)} not found`);
123
+ (0, utils_1.exitWithError)(`Organization ${(0, colorette_1.blue)(organizationId)} not found`);
124
124
  }
125
125
  if (error.message === 'API_VERSION_NOT_FOUND') {
126
- utils_1.exitWithError(`The definition version ${colorette_1.blue(`${name}@${version}`)} does not exist in organization ${colorette_1.blue(organizationId)}!\n${colorette_1.yellow('Suggestion:')} please use ${colorette_1.blue('-u')} or ${colorette_1.blue('--upsert')} to create definition.\n\n`);
126
+ (0, utils_1.exitWithError)(`The definition version ${(0, colorette_1.blue)(`${name}@${version}`)} does not exist in organization ${(0, colorette_1.blue)(organizationId)}!\n${(0, colorette_1.yellow)('Suggestion:')} please use ${(0, colorette_1.blue)('-u')} or ${(0, colorette_1.blue)('--upsert')} to create definition.\n\n`);
127
127
  }
128
128
  throw error;
129
129
  }
130
- process.stdout.write(`Definition: ${colorette_1.blue(api)} is successfully pushed to Redocly API Registry \n`);
130
+ process.stdout.write(`Definition: ${(0, colorette_1.blue)(api)} is successfully pushed to Redocly API Registry \n`);
131
131
  }
132
- utils_1.printExecutionTime('push', startedAt, api || `apis in organization ${organizationId}`);
132
+ (0, utils_1.printExecutionTime)('push', startedAt, api || `apis in organization ${organizationId}`);
133
133
  });
134
134
  }
135
135
  exports.handlePush = handlePush;
@@ -151,22 +151,22 @@ function collectFilesToUpload(api, config) {
151
151
  var _a, _b;
152
152
  return __awaiter(this, void 0, void 0, function* () {
153
153
  const files = [];
154
- const [{ path: apiPath }] = yield utils_1.getFallbackApisOrExit([api], config);
154
+ const [{ path: apiPath }] = yield (0, utils_1.getFallbackApisOrExit)([api], config);
155
155
  process.stdout.write('Bundling definition\n');
156
- const { bundle: openapiBundle, problems } = yield openapi_core_1.bundle({
156
+ const { bundle: openapiBundle, problems } = yield (0, openapi_core_1.bundle)({
157
157
  config,
158
158
  ref: apiPath,
159
159
  skipRedoclyRegistryRefs: true,
160
160
  });
161
- const fileTotals = openapi_core_1.getTotals(problems);
161
+ const fileTotals = (0, openapi_core_1.getTotals)(problems);
162
162
  if (fileTotals.errors === 0) {
163
- process.stdout.write(`Created a bundle for ${colorette_1.blue(api)} ${fileTotals.warnings > 0 ? 'with warnings' : ''}\n`);
163
+ process.stdout.write(`Created a bundle for ${(0, colorette_1.blue)(api)} ${fileTotals.warnings > 0 ? 'with warnings' : ''}\n`);
164
164
  }
165
165
  else {
166
- utils_1.exitWithError(`Failed to create a bundle for ${colorette_1.blue(api)}\n`);
166
+ (0, utils_1.exitWithError)(`Failed to create a bundle for ${(0, colorette_1.blue)(api)}\n`);
167
167
  }
168
168
  const fileExt = path.extname(apiPath).split('.').pop();
169
- files.push(getFileEntry(apiPath, utils_1.dumpBundle(openapiBundle.parsed, fileExt)));
169
+ files.push(getFileEntry(apiPath, (0, utils_1.dumpBundle)(openapiBundle.parsed, fileExt)));
170
170
  if (fs.existsSync('package.json')) {
171
171
  files.push(getFileEntry('package.json'));
172
172
  }
@@ -217,8 +217,8 @@ function collectFilesToUpload(api, config) {
217
217
  return {
218
218
  filePath: path.resolve(filename),
219
219
  keyOnS3: config.configFile
220
- ? openapi_core_1.slash(path.relative(path.dirname(config.configFile), filename))
221
- : openapi_core_1.slash(path.basename(filename)),
220
+ ? (0, openapi_core_1.slash)(path.relative(path.dirname(config.configFile), filename))
221
+ : (0, openapi_core_1.slash)(path.basename(filename)),
222
222
  contents: (contents && Buffer.from(contents, 'utf-8')) || undefined,
223
223
  };
224
224
  }
@@ -228,7 +228,7 @@ function getFolder(filePath) {
228
228
  return path.resolve(path.dirname(filePath));
229
229
  }
230
230
  function hashFiles(filePaths) {
231
- const sum = crypto_1.createHash('sha256');
231
+ const sum = (0, crypto_1.createHash)('sha256');
232
232
  filePaths.forEach((file) => sum.update(fs.readFileSync(file.filePath)));
233
233
  return sum.digest('hex');
234
234
  }
@@ -253,19 +253,19 @@ exports.getDestinationProps = getDestinationProps;
253
253
  const transformPush = (callback) => (_a, config) => {
254
254
  var { api: maybeApiOrDestination, maybeDestination, maybeBranchName, branch, 'batch-id': batchId, 'job-id': jobId } = _a, rest = __rest(_a, ["api", "maybeDestination", "maybeBranchName", "branch", 'batch-id', 'job-id']);
255
255
  if (batchId) {
256
- process.stderr.write(colorette_1.yellow(`The ${colorette_1.red('batch-id')} option is deprecated. Please use ${colorette_1.green('job-id')} instead.\n\n`));
256
+ process.stderr.write((0, colorette_1.yellow)(`The ${(0, colorette_1.red)('batch-id')} option is deprecated. Please use ${(0, colorette_1.green)('job-id')} instead.\n\n`));
257
257
  }
258
258
  if (maybeBranchName) {
259
- process.stderr.write(colorette_1.yellow('Deprecation warning: Do not use the third parameter as a branch name. Please use a separate --branch option instead.\n\n'));
259
+ process.stderr.write((0, colorette_1.yellow)('Deprecation warning: Do not use the third parameter as a branch name. Please use a separate --branch option instead.\n\n'));
260
260
  }
261
261
  let apiFile, destination;
262
262
  if (maybeDestination) {
263
- process.stderr.write(colorette_1.yellow('Deprecation warning: Do not use the second parameter as a destination. Please use a separate --destination and --organization instead.\n\n'));
263
+ process.stderr.write((0, colorette_1.yellow)('Deprecation warning: Do not use the second parameter as a destination. Please use a separate --destination and --organization instead.\n\n'));
264
264
  apiFile = maybeApiOrDestination;
265
265
  destination = maybeDestination;
266
266
  }
267
267
  else if (maybeApiOrDestination && exports.DESTINATION_REGEX.test(maybeApiOrDestination)) {
268
- process.stderr.write(colorette_1.yellow('Deprecation warning: Do not use the first parameter as a destination. Please use a separate --destination and --organization options instead.\n\n'));
268
+ process.stderr.write((0, colorette_1.yellow)('Deprecation warning: Do not use the first parameter as a destination. Please use a separate --destination and --organization options instead.\n\n'));
269
269
  destination = maybeApiOrDestination;
270
270
  }
271
271
  else if (maybeApiOrDestination && !exports.DESTINATION_REGEX.test(maybeApiOrDestination)) {
@@ -285,7 +285,7 @@ function uploadFileToS3(url, filePathOrBuffer) {
285
285
  ? fs.statSync(filePathOrBuffer).size
286
286
  : filePathOrBuffer.byteLength;
287
287
  const readStream = typeof filePathOrBuffer === 'string' ? fs.createReadStream(filePathOrBuffer) : filePathOrBuffer;
288
- return node_fetch_1.default(url, {
288
+ return (0, node_fetch_1.default)(url, {
289
289
  method: 'PUT',
290
290
  headers: {
291
291
  'Content-Length': fileSizeInBytes.toString(),
@@ -14,7 +14,7 @@ const path = require("path");
14
14
  const openapiCore = require("@redocly/openapi-core");
15
15
  const colorette_1 = require("colorette");
16
16
  const utils = require('../../../utils');
17
- jest.mock('../../../utils', () => (Object.assign(Object.assign({}, jest.requireActual('../../../utils')), { writeYaml: jest.fn() })));
17
+ jest.mock('../../../utils', () => (Object.assign(Object.assign({}, jest.requireActual('../../../utils')), { writeToFileByExtension: jest.fn() })));
18
18
  jest.mock('@redocly/openapi-core', () => (Object.assign(Object.assign({}, jest.requireActual('@redocly/openapi-core')), { isRef: jest.fn() })));
19
19
  describe('#split', () => {
20
20
  const openapiDir = 'test';
@@ -22,20 +22,20 @@ describe('#split', () => {
22
22
  it('should split the file and show the success message', () => __awaiter(void 0, void 0, void 0, function* () {
23
23
  const filePath = 'packages/cli/src/commands/split/__tests__/fixtures/spec.json';
24
24
  jest.spyOn(process.stderr, 'write').mockImplementation(() => true);
25
- yield index_1.handleSplit({
25
+ yield (0, index_1.handleSplit)({
26
26
  api: filePath,
27
27
  outDir: openapiDir,
28
28
  separator: '_',
29
29
  });
30
30
  expect(process.stderr.write).toBeCalledTimes(2);
31
- expect(process.stderr.write.mock.calls[0][0]).toBe(`🪓 Document: ${colorette_1.blue(filePath)} ${colorette_1.green('is successfully split')}
32
- and all related files are saved to the directory: ${colorette_1.blue(openapiDir)} \n`);
31
+ expect(process.stderr.write.mock.calls[0][0]).toBe(`🪓 Document: ${(0, colorette_1.blue)(filePath)} ${(0, colorette_1.green)('is successfully split')}
32
+ and all related files are saved to the directory: ${(0, colorette_1.blue)(openapiDir)} \n`);
33
33
  expect(process.stderr.write.mock.calls[1][0]).toContain(`${filePath}: split processed in <test>ms`);
34
34
  }));
35
35
  it('should use the correct separator', () => __awaiter(void 0, void 0, void 0, function* () {
36
36
  const filePath = 'packages/cli/src/commands/split/__tests__/fixtures/spec.json';
37
37
  jest.spyOn(utils, 'pathToFilename').mockImplementation(() => 'newFilePath');
38
- yield index_1.handleSplit({
38
+ yield (0, index_1.handleSplit)({
39
39
  api: filePath,
40
40
  outDir: openapiDir,
41
41
  separator: '_',
@@ -47,7 +47,7 @@ describe('#split', () => {
47
47
  const openapi = require('./fixtures/spec.json');
48
48
  jest.spyOn(openapiCore, 'slash').mockImplementation(() => 'paths/test.yaml');
49
49
  jest.spyOn(path, 'relative').mockImplementation(() => 'paths/test.yaml');
50
- index_1.iteratePathItems(openapi.paths, openapiDir, path.join(openapiDir, 'paths'), componentsFiles, '_');
50
+ (0, index_1.iteratePathItems)(openapi.paths, openapiDir, path.join(openapiDir, 'paths'), componentsFiles, '_', undefined, 'yaml');
51
51
  expect(openapiCore.slash).toHaveBeenCalledWith('paths/test.yaml');
52
52
  expect(path.relative).toHaveBeenCalledWith('test', 'test/paths/test.yaml');
53
53
  });
@@ -55,7 +55,7 @@ describe('#split', () => {
55
55
  const openapi = require('./fixtures/webhooks.json');
56
56
  jest.spyOn(openapiCore, 'slash').mockImplementation(() => 'webhooks/test.yaml');
57
57
  jest.spyOn(path, 'relative').mockImplementation(() => 'webhooks/test.yaml');
58
- index_1.iteratePathItems(openapi.webhooks, openapiDir, path.join(openapiDir, 'webhooks'), componentsFiles, 'webhook_');
58
+ (0, index_1.iteratePathItems)(openapi.webhooks, openapiDir, path.join(openapiDir, 'webhooks'), componentsFiles, 'webhook_', undefined, 'yaml');
59
59
  expect(openapiCore.slash).toHaveBeenCalledWith('webhooks/test.yaml');
60
60
  expect(path.relative).toHaveBeenCalledWith('test', 'test/webhooks/test.yaml');
61
61
  });
@@ -63,7 +63,7 @@ describe('#split', () => {
63
63
  const openapi = require('./fixtures/spec.json');
64
64
  jest.spyOn(openapiCore, 'slash').mockImplementation(() => 'webhooks/test.yaml');
65
65
  jest.spyOn(path, 'relative').mockImplementation(() => 'webhooks/test.yaml');
66
- index_1.iteratePathItems(openapi['x-webhooks'], openapiDir, path.join(openapiDir, 'webhooks'), componentsFiles, 'webhook_');
66
+ (0, index_1.iteratePathItems)(openapi['x-webhooks'], openapiDir, path.join(openapiDir, 'webhooks'), componentsFiles, 'webhook_', undefined, 'yaml');
67
67
  expect(openapiCore.slash).toHaveBeenCalledWith('webhooks/test.yaml');
68
68
  expect(path.relative).toHaveBeenCalledWith('test', 'test/webhooks/test.yaml');
69
69
  });
@@ -72,7 +72,7 @@ describe('#split', () => {
72
72
  const fs = require('fs');
73
73
  jest.spyOn(fs, 'writeFileSync').mockImplementation(() => { });
74
74
  jest.spyOn(utils, 'escapeLanguageName');
75
- index_1.iteratePathItems(openapi.paths, openapiDir, path.join(openapiDir, 'paths'), componentsFiles, '_');
75
+ (0, index_1.iteratePathItems)(openapi.paths, openapiDir, path.join(openapiDir, 'paths'), componentsFiles, '_', undefined, 'yaml');
76
76
  expect(utils.escapeLanguageName).nthCalledWith(1, 'C#');
77
77
  expect(utils.escapeLanguageName).nthReturnedWith(1, 'C_sharp');
78
78
  expect(utils.escapeLanguageName).nthCalledWith(2, 'C/AL');
@@ -1,10 +1,10 @@
1
1
  import { Oas3PathItem, Referenced } from './types';
2
- export declare type SplitOptions = {
2
+ export type SplitOptions = {
3
3
  api: string;
4
4
  outDir: string;
5
5
  separator: string;
6
6
  config?: string;
7
7
  };
8
8
  export declare function handleSplit(argv: SplitOptions): Promise<void>;
9
- declare function iteratePathItems(pathItems: Record<string, Referenced<Oas3PathItem>> | undefined, openapiDir: string, outDir: string, componentsFiles: object, pathSeparator: string, codeSamplesPathPrefix?: string): void;
9
+ declare function iteratePathItems(pathItems: Record<string, Referenced<Oas3PathItem>> | undefined, openapiDir: string, outDir: string, componentsFiles: object, pathSeparator: string, codeSamplesPathPrefix: string | undefined, ext: string): void;
10
10
  export { iteratePathItems };
@@ -24,24 +24,25 @@ function handleSplit(argv) {
24
24
  const startedAt = perf_hooks_1.performance.now();
25
25
  const { api, outDir, separator } = argv;
26
26
  validateDefinitionFileName(api);
27
- const openapi = utils_1.readYaml(api);
28
- splitDefinition(openapi, outDir, separator);
29
- process.stderr.write(`🪓 Document: ${colorette_1.blue(api)} ${colorette_1.green('is successfully split')}
30
- and all related files are saved to the directory: ${colorette_1.blue(outDir)} \n`);
31
- utils_1.printExecutionTime('split', startedAt, api);
27
+ const ext = (0, utils_1.getAndValidateFileExtension)(api);
28
+ const openapi = (0, utils_1.readYaml)(api);
29
+ splitDefinition(openapi, outDir, separator, ext);
30
+ process.stderr.write(`🪓 Document: ${(0, colorette_1.blue)(api)} ${(0, colorette_1.green)('is successfully split')}
31
+ and all related files are saved to the directory: ${(0, colorette_1.blue)(outDir)} \n`);
32
+ (0, utils_1.printExecutionTime)('split', startedAt, api);
32
33
  });
33
34
  }
34
35
  exports.handleSplit = handleSplit;
35
- function splitDefinition(openapi, openapiDir, pathSeparator) {
36
+ function splitDefinition(openapi, openapiDir, pathSeparator, ext) {
36
37
  fs.mkdirSync(openapiDir, { recursive: true });
37
38
  const componentsFiles = {};
38
- iterateComponents(openapi, openapiDir, componentsFiles);
39
- iteratePathItems(openapi.paths, openapiDir, path.join(openapiDir, 'paths'), componentsFiles, pathSeparator);
39
+ iterateComponents(openapi, openapiDir, componentsFiles, ext);
40
+ iteratePathItems(openapi.paths, openapiDir, path.join(openapiDir, 'paths'), componentsFiles, pathSeparator, undefined, ext);
40
41
  const webhooks = openapi.webhooks || openapi['x-webhooks'];
41
42
  // use webhook_ prefix for code samples to prevent potential name-clashes with paths samples
42
- iteratePathItems(webhooks, openapiDir, path.join(openapiDir, 'webhooks'), componentsFiles, pathSeparator, 'webhook_');
43
+ iteratePathItems(webhooks, openapiDir, path.join(openapiDir, 'webhooks'), componentsFiles, pathSeparator, 'webhook_', ext);
43
44
  replace$Refs(openapi, openapiDir, componentsFiles);
44
- utils_1.writeYaml(openapi, path.join(openapiDir, 'openapi.yaml'));
45
+ (0, utils_1.writeToFileByExtension)(openapi, path.join(openapiDir, `openapi.${ext}`));
45
46
  }
46
47
  function isStartsWithComponents(node) {
47
48
  return node.startsWith(types_1.componentsPath);
@@ -51,20 +52,20 @@ function isNotYaml(filename) {
51
52
  }
52
53
  function loadFile(fileName) {
53
54
  try {
54
- return openapi_core_1.parseYaml(fs.readFileSync(fileName, 'utf8'));
55
+ return (0, openapi_core_1.parseYaml)(fs.readFileSync(fileName, 'utf8'));
55
56
  }
56
57
  catch (e) {
57
- return utils_1.exitWithError(e.message);
58
+ return (0, utils_1.exitWithError)(e.message);
58
59
  }
59
60
  }
60
61
  function validateDefinitionFileName(fileName) {
61
62
  if (!fs.existsSync(fileName))
62
- utils_1.exitWithError(`File ${colorette_1.blue(fileName)} does not exist \n`);
63
+ (0, utils_1.exitWithError)(`File ${(0, colorette_1.blue)(fileName)} does not exist \n`);
63
64
  const file = loadFile(fileName);
64
65
  if (file.swagger)
65
- utils_1.exitWithError('OpenAPI 2 is not supported by this command');
66
+ (0, utils_1.exitWithError)('OpenAPI 2 is not supported by this command');
66
67
  if (!file.openapi)
67
- utils_1.exitWithError('File does not conform to the OpenAPI Specification. OpenAPI version is not specified');
68
+ (0, utils_1.exitWithError)('File does not conform to the OpenAPI Specification. OpenAPI version is not specified');
68
69
  return true;
69
70
  }
70
71
  function traverseDirectoryDeep(directory, callback, componentsFiles) {
@@ -84,12 +85,12 @@ function traverseDirectoryDeep(directory, callback, componentsFiles) {
84
85
  function traverseDirectoryDeepCallback(filename, directory, componentsFiles) {
85
86
  if (isNotYaml(filename))
86
87
  return;
87
- const pathData = utils_1.readYaml(filename);
88
+ const pathData = (0, utils_1.readYaml)(filename);
88
89
  replace$Refs(pathData, directory, componentsFiles);
89
- utils_1.writeYaml(pathData, filename);
90
+ (0, utils_1.writeToFileByExtension)(pathData, filename);
90
91
  }
91
92
  function crawl(object, visitor) {
92
- if (!js_utils_1.isObject(object))
93
+ if (!(0, js_utils_1.isObject)(object))
93
94
  return;
94
95
  for (const key of Object.keys(object)) {
95
96
  visitor(object, key);
@@ -98,15 +99,15 @@ function crawl(object, visitor) {
98
99
  }
99
100
  function replace$Refs(obj, relativeFrom, componentFiles = {}) {
100
101
  crawl(obj, (node) => {
101
- if (node.$ref && js_utils_1.isString(node.$ref) && isStartsWithComponents(node.$ref)) {
102
+ if (node.$ref && (0, js_utils_1.isString)(node.$ref) && isStartsWithComponents(node.$ref)) {
102
103
  replace(node, '$ref');
103
104
  }
104
105
  else if (node.discriminator &&
105
106
  node.discriminator.mapping &&
106
- js_utils_1.isObject(node.discriminator.mapping)) {
107
+ (0, js_utils_1.isObject)(node.discriminator.mapping)) {
107
108
  const { mapping } = node.discriminator;
108
109
  for (const name of Object.keys(mapping)) {
109
- if (js_utils_1.isString(mapping[name]) && isStartsWithComponents(mapping[name])) {
110
+ if ((0, js_utils_1.isString)(mapping[name]) && isStartsWithComponents(mapping[name])) {
110
111
  replace(node.discriminator.mapping, name);
111
112
  }
112
113
  }
@@ -137,7 +138,7 @@ function implicitlyReferenceDiscriminator(obj, defName, filename, schemaFiles) {
137
138
  implicitMapping[name] = res.startsWith('.') ? res : '.' + path.sep + res;
138
139
  }
139
140
  }
140
- if (js_utils_1.isEmptyObject(implicitMapping))
141
+ if ((0, js_utils_1.isEmptyObject)(implicitMapping))
141
142
  return;
142
143
  const discriminatorPropSchema = obj.properties[obj.discriminator.propertyName];
143
144
  const discriminatorEnum = discriminatorPropSchema && discriminatorPropSchema.enum;
@@ -147,7 +148,7 @@ function implicitlyReferenceDiscriminator(obj, defName, filename, schemaFiles) {
147
148
  continue;
148
149
  }
149
150
  if (mapping[name] && mapping[name] !== implicitMapping[name]) {
150
- process.stderr.write(colorette_1.yellow(`warning: explicit mapping overlaps with local mapping entry ${colorette_1.red(name)} at ${colorette_1.blue(filename)}. Please check it.`));
151
+ process.stderr.write((0, colorette_1.yellow)(`warning: explicit mapping overlaps with local mapping entry ${(0, colorette_1.red)(name)} at ${(0, colorette_1.blue)(filename)}. Please check it.`));
151
152
  }
152
153
  mapping[name] = implicitMapping[name];
153
154
  }
@@ -159,13 +160,13 @@ function findComponentTypes(components) {
159
160
  return types_1.OPENAPI3_COMPONENT_NAMES.filter((item) => isNotSecurityComponentType(item) && Object.keys(components).includes(item));
160
161
  }
161
162
  function doesFileDiffer(filename, componentData) {
162
- return fs.existsSync(filename) && !isEqual(utils_1.readYaml(filename), componentData);
163
+ return fs.existsSync(filename) && !isEqual((0, utils_1.readYaml)(filename), componentData);
163
164
  }
164
165
  function removeEmptyComponents(openapi, componentType) {
165
- if (openapi.components && js_utils_1.isEmptyObject(openapi.components[componentType])) {
166
+ if (openapi.components && (0, js_utils_1.isEmptyObject)(openapi.components[componentType])) {
166
167
  delete openapi.components[componentType];
167
168
  }
168
- if (js_utils_1.isEmptyObject(openapi.components)) {
169
+ if ((0, js_utils_1.isEmptyObject)(openapi.components)) {
169
170
  delete openapi.components;
170
171
  }
171
172
  }
@@ -177,8 +178,8 @@ function createComponentDir(componentDirPath, componentType) {
177
178
  function extractFileNameFromPath(filename) {
178
179
  return path.basename(filename, path.extname(filename));
179
180
  }
180
- function getFileNamePath(componentDirPath, componentName) {
181
- return path.join(componentDirPath, componentName) + '.yaml';
181
+ function getFileNamePath(componentDirPath, componentName, ext) {
182
+ return path.join(componentDirPath, componentName) + `.${ext}`;
182
183
  }
183
184
  function gatherComponentsFiles(components, componentsFiles, componentType, componentName, filename) {
184
185
  var _a, _b;
@@ -191,14 +192,14 @@ function gatherComponentsFiles(components, componentsFiles, componentType, compo
191
192
  componentsFiles[componentType] = componentsFiles[componentType] || {};
192
193
  componentsFiles[componentType][componentName] = { inherits, filename };
193
194
  }
194
- function iteratePathItems(pathItems, openapiDir, outDir, componentsFiles, pathSeparator, codeSamplesPathPrefix = '') {
195
+ function iteratePathItems(pathItems, openapiDir, outDir, componentsFiles, pathSeparator, codeSamplesPathPrefix = '', ext) {
195
196
  if (!pathItems)
196
197
  return;
197
198
  fs.mkdirSync(outDir, { recursive: true });
198
199
  for (const pathName of Object.keys(pathItems)) {
199
- const pathFile = `${path.join(outDir, utils_1.pathToFilename(pathName, pathSeparator))}.yaml`;
200
+ const pathFile = `${path.join(outDir, (0, utils_1.pathToFilename)(pathName, pathSeparator))}.${ext}`;
200
201
  const pathData = pathItems[pathName];
201
- if (openapi_core_1.isRef(pathData))
202
+ if ((0, openapi_core_1.isRef)(pathData))
202
203
  continue;
203
204
  for (const method of types_1.OPENAPI3_METHOD_NAMES) {
204
205
  const methodData = pathData[method];
@@ -209,25 +210,25 @@ function iteratePathItems(pathItems, openapiDir, outDir, componentsFiles, pathSe
209
210
  for (const sample of methodDataXCode) {
210
211
  if (sample.source && sample.source.$ref)
211
212
  continue;
212
- const sampleFileName = path.join(openapiDir, 'code_samples', utils_1.escapeLanguageName(sample.lang), codeSamplesPathPrefix + utils_1.pathToFilename(pathName, pathSeparator), method + utils_1.langToExt(sample.lang));
213
+ const sampleFileName = path.join(openapiDir, 'code_samples', (0, utils_1.escapeLanguageName)(sample.lang), codeSamplesPathPrefix + (0, utils_1.pathToFilename)(pathName, pathSeparator), method + (0, utils_1.langToExt)(sample.lang));
213
214
  fs.mkdirSync(path.dirname(sampleFileName), { recursive: true });
214
215
  fs.writeFileSync(sampleFileName, sample.source);
215
216
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
216
217
  // @ts-ignore
217
218
  sample.source = {
218
- $ref: openapi_core_1.slash(path.relative(outDir, sampleFileName)),
219
+ $ref: (0, openapi_core_1.slash)(path.relative(outDir, sampleFileName)),
219
220
  };
220
221
  }
221
222
  }
222
- utils_1.writeYaml(pathData, pathFile);
223
+ (0, utils_1.writeToFileByExtension)(pathData, pathFile);
223
224
  pathItems[pathName] = {
224
- $ref: openapi_core_1.slash(path.relative(openapiDir, pathFile)),
225
+ $ref: (0, openapi_core_1.slash)(path.relative(openapiDir, pathFile)),
225
226
  };
226
227
  traverseDirectoryDeep(outDir, traverseDirectoryDeepCallback, componentsFiles);
227
228
  }
228
229
  }
229
230
  exports.iteratePathItems = iteratePathItems;
230
- function iterateComponents(openapi, openapiDir, componentsFiles) {
231
+ function iterateComponents(openapi, openapiDir, componentsFiles, ext) {
231
232
  const { components } = openapi;
232
233
  if (components) {
233
234
  const componentsDir = path.join(openapiDir, types_1.COMPONENTS);
@@ -239,7 +240,7 @@ function iterateComponents(openapi, openapiDir, componentsFiles) {
239
240
  function iterateAndGatherComponentsFiles(componentType) {
240
241
  const componentDirPath = path.join(componentsDir, componentType);
241
242
  for (const componentName of Object.keys((components === null || components === void 0 ? void 0 : components[componentType]) || {})) {
242
- const filename = getFileNamePath(componentDirPath, componentName);
243
+ const filename = getFileNamePath(componentDirPath, componentName, ext);
243
244
  gatherComponentsFiles(components, componentsFiles, componentType, componentName, filename);
244
245
  }
245
246
  }
@@ -249,15 +250,15 @@ function iterateComponents(openapi, openapiDir, componentsFiles) {
249
250
  const componentDirPath = path.join(componentsDir, componentType);
250
251
  createComponentDir(componentDirPath, componentType);
251
252
  for (const componentName of Object.keys((components === null || components === void 0 ? void 0 : components[componentType]) || {})) {
252
- const filename = getFileNamePath(componentDirPath, componentName);
253
+ const filename = getFileNamePath(componentDirPath, componentName, ext);
253
254
  const componentData = (_a = components === null || components === void 0 ? void 0 : components[componentType]) === null || _a === void 0 ? void 0 : _a[componentName];
254
255
  replace$Refs(componentData, path.dirname(filename), componentsFiles);
255
256
  implicitlyReferenceDiscriminator(componentData, extractFileNameFromPath(filename), filename, componentsFiles.schemas || {});
256
257
  if (doesFileDiffer(filename, componentData)) {
257
- process.stderr.write(colorette_1.yellow(`warning: conflict for ${componentName} - file already exists with different content: ${colorette_1.blue(filename)} ... Skip.\n`));
258
+ process.stderr.write((0, colorette_1.yellow)(`warning: conflict for ${componentName} - file already exists with different content: ${(0, colorette_1.blue)(filename)} ... Skip.\n`));
258
259
  }
259
260
  else {
260
- utils_1.writeYaml(componentData, filename);
261
+ (0, utils_1.writeToFileByExtension)(componentData, filename);
261
262
  }
262
263
  if (isNotSecurityComponentType(componentType)) {
263
264
  // security schemas must referenced from components
@@ -1,6 +1,6 @@
1
1
  import { Oas3Schema, Oas3_1Schema, Oas3Definition, Oas3_1Definition, Oas3Components, Oas3PathItem, Oas3Paths, Oas3ComponentName, Oas3_1Webhooks, Oas2Definition, Referenced } from '@redocly/openapi-core';
2
2
  export { Oas3_1Definition, Oas3Definition, Oas2Definition, Oas3Components, Oas3Paths, Oas3PathItem, Oas3ComponentName, Oas3_1Schema, Oas3Schema, Oas3_1Webhooks, Referenced, };
3
- export declare type Definition = Oas3_1Definition | Oas3Definition | Oas2Definition;
3
+ export type Definition = Oas3_1Definition | Oas3Definition | Oas2Definition;
4
4
  export interface ComponentsFiles {
5
5
  [schemas: string]: any;
6
6
  }
@@ -11,7 +11,7 @@ export declare const COMPONENTS = "components";
11
11
  export declare const PATHS = "paths";
12
12
  export declare const WEBHOOKS = "webhooks";
13
13
  export declare const xWEBHOOKS = "x-webhooks";
14
- export declare const componentsPath: string;
14
+ export declare const componentsPath = "#/components/";
15
15
  export declare enum OPENAPI3_METHOD {
16
16
  get = "get",
17
17
  put = "put",
@@ -16,7 +16,7 @@ var OPENAPI3_METHOD;
16
16
  OPENAPI3_METHOD["head"] = "head";
17
17
  OPENAPI3_METHOD["patch"] = "patch";
18
18
  OPENAPI3_METHOD["trace"] = "trace";
19
- })(OPENAPI3_METHOD = exports.OPENAPI3_METHOD || (exports.OPENAPI3_METHOD = {}));
19
+ })(OPENAPI3_METHOD || (exports.OPENAPI3_METHOD = OPENAPI3_METHOD = {}));
20
20
  exports.OPENAPI3_METHOD_NAMES = [
21
21
  OPENAPI3_METHOD.get,
22
22
  OPENAPI3_METHOD.put,
@@ -38,7 +38,7 @@ var OPENAPI3_COMPONENT;
38
38
  OPENAPI3_COMPONENT["Links"] = "links";
39
39
  OPENAPI3_COMPONENT["Callbacks"] = "callbacks";
40
40
  OPENAPI3_COMPONENT["SecuritySchemes"] = "securitySchemes";
41
- })(OPENAPI3_COMPONENT = exports.OPENAPI3_COMPONENT || (exports.OPENAPI3_COMPONENT = {}));
41
+ })(OPENAPI3_COMPONENT || (exports.OPENAPI3_COMPONENT = OPENAPI3_COMPONENT = {}));
42
42
  exports.OPENAPI3_COMPONENT_NAMES = [
43
43
  OPENAPI3_COMPONENT.RequestBodies,
44
44
  OPENAPI3_COMPONENT.Schemas,
@@ -1,6 +1,6 @@
1
1
  import { Config } from '@redocly/openapi-core';
2
2
  import type { OutputFormat } from '@redocly/openapi-core';
3
- export declare type StatsOptions = {
3
+ export type StatsOptions = {
4
4
  api?: string;
5
5
  format: OutputFormat;
6
6
  config?: string;
@@ -54,31 +54,31 @@ function printStats(statsAccumulator, api, format) {
54
54
  }
55
55
  function handleStats(argv, config) {
56
56
  return __awaiter(this, void 0, void 0, function* () {
57
- const [{ path }] = yield utils_1.getFallbackApisOrExit(argv.api ? [argv.api] : [], config);
57
+ const [{ path }] = yield (0, utils_1.getFallbackApisOrExit)(argv.api ? [argv.api] : [], config);
58
58
  const externalRefResolver = new openapi_core_1.BaseResolver(config.resolve);
59
- const { bundle: document } = yield openapi_core_1.bundle({ config, ref: path });
59
+ const { bundle: document } = yield (0, openapi_core_1.bundle)({ config, ref: path });
60
60
  const lintConfig = config.styleguide;
61
- const specVersion = openapi_core_1.detectSpec(document.parsed);
62
- const types = openapi_core_1.normalizeTypes(lintConfig.extendTypes(openapi_core_1.getTypes(specVersion), specVersion), lintConfig);
61
+ const specVersion = (0, openapi_core_1.detectSpec)(document.parsed);
62
+ const types = (0, openapi_core_1.normalizeTypes)(lintConfig.extendTypes((0, openapi_core_1.getTypes)(specVersion), specVersion), lintConfig);
63
63
  const startedAt = perf_hooks_1.performance.now();
64
64
  const ctx = {
65
65
  problems: [],
66
66
  oasVersion: specVersion,
67
67
  visitorsData: {},
68
68
  };
69
- const resolvedRefMap = yield openapi_core_1.resolveDocument({
69
+ const resolvedRefMap = yield (0, openapi_core_1.resolveDocument)({
70
70
  rootDocument: document,
71
71
  rootType: types.Root,
72
72
  externalRefResolver,
73
73
  });
74
- const statsVisitor = openapi_core_1.normalizeVisitors([
74
+ const statsVisitor = (0, openapi_core_1.normalizeVisitors)([
75
75
  {
76
76
  severity: 'warn',
77
77
  ruleId: 'stats',
78
- visitor: openapi_core_1.Stats(statsAccumulator),
78
+ visitor: (0, openapi_core_1.Stats)(statsAccumulator),
79
79
  },
80
80
  ], types);
81
- openapi_core_1.walkDocument({
81
+ (0, openapi_core_1.walkDocument)({
82
82
  document,
83
83
  rootType: types.Root,
84
84
  normalizedVisitors: statsVisitor,
@@ -86,7 +86,7 @@ function handleStats(argv, config) {
86
86
  ctx,
87
87
  });
88
88
  printStats(statsAccumulator, path, argv.format);
89
- utils_2.printExecutionTime('stats', startedAt, path);
89
+ (0, utils_2.printExecutionTime)('stats', startedAt, path);
90
90
  });
91
91
  }
92
92
  exports.handleStats = handleStats;