@redocly/cli 1.18.0 → 1.19.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 (91) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/lib/__mocks__/@redocly/openapi-core.d.ts +2 -2
  3. package/lib/__mocks__/@redocly/openapi-core.js +1 -0
  4. package/lib/__mocks__/fs.d.ts +0 -1
  5. package/lib/__mocks__/perf_hooks.d.ts +0 -1
  6. package/lib/__mocks__/redoc.d.ts +0 -1
  7. package/lib/__tests__/commands/build-docs.test.js +21 -23
  8. package/lib/__tests__/commands/bundle.test.js +21 -30
  9. package/lib/__tests__/commands/join.test.js +101 -70
  10. package/lib/__tests__/commands/lint.test.js +54 -54
  11. package/lib/__tests__/commands/push-region.test.js +24 -25
  12. package/lib/__tests__/commands/push.test.js +269 -170
  13. package/lib/__tests__/fetch-with-timeout.test.js +3 -12
  14. package/lib/__tests__/fixtures/config.d.ts +0 -1
  15. package/lib/__tests__/utils.test.js +32 -37
  16. package/lib/__tests__/wrapper.test.js +31 -20
  17. package/lib/cms/api/__tests__/api.client.test.js +29 -38
  18. package/lib/cms/api/api-client.d.ts +0 -2
  19. package/lib/cms/api/api-client.js +106 -127
  20. package/lib/cms/api/api-keys.js +1 -2
  21. package/lib/cms/api/domains.js +1 -2
  22. package/lib/cms/commands/__tests__/push-status.test.js +251 -162
  23. package/lib/cms/commands/__tests__/push.test.js +120 -102
  24. package/lib/cms/commands/__tests__/utils.test.js +12 -21
  25. package/lib/cms/commands/push-status.d.ts +3 -2
  26. package/lib/cms/commands/push-status.js +94 -106
  27. package/lib/cms/commands/push.d.ts +3 -2
  28. package/lib/cms/commands/push.js +66 -75
  29. package/lib/cms/commands/utils.js +20 -34
  30. package/lib/commands/build-docs/index.d.ts +2 -2
  31. package/lib/commands/build-docs/index.js +8 -17
  32. package/lib/commands/build-docs/utils.js +26 -38
  33. package/lib/commands/bundle.d.ts +2 -2
  34. package/lib/commands/bundle.js +70 -94
  35. package/lib/commands/join.d.ts +2 -2
  36. package/lib/commands/join.js +377 -390
  37. package/lib/commands/lint.d.ts +2 -2
  38. package/lib/commands/lint.js +70 -78
  39. package/lib/commands/login.d.ts +3 -2
  40. package/lib/commands/login.js +9 -21
  41. package/lib/commands/preview-docs/index.d.ts +2 -2
  42. package/lib/commands/preview-docs/index.js +92 -106
  43. package/lib/commands/preview-docs/preview-server/preview-server.js +64 -76
  44. package/lib/commands/preview-docs/preview-server/server.d.ts +0 -3
  45. package/lib/commands/preview-docs/preview-server/server.js +6 -6
  46. package/lib/commands/preview-project/index.d.ts +2 -1
  47. package/lib/commands/preview-project/index.js +5 -14
  48. package/lib/commands/push.d.ts +8 -11
  49. package/lib/commands/push.js +177 -195
  50. package/lib/commands/split/__tests__/index.test.js +31 -25
  51. package/lib/commands/split/index.d.ts +2 -1
  52. package/lib/commands/split/index.js +22 -35
  53. package/lib/commands/stats.d.ts +2 -2
  54. package/lib/commands/stats.js +34 -45
  55. package/lib/index.js +32 -46
  56. package/lib/types.d.ts +2 -2
  57. package/lib/utils/__mocks__/miscellaneous.d.ts +0 -1
  58. package/lib/utils/fetch-with-timeout.js +7 -12
  59. package/lib/utils/getCommandNameFromArgs.js +2 -4
  60. package/lib/utils/js-utils.js +6 -7
  61. package/lib/utils/miscellaneous.d.ts +9 -5
  62. package/lib/utils/miscellaneous.js +150 -160
  63. package/lib/utils/update-version-notifier.js +4 -13
  64. package/lib/wrapper.d.ts +9 -2
  65. package/lib/wrapper.js +27 -16
  66. package/package.json +5 -3
  67. package/src/__mocks__/@redocly/openapi-core.ts +1 -0
  68. package/src/__tests__/commands/build-docs.test.ts +5 -4
  69. package/src/__tests__/commands/join.test.ts +51 -51
  70. package/src/__tests__/commands/push-region.test.ts +10 -8
  71. package/src/__tests__/commands/push.test.ts +127 -102
  72. package/src/__tests__/utils.test.ts +1 -0
  73. package/src/__tests__/wrapper.test.ts +24 -2
  74. package/src/cms/commands/__tests__/push-status.test.ts +70 -56
  75. package/src/cms/commands/__tests__/push.test.ts +30 -24
  76. package/src/cms/commands/push-status.ts +8 -7
  77. package/src/cms/commands/push.ts +19 -13
  78. package/src/commands/build-docs/index.ts +10 -5
  79. package/src/commands/bundle.ts +14 -6
  80. package/src/commands/join.ts +10 -6
  81. package/src/commands/lint.ts +20 -9
  82. package/src/commands/login.ts +4 -2
  83. package/src/commands/preview-docs/index.ts +6 -1
  84. package/src/commands/preview-project/index.ts +5 -4
  85. package/src/commands/push.ts +14 -16
  86. package/src/commands/split/__tests__/index.test.ts +17 -6
  87. package/src/commands/split/index.ts +6 -4
  88. package/src/commands/stats.ts +4 -2
  89. package/src/utils/miscellaneous.ts +55 -26
  90. package/src/wrapper.ts +37 -11
  91. package/tsconfig.tsbuildinfo +1 -1
@@ -1,76 +1,66 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.handlePush = void 0;
3
+ exports.handlePush = handlePush;
13
4
  const fs = require("fs");
14
5
  const path = require("path");
15
6
  const openapi_core_1 = require("@redocly/openapi-core");
16
7
  const colorette_1 = require("colorette");
17
- const pluralize = require("pluralize");
18
8
  const miscellaneous_1 = require("../../utils/miscellaneous");
19
9
  const push_status_1 = require("./push-status");
20
10
  const api_1 = require("../api");
21
- function handlePush(argv, config) {
22
- return __awaiter(this, void 0, void 0, function* () {
23
- const startedAt = performance.now(); // for printing execution time
24
- const startTime = Date.now(); // for push-status command
25
- const { organization, project: projectId, 'mount-path': mountPath, verbose } = argv;
26
- const orgId = organization || config.organization;
27
- if (!argv.message || !argv.author || !argv.branch) {
28
- (0, miscellaneous_1.exitWithError)('Error: message, author and branch are required for push to the CMS.');
29
- }
30
- if (!orgId) {
31
- return (0, miscellaneous_1.exitWithError)(`No organization provided, please use --organization option or specify the 'organization' field in the config file.`);
32
- }
33
- const domain = argv.domain || (0, api_1.getDomain)();
34
- if (!domain) {
35
- return (0, miscellaneous_1.exitWithError)(`No domain provided, please use --domain option or environment variable REDOCLY_AUTHORIZATION.`);
11
+ async function handlePush({ argv, config, version, }) {
12
+ const startedAt = performance.now(); // for printing execution time
13
+ const startTime = Date.now(); // for push-status command
14
+ const { organization, project: projectId, 'mount-path': mountPath, verbose } = argv;
15
+ const orgId = organization || config.organization;
16
+ if (!argv.message || !argv.author || !argv.branch) {
17
+ (0, miscellaneous_1.exitWithError)('Error: message, author and branch are required for push to the CMS.');
18
+ }
19
+ if (!orgId) {
20
+ return (0, miscellaneous_1.exitWithError)(`No organization provided, please use --organization option or specify the 'organization' field in the config file.`);
21
+ }
22
+ const domain = argv.domain || (0, api_1.getDomain)();
23
+ if (!domain) {
24
+ return (0, miscellaneous_1.exitWithError)(`No domain provided, please use --domain option or environment variable REDOCLY_AUTHORIZATION.`);
25
+ }
26
+ try {
27
+ const { 'commit-sha': commitSha, 'commit-url': commitUrl, 'default-branch': defaultBranch, 'wait-for-deployment': waitForDeployment, 'max-execution-time': maxExecutionTime, } = argv;
28
+ const author = parseCommitAuthor(argv.author);
29
+ const apiKey = (0, api_1.getApiKeys)(domain);
30
+ const filesToUpload = collectFilesToPush(argv.files || argv.apis);
31
+ if (!filesToUpload.length) {
32
+ return (0, miscellaneous_1.printExecutionTime)('push', startedAt, `No files to upload`);
36
33
  }
37
- try {
38
- const { 'commit-sha': commitSha, 'commit-url': commitUrl, 'default-branch': defaultBranch, 'wait-for-deployment': waitForDeployment, 'max-execution-time': maxExecutionTime, } = argv;
39
- const author = parseCommitAuthor(argv.author);
40
- const apiKey = (0, api_1.getApiKeys)(domain);
41
- const filesToUpload = collectFilesToPush(argv.files || argv.apis);
42
- if (!filesToUpload.length) {
43
- return (0, miscellaneous_1.printExecutionTime)('push', startedAt, `No files to upload`);
44
- }
45
- const client = new api_1.ReuniteApiClient(domain, apiKey);
46
- const projectDefaultBranch = yield client.remotes.getDefaultBranch(orgId, projectId);
47
- const remote = yield client.remotes.upsert(orgId, projectId, {
48
- mountBranchName: projectDefaultBranch,
49
- mountPath,
50
- });
51
- process.stderr.write(`Uploading to ${remote.mountPath} ${filesToUpload.length} ${pluralize('file', filesToUpload.length)}:\n`);
52
- const { id } = yield client.remotes.push(orgId, projectId, {
53
- remoteId: remote.id,
54
- commit: {
55
- message: argv.message,
56
- branchName: argv.branch,
57
- sha: commitSha,
58
- url: commitUrl,
59
- createdAt: argv['created-at'],
60
- namespace: argv.namespace,
61
- repository: argv.repository,
62
- author,
63
- },
64
- isMainBranch: defaultBranch === argv.branch,
65
- }, filesToUpload.map((f) => ({ path: (0, openapi_core_1.slash)(f.name), stream: fs.createReadStream(f.path) })));
66
- filesToUpload.forEach((f) => {
67
- process.stderr.write((0, colorette_1.green)(`✓ ${f.name}\n`));
68
- });
34
+ const client = new api_1.ReuniteApiClient(domain, apiKey);
35
+ const projectDefaultBranch = await client.remotes.getDefaultBranch(orgId, projectId);
36
+ const remote = await client.remotes.upsert(orgId, projectId, {
37
+ mountBranchName: projectDefaultBranch,
38
+ mountPath,
39
+ });
40
+ process.stderr.write(`Uploading to ${remote.mountPath} ${filesToUpload.length} ${(0, miscellaneous_1.pluralize)('file', filesToUpload.length)}:\n`);
41
+ const { id } = await client.remotes.push(orgId, projectId, {
42
+ remoteId: remote.id,
43
+ commit: {
44
+ message: argv.message,
45
+ branchName: argv.branch,
46
+ sha: commitSha,
47
+ url: commitUrl,
48
+ createdAt: argv['created-at'],
49
+ namespace: argv.namespace,
50
+ repository: argv.repository,
51
+ author,
52
+ },
53
+ isMainBranch: defaultBranch === argv.branch,
54
+ }, filesToUpload.map((f) => ({ path: (0, openapi_core_1.slash)(f.name), stream: fs.createReadStream(f.path) })));
55
+ filesToUpload.forEach((f) => {
56
+ process.stderr.write((0, colorette_1.green)(`✓ ${f.name}\n`));
57
+ });
58
+ process.stdout.write('\n');
59
+ process.stdout.write(`Push ID: ${id}\n`);
60
+ if (waitForDeployment) {
69
61
  process.stdout.write('\n');
70
- process.stdout.write(`Push ID: ${id}\n`);
71
- if (waitForDeployment) {
72
- process.stdout.write('\n');
73
- yield (0, push_status_1.handlePushStatus)({
62
+ await (0, push_status_1.handlePushStatus)({
63
+ argv: {
74
64
  organization: orgId,
75
65
  project: projectId,
76
66
  pushId: id,
@@ -79,21 +69,22 @@ function handlePush(argv, config) {
79
69
  'max-execution-time': maxExecutionTime,
80
70
  'start-time': startTime,
81
71
  'continue-on-deploy-failures': argv['continue-on-deploy-failures'],
82
- }, config);
83
- }
84
- verbose &&
85
- (0, miscellaneous_1.printExecutionTime)('push', startedAt, `${pluralize('file', filesToUpload.length)} uploaded to organization ${orgId}, project ${projectId}. Push ID: ${id}.`);
86
- return {
87
- pushId: id,
88
- };
89
- }
90
- catch (err) {
91
- const message = err instanceof miscellaneous_1.HandledError ? '' : `✗ File upload failed. Reason: ${err.message}`;
92
- (0, miscellaneous_1.exitWithError)(message);
72
+ },
73
+ config,
74
+ version,
75
+ });
93
76
  }
94
- });
77
+ verbose &&
78
+ (0, miscellaneous_1.printExecutionTime)('push', startedAt, `${(0, miscellaneous_1.pluralize)('file', filesToUpload.length)} uploaded to organization ${orgId}, project ${projectId}. Push ID: ${id}.`);
79
+ return {
80
+ pushId: id,
81
+ };
82
+ }
83
+ catch (err) {
84
+ const message = err instanceof miscellaneous_1.HandledError ? '' : `✗ File upload failed. Reason: ${err.message}`;
85
+ (0, miscellaneous_1.exitWithError)(message);
86
+ }
95
87
  }
96
- exports.handlePush = handlePush;
97
88
  function parseCommitAuthor(author) {
98
89
  // Author Name <author@email.com>
99
90
  const reg = /^.+\s<[^<>]+>$/;
@@ -1,15 +1,6 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.retryUntilConditionMet = void 0;
3
+ exports.retryUntilConditionMet = retryUntilConditionMet;
13
4
  const openapi_core_1 = require("@redocly/openapi-core");
14
5
  /**
15
6
  * This function retries an operation until a condition is met or a timeout is exceeded.
@@ -23,31 +14,26 @@ const openapi_core_1 = require("@redocly/openapi-core");
23
14
  * @param retryTimeoutMs The maximum time to retry the operation. Default is 10 minutes.
24
15
  * @param retryIntervalMs The interval between retries. Default is 5 seconds.
25
16
  */
26
- function retryUntilConditionMet({ operation, condition, onConditionNotMet, onRetry, startTime = Date.now(), retryTimeoutMs = 600000, // 10 min
17
+ async function retryUntilConditionMet({ operation, condition, onConditionNotMet, onRetry, startTime = Date.now(), retryTimeoutMs = 600000, // 10 min
27
18
  retryIntervalMs = 5000, // 5 sec
28
19
  }) {
29
- return __awaiter(this, void 0, void 0, function* () {
30
- function attempt() {
31
- return __awaiter(this, void 0, void 0, function* () {
32
- const result = yield operation();
33
- if (!condition) {
34
- return result;
35
- }
36
- if (condition(result)) {
37
- return result;
38
- }
39
- else if (Date.now() - startTime > retryTimeoutMs) {
40
- throw new Error('Timeout exceeded');
41
- }
42
- else {
43
- onConditionNotMet === null || onConditionNotMet === void 0 ? void 0 : onConditionNotMet(result);
44
- yield (0, openapi_core_1.pause)(retryIntervalMs);
45
- yield (onRetry === null || onRetry === void 0 ? void 0 : onRetry(result));
46
- return attempt();
47
- }
48
- });
20
+ async function attempt() {
21
+ const result = await operation();
22
+ if (!condition) {
23
+ return result;
24
+ }
25
+ if (condition(result)) {
26
+ return result;
27
+ }
28
+ else if (Date.now() - startTime > retryTimeoutMs) {
29
+ throw new Error('Timeout exceeded');
49
30
  }
50
- return attempt();
51
- });
31
+ else {
32
+ onConditionNotMet?.(result);
33
+ await (0, openapi_core_1.pause)(retryIntervalMs);
34
+ await onRetry?.(result);
35
+ return attempt();
36
+ }
37
+ }
38
+ return attempt();
52
39
  }
53
- exports.retryUntilConditionMet = retryUntilConditionMet;
@@ -1,3 +1,3 @@
1
1
  import type { BuildDocsArgv } from './types';
2
- import { Config } from '@redocly/openapi-core';
3
- export declare const handlerBuildCommand: (argv: BuildDocsArgv, configFromFile: Config) => Promise<void>;
2
+ import type { CommandArgs } from '../../wrapper';
3
+ export declare const handlerBuildCommand: ({ argv, config: configFromFile, collectSpecData, }: CommandArgs<BuildDocsArgv>) => Promise<void>;
@@ -1,27 +1,17 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.handlerBuildCommand = void 0;
13
4
  const redoc_1 = require("redoc");
14
5
  const path_1 = require("path");
15
6
  const fs_1 = require("fs");
16
7
  const perf_hooks_1 = require("perf_hooks");
17
- const utils_1 = require("./utils");
18
8
  const openapi_core_1 = require("@redocly/openapi-core");
9
+ const utils_1 = require("./utils");
19
10
  const miscellaneous_1 = require("../../utils/miscellaneous");
20
- const handlerBuildCommand = (argv, configFromFile) => __awaiter(void 0, void 0, void 0, function* () {
21
- var _a;
11
+ const handlerBuildCommand = async ({ argv, config: configFromFile, collectSpecData, }) => {
22
12
  const startedAt = perf_hooks_1.performance.now();
23
13
  const config = (0, openapi_core_1.getMergedConfig)(configFromFile, argv.api);
24
- const apis = yield (0, miscellaneous_1.getFallbackApisOrExit)(argv.api ? [argv.api] : [], config);
14
+ const apis = await (0, miscellaneous_1.getFallbackApisOrExit)(argv.api ? [argv.api] : [], config);
25
15
  const { path: pathToApi } = apis[0];
26
16
  const options = {
27
17
  output: argv.o,
@@ -29,13 +19,14 @@ const handlerBuildCommand = (argv, configFromFile) => __awaiter(void 0, void 0,
29
19
  disableGoogleFont: argv.disableGoogleFont,
30
20
  templateFileName: argv.template,
31
21
  templateOptions: argv.templateOptions || {},
32
- redocOptions: (0, utils_1.getObjectOrJSON)((_a = argv.theme) === null || _a === void 0 ? void 0 : _a.openapi, config),
22
+ redocOptions: (0, utils_1.getObjectOrJSON)(argv.theme?.openapi, config),
33
23
  };
34
24
  const redocCurrentVersion = require('../../../package.json').dependencies.redoc.substring(1); // remove ~
35
25
  try {
36
26
  const elapsed = (0, miscellaneous_1.getExecutionTime)(startedAt);
37
- const api = yield (0, redoc_1.loadAndBundleSpec)((0, openapi_core_1.isAbsoluteUrl)(pathToApi) ? pathToApi : (0, path_1.resolve)(pathToApi));
38
- const pageHTML = yield (0, utils_1.getPageHTML)(api, pathToApi, Object.assign(Object.assign({}, options), { redocCurrentVersion }), argv.config);
27
+ const api = await (0, redoc_1.loadAndBundleSpec)((0, openapi_core_1.isAbsoluteUrl)(pathToApi) ? pathToApi : (0, path_1.resolve)(pathToApi));
28
+ collectSpecData?.(api);
29
+ const pageHTML = await (0, utils_1.getPageHTML)(api, pathToApi, { ...options, redocCurrentVersion }, argv.config);
39
30
  (0, fs_1.mkdirSync)((0, path_1.dirname)(options.output), { recursive: true });
40
31
  (0, fs_1.writeFileSync)(options.output, pageHTML);
41
32
  const sizeInKiB = Math.ceil(Buffer.byteLength(pageHTML) / 1024);
@@ -44,5 +35,5 @@ const handlerBuildCommand = (argv, configFromFile) => __awaiter(void 0, void 0,
44
35
  catch (e) {
45
36
  (0, miscellaneous_1.exitWithError)(e);
46
37
  }
47
- });
38
+ };
48
39
  exports.handlerBuildCommand = handlerBuildCommand;
@@ -1,15 +1,10 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.escapeUnicode = exports.escapeClosingScriptTag = exports.sanitizeJSONString = exports.getPageHTML = exports.getObjectOrJSON = void 0;
3
+ exports.getObjectOrJSON = getObjectOrJSON;
4
+ exports.getPageHTML = getPageHTML;
5
+ exports.sanitizeJSONString = sanitizeJSONString;
6
+ exports.escapeClosingScriptTag = escapeClosingScriptTag;
7
+ exports.escapeUnicode = escapeUnicode;
13
8
  const react_1 = require("react");
14
9
  const redoc_1 = require("redoc");
15
10
  const openapi_core_1 = require("@redocly/openapi-core");
@@ -48,24 +43,22 @@ function getObjectOrJSON(openapiOptions, config) {
48
43
  }
49
44
  return {};
50
45
  }
51
- exports.getObjectOrJSON = getObjectOrJSON;
52
- function getPageHTML(api, pathToApi, { title, disableGoogleFont, templateFileName, templateOptions, redocOptions = {}, redocCurrentVersion, }, configPath) {
53
- return __awaiter(this, void 0, void 0, function* () {
54
- process.stderr.write('Prerendering docs\n');
55
- const apiUrl = redocOptions.specUrl || ((0, openapi_core_1.isAbsoluteUrl)(pathToApi) ? pathToApi : undefined);
56
- const store = yield (0, redoc_1.createStore)(api, apiUrl, redocOptions);
57
- const sheet = new styled_components_1.ServerStyleSheet();
58
- const html = (0, server_1.renderToString)(sheet.collectStyles((0, react_1.createElement)(redoc_1.Redoc, { store })));
59
- const state = yield store.toJS();
60
- const css = sheet.getStyleTags();
61
- templateFileName = templateFileName
62
- ? templateFileName
63
- : (redocOptions === null || redocOptions === void 0 ? void 0 : redocOptions.htmlTemplate)
64
- ? (0, path_1.resolve)(configPath ? (0, path_1.dirname)(configPath) : '', redocOptions.htmlTemplate)
65
- : (0, path_1.join)(__dirname, './template.hbs');
66
- const template = (0, handlebars_1.compile)((0, fs_1.readFileSync)(templateFileName).toString());
67
- return template({
68
- redocHTML: `
46
+ async function getPageHTML(api, pathToApi, { title, disableGoogleFont, templateFileName, templateOptions, redocOptions = {}, redocCurrentVersion, }, configPath) {
47
+ process.stderr.write('Prerendering docs\n');
48
+ const apiUrl = redocOptions.specUrl || ((0, openapi_core_1.isAbsoluteUrl)(pathToApi) ? pathToApi : undefined);
49
+ const store = await (0, redoc_1.createStore)(api, apiUrl, redocOptions);
50
+ const sheet = new styled_components_1.ServerStyleSheet();
51
+ const html = (0, server_1.renderToString)(sheet.collectStyles((0, react_1.createElement)(redoc_1.Redoc, { store })));
52
+ const state = await store.toJS();
53
+ const css = sheet.getStyleTags();
54
+ templateFileName = templateFileName
55
+ ? templateFileName
56
+ : redocOptions?.htmlTemplate
57
+ ? (0, path_1.resolve)(configPath ? (0, path_1.dirname)(configPath) : '', redocOptions.htmlTemplate)
58
+ : (0, path_1.join)(__dirname, './template.hbs');
59
+ const template = (0, handlebars_1.compile)((0, fs_1.readFileSync)(templateFileName).toString());
60
+ return template({
61
+ redocHTML: `
69
62
  <div id="redoc">${html || ''}</div>
70
63
  <script>
71
64
  ${`const __redoc_state = ${sanitizeJSONString(JSON.stringify(state))};` || ''}
@@ -74,26 +67,21 @@ function getPageHTML(api, pathToApi, { title, disableGoogleFont, templateFileNam
74
67
  Redoc.${'hydrate(__redoc_state, container)'};
75
68
 
76
69
  </script>`,
77
- redocHead: `<script src="https://cdn.redoc.ly/redoc/v${redocCurrentVersion}/bundles/redoc.standalone.js"></script>` +
78
- css,
79
- title: title || api.info.title || 'ReDoc documentation',
80
- disableGoogleFont,
81
- templateOptions,
82
- });
70
+ redocHead: `<script src="https://cdn.redoc.ly/redoc/v${redocCurrentVersion}/bundles/redoc.standalone.js"></script>` +
71
+ css,
72
+ title: title || api.info.title || 'ReDoc documentation',
73
+ disableGoogleFont,
74
+ templateOptions,
83
75
  });
84
76
  }
85
- exports.getPageHTML = getPageHTML;
86
77
  function sanitizeJSONString(str) {
87
78
  return escapeClosingScriptTag(escapeUnicode(str));
88
79
  }
89
- exports.sanitizeJSONString = sanitizeJSONString;
90
80
  // see http://www.thespanner.co.uk/2011/07/25/the-json-specification-is-now-wrong/
91
81
  function escapeClosingScriptTag(str) {
92
82
  return str.replace(/<\/script>/g, '<\\/script>');
93
83
  }
94
- exports.escapeClosingScriptTag = escapeClosingScriptTag;
95
84
  // see http://www.thespanner.co.uk/2011/07/25/the-json-specification-is-now-wrong/
96
85
  function escapeUnicode(str) {
97
86
  return str.replace(/\u2028|\u2029/g, (m) => '\\u202' + (m === '\u2028' ? '8' : '9'));
98
87
  }
99
- exports.escapeUnicode = escapeUnicode;
@@ -1,5 +1,5 @@
1
- import { Config } from '@redocly/openapi-core';
2
1
  import type { OutputExtensions, Skips } from '../types';
2
+ import type { CommandArgs } from '../wrapper';
3
3
  export type BundleOptions = {
4
4
  apis?: string[];
5
5
  extends?: string[];
@@ -12,4 +12,4 @@ export type BundleOptions = {
12
12
  'remove-unused-components'?: boolean;
13
13
  'keep-url-references'?: boolean;
14
14
  } & Skips;
15
- export declare function handleBundle(argv: BundleOptions, config: Config, version: string): Promise<void>;
15
+ export declare function handleBundle({ argv, config, version, collectSpecData, }: CommandArgs<BundleOptions>): Promise<void>;
@@ -1,109 +1,85 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
22
2
  Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.handleBundle = void 0;
24
- const openapi_core_1 = require("@redocly/openapi-core");
25
- const miscellaneous_1 = require("../utils/miscellaneous");
3
+ exports.handleBundle = handleBundle;
26
4
  const perf_hooks_1 = require("perf_hooks");
27
5
  const colorette_1 = require("colorette");
28
6
  const fs_1 = require("fs");
29
- const miscellaneous_2 = require("../utils/miscellaneous");
30
- function handleBundle(argv, config, version) {
31
- var _a, _b, _c, _d, _e;
32
- return __awaiter(this, void 0, void 0, function* () {
33
- const removeUnusedComponents = argv['remove-unused-components'] ||
34
- ((_c = (_b = (_a = config.rawConfig) === null || _a === void 0 ? void 0 : _a.styleguide) === null || _b === void 0 ? void 0 : _b.decorators) === null || _c === void 0 ? void 0 : _c.hasOwnProperty('remove-unused-components'));
35
- const apis = yield (0, miscellaneous_1.getFallbackApisOrExit)(argv.apis, config);
36
- const totals = { errors: 0, warnings: 0, ignored: 0 };
37
- const deprecatedOptions = [];
38
- (0, miscellaneous_2.checkForDeprecatedOptions)(argv, deprecatedOptions);
39
- for (const { path, alias } of apis) {
40
- try {
41
- const startedAt = perf_hooks_1.performance.now();
42
- const resolvedConfig = (0, openapi_core_1.getMergedConfig)(config, alias);
43
- const { styleguide } = resolvedConfig;
44
- styleguide.skipPreprocessors(argv['skip-preprocessor']);
45
- styleguide.skipDecorators(argv['skip-decorator']);
46
- process.stderr.write((0, colorette_1.gray)(`bundling ${path}...\n`));
47
- const _f = yield (0, openapi_core_1.bundle)({
48
- config: resolvedConfig,
49
- ref: path,
50
- dereference: argv.dereferenced,
51
- removeUnusedComponents,
52
- keepUrlRefs: argv['keep-url-references'],
53
- }), { bundle: result, problems } = _f, meta = __rest(_f, ["bundle", "problems"]);
54
- const fileTotals = (0, openapi_core_1.getTotals)(problems);
55
- const { outputFile, ext } = (0, miscellaneous_1.getOutputFileName)(path, apis.length, argv.output, argv.ext);
56
- if (fileTotals.errors === 0 || argv.force) {
57
- if (!argv.output) {
58
- const output = (0, miscellaneous_1.dumpBundle)((0, miscellaneous_1.sortTopLevelKeysForOas)(result.parsed), argv.ext || 'yaml', argv.dereferenced);
59
- process.stdout.write(output);
60
- }
61
- else {
62
- const output = (0, miscellaneous_1.dumpBundle)((0, miscellaneous_1.sortTopLevelKeysForOas)(result.parsed), ext, argv.dereferenced);
63
- (0, miscellaneous_1.saveBundle)(outputFile, output);
64
- }
7
+ const openapi_core_1 = require("@redocly/openapi-core");
8
+ const miscellaneous_1 = require("../utils/miscellaneous");
9
+ async function handleBundle({ argv, config, version, collectSpecData, }) {
10
+ const removeUnusedComponents = argv['remove-unused-components'] ||
11
+ config.rawConfig?.styleguide?.decorators?.hasOwnProperty('remove-unused-components');
12
+ const apis = await (0, miscellaneous_1.getFallbackApisOrExit)(argv.apis, config);
13
+ const totals = { errors: 0, warnings: 0, ignored: 0 };
14
+ const deprecatedOptions = [];
15
+ (0, miscellaneous_1.checkForDeprecatedOptions)(argv, deprecatedOptions);
16
+ for (const { path, alias } of apis) {
17
+ try {
18
+ const startedAt = perf_hooks_1.performance.now();
19
+ const resolvedConfig = (0, openapi_core_1.getMergedConfig)(config, alias);
20
+ const { styleguide } = resolvedConfig;
21
+ styleguide.skipPreprocessors(argv['skip-preprocessor']);
22
+ styleguide.skipDecorators(argv['skip-decorator']);
23
+ process.stderr.write((0, colorette_1.gray)(`bundling ${path}...\n`));
24
+ const { bundle: result, problems, ...meta } = await (0, openapi_core_1.bundle)({
25
+ config: resolvedConfig,
26
+ ref: path,
27
+ dereference: argv.dereferenced,
28
+ removeUnusedComponents,
29
+ keepUrlRefs: argv['keep-url-references'],
30
+ collectSpecData,
31
+ });
32
+ const fileTotals = (0, openapi_core_1.getTotals)(problems);
33
+ const { outputFile, ext } = (0, miscellaneous_1.getOutputFileName)(path, apis.length, argv.output, argv.ext);
34
+ if (fileTotals.errors === 0 || argv.force) {
35
+ if (!argv.output) {
36
+ const output = (0, miscellaneous_1.dumpBundle)((0, miscellaneous_1.sortTopLevelKeysForOas)(result.parsed), argv.ext || 'yaml', argv.dereferenced);
37
+ process.stdout.write(output);
38
+ }
39
+ else {
40
+ const output = (0, miscellaneous_1.dumpBundle)((0, miscellaneous_1.sortTopLevelKeysForOas)(result.parsed), ext, argv.dereferenced);
41
+ (0, miscellaneous_1.saveBundle)(outputFile, output);
65
42
  }
66
- totals.errors += fileTotals.errors;
67
- totals.warnings += fileTotals.warnings;
68
- totals.ignored += fileTotals.ignored;
69
- (0, openapi_core_1.formatProblems)(problems, {
70
- format: 'codeframe',
71
- totals: fileTotals,
72
- version,
73
- });
74
- if (argv.metafile) {
75
- if (apis.length > 1) {
76
- process.stderr.write((0, colorette_1.yellow)(`[WARNING] "--metafile" cannot be used with multiple apis. Skipping...`));
77
- }
78
- {
79
- (0, fs_1.writeFileSync)(argv.metafile, JSON.stringify(meta), 'utf-8');
80
- }
43
+ }
44
+ totals.errors += fileTotals.errors;
45
+ totals.warnings += fileTotals.warnings;
46
+ totals.ignored += fileTotals.ignored;
47
+ (0, openapi_core_1.formatProblems)(problems, {
48
+ format: 'codeframe',
49
+ totals: fileTotals,
50
+ version,
51
+ });
52
+ if (argv.metafile) {
53
+ if (apis.length > 1) {
54
+ process.stderr.write((0, colorette_1.yellow)(`[WARNING] "--metafile" cannot be used with multiple apis. Skipping...`));
81
55
  }
82
- const elapsed = (0, miscellaneous_1.getExecutionTime)(startedAt);
83
- if (fileTotals.errors > 0) {
84
- if (argv.force) {
85
- process.stderr.write(`❓ Created a bundle for ${(0, colorette_1.blue)(path)} at ${(0, colorette_1.blue)(outputFile)} with errors ${(0, colorette_1.green)(elapsed)}.\n${(0, colorette_1.yellow)('Errors ignored because of --force')}.\n`);
86
- }
87
- else {
88
- process.stderr.write(`❌ Errors encountered while bundling ${(0, colorette_1.blue)(path)}: bundle not created (use --force to ignore errors).\n`);
89
- }
56
+ {
57
+ (0, fs_1.writeFileSync)(argv.metafile, JSON.stringify(meta), 'utf-8');
90
58
  }
91
- else {
92
- process.stderr.write(`📦 Created a bundle for ${(0, colorette_1.blue)(path)} at ${(0, colorette_1.blue)(outputFile)} ${(0, colorette_1.green)(elapsed)}.\n`);
59
+ }
60
+ const elapsed = (0, miscellaneous_1.getExecutionTime)(startedAt);
61
+ if (fileTotals.errors > 0) {
62
+ if (argv.force) {
63
+ process.stderr.write(`❓ Created a bundle for ${(0, colorette_1.blue)(path)} at ${(0, colorette_1.blue)(outputFile)} with errors ${(0, colorette_1.green)(elapsed)}.\n${(0, colorette_1.yellow)('Errors ignored because of --force')}.\n`);
93
64
  }
94
- const removedCount = (_e = (_d = meta.visitorsData) === null || _d === void 0 ? void 0 : _d['remove-unused-components']) === null || _e === void 0 ? void 0 : _e.removedCount;
95
- if (removedCount) {
96
- process.stderr.write((0, colorette_1.gray)(`🧹 Removed ${removedCount} unused components.\n`));
65
+ else {
66
+ process.stderr.write(`❌ Errors encountered while bundling ${(0, colorette_1.blue)(path)}: bundle not created (use --force to ignore errors).\n`);
97
67
  }
98
68
  }
99
- catch (e) {
100
- (0, miscellaneous_1.handleError)(e, path);
69
+ else {
70
+ process.stderr.write(`📦 Created a bundle for ${(0, colorette_1.blue)(path)} at ${(0, colorette_1.blue)(outputFile)} ${(0, colorette_1.green)(elapsed)}.\n`);
71
+ }
72
+ const removedCount = meta.visitorsData?.['remove-unused-components']?.removedCount;
73
+ if (removedCount) {
74
+ process.stderr.write((0, colorette_1.gray)(`🧹 Removed ${removedCount} unused components.\n`));
101
75
  }
102
76
  }
103
- (0, miscellaneous_1.printUnusedWarnings)(config.styleguide);
104
- if (!(totals.errors === 0 || argv.force)) {
105
- throw new Error('Bundle failed.');
77
+ catch (e) {
78
+ (0, miscellaneous_1.handleError)(e, path);
106
79
  }
107
- });
80
+ }
81
+ (0, miscellaneous_1.printUnusedWarnings)(config.styleguide);
82
+ if (!(totals.errors === 0 || argv.force)) {
83
+ throw new Error('Bundle failed.');
84
+ }
108
85
  }
109
- exports.handleBundle = handleBundle;
@@ -1,5 +1,5 @@
1
- import { Config } from '@redocly/openapi-core';
2
1
  import type { RuleSeverity } from '@redocly/openapi-core';
2
+ import type { CommandArgs } from '../wrapper';
3
3
  export type JoinOptions = {
4
4
  apis: string[];
5
5
  'prefix-tags-with-info-prop'?: string;
@@ -10,4 +10,4 @@ export type JoinOptions = {
10
10
  config?: string;
11
11
  'lint-config'?: RuleSeverity;
12
12
  };
13
- export declare function handleJoin(argv: JoinOptions, config: Config, packageVersion: string): Promise<void>;
13
+ export declare function handleJoin({ argv, config, version: packageVersion, }: CommandArgs<JoinOptions>): Promise<void>;