@redocly/cli 1.0.0-beta.126 → 1.0.0-beta.128

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 (51) hide show
  1. package/lib/__tests__/utils.test.js +19 -0
  2. package/lib/index.js +5 -1
  3. package/lib/update-version-notifier.d.ts +2 -0
  4. package/lib/update-version-notifier.js +100 -0
  5. package/lib/utils.d.ts +1 -0
  6. package/lib/utils.js +13 -5
  7. package/package.json +5 -3
  8. package/src/__mocks__/@redocly/openapi-core.ts +0 -80
  9. package/src/__mocks__/documents.ts +0 -63
  10. package/src/__mocks__/fs.ts +0 -6
  11. package/src/__mocks__/perf_hooks.ts +0 -3
  12. package/src/__mocks__/redoc.ts +0 -2
  13. package/src/__mocks__/utils.ts +0 -19
  14. package/src/__tests__/commands/build-docs.test.ts +0 -61
  15. package/src/__tests__/commands/bundle.test.ts +0 -169
  16. package/src/__tests__/commands/join.test.ts +0 -114
  17. package/src/__tests__/commands/lint.test.ts +0 -166
  18. package/src/__tests__/commands/push-region.test.ts +0 -51
  19. package/src/__tests__/commands/push.test.ts +0 -364
  20. package/src/__tests__/fixtures/config.ts +0 -21
  21. package/src/__tests__/utils.test.ts +0 -441
  22. package/src/assert-node-version.ts +0 -8
  23. package/src/commands/build-docs/index.ts +0 -56
  24. package/src/commands/build-docs/template.hbs +0 -23
  25. package/src/commands/build-docs/types.ts +0 -26
  26. package/src/commands/build-docs/utils.ts +0 -112
  27. package/src/commands/bundle.ts +0 -170
  28. package/src/commands/join.ts +0 -810
  29. package/src/commands/lint.ts +0 -161
  30. package/src/commands/login.ts +0 -21
  31. package/src/commands/preview-docs/index.ts +0 -183
  32. package/src/commands/preview-docs/preview-server/default.hbs +0 -24
  33. package/src/commands/preview-docs/preview-server/hot.js +0 -42
  34. package/src/commands/preview-docs/preview-server/oauth2-redirect.html +0 -21
  35. package/src/commands/preview-docs/preview-server/preview-server.ts +0 -156
  36. package/src/commands/preview-docs/preview-server/server.ts +0 -91
  37. package/src/commands/push.ts +0 -387
  38. package/src/commands/split/__tests__/fixtures/samples.json +0 -61
  39. package/src/commands/split/__tests__/fixtures/spec.json +0 -70
  40. package/src/commands/split/__tests__/fixtures/webhooks.json +0 -88
  41. package/src/commands/split/__tests__/index.test.ts +0 -137
  42. package/src/commands/split/index.ts +0 -378
  43. package/src/commands/split/types.ts +0 -85
  44. package/src/commands/stats.ts +0 -117
  45. package/src/custom.d.ts +0 -1
  46. package/src/index.ts +0 -431
  47. package/src/js-utils.ts +0 -17
  48. package/src/types.ts +0 -28
  49. package/src/utils.ts +0 -472
  50. package/tsconfig.json +0 -9
  51. package/tsconfig.tsbuildinfo +0 -1
@@ -1,387 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
- import fetch from 'node-fetch';
4
- import { performance } from 'perf_hooks';
5
- import { yellow, green, blue } from 'colorette';
6
- import { createHash } from 'crypto';
7
- import {
8
- bundle,
9
- Config,
10
- RedoclyClient,
11
- IGNORE_FILE,
12
- BundleOutputFormat,
13
- getTotals,
14
- slash,
15
- Region,
16
- getMergedConfig,
17
- } from '@redocly/openapi-core';
18
- import {
19
- exitWithError,
20
- printExecutionTime,
21
- getFallbackApisOrExit,
22
- pluralize,
23
- dumpBundle,
24
- loadConfigAndHandleErrors,
25
- } from '../utils';
26
- import { promptClientToken } from './login';
27
-
28
- const DEFAULT_VERSION = 'latest';
29
-
30
- const DESTINATION_REGEX =
31
- /^(@(?<organizationId>[\w\-\s]+)\/)?(?<name>[^@]*)@(?<version>[\w\.\-]+)$/;
32
-
33
- type PushArgs = {
34
- api?: string;
35
- destination?: string;
36
- branchName?: string;
37
- upsert?: boolean;
38
- 'batch-id'?: string;
39
- 'batch-size'?: number;
40
- region?: Region;
41
- 'skip-decorator'?: string[];
42
- public?: boolean;
43
- files?: string[];
44
- };
45
-
46
- export async function handlePush(argv: PushArgs): Promise<void> {
47
- const config = await loadConfigAndHandleErrors({ region: argv.region, files: argv.files });
48
- const client = new RedoclyClient(config.region);
49
- const isAuthorized = await client.isAuthorizedWithRedoclyByRegion();
50
- if (!isAuthorized) {
51
- const clientToken = await promptClientToken(client.domain);
52
- await client.login(clientToken);
53
- }
54
-
55
- const startedAt = performance.now();
56
- const { destination, branchName, upsert } = argv;
57
-
58
- const batchId = argv['batch-id'];
59
- const batchSize = argv['batch-size'];
60
-
61
- if (destination && !DESTINATION_REGEX.test(destination)) {
62
- exitWithError(
63
- `Destination argument value is not valid, please use the right format: ${yellow(
64
- '<@organization-id/api-name@api-version>'
65
- )}`
66
- );
67
- }
68
-
69
- const { organizationId, name, version } = getDestinationProps(destination, config.organization);
70
-
71
- if (!organizationId) {
72
- return exitWithError(
73
- `No organization provided, please use the right format: ${yellow(
74
- '<@organization-id/api-name@api-version>'
75
- )} or specify the 'organization' field in the config file.`
76
- );
77
- }
78
- const api = argv.api || (name && version && getApiRoot({ name, version, config }));
79
-
80
- if (name && version && !api) {
81
- exitWithError(
82
- `No api found that matches ${blue(
83
- `${name}@${version}`
84
- )}. Please make sure you have provided the correct data in the config file.`
85
- );
86
- }
87
-
88
- if (batchId && !batchId.trim()) {
89
- exitWithError(
90
- `The ${blue(`batch-id`)} option value is not valid, please avoid using an empty string.`
91
- );
92
- }
93
-
94
- if (batchSize && batchSize < 2) {
95
- exitWithError(
96
- `The ${blue(`batch-size`)} option value is not valid, please use the integer bigger than 1.`
97
- );
98
- }
99
-
100
- const apis = api ? { [`${name}@${version}`]: { root: api } } : config.apis;
101
- if (!Object.keys(apis).length) {
102
- exitWithError(
103
- `Api not found. Please make sure you have provided the correct data in the config file.`
104
- );
105
- }
106
-
107
- for (const [apiNameAndVersion, { root: api }] of Object.entries(apis)) {
108
- const resolvedConfig = getMergedConfig(config, apiNameAndVersion);
109
- resolvedConfig.styleguide.skipDecorators(argv['skip-decorator']);
110
-
111
- const [name, version = DEFAULT_VERSION] = apiNameAndVersion.split('@');
112
- const encodedName = encodeURIComponent(name);
113
- try {
114
- let rootFilePath = '';
115
- const filePaths: string[] = [];
116
- const filesToUpload = await collectFilesToUpload(api, resolvedConfig);
117
- const filesHash = hashFiles(filesToUpload.files);
118
-
119
- process.stdout.write(
120
- `Uploading ${filesToUpload.files.length} ${pluralize(
121
- 'file',
122
- filesToUpload.files.length
123
- )}:\n`
124
- );
125
-
126
- let uploaded = 0;
127
-
128
- for (const file of filesToUpload.files) {
129
- const { signedUploadUrl, filePath } = await client.registryApi.prepareFileUpload({
130
- organizationId,
131
- name: encodedName,
132
- version,
133
- filesHash,
134
- filename: file.keyOnS3,
135
- isUpsert: upsert,
136
- });
137
-
138
- if (file.filePath === filesToUpload.root) {
139
- rootFilePath = filePath;
140
- }
141
-
142
- filePaths.push(filePath);
143
-
144
- process.stdout.write(
145
- `Uploading ${file.contents ? 'bundle for ' : ''}${blue(file.filePath)}...`
146
- );
147
-
148
- const uploadResponse = await uploadFileToS3(
149
- signedUploadUrl,
150
- file.contents || file.filePath
151
- );
152
-
153
- const fileCounter = `(${++uploaded}/${filesToUpload.files.length})`;
154
-
155
- if (!uploadResponse.ok) {
156
- exitWithError(`✗ ${fileCounter}\nFile upload failed\n`);
157
- }
158
-
159
- process.stdout.write(green(`✓ ${fileCounter}\n`));
160
- }
161
-
162
- process.stdout.write('\n');
163
-
164
- await client.registryApi.pushApi({
165
- organizationId,
166
- name: encodedName,
167
- version,
168
- rootFilePath,
169
- filePaths,
170
- branch: branchName,
171
- isUpsert: upsert,
172
- isPublic: argv['public'],
173
- batchId: batchId,
174
- batchSize: batchSize,
175
- });
176
- } catch (error) {
177
- if (error.message === 'ORGANIZATION_NOT_FOUND') {
178
- exitWithError(`Organization ${blue(organizationId)} not found`);
179
- }
180
-
181
- if (error.message === 'API_VERSION_NOT_FOUND') {
182
- exitWithError(`The definition version ${blue(name)}/${blue(
183
- version
184
- )} does not exist in organization ${blue(organizationId)}!\n${yellow(
185
- 'Suggestion:'
186
- )} please use ${blue('-u')} or ${blue('--upsert')} to create definition.
187
- `);
188
- }
189
-
190
- throw error;
191
- }
192
-
193
- process.stdout.write(
194
- `Definition: ${blue(api!)} is successfully pushed to Redocly API Registry \n`
195
- );
196
- }
197
- printExecutionTime('push', startedAt, api || `apis in organization ${organizationId}`);
198
- }
199
-
200
- function getFilesList(dir: string, files?: any): string[] {
201
- files = files || [];
202
- const filesAndDirs = fs.readdirSync(dir);
203
- for (const name of filesAndDirs) {
204
- if (fs.statSync(path.join(dir, name)).isDirectory()) {
205
- files = getFilesList(path.join(dir, name), files);
206
- } else {
207
- const currentPath = dir + '/' + name;
208
- files.push(currentPath);
209
- }
210
- }
211
- return files;
212
- }
213
-
214
- async function collectFilesToUpload(api: string, config: Config) {
215
- const files: { filePath: string; keyOnS3: string; contents?: Buffer }[] = [];
216
- const [{ path: apiPath }] = await getFallbackApisOrExit([api], config);
217
-
218
- process.stdout.write('Bundling definition\n');
219
-
220
- const { bundle: openapiBundle, problems } = await bundle({
221
- config,
222
- ref: apiPath,
223
- skipRedoclyRegistryRefs: true,
224
- });
225
-
226
- const fileTotals = getTotals(problems);
227
-
228
- if (fileTotals.errors === 0) {
229
- process.stdout.write(
230
- `Created a bundle for ${blue(api)} ${fileTotals.warnings > 0 ? 'with warnings' : ''}\n`
231
- );
232
- } else {
233
- exitWithError(`Failed to create a bundle for ${blue(api)}\n`);
234
- }
235
-
236
- const fileExt = path.extname(apiPath).split('.').pop();
237
- files.push(
238
- getFileEntry(apiPath, dumpBundle(openapiBundle.parsed, fileExt as BundleOutputFormat))
239
- );
240
-
241
- if (fs.existsSync('package.json')) {
242
- files.push(getFileEntry('package.json'));
243
- }
244
- if (fs.existsSync(IGNORE_FILE)) {
245
- files.push(getFileEntry(IGNORE_FILE));
246
- }
247
- if (config.configFile) {
248
- // All config file paths including the root one
249
- files.push(...[...new Set(config.styleguide.extendPaths)].map((f) => getFileEntry(f)));
250
- if (config.theme?.openapi?.htmlTemplate) {
251
- const dir = getFolder(config.theme.openapi.htmlTemplate);
252
- const fileList = getFilesList(dir, []);
253
- files.push(...fileList.map((f) => getFileEntry(f)));
254
- }
255
- const pluginFiles = new Set<string>();
256
- for (const plugin of config.styleguide.pluginPaths) {
257
- if (typeof plugin !== 'string') continue;
258
- const fileList = getFilesList(getFolder(plugin), []);
259
- fileList.forEach((f) => pluginFiles.add(f));
260
- }
261
- files.push(...filterPluginFilesByExt(Array.from(pluginFiles)).map((f) => getFileEntry(f)));
262
- }
263
-
264
- if (config.files) {
265
- const otherFiles = new Set<string>();
266
- for (const file of config.files) {
267
- if (fs.statSync(file).isDirectory()) {
268
- const fileList = getFilesList(file, []);
269
- fileList.forEach((f) => otherFiles.add(f));
270
- } else {
271
- otherFiles.add(file);
272
- }
273
- }
274
- files.push(...Array.from(otherFiles).map((f) => getFileEntry(f)));
275
- }
276
-
277
- return {
278
- files,
279
- root: path.resolve(apiPath),
280
- };
281
-
282
- function filterPluginFilesByExt(files: string[]) {
283
- return files.filter((file: string) => {
284
- const fileExt = path.extname(file).toLowerCase();
285
- return fileExt === '.js' || fileExt === '.ts' || fileExt === '.mjs' || fileExt === 'json';
286
- });
287
- }
288
-
289
- function getFileEntry(filename: string, contents?: string) {
290
- return {
291
- filePath: path.resolve(filename),
292
- keyOnS3: config.configFile
293
- ? slash(path.relative(path.dirname(config.configFile), filename))
294
- : slash(path.basename(filename)),
295
- contents: (contents && Buffer.from(contents, 'utf-8')) || undefined,
296
- };
297
- }
298
- }
299
-
300
- function getFolder(filePath: string) {
301
- return path.resolve(path.dirname(filePath));
302
- }
303
-
304
- function hashFiles(filePaths: { filePath: string }[]) {
305
- const sum = createHash('sha256');
306
- filePaths.forEach((file) => sum.update(fs.readFileSync(file.filePath)));
307
- return sum.digest('hex');
308
- }
309
-
310
- function parseDestination(
311
- destination?: string
312
- ): { organizationId?: string; name?: string; version?: string } | undefined {
313
- return destination?.match(DESTINATION_REGEX)?.groups;
314
- }
315
-
316
- export function getDestinationProps(
317
- destination: string | undefined,
318
- organization: string | undefined
319
- ) {
320
- const groups = destination && parseDestination(destination);
321
- if (groups) {
322
- return {
323
- organizationId: groups.organizationId || organization,
324
- name: groups.name,
325
- version: groups.version,
326
- };
327
- } else {
328
- return { organizationId: organization, name: undefined, version: undefined };
329
- }
330
- }
331
-
332
- type BarePushArgs = Omit<PushArgs, 'api' | 'destination' | 'branchName'> & {
333
- maybeApiOrDestination?: string;
334
- maybeDestination?: string;
335
- maybeBranchName?: string;
336
- branch?: string;
337
- };
338
-
339
- export const transformPush =
340
- (callback: typeof handlePush) =>
341
- ({ maybeApiOrDestination, maybeDestination, maybeBranchName, branch, ...rest }: BarePushArgs) => {
342
- if (maybeBranchName) {
343
- process.stderr.write(
344
- yellow(
345
- 'Deprecation warning: Do not use the third parameter as a branch name. Please use a separate --branch option instead.'
346
- )
347
- );
348
- }
349
- const api = maybeDestination ? maybeApiOrDestination : undefined;
350
- const destination = maybeDestination || maybeApiOrDestination;
351
- return callback({
352
- ...rest,
353
- destination,
354
- api,
355
- branchName: branch ?? maybeBranchName,
356
- });
357
- };
358
-
359
- export function getApiRoot({
360
- name,
361
- version,
362
- config: { apis },
363
- }: {
364
- name: string;
365
- version: string;
366
- config: Config;
367
- }): string {
368
- const api = apis?.[`${name}@${version}`] || (version === DEFAULT_VERSION && apis?.[name]);
369
- return api?.root;
370
- }
371
-
372
- function uploadFileToS3(url: string, filePathOrBuffer: string | Buffer) {
373
- const fileSizeInBytes =
374
- typeof filePathOrBuffer === 'string'
375
- ? fs.statSync(filePathOrBuffer).size
376
- : filePathOrBuffer.byteLength;
377
- const readStream =
378
- typeof filePathOrBuffer === 'string' ? fs.createReadStream(filePathOrBuffer) : filePathOrBuffer;
379
-
380
- return fetch(url, {
381
- method: 'PUT',
382
- headers: {
383
- 'Content-Length': fileSizeInBytes.toString(),
384
- },
385
- body: readStream,
386
- });
387
- }
@@ -1,61 +0,0 @@
1
- {
2
- "openapi": "3.0.1",
3
- "info": {
4
- "title": "TEST",
5
- "description": "TEST",
6
- "version": "v1",
7
- "license": {
8
- "name": "Apache 2.0",
9
- "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
10
- }
11
- },
12
- "servers": [
13
- {
14
- "url": "http://petstore.swagger.io/v1"
15
- }
16
- ],
17
- "components": {
18
- "schemas": {
19
- "Test": {
20
- "nullable": true
21
- }
22
- }
23
- },
24
- "paths": {
25
- "/test": {
26
- "get": {
27
- "summary": "test",
28
- "operationId": "test",
29
- "responses": {
30
- "202": {
31
- "description": "Test",
32
- "content": {
33
- "application/json": {
34
- "schema": {
35
- "$ref": "#/components/schemas/Test"
36
- }
37
- }
38
- }
39
- },
40
- "400": {
41
- "description": "An error response"
42
- }
43
- },
44
- "x-codeSamples": [
45
- {
46
- "lang": "C#",
47
- "source": "PetStore.v1.Pet pet = new PetStore.v1.Pet();"
48
- },
49
- {
50
- "lang": "C/AL",
51
- "source": "PetStore.v1.Pet pet = new PetStore.v1.Pet();"
52
- },
53
- {
54
- "lang": "Visual Basic",
55
- "source": "PetStore.v1.Pet pet = new PetStore.v1.Pet();"
56
- }
57
- ]
58
- }
59
- }
60
- }
61
- }
@@ -1,70 +0,0 @@
1
- {
2
- "openapi": "3.0.1",
3
- "info": {
4
- "title": "TEST",
5
- "description": "TEST",
6
- "version": "v1",
7
- "license": {
8
- "name": "Apache 2.0",
9
- "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
10
- }
11
- },
12
- "servers": [
13
- {
14
- "url": "http://petstore.swagger.io/v1"
15
- }
16
- ],
17
- "components": {
18
- "schemas": {
19
- "Test": {
20
- "nullable": true
21
- }
22
- }
23
- },
24
- "paths": {
25
- "/test": {
26
- "get": {
27
- "summary": "test",
28
- "operationId": "test",
29
- "responses": {
30
- "202": {
31
- "description": "Test",
32
- "content": {
33
- "application/json": {
34
- "schema": {
35
- "$ref": "#/components/schemas/Test"
36
- },
37
- "example": {}
38
- }
39
- }
40
- },
41
- "400": {
42
- "description": "An error response"
43
- }
44
- }
45
- }
46
- }
47
- },
48
- "x-webhooks": {
49
- "test": {
50
- "post": {
51
- "summary": "New pet",
52
- "description": "Information about a new pet in the systems",
53
- "operationId": "newPet",
54
- "tags": ["pet"],
55
- "requestBody": {
56
- "content": {
57
- "application/json": {
58
- "schema": { "$ref": "#/components/schemas/Test" }
59
- }
60
- }
61
- },
62
- "responses": {
63
- "200": {
64
- "description": "Return a 200 status to indicate that the data was received successfully"
65
- }
66
- }
67
- }
68
- }
69
- }
70
- }
@@ -1,88 +0,0 @@
1
- {
2
- "openapi": "3.1.0",
3
- "info": {
4
- "title": "Webhook Example",
5
- "version": "1.0.0"
6
- },
7
- "paths": {
8
- "/pets": {
9
- "get": {
10
- "summary": "List all pets",
11
- "operationId": "listPets",
12
- "parameters": [
13
- {
14
- "name": "limit",
15
- "in": "query",
16
- "description": "How many items to return at one time (max 100)",
17
- "required": false,
18
- "schema": {
19
- "type": "integer",
20
- "format": "int32"
21
- }
22
- }
23
- ],
24
- "responses": {
25
- "200": {
26
- "description": "A paged array of pets",
27
- "content": {
28
- "application/json": {
29
- "schema": {
30
- "$ref": "#/components/schemas/Pets"
31
- }
32
- }
33
- }
34
- }
35
- }
36
- }
37
- }
38
- },
39
- "webhooks": {
40
- "test": {
41
- "post": {
42
- "requestBody": {
43
- "description": "Information about a new pet in the system",
44
- "content": {
45
- "application/json": {
46
- "schema": {
47
- "$ref": "#/components/schemas/Pet"
48
- }
49
- }
50
- }
51
- },
52
- "responses": {
53
- "200": {
54
- "description": "Return a 200 status to indicate that the data was received successfully"
55
- }
56
- }
57
- }
58
- }
59
- },
60
- "components": {
61
- "schemas": {
62
- "Pet": {
63
- "required": [
64
- "id",
65
- "name"
66
- ],
67
- "properties": {
68
- "id": {
69
- "type": "integer",
70
- "format": "int64"
71
- },
72
- "name": {
73
- "type": "string"
74
- },
75
- "tag": {
76
- "type": "string"
77
- }
78
- }
79
- },
80
- "Pets": {
81
- "type": "array",
82
- "items": {
83
- "$ref": "#/components/schemas/Pet"
84
- }
85
- }
86
- }
87
- }
88
- }