@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,21 +0,0 @@
1
- export const ConfigFixture = {
2
- configFile: null,
3
- styleguide: {
4
- addIgnore: jest.fn(),
5
- skipRules: jest.fn(),
6
- skipPreprocessors: jest.fn(),
7
- saveIgnore: jest.fn(),
8
- skipDecorators: jest.fn(),
9
- ignore: null,
10
- decorators: {
11
- oas2: {},
12
- oas3_0: {},
13
- oas3_1: {},
14
- },
15
- preprocessors: {
16
- oas2: {},
17
- oas3_0: {},
18
- oas3_1: {},
19
- },
20
- },
21
- };
@@ -1,441 +0,0 @@
1
- import {
2
- getFallbackApisOrExit,
3
- isSubdir,
4
- pathToFilename,
5
- printConfigLintTotals,
6
- langToExt,
7
- checkIfRulesetExist,
8
- handleError,
9
- CircularJSONNotSupportedError,
10
- sortTopLevelKeysForOas,
11
- } from '../utils';
12
- import {
13
- ResolvedApi,
14
- Totals,
15
- isAbsoluteUrl,
16
- ResolveError,
17
- YamlParseError,
18
- Oas3Definition,
19
- } from '@redocly/openapi-core';
20
- import { blue, red, yellow } from 'colorette';
21
- import { existsSync } from 'fs';
22
- import * as path from 'path';
23
- import * as process from 'process';
24
-
25
- jest.mock('os');
26
- jest.mock('colorette');
27
- jest.mock('fs');
28
-
29
- describe('isSubdir', () => {
30
- it('can correctly determine if subdir', () => {
31
- (
32
- [
33
- ['/foo', '/foo', false],
34
- ['/foo', '/bar', false],
35
- ['/foo', '/foobar', false],
36
- ['/foo', '/foo/bar', true],
37
- ['/foo', '/foo/../bar', false],
38
- ['/foo', '/foo/./bar', true],
39
- ['/bar/../foo', '/foo/bar', true],
40
- ['/foo', './bar', false],
41
- ['/foo', '/foo/..bar', true],
42
- ] as [string, string, boolean][]
43
- ).forEach(([parent, child, expectRes]) => {
44
- expect(isSubdir(parent, child)).toBe(expectRes);
45
- });
46
- });
47
-
48
- it('can correctly determine if subdir for windows-based paths', () => {
49
- const os = require('os');
50
- os.platform.mockImplementation(() => 'win32');
51
-
52
- (
53
- [
54
- ['C:/Foo', 'C:/Foo/Bar', true],
55
- ['C:\\Foo', 'C:\\Bar', false],
56
- ['C:\\Foo', 'D:\\Foo\\Bar', false],
57
- ] as [string, string, boolean][]
58
- ).forEach(([parent, child, expectRes]) => {
59
- expect(isSubdir(parent, child)).toBe(expectRes);
60
- });
61
- });
62
-
63
- afterEach(() => {
64
- jest.resetModules();
65
- });
66
- });
67
-
68
- describe('pathToFilename', () => {
69
- it('should use correct path separator', () => {
70
- const processedPath = pathToFilename('/user/createWithList', '_');
71
- expect(processedPath).toEqual('user_createWithList');
72
- });
73
- });
74
-
75
- describe('getFallbackApisOrExit', () => {
76
- it('should find alias by filename', async () => {
77
- (existsSync as jest.Mock<any, any>).mockImplementationOnce(() => true);
78
- const entry = await getFallbackApisOrExit(['./test.yaml'], {
79
- apis: {
80
- main: {
81
- root: 'test.yaml',
82
- },
83
- },
84
- } as any);
85
- expect(entry).toEqual([{ path: './test.yaml', alias: 'main' }]);
86
- });
87
- });
88
-
89
- describe('printConfigLintTotals', () => {
90
- const totalProblemsMock: Totals = {
91
- errors: 1,
92
- warnings: 0,
93
- ignored: 0,
94
- };
95
-
96
- const redColoretteMocks = red as jest.Mock<any, any>;
97
- const yellowColoretteMocks = yellow as jest.Mock<any, any>;
98
-
99
- beforeEach(() => {
100
- yellowColoretteMocks.mockImplementation((text: string) => text);
101
- redColoretteMocks.mockImplementation((text: string) => text);
102
- jest.spyOn(process.stderr, 'write').mockImplementation(() => true);
103
- });
104
-
105
- it('should print errors if such exist', () => {
106
- printConfigLintTotals(totalProblemsMock);
107
- expect(process.stderr.write).toHaveBeenCalledWith('❌ Your config has 1 error.\n');
108
- expect(redColoretteMocks).toHaveBeenCalledWith('❌ Your config has 1 error.\n');
109
- });
110
-
111
- it('should print warnign and error', () => {
112
- printConfigLintTotals({ ...totalProblemsMock, warnings: 2 });
113
- expect(process.stderr.write).toHaveBeenCalledWith(
114
- '❌ Your config has 1 error and 2 warnings.\n'
115
- );
116
- expect(redColoretteMocks).toHaveBeenCalledWith('❌ Your config has 1 error and 2 warnings.\n');
117
- });
118
-
119
- it('should print warnign if no error', () => {
120
- printConfigLintTotals({ ...totalProblemsMock, errors: 0, warnings: 2 });
121
- expect(process.stderr.write).toHaveBeenCalledWith('You have 2 warnings.\n');
122
- expect(yellowColoretteMocks).toHaveBeenCalledWith('You have 2 warnings.\n');
123
- });
124
-
125
- it('should print nothing if no error and no warnings', () => {
126
- const result = printConfigLintTotals({ ...totalProblemsMock, errors: 0 });
127
- expect(result).toBeUndefined();
128
- expect(process.stderr.write).toHaveBeenCalledTimes(0);
129
- expect(yellowColoretteMocks).toHaveBeenCalledTimes(0);
130
- expect(redColoretteMocks).toHaveBeenCalledTimes(0);
131
- });
132
- });
133
-
134
- describe('getFallbackApisOrExit', () => {
135
- const redColoretteMocks = red as jest.Mock<any, any>;
136
- const yellowColoretteMocks = yellow as jest.Mock<any, any>;
137
-
138
- const apis: Record<string, ResolvedApi> = {
139
- main: {
140
- root: 'someFile.yaml',
141
- styleguide: {},
142
- },
143
- };
144
-
145
- const config = { apis };
146
-
147
- beforeEach(() => {
148
- yellowColoretteMocks.mockImplementation((text: string) => text);
149
- redColoretteMocks.mockImplementation((text: string) => text);
150
- jest.spyOn(process.stderr, 'write').mockImplementation(() => true);
151
- jest.spyOn(process, 'exit').mockImplementation();
152
- });
153
-
154
- it('should exit with error because no path provided', async () => {
155
- const apisConfig = {
156
- apis: {},
157
- };
158
- await getFallbackApisOrExit([''], apisConfig);
159
- expect(process.exit).toHaveBeenCalledWith(1);
160
- });
161
-
162
- it('should error if file from config do not exist', async () => {
163
- (existsSync as jest.Mock<any, any>).mockImplementationOnce(() => false);
164
- await getFallbackApisOrExit(undefined, config);
165
-
166
- expect(process.stderr.write).toHaveBeenCalledWith(
167
- '\n someFile.yaml does not exist or is invalid. Please provide a valid path. \n\n'
168
- );
169
- expect(process.exit).toHaveBeenCalledWith(1);
170
- });
171
-
172
- it('should return valid array with results if such file exist', async () => {
173
- (existsSync as jest.Mock<any, any>).mockImplementationOnce(() => true);
174
- jest.spyOn(path, 'resolve').mockImplementationOnce((_, path) => path);
175
-
176
- const result = await getFallbackApisOrExit(undefined, config);
177
- expect(process.stderr.write).toHaveBeenCalledTimes(0);
178
- expect(process.exit).toHaveBeenCalledTimes(0);
179
- expect(result).toStrictEqual([
180
- {
181
- alias: 'main',
182
- path: 'someFile.yaml',
183
- },
184
- ]);
185
- });
186
-
187
- it('should exit with error in case if invalid path provided as args', async () => {
188
- const apisConfig = {
189
- apis: {},
190
- };
191
- (existsSync as jest.Mock<any, any>).mockImplementationOnce(() => false);
192
- await getFallbackApisOrExit(['someFile.yaml'], apisConfig);
193
-
194
- expect(process.stderr.write).toHaveBeenCalledWith(
195
- '\n someFile.yaml does not exist or is invalid. Please provide a valid path. \n\n'
196
- );
197
- expect(process.exit).toHaveBeenCalledWith(1);
198
- });
199
-
200
- it('should exit with error in case if invalid 2 path provided as args', async () => {
201
- const apisConfig = {
202
- apis: {},
203
- };
204
- (existsSync as jest.Mock<any, any>).mockImplementationOnce(() => false);
205
- await getFallbackApisOrExit(['someFile.yaml', 'someFile2.yaml'], apisConfig);
206
-
207
- expect(process.stderr.write).lastCalledWith(
208
- '\n someFile2.yaml does not exist or is invalid. Please provide a valid path. \n\n'
209
- );
210
- expect(process.exit).toHaveBeenCalledWith(1);
211
- });
212
-
213
- it('should exit with error if only one file exist ', async () => {
214
- const apisStub = {
215
- ...apis,
216
- notExist: {
217
- root: 'notExist.yaml',
218
- styleguide: {},
219
- },
220
- };
221
- const configStub = { apis: apisStub };
222
-
223
- (existsSync as jest.Mock<any, any>).mockImplementationOnce((path) => path === 'someFile.yaml');
224
-
225
- await getFallbackApisOrExit(undefined, configStub);
226
-
227
- expect(process.stderr.write).toBeCalledWith(
228
- '\n notExist.yaml does not exist or is invalid. Please provide a valid path. \n\n'
229
- );
230
- expect(process.exit).toHaveBeenCalledWith(1);
231
- });
232
-
233
- it('should work ok if it is url passed', async () => {
234
- (existsSync as jest.Mock<any, any>).mockImplementationOnce(() => false);
235
- (isAbsoluteUrl as jest.Mock<any, any>).mockImplementation(() => true);
236
- const apisConfig = {
237
- apis: {
238
- main: {
239
- root: 'https://someLinkt/petstore.yaml?main',
240
- styleguide: {},
241
- },
242
- },
243
- };
244
-
245
- const result = await getFallbackApisOrExit(undefined, apisConfig);
246
-
247
- expect(process.stderr.write).toHaveBeenCalledTimes(0);
248
- expect(process.exit).toHaveBeenCalledTimes(0);
249
- expect(result).toStrictEqual([
250
- {
251
- alias: 'main',
252
- path: 'https://someLinkt/petstore.yaml?main',
253
- },
254
- ]);
255
- });
256
- });
257
-
258
- describe('langToExt', () => {
259
- it.each([
260
- ['php', '.php'],
261
- ['c#', '.cs'],
262
- ['shell', '.sh'],
263
- ['curl', '.sh'],
264
- ['bash', '.sh'],
265
- ['javascript', '.js'],
266
- ['js', '.js'],
267
- ['python', '.py'],
268
- ])('should infer file extension from lang - %s', (lang, expected) => {
269
- expect(langToExt(lang)).toBe(expected);
270
- });
271
-
272
- it('should ignore case when inferring file extension', () => {
273
- expect(langToExt('JavaScript')).toBe('.js');
274
- });
275
- });
276
-
277
- describe('sorTopLevelKeysForOas', () => {
278
- it('should sort oas3 top level keys', () => {
279
- const openApi = {
280
- openapi: '3.0.0',
281
- components: {},
282
- security: [],
283
- tags: [],
284
- servers: [],
285
- paths: {},
286
- info: {},
287
- externalDocs: {},
288
- webhooks: [],
289
- 'x-webhooks': [],
290
- jsonSchemaDialect: '',
291
- } as any;
292
- const orderedKeys = [
293
- 'openapi',
294
- 'info',
295
- 'jsonSchemaDialect',
296
- 'servers',
297
- 'security',
298
- 'tags',
299
- 'externalDocs',
300
- 'paths',
301
- 'webhooks',
302
- 'x-webhooks',
303
- 'components',
304
- ];
305
- const result = sortTopLevelKeysForOas(openApi);
306
-
307
- Object.keys(result).forEach((key, index) => {
308
- expect(key).toEqual(orderedKeys[index]);
309
- });
310
- });
311
-
312
- it('should sort oas2 top level keys', () => {
313
- const openApi = {
314
- swagger: '2.0.0',
315
- security: [],
316
- tags: [],
317
- paths: {},
318
- info: {},
319
- externalDocs: {},
320
- host: '',
321
- basePath: '',
322
- securityDefinitions: [],
323
- schemes: [],
324
- consumes: [],
325
- parameters: [],
326
- produces: [],
327
- definitions: [],
328
- responses: [],
329
- } as any;
330
- const orderedKeys = [
331
- 'swagger',
332
- 'info',
333
- 'host',
334
- 'basePath',
335
- 'schemes',
336
- 'consumes',
337
- 'produces',
338
- 'security',
339
- 'tags',
340
- 'externalDocs',
341
- 'paths',
342
- 'definitions',
343
- 'parameters',
344
- 'responses',
345
- 'securityDefinitions',
346
- ];
347
- const result = sortTopLevelKeysForOas(openApi);
348
-
349
- Object.keys(result).forEach((key, index) => {
350
- expect(key).toEqual(orderedKeys[index]);
351
- });
352
- });
353
- });
354
-
355
- describe('handleErrors', () => {
356
- const ref = 'openapi/test.yaml';
357
-
358
- const redColoretteMocks = red as jest.Mock<any, any>;
359
-
360
- beforeEach(() => {
361
- jest.spyOn(process.stderr, 'write').mockImplementation(() => true);
362
- jest.spyOn(process, 'exit').mockImplementation((code) => code as never);
363
- redColoretteMocks.mockImplementation((text) => text);
364
- });
365
-
366
- afterEach(() => {
367
- jest.clearAllMocks();
368
- });
369
-
370
- it('should handle ResolveError', () => {
371
- const resolveError = new ResolveError(new Error('File not found'));
372
- handleError(resolveError, ref);
373
- expect(redColoretteMocks).toHaveBeenCalledTimes(1);
374
- expect(process.exit).toHaveBeenCalledWith(1);
375
- expect(process.stderr.write).toHaveBeenCalledWith(
376
- `Failed to resolve api definition at openapi/test.yaml:\n\n - File not found.\n\n`
377
- );
378
- });
379
-
380
- it('should handle YamlParseError', () => {
381
- const yamlParseError = new YamlParseError(new Error('Invalid yaml'), {} as any);
382
- handleError(yamlParseError, ref);
383
- expect(redColoretteMocks).toHaveBeenCalledTimes(1);
384
- expect(process.exit).toHaveBeenCalledWith(1);
385
- expect(process.stderr.write).toHaveBeenCalledWith(
386
- `Failed to parse api definition at openapi/test.yaml:\n\n - Invalid yaml.\n\n`
387
- );
388
- });
389
-
390
- it('should handle CircularJSONNotSupportedError', () => {
391
- const circularError = new CircularJSONNotSupportedError(new Error('Circular json'));
392
- handleError(circularError, ref);
393
- expect(process.exit).toHaveBeenCalledWith(1);
394
- expect(process.stderr.write).toHaveBeenCalledWith(
395
- `Detected circular reference which can't be converted to JSON.\n` +
396
- `Try to use ${blue('yaml')} output or remove ${blue('--dereferenced')}.\n\n`
397
- );
398
- });
399
-
400
- it('should throw unknown error', () => {
401
- const testError = new Error('Test error');
402
- try {
403
- handleError(testError, ref);
404
- } catch (e) {
405
- expect(e).toEqual(testError);
406
- }
407
- expect(process.stderr.write).toHaveBeenCalledWith(
408
- `Something went wrong when processing openapi/test.yaml:\n\n - Test error.\n\n`
409
- );
410
- });
411
- });
412
-
413
- describe('checkIfRulesetExist', () => {
414
- beforeEach(() => {
415
- jest.spyOn(process, 'exit').mockImplementation((code?: number) => code as never);
416
- });
417
-
418
- afterEach(() => {
419
- jest.clearAllMocks();
420
- });
421
-
422
- it('should exit if rules not provided', () => {
423
- const rules = {
424
- oas2: {},
425
- oas3_0: {},
426
- oas3_1: {},
427
- };
428
- checkIfRulesetExist(rules);
429
- expect(process.exit).toHaveBeenCalledWith(1);
430
- });
431
-
432
- it('should not exit if rules provided', () => {
433
- const rules = {
434
- oas2: { 'operation-4xx-response': 'error' },
435
- oas3_0: {},
436
- oas3_1: {},
437
- } as any;
438
- checkIfRulesetExist(rules);
439
- expect(process.exit).not.toHaveBeenCalled();
440
- });
441
- });
@@ -1,8 +0,0 @@
1
- import * as path from 'path';
2
- import { exitWithError } from './utils';
3
-
4
- try {
5
- require('assert-node-version')(path.join(__dirname, '../'));
6
- } catch (err) {
7
- exitWithError(err.message);
8
- }
@@ -1,56 +0,0 @@
1
- import { loadAndBundleSpec } from 'redoc';
2
- import { dirname, resolve } from 'path';
3
- import { writeFileSync, mkdirSync } from 'fs';
4
- import { performance } from 'perf_hooks';
5
-
6
- import { getObjectOrJSON, getPageHTML } from './utils';
7
- import type { BuildDocsArgv } from './types';
8
- import { getMergedConfig, isAbsoluteUrl } from '@redocly/openapi-core';
9
- import {
10
- exitWithError,
11
- getExecutionTime,
12
- getFallbackApisOrExit,
13
- loadConfigAndHandleErrors,
14
- } from '../../utils';
15
-
16
- export const handlerBuildCommand = async (argv: BuildDocsArgv) => {
17
- const startedAt = performance.now();
18
-
19
- const configFromFile = await loadConfigAndHandleErrors({ configPath: argv.config });
20
- const config = getMergedConfig(configFromFile, argv.api);
21
-
22
- const apis = await getFallbackApisOrExit(argv.api ? [argv.api] : [], config);
23
- const { path: pathToApi } = apis[0];
24
-
25
- const options = {
26
- output: argv.o,
27
- cdn: argv.cdn,
28
- title: argv.title,
29
- disableGoogleFont: argv.disableGoogleFont,
30
- templateFileName: argv.template,
31
- templateOptions: argv.templateOptions || {},
32
- redocOptions: getObjectOrJSON(argv.theme?.openapi, config),
33
- };
34
-
35
- const redocCurrentVersion = require('../../../package.json').dependencies.redoc.substring(1); // remove ~
36
-
37
- try {
38
- const elapsed = getExecutionTime(startedAt);
39
-
40
- const api = await loadAndBundleSpec(
41
- isAbsoluteUrl(pathToApi)
42
- ? pathToApi
43
- : resolve(argv.config ? dirname(argv.config) : '', pathToApi)
44
- );
45
- const pageHTML = await getPageHTML(api, pathToApi, { ...options, redocCurrentVersion });
46
-
47
- mkdirSync(dirname(options.output), { recursive: true });
48
- writeFileSync(options.output, pageHTML);
49
- const sizeInKiB = Math.ceil(Buffer.byteLength(pageHTML) / 1024);
50
- process.stdout.write(
51
- `\n🎉 bundled successfully in: ${options.output} (${sizeInKiB} KiB) [⏱ ${elapsed}].\n`
52
- );
53
- } catch (e) {
54
- exitWithError(e);
55
- }
56
- };
@@ -1,23 +0,0 @@
1
- <!DOCTYPE html>
2
- <html>
3
-
4
- <head>
5
- <meta charset="utf8" />
6
- <title>{{title}}</title>
7
- <!-- needed for adaptive design -->
8
- <meta name="viewport" content="width=device-width, initial-scale=1">
9
- <style>
10
- body {
11
- padding: 0;
12
- margin: 0;
13
- }
14
- </style>
15
- {{{redocHead}}}
16
- {{#unless disableGoogleFont}}<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">{{/unless}}
17
- </head>
18
-
19
- <body>
20
- {{{redocHTML}}}
21
- </body>
22
-
23
- </html>
@@ -1,26 +0,0 @@
1
- export type BuildDocsOptions = {
2
- watch?: boolean;
3
- cdn?: boolean;
4
- output?: string;
5
- title?: string;
6
- disableGoogleFont?: boolean;
7
- port?: number;
8
- templateFileName?: string;
9
- templateOptions?: any;
10
- redocOptions?: any;
11
- redocCurrentVersion: string;
12
- };
13
-
14
- export type BuildDocsArgv = {
15
- api: string;
16
- o: string;
17
- cdn: boolean;
18
- title?: string;
19
- disableGoogleFont?: boolean;
20
- template?: string;
21
- templateOptions: Record<string, any>;
22
- theme: {
23
- openapi: string | Record<string, unknown>;
24
- };
25
- config?: string;
26
- };
@@ -1,112 +0,0 @@
1
- import { createElement } from 'react';
2
- import { createStore, Redoc } from 'redoc';
3
- import { Config, isAbsoluteUrl } from '@redocly/openapi-core';
4
-
5
- import { renderToString } from 'react-dom/server';
6
- import { ServerStyleSheet } from 'styled-components';
7
- import { compile } from 'handlebars';
8
- import { join } from 'path';
9
- import { existsSync, lstatSync, readFileSync } from 'fs';
10
-
11
- import type { BuildDocsOptions } from './types';
12
- import { red } from 'colorette';
13
- import { exitWithError } from '../../utils';
14
-
15
- export function getObjectOrJSON(
16
- openapiOptions: string | Record<string, unknown>,
17
- config: Config
18
- ): JSON | Record<string, unknown> | Config {
19
- switch (typeof openapiOptions) {
20
- case 'object':
21
- return openapiOptions;
22
- case 'string':
23
- try {
24
- if (existsSync(openapiOptions) && lstatSync(openapiOptions).isFile()) {
25
- return JSON.parse(readFileSync(openapiOptions, 'utf-8'));
26
- } else {
27
- return JSON.parse(openapiOptions);
28
- }
29
- } catch (e) {
30
- process.stderr.write(
31
- red(
32
- `Encountered error:\n\n${openapiOptions}\n\nis neither a file with a valid JSON object neither a stringified JSON object.`
33
- )
34
- );
35
- exitWithError(e);
36
- }
37
- break;
38
- default: {
39
- if (config) {
40
- process.stderr.write(`Found ${config.configFile} and using theme.openapi options\n`);
41
-
42
- return config.theme.openapi ? config.theme.openapi : {};
43
- }
44
- return {};
45
- }
46
- }
47
- return {};
48
- }
49
-
50
- export async function getPageHTML(
51
- api: any,
52
- pathToApi: string,
53
- {
54
- cdn,
55
- title,
56
- disableGoogleFont,
57
- templateFileName,
58
- templateOptions,
59
- redocOptions = {},
60
- redocCurrentVersion,
61
- }: BuildDocsOptions
62
- ) {
63
- process.stderr.write('Prerendering docs');
64
-
65
- const apiUrl = redocOptions.specUrl || (isAbsoluteUrl(pathToApi) ? pathToApi : undefined);
66
- const store = await createStore(api, apiUrl, redocOptions);
67
- const sheet = new ServerStyleSheet();
68
-
69
- const html = renderToString(sheet.collectStyles(createElement(Redoc, { store })));
70
- const state = await store.toJS();
71
- const css = sheet.getStyleTags();
72
-
73
- templateFileName = templateFileName
74
- ? templateFileName
75
- : redocOptions?.htmlTemplate
76
- ? (redocOptions.htmlTemplate as string)
77
- : join(__dirname, './template.hbs');
78
- const template = compile(readFileSync(templateFileName).toString());
79
- return template({
80
- redocHTML: `
81
- <div id="redoc">${html || ''}</div>
82
- <script>
83
- ${`const __redoc_state = ${sanitizeJSONString(JSON.stringify(state))};` || ''}
84
-
85
- var container = document.getElementById('redoc');
86
- Redoc.${'hydrate(__redoc_state, container)'};
87
-
88
- </script>`,
89
- redocHead:
90
- (cdn
91
- ? '<script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>'
92
- : `<script src="https://cdn.redoc.ly/redoc/v${redocCurrentVersion}/bundles/redoc.standalone.js"></script>`) +
93
- css,
94
- title: title || api.info.title || 'ReDoc documentation',
95
- disableGoogleFont,
96
- templateOptions,
97
- });
98
- }
99
-
100
- export function sanitizeJSONString(str: string): string {
101
- return escapeClosingScriptTag(escapeUnicode(str));
102
- }
103
-
104
- // see http://www.thespanner.co.uk/2011/07/25/the-json-specification-is-now-wrong/
105
- export function escapeClosingScriptTag(str: string): string {
106
- return str.replace(/<\/script>/g, '<\\/script>');
107
- }
108
-
109
- // see http://www.thespanner.co.uk/2011/07/25/the-json-specification-is-now-wrong/
110
- export function escapeUnicode(str: string): string {
111
- return str.replace(/\u2028|\u2029/g, (m) => '\\u202' + (m === '\u2028' ? '8' : '9'));
112
- }