docusaurus-plugin-openapi-docs 0.0.0-1000

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 (163) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +361 -0
  3. package/lib/index.d.ts +9 -0
  4. package/lib/index.js +709 -0
  5. package/lib/markdown/createArrayBracket.d.ts +2 -0
  6. package/lib/markdown/createArrayBracket.js +36 -0
  7. package/lib/markdown/createAuthentication.d.ts +2 -0
  8. package/lib/markdown/createAuthentication.js +171 -0
  9. package/lib/markdown/createAuthorization.d.ts +1 -0
  10. package/lib/markdown/createAuthorization.js +15 -0
  11. package/lib/markdown/createCallbackMethodEndpoint.d.ts +1 -0
  12. package/lib/markdown/createCallbackMethodEndpoint.js +20 -0
  13. package/lib/markdown/createCallbacks.d.ts +6 -0
  14. package/lib/markdown/createCallbacks.js +77 -0
  15. package/lib/markdown/createContactInfo.d.ts +2 -0
  16. package/lib/markdown/createContactInfo.js +39 -0
  17. package/lib/markdown/createDeprecationNotice.d.ts +6 -0
  18. package/lib/markdown/createDeprecationNotice.js +20 -0
  19. package/lib/markdown/createDescription.d.ts +1 -0
  20. package/lib/markdown/createDescription.js +13 -0
  21. package/lib/markdown/createDetails.d.ts +2 -0
  22. package/lib/markdown/createDetails.js +17 -0
  23. package/lib/markdown/createDetailsSummary.d.ts +2 -0
  24. package/lib/markdown/createDetailsSummary.js +17 -0
  25. package/lib/markdown/createDownload.d.ts +1 -0
  26. package/lib/markdown/createDownload.js +16 -0
  27. package/lib/markdown/createHeading.d.ts +1 -0
  28. package/lib/markdown/createHeading.js +20 -0
  29. package/lib/markdown/createLicense.d.ts +2 -0
  30. package/lib/markdown/createLicense.js +32 -0
  31. package/lib/markdown/createLogo.d.ts +2 -0
  32. package/lib/markdown/createLogo.js +18 -0
  33. package/lib/markdown/createMethodEndpoint.d.ts +1 -0
  34. package/lib/markdown/createMethodEndpoint.js +20 -0
  35. package/lib/markdown/createParamsDetails.d.ts +6 -0
  36. package/lib/markdown/createParamsDetails.js +18 -0
  37. package/lib/markdown/createRequestBodyDetails.d.ts +13 -0
  38. package/lib/markdown/createRequestBodyDetails.js +13 -0
  39. package/lib/markdown/createRequestHeader.d.ts +1 -0
  40. package/lib/markdown/createRequestHeader.js +21 -0
  41. package/lib/markdown/createRequestSchema.d.ts +14 -0
  42. package/lib/markdown/createRequestSchema.js +20 -0
  43. package/lib/markdown/createResponseSchema.d.ts +14 -0
  44. package/lib/markdown/createResponseSchema.js +20 -0
  45. package/lib/markdown/createSchema.d.ts +9 -0
  46. package/lib/markdown/createSchema.js +668 -0
  47. package/lib/markdown/createSchema.test.d.ts +1 -0
  48. package/lib/markdown/createSchema.test.js +913 -0
  49. package/lib/markdown/createStatusCodes.d.ts +9 -0
  50. package/lib/markdown/createStatusCodes.js +63 -0
  51. package/lib/markdown/createTermsOfService.d.ts +1 -0
  52. package/lib/markdown/createTermsOfService.js +31 -0
  53. package/lib/markdown/createVendorExtensions.d.ts +1 -0
  54. package/lib/markdown/createVendorExtensions.js +24 -0
  55. package/lib/markdown/createVersionBadge.d.ts +1 -0
  56. package/lib/markdown/createVersionBadge.js +19 -0
  57. package/lib/markdown/index.d.ts +5 -0
  58. package/lib/markdown/index.js +92 -0
  59. package/lib/markdown/schema.d.ts +3 -0
  60. package/lib/markdown/schema.js +154 -0
  61. package/lib/markdown/schema.test.d.ts +1 -0
  62. package/lib/markdown/schema.test.js +181 -0
  63. package/lib/markdown/utils.d.ts +20 -0
  64. package/lib/markdown/utils.js +68 -0
  65. package/lib/openapi/createRequestExample.d.ts +2 -0
  66. package/lib/openapi/createRequestExample.js +191 -0
  67. package/lib/openapi/createResponseExample.d.ts +2 -0
  68. package/lib/openapi/createResponseExample.js +192 -0
  69. package/lib/openapi/index.d.ts +1 -0
  70. package/lib/openapi/index.js +12 -0
  71. package/lib/openapi/openapi.d.ts +12 -0
  72. package/lib/openapi/openapi.js +544 -0
  73. package/lib/openapi/openapi.test.d.ts +1 -0
  74. package/lib/openapi/openapi.test.js +33 -0
  75. package/lib/openapi/types.d.ts +354 -0
  76. package/lib/openapi/types.js +8 -0
  77. package/lib/openapi/utils/loadAndResolveSpec.d.ts +2 -0
  78. package/lib/openapi/utils/loadAndResolveSpec.js +153 -0
  79. package/lib/openapi/utils/services/OpenAPIParser.d.ts +52 -0
  80. package/lib/openapi/utils/services/OpenAPIParser.js +343 -0
  81. package/lib/openapi/utils/services/RedocNormalizedOptions.d.ts +100 -0
  82. package/lib/openapi/utils/services/RedocNormalizedOptions.js +170 -0
  83. package/lib/openapi/utils/types/index.d.ts +2 -0
  84. package/lib/openapi/utils/types/index.js +23 -0
  85. package/lib/openapi/utils/types/open-api.d.ts +305 -0
  86. package/lib/openapi/utils/types/open-api.js +8 -0
  87. package/lib/openapi/utils/types.d.ts +306 -0
  88. package/lib/openapi/utils/types.js +8 -0
  89. package/lib/openapi/utils/utils/JsonPointer.d.ts +51 -0
  90. package/lib/openapi/utils/utils/JsonPointer.js +95 -0
  91. package/lib/openapi/utils/utils/helpers.d.ts +43 -0
  92. package/lib/openapi/utils/utils/helpers.js +230 -0
  93. package/lib/openapi/utils/utils/index.d.ts +3 -0
  94. package/lib/openapi/utils/utils/index.js +25 -0
  95. package/lib/openapi/utils/utils/openapi.d.ts +40 -0
  96. package/lib/openapi/utils/utils/openapi.js +605 -0
  97. package/lib/options.d.ts +2 -0
  98. package/lib/options.js +69 -0
  99. package/lib/sidebars/index.d.ts +4 -0
  100. package/lib/sidebars/index.js +226 -0
  101. package/lib/sidebars/utils.d.ts +2 -0
  102. package/lib/sidebars/utils.js +30 -0
  103. package/lib/types.d.ts +135 -0
  104. package/lib/types.js +8 -0
  105. package/package.json +69 -0
  106. package/src/index.ts +945 -0
  107. package/src/markdown/__snapshots__/createSchema.test.ts.snap +1605 -0
  108. package/src/markdown/createArrayBracket.ts +35 -0
  109. package/src/markdown/createAuthentication.ts +201 -0
  110. package/src/markdown/createAuthorization.ts +13 -0
  111. package/src/markdown/createCallbackMethodEndpoint.ts +19 -0
  112. package/src/markdown/createCallbacks.ts +101 -0
  113. package/src/markdown/createContactInfo.ts +41 -0
  114. package/src/markdown/createDeprecationNotice.ts +31 -0
  115. package/src/markdown/createDescription.ts +12 -0
  116. package/src/markdown/createDetails.ts +16 -0
  117. package/src/markdown/createDetailsSummary.ts +16 -0
  118. package/src/markdown/createDownload.ts +15 -0
  119. package/src/markdown/createHeading.ts +23 -0
  120. package/src/markdown/createLicense.ts +34 -0
  121. package/src/markdown/createLogo.ts +21 -0
  122. package/src/markdown/createMethodEndpoint.ts +19 -0
  123. package/src/markdown/createParamsDetails.ts +22 -0
  124. package/src/markdown/createRequestBodyDetails.ts +24 -0
  125. package/src/markdown/createRequestHeader.ts +24 -0
  126. package/src/markdown/createRequestSchema.ts +32 -0
  127. package/src/markdown/createResponseSchema.ts +32 -0
  128. package/src/markdown/createSchema.test.ts +1075 -0
  129. package/src/markdown/createSchema.ts +862 -0
  130. package/src/markdown/createStatusCodes.ts +63 -0
  131. package/src/markdown/createTermsOfService.ts +30 -0
  132. package/src/markdown/createVendorExtensions.ts +22 -0
  133. package/src/markdown/createVersionBadge.ts +22 -0
  134. package/src/markdown/index.ts +144 -0
  135. package/src/markdown/schema.test.ts +208 -0
  136. package/src/markdown/schema.ts +185 -0
  137. package/src/markdown/utils.ts +89 -0
  138. package/src/openapi/__fixtures__/examples/openapi.yaml +49 -0
  139. package/src/openapi/createRequestExample.ts +235 -0
  140. package/src/openapi/createResponseExample.ts +238 -0
  141. package/src/openapi/index.ts +8 -0
  142. package/src/openapi/openapi.test.ts +40 -0
  143. package/src/openapi/openapi.ts +697 -0
  144. package/src/openapi/types.ts +455 -0
  145. package/src/openapi/utils/loadAndResolveSpec.ts +171 -0
  146. package/src/openapi/utils/services/OpenAPIParser.ts +434 -0
  147. package/src/openapi/utils/services/RedocNormalizedOptions.ts +330 -0
  148. package/src/openapi/utils/types/index.ts +10 -0
  149. package/src/openapi/utils/types/open-api.ts +303 -0
  150. package/src/openapi/utils/types.ts +303 -0
  151. package/src/openapi/utils/utils/JsonPointer.ts +99 -0
  152. package/src/openapi/utils/utils/helpers.ts +239 -0
  153. package/src/openapi/utils/utils/index.ts +11 -0
  154. package/src/openapi/utils/utils/openapi.ts +771 -0
  155. package/src/openapi-to-postmanv2.d.ts +10 -0
  156. package/src/options.ts +77 -0
  157. package/src/plugin-content-docs-types.d.ts +42 -0
  158. package/src/plugin-openapi.d.ts +87 -0
  159. package/src/postman-collection.d.ts +10 -0
  160. package/src/sidebars/index.ts +322 -0
  161. package/src/sidebars/utils.ts +29 -0
  162. package/src/types.ts +176 -0
  163. package/tsconfig.json +7 -0
package/src/index.ts ADDED
@@ -0,0 +1,945 @@
1
+ /* ============================================================================
2
+ * Copyright (c) Palo Alto Networks
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ * ========================================================================== */
7
+
8
+ import fs from "fs";
9
+ import path from "path";
10
+ import zlib from "zlib";
11
+
12
+ import type { LoadContext, Plugin } from "@docusaurus/types";
13
+ import { Globby, posixPath } from "@docusaurus/utils";
14
+ import chalk from "chalk";
15
+ import JSON5 from "json5";
16
+ import { render } from "mustache";
17
+
18
+ import {
19
+ createApiPageMD,
20
+ createInfoPageMD,
21
+ createSchemaPageMD,
22
+ createTagPageMD,
23
+ } from "./markdown";
24
+ import { processOpenapiFiles, readOpenapiFiles } from "./openapi";
25
+ import { OptionsSchema } from "./options";
26
+ import generateSidebarSlice from "./sidebars";
27
+ import type {
28
+ ApiMetadata,
29
+ APIOptions,
30
+ ApiPageMetadata,
31
+ InfoPageMetadata,
32
+ LoadedContent,
33
+ PluginOptions,
34
+ SchemaPageMetadata,
35
+ TagPageMetadata,
36
+ } from "./types";
37
+
38
+ export function isURL(str: string): boolean {
39
+ return /^(https?:)\/\//m.test(str);
40
+ }
41
+
42
+ export function getDocsPluginConfig(
43
+ presetsPlugins: any[],
44
+ plugin: string,
45
+ pluginId: string
46
+ ): Object | undefined {
47
+ // eslint-disable-next-line array-callback-return
48
+ const filteredConfig = presetsPlugins.filter((data) => {
49
+ // Search presets
50
+ if (Array.isArray(data)) {
51
+ if (typeof data[0] === "string" && data[0].endsWith(pluginId)) {
52
+ return data[1];
53
+ }
54
+
55
+ // Search plugin-content-docs instances
56
+ if (typeof data[0] === "string" && data[0] === plugin) {
57
+ const configPluginId = data[1].id ? data[1].id : "default";
58
+ if (configPluginId === pluginId) {
59
+ return data[1];
60
+ }
61
+ }
62
+ }
63
+ })[0];
64
+
65
+ if (filteredConfig) {
66
+ // Search presets, e.g. "classic"
67
+ if (filteredConfig[0].endsWith(pluginId)) {
68
+ return filteredConfig[1].docs;
69
+ }
70
+
71
+ // Search plugin-content-docs instances
72
+ if (filteredConfig[0] === plugin) {
73
+ const configPluginId = filteredConfig[1].id
74
+ ? filteredConfig[1].id
75
+ : "default";
76
+ if (configPluginId === pluginId) {
77
+ return filteredConfig[1];
78
+ }
79
+ }
80
+ }
81
+ return;
82
+ }
83
+
84
+ function getPluginConfig(plugins: any[], pluginId: string): any {
85
+ return plugins.filter((data) => data[1].id === pluginId)[0][1];
86
+ }
87
+
88
+ function getPluginInstances(plugins: any[]): any {
89
+ return plugins.filter((data) => data[0] === "docusaurus-plugin-openapi-docs");
90
+ }
91
+
92
+ export default function pluginOpenAPIDocs(
93
+ context: LoadContext,
94
+ options: PluginOptions
95
+ ): Plugin<LoadedContent> {
96
+ const {
97
+ config,
98
+ docsPlugin = "@docusaurus/plugin-content-docs",
99
+ docsPluginId,
100
+ } = options;
101
+ const { siteDir, siteConfig } = context;
102
+
103
+ // Get routeBasePath and path from plugin-content-docs or preset
104
+ const presets: any = siteConfig.presets;
105
+ const plugins: any = siteConfig.plugins;
106
+ const presetsPlugins = presets.concat(plugins);
107
+ let docData: any = getDocsPluginConfig(
108
+ presetsPlugins,
109
+ docsPlugin,
110
+ docsPluginId
111
+ );
112
+ let docRouteBasePath = docData ? docData.routeBasePath : undefined;
113
+ let docPath = docData ? (docData.path ? docData.path : "docs") : undefined;
114
+
115
+ async function generateApiDocs(options: APIOptions, pluginId: any) {
116
+ let {
117
+ specPath,
118
+ outputDir,
119
+ template,
120
+ infoTemplate,
121
+ tagTemplate,
122
+ schemaTemplate,
123
+ markdownGenerators,
124
+ downloadUrl,
125
+ sidebarOptions,
126
+ disableCompression,
127
+ } = options;
128
+
129
+ // Remove trailing slash before proceeding
130
+ outputDir = outputDir.replace(/\/$/, "");
131
+
132
+ // Override docPath if pluginId provided
133
+ if (pluginId) {
134
+ docData = getDocsPluginConfig(presetsPlugins, docsPlugin, pluginId);
135
+ docRouteBasePath = docData ? docData.routeBasePath : undefined;
136
+ docPath = docData ? (docData.path ? docData.path : "docs") : undefined;
137
+ }
138
+
139
+ const contentPath = isURL(specPath)
140
+ ? specPath
141
+ : path.resolve(siteDir, specPath);
142
+
143
+ try {
144
+ const openapiFiles = await readOpenapiFiles(contentPath);
145
+ const [loadedApi, tags, tagGroups] = await processOpenapiFiles(
146
+ openapiFiles,
147
+ options,
148
+ sidebarOptions!
149
+ );
150
+ if (!fs.existsSync(outputDir)) {
151
+ try {
152
+ fs.mkdirSync(outputDir, { recursive: true });
153
+ console.log(chalk.green(`Successfully created "${outputDir}"`));
154
+ } catch (err) {
155
+ console.error(
156
+ chalk.red(`Failed to create "${outputDir}"`),
157
+ chalk.yellow(err)
158
+ );
159
+ }
160
+ }
161
+
162
+ // TODO: figure out better way to set default
163
+ if (Object.keys(sidebarOptions ?? {}).length > 0) {
164
+ const sidebarSlice = generateSidebarSlice(
165
+ sidebarOptions!,
166
+ options,
167
+ loadedApi,
168
+ tags,
169
+ docPath,
170
+ tagGroups
171
+ );
172
+
173
+ let sidebarSliceTemplate = `import type { SidebarsConfig } from "@docusaurus/plugin-content-docs";\n\n`;
174
+ sidebarSliceTemplate += `const sidebar: SidebarsConfig = {{{slice}}};\n\n`;
175
+ sidebarSliceTemplate += `export default sidebar.apisidebar;\n`;
176
+
177
+ const view = render(sidebarSliceTemplate, {
178
+ slice: JSON5.stringify(
179
+ { apisidebar: sidebarSlice },
180
+ { space: 2, quote: '"' }
181
+ ),
182
+ });
183
+
184
+ if (!fs.existsSync(`${outputDir}/sidebar.ts`)) {
185
+ try {
186
+ fs.writeFileSync(`${outputDir}/sidebar.ts`, view, "utf8");
187
+ console.log(
188
+ chalk.green(`Successfully created "${outputDir}/sidebar.ts"`)
189
+ );
190
+ } catch (err) {
191
+ console.error(
192
+ chalk.red(`Failed to write "${outputDir}/sidebar.ts"`),
193
+ chalk.yellow(err)
194
+ );
195
+ }
196
+ }
197
+ }
198
+
199
+ const mdTemplate = template
200
+ ? fs.readFileSync(template).toString()
201
+ : `---
202
+ id: {{{id}}}
203
+ title: "{{{title}}}"
204
+ description: "{{{frontMatter.description}}}"
205
+ {{^api}}
206
+ sidebar_label: Introduction
207
+ {{/api}}
208
+ {{#api}}
209
+ sidebar_label: "{{{title}}}"
210
+ {{/api}}
211
+ {{^api}}
212
+ sidebar_position: 0
213
+ {{/api}}
214
+ hide_title: true
215
+ {{#api}}
216
+ hide_table_of_contents: true
217
+ {{/api}}
218
+ {{#json}}
219
+ api: {{{json}}}
220
+ {{/json}}
221
+ {{#api.method}}
222
+ sidebar_class_name: "{{{api.method}}} api-method"
223
+ {{/api.method}}
224
+ {{#infoPath}}
225
+ info_path: {{{infoPath}}}
226
+ {{/infoPath}}
227
+ custom_edit_url: null
228
+ {{#frontMatter.proxy}}
229
+ proxy: {{{frontMatter.proxy}}}
230
+ {{/frontMatter.proxy}}
231
+ {{#frontMatter.hide_send_button}}
232
+ hide_send_button: true
233
+ {{/frontMatter.hide_send_button}}
234
+ {{#frontMatter.show_extensions}}
235
+ show_extensions: true
236
+ {{/frontMatter.show_extensions}}
237
+ ---
238
+
239
+ {{{markdown}}}
240
+ `;
241
+
242
+ const infoMdTemplate = infoTemplate
243
+ ? fs.readFileSync(infoTemplate).toString()
244
+ : `---
245
+ id: {{{id}}}
246
+ title: "{{{title}}}"
247
+ description: "{{{frontMatter.description}}}"
248
+ sidebar_label: "{{{title}}}"
249
+ hide_title: true
250
+ custom_edit_url: null
251
+ ---
252
+
253
+ {{{markdown}}}
254
+
255
+ \`\`\`mdx-code-block
256
+ import DocCardList from '@theme/DocCardList';
257
+ import {useCurrentSidebarCategory} from '@docusaurus/theme-common';
258
+
259
+ <DocCardList items={useCurrentSidebarCategory().items}/>
260
+ \`\`\`
261
+ `;
262
+
263
+ const tagMdTemplate = tagTemplate
264
+ ? fs.readFileSync(tagTemplate).toString()
265
+ : `---
266
+ id: {{{id}}}
267
+ title: "{{{frontMatter.description}}}"
268
+ description: "{{{frontMatter.description}}}"
269
+ custom_edit_url: null
270
+ ---
271
+
272
+ {{{markdown}}}
273
+
274
+ \`\`\`mdx-code-block
275
+ import DocCardList from '@theme/DocCardList';
276
+ import {useCurrentSidebarCategory} from '@docusaurus/theme-common';
277
+
278
+ <DocCardList items={useCurrentSidebarCategory().items}/>
279
+ \`\`\`
280
+ `;
281
+
282
+ const schemaMdTemplate = schemaTemplate
283
+ ? fs.readFileSync(schemaTemplate).toString()
284
+ : `---
285
+ id: {{{id}}}
286
+ title: "{{{title}}}"
287
+ description: "{{{frontMatter.description}}}"
288
+ sidebar_label: "{{{title}}}"
289
+ hide_title: true
290
+ {{#schema}}
291
+ hide_table_of_contents: true
292
+ {{/schema}}
293
+ schema: true
294
+ sample: {{{frontMatter.sample}}}
295
+ custom_edit_url: null
296
+ ---
297
+
298
+ {{{markdown}}}
299
+ `;
300
+
301
+ const apiPageGenerator =
302
+ markdownGenerators?.createApiPageMD ?? createApiPageMD;
303
+ const infoPageGenerator =
304
+ markdownGenerators?.createInfoPageMD ?? createInfoPageMD;
305
+ const tagPageGenerator =
306
+ markdownGenerators?.createTagPageMD ?? createTagPageMD;
307
+ const schemaPageGenerator =
308
+ markdownGenerators?.createSchemaPageMD ?? createSchemaPageMD;
309
+
310
+ const pageGeneratorByType: {
311
+ [key in ApiMetadata["type"]]: (
312
+ pageData: {
313
+ api: ApiPageMetadata;
314
+ info: InfoPageMetadata;
315
+ tag: TagPageMetadata;
316
+ schema: SchemaPageMetadata;
317
+ }[key]
318
+ ) => string;
319
+ } = {
320
+ api: apiPageGenerator,
321
+ info: infoPageGenerator,
322
+ tag: tagPageGenerator,
323
+ schema: schemaPageGenerator,
324
+ };
325
+
326
+ loadedApi.map(async (item) => {
327
+ if (downloadUrl) {
328
+ item.downloadUrl = downloadUrl;
329
+ }
330
+ const markdown = pageGeneratorByType[item.type](item as any);
331
+ item.markdown = markdown;
332
+ if (item.type === "api") {
333
+ // opportunity to compress JSON
334
+ // const serialize = (o: any) => {
335
+ // return zlib.deflateSync(JSON.stringify(o)).toString("base64");
336
+ // };
337
+ // const deserialize = (s: any) => {
338
+ // return zlib.inflateSync(Buffer.from(s, "base64")).toString();
339
+ // };
340
+ disableCompression === true
341
+ ? (item.json = JSON.stringify(item.api))
342
+ : (item.json = zlib
343
+ .deflateSync(JSON.stringify(item.api))
344
+ .toString("base64"));
345
+ let infoBasePath = `${outputDir}/${item.infoId}`;
346
+ if (docRouteBasePath) {
347
+ infoBasePath = `${docRouteBasePath}/${outputDir
348
+ .split(docPath!)[1]
349
+ .replace(/^\/+/g, "")}/${item.infoId}`.replace(/^\/+/g, "");
350
+ }
351
+ if (item.infoId) item.infoPath = infoBasePath;
352
+ }
353
+
354
+ const view = render(mdTemplate, item);
355
+ const utils = render(infoMdTemplate, item);
356
+ // eslint-disable-next-line testing-library/render-result-naming-convention
357
+ const tagUtils = render(tagMdTemplate, item);
358
+
359
+ if (item.type === "api") {
360
+ if (!fs.existsSync(`${outputDir}/${item.id}.api.mdx`)) {
361
+ try {
362
+ // kebabCase(arg) returns 0-length string when arg is undefined
363
+ if (item.id.length === 0) {
364
+ throw Error(
365
+ "Operation must have summary or operationId defined"
366
+ );
367
+ }
368
+ fs.writeFileSync(`${outputDir}/${item.id}.api.mdx`, view, "utf8");
369
+ console.log(
370
+ chalk.green(
371
+ `Successfully created "${outputDir}/${item.id}.api.mdx"`
372
+ )
373
+ );
374
+ } catch (err) {
375
+ console.error(
376
+ chalk.red(`Failed to write "${outputDir}/${item.id}.api.mdx"`),
377
+ chalk.yellow(err)
378
+ );
379
+ }
380
+ }
381
+ }
382
+
383
+ if (item.type === "info") {
384
+ if (!fs.existsSync(`${outputDir}/${item.id}.info.mdx`)) {
385
+ try {
386
+ fs.writeFileSync(
387
+ `${outputDir}/${item.id}.info.mdx`,
388
+ utils,
389
+ "utf8"
390
+ );
391
+ console.log(
392
+ chalk.green(
393
+ `Successfully created "${outputDir}/${item.id}.info.mdx"`
394
+ )
395
+ );
396
+ } catch (err) {
397
+ console.error(
398
+ chalk.red(`Failed to write "${outputDir}/${item.id}.info.mdx"`),
399
+ chalk.yellow(err)
400
+ );
401
+ }
402
+ }
403
+ }
404
+
405
+ if (item.type === "tag") {
406
+ if (!fs.existsSync(`${outputDir}/${item.id}.tag.mdx`)) {
407
+ try {
408
+ fs.writeFileSync(
409
+ `${outputDir}/${item.id}.tag.mdx`,
410
+ tagUtils,
411
+ "utf8"
412
+ );
413
+ console.log(
414
+ chalk.green(
415
+ `Successfully created "${outputDir}/${item.id}.tag.mdx"`
416
+ )
417
+ );
418
+ } catch (err) {
419
+ console.error(
420
+ chalk.red(`Failed to write "${outputDir}/${item.id}.tag.mdx"`),
421
+ chalk.yellow(err)
422
+ );
423
+ }
424
+ }
425
+ }
426
+
427
+ if (item.type === "schema") {
428
+ if (!fs.existsSync(`${outputDir}/schemas/${item.id}.schema.mdx`)) {
429
+ if (!fs.existsSync(`${outputDir}/schemas`)) {
430
+ try {
431
+ fs.mkdirSync(`${outputDir}/schemas`, { recursive: true });
432
+ console.log(
433
+ chalk.green(`Successfully created "${outputDir}/schemas"`)
434
+ );
435
+ } catch (err) {
436
+ console.error(
437
+ chalk.red(`Failed to create "${outputDir}/schemas"`),
438
+ chalk.yellow(err)
439
+ );
440
+ }
441
+ }
442
+ try {
443
+ // kebabCase(arg) returns 0-length string when arg is undefined
444
+ if (item.id.length === 0) {
445
+ throw Error("Schema must have title defined");
446
+ }
447
+ // eslint-disable-next-line testing-library/render-result-naming-convention
448
+ const schemaView = render(schemaMdTemplate, item);
449
+ fs.writeFileSync(
450
+ `${outputDir}/schemas/${item.id}.schema.mdx`,
451
+ schemaView,
452
+ "utf8"
453
+ );
454
+ console.log(
455
+ chalk.green(
456
+ `Successfully created "${outputDir}/${item.id}.schema.mdx"`
457
+ )
458
+ );
459
+ } catch (err) {
460
+ console.error(
461
+ chalk.red(
462
+ `Failed to write "${outputDir}/${item.id}.schema.mdx"`
463
+ ),
464
+ chalk.yellow(err)
465
+ );
466
+ }
467
+ }
468
+ }
469
+ return;
470
+ });
471
+
472
+ return;
473
+ } catch (e) {
474
+ console.error(chalk.red(`Loading of api failed for "${contentPath}"`));
475
+ throw e;
476
+ }
477
+ }
478
+
479
+ async function cleanApiDocs(options: APIOptions) {
480
+ const { outputDir } = options;
481
+ const apiDir = posixPath(path.join(siteDir, outputDir));
482
+ const apiMdxFiles = await Globby(["*.api.mdx", "*.info.mdx", "*.tag.mdx"], {
483
+ cwd: path.resolve(apiDir),
484
+ deep: 1,
485
+ });
486
+ const sidebarFile = await Globby(["sidebar.js", "sidebar.ts"], {
487
+ cwd: path.resolve(apiDir),
488
+ deep: 1,
489
+ });
490
+ apiMdxFiles.map((mdx) =>
491
+ fs.unlink(`${apiDir}/${mdx}`, (err) => {
492
+ if (err) {
493
+ console.error(
494
+ chalk.red(`Cleanup failed for "${apiDir}/${mdx}"`),
495
+ chalk.yellow(err)
496
+ );
497
+ } else {
498
+ console.log(chalk.green(`Cleanup succeeded for "${apiDir}/${mdx}"`));
499
+ }
500
+ })
501
+ );
502
+
503
+ try {
504
+ fs.rmSync(`${apiDir}/schemas`, { recursive: true });
505
+ console.log(chalk.green(`Cleanup succeeded for "${apiDir}/schemas"`));
506
+ } catch (err: any) {
507
+ if (err.code !== "ENOENT") {
508
+ console.error(
509
+ chalk.red(`Cleanup failed for "${apiDir}/schemas"`),
510
+ chalk.yellow(err)
511
+ );
512
+ }
513
+ }
514
+
515
+ sidebarFile.map((sidebar) =>
516
+ fs.unlink(`${apiDir}/${sidebar}`, (err) => {
517
+ if (err) {
518
+ console.error(
519
+ chalk.red(`Cleanup failed for "${apiDir}/${sidebar}"`),
520
+ chalk.yellow(err)
521
+ );
522
+ } else {
523
+ console.log(
524
+ chalk.green(`Cleanup succeeded for "${apiDir}/${sidebar}"`)
525
+ );
526
+ }
527
+ })
528
+ );
529
+ }
530
+
531
+ async function generateVersions(versions: object, outputDir: string) {
532
+ let versionsArray = [] as object[];
533
+ for (const [version, metadata] of Object.entries(versions)) {
534
+ versionsArray.push({
535
+ version: version,
536
+ label: metadata.label,
537
+ baseUrl: metadata.baseUrl,
538
+ downloadUrl: metadata.downloadUrl,
539
+ });
540
+ }
541
+
542
+ if (!fs.existsSync(outputDir)) {
543
+ try {
544
+ fs.mkdirSync(outputDir, { recursive: true });
545
+ console.log(chalk.green(`Successfully created "${outputDir}"`));
546
+ } catch (err) {
547
+ console.error(
548
+ chalk.red(`Failed to create "${outputDir}"`),
549
+ chalk.yellow(err)
550
+ );
551
+ }
552
+ }
553
+
554
+ const versionsJson = JSON.stringify(versionsArray, null, 2);
555
+ try {
556
+ fs.writeFileSync(
557
+ `${outputDir}/versions.json`,
558
+ versionsJson + "\n",
559
+ "utf8"
560
+ );
561
+ console.log(
562
+ chalk.green(`Successfully created "${outputDir}/versions.json"`)
563
+ );
564
+ } catch (err) {
565
+ console.error(
566
+ chalk.red(`Failed to write "${outputDir}/versions.json"`),
567
+ chalk.yellow(err)
568
+ );
569
+ }
570
+ }
571
+
572
+ async function cleanVersions(outputDir: string) {
573
+ if (fs.existsSync(`${outputDir}/versions.json`)) {
574
+ fs.unlink(`${outputDir}/versions.json`, (err) => {
575
+ if (err) {
576
+ console.error(
577
+ chalk.red(`Cleanup failed for "${outputDir}/versions.json"`),
578
+ chalk.yellow(err)
579
+ );
580
+ } else {
581
+ console.log(
582
+ chalk.green(`Cleanup succeeded for "${outputDir}/versions.json"`)
583
+ );
584
+ }
585
+ });
586
+ }
587
+ }
588
+
589
+ async function generateAllVersions(options: APIOptions, pluginId: any) {
590
+ const parentOptions = Object.assign({}, options);
591
+ const { versions } = parentOptions as any;
592
+
593
+ if (versions != null && Object.keys(versions).length > 0) {
594
+ const version = parentOptions.version as string;
595
+ const label = parentOptions.label as string;
596
+
597
+ const baseUrl = parentOptions.baseUrl as string;
598
+ let parentVersion = {} as any;
599
+
600
+ parentVersion[version] = { label: label, baseUrl: baseUrl };
601
+ const mergedVersions = Object.assign(parentVersion, versions);
602
+
603
+ // Prepare for merge
604
+ delete parentOptions.versions;
605
+ delete parentOptions.version;
606
+ delete parentOptions.label;
607
+ delete parentOptions.baseUrl;
608
+ delete parentOptions.downloadUrl;
609
+
610
+ await generateVersions(mergedVersions, parentOptions.outputDir);
611
+ Object.keys(versions).forEach(async (key) => {
612
+ if (key === "all") {
613
+ console.error(
614
+ chalk.red(
615
+ "Can't use id 'all' for OpenAPI docs versions configuration key."
616
+ )
617
+ );
618
+ }
619
+ const versionOptions = versions[key];
620
+ const mergedOptions = {
621
+ ...parentOptions,
622
+ ...versionOptions,
623
+ };
624
+ await generateApiDocs(mergedOptions, pluginId);
625
+ });
626
+ }
627
+ }
628
+
629
+ async function cleanAllVersions(options: APIOptions) {
630
+ const parentOptions = Object.assign({}, options);
631
+
632
+ const { versions } = parentOptions as any;
633
+
634
+ delete parentOptions.versions;
635
+
636
+ if (versions != null && Object.keys(versions).length > 0) {
637
+ await cleanVersions(parentOptions.outputDir);
638
+ Object.keys(versions).forEach(async (key) => {
639
+ const versionOptions = versions[key];
640
+ const mergedOptions = {
641
+ ...parentOptions,
642
+ ...versionOptions,
643
+ };
644
+ await cleanApiDocs(mergedOptions);
645
+ });
646
+ }
647
+ }
648
+
649
+ return {
650
+ name: `docusaurus-plugin-openapi-docs`,
651
+
652
+ extendCli(cli): void {
653
+ cli
654
+ .command(`gen-api-docs`)
655
+ .description(
656
+ `Generates OpenAPI docs in MDX file format and sidebar.ts (if enabled).`
657
+ )
658
+ .usage("<id>")
659
+ .arguments("<id>")
660
+ .option("-p, --plugin-id <plugin>", "OpenAPI docs plugin ID.")
661
+ .option("--all-versions", "Generate all versions.")
662
+ .action(async (id, instance) => {
663
+ const options = instance.opts();
664
+ const pluginId = options.pluginId;
665
+ const allVersions = options.allVersions;
666
+ const pluginInstances = getPluginInstances(plugins);
667
+ let targetConfig: any;
668
+ let targetDocsPluginId: any;
669
+ if (pluginId) {
670
+ try {
671
+ const pluginConfig = getPluginConfig(plugins, pluginId);
672
+ targetConfig = pluginConfig.config ?? {};
673
+ targetDocsPluginId = pluginConfig.docsPluginId;
674
+ } catch {
675
+ console.error(
676
+ chalk.red(`OpenAPI docs plugin ID '${pluginId}' not found.`)
677
+ );
678
+ return;
679
+ }
680
+ } else {
681
+ if (pluginInstances.length > 1) {
682
+ console.error(
683
+ chalk.red(
684
+ "OpenAPI docs plugin ID must be specified when more than one plugin instance exists."
685
+ )
686
+ );
687
+ return;
688
+ }
689
+ targetConfig = config;
690
+ }
691
+
692
+ if (id === "all") {
693
+ if (targetConfig[id]) {
694
+ console.error(
695
+ chalk.red(
696
+ "Can't use id 'all' for OpenAPI docs configuration key."
697
+ )
698
+ );
699
+ } else {
700
+ Object.keys(targetConfig).forEach(async function (key) {
701
+ await generateApiDocs(targetConfig[key], targetDocsPluginId);
702
+ if (allVersions) {
703
+ await generateAllVersions(
704
+ targetConfig[key],
705
+ targetDocsPluginId
706
+ );
707
+ }
708
+ });
709
+ }
710
+ } else if (!targetConfig[id]) {
711
+ console.error(
712
+ chalk.red(`ID '${id}' does not exist in OpenAPI docs config.`)
713
+ );
714
+ } else {
715
+ await generateApiDocs(targetConfig[id], targetDocsPluginId);
716
+ if (allVersions) {
717
+ await generateAllVersions(targetConfig[id], targetDocsPluginId);
718
+ }
719
+ }
720
+ });
721
+
722
+ cli
723
+ .command(`gen-api-docs:version`)
724
+ .description(
725
+ `Generates versioned OpenAPI docs in MDX file format, versions.js and sidebar.ts (if enabled).`
726
+ )
727
+ .usage("<id:version>")
728
+ .arguments("<id:version>")
729
+ .option("-p, --plugin-id <plugin>", "OpenAPI docs plugin ID.")
730
+ .action(async (id, instance) => {
731
+ const options = instance.opts();
732
+ const pluginId = options.pluginId;
733
+ const pluginInstances = getPluginInstances(plugins);
734
+ let targetConfig: any;
735
+ let targetDocsPluginId: any;
736
+ if (pluginId) {
737
+ try {
738
+ const pluginConfig = getPluginConfig(plugins, pluginId);
739
+ targetConfig = pluginConfig.config ?? {};
740
+ targetDocsPluginId = pluginConfig.docsPluginId;
741
+ } catch {
742
+ console.error(
743
+ chalk.red(`OpenAPI docs plugin ID '${pluginId}' not found.`)
744
+ );
745
+ return;
746
+ }
747
+ } else {
748
+ if (pluginInstances.length > 1) {
749
+ console.error(
750
+ chalk.red(
751
+ "OpenAPI docs plugin ID must be specified when more than one plugin instance exists."
752
+ )
753
+ );
754
+ return;
755
+ }
756
+ targetConfig = config;
757
+ }
758
+ const [parentId, versionId] = id.split(":");
759
+ const parentConfig = Object.assign({}, targetConfig[parentId]);
760
+
761
+ const version = parentConfig.version as string;
762
+ const label = parentConfig.label as string;
763
+ const baseUrl = parentConfig.baseUrl as string;
764
+
765
+ let parentVersion = {} as any;
766
+ parentVersion[version] = { label: label, baseUrl: baseUrl };
767
+
768
+ const { versions } = targetConfig[parentId] as any;
769
+ const mergedVersions = Object.assign(parentVersion, versions);
770
+
771
+ // Prepare for merge
772
+ delete parentConfig.versions;
773
+ delete parentConfig.version;
774
+ delete parentConfig.label;
775
+ delete parentConfig.baseUrl;
776
+ delete parentConfig.downloadUrl;
777
+
778
+ // TODO: handle when no versions are defined by version command is passed
779
+ if (versionId === "all") {
780
+ if (versions[id]) {
781
+ console.error(
782
+ chalk.red(
783
+ "Can't use id 'all' for OpenAPI docs versions configuration key."
784
+ )
785
+ );
786
+ } else {
787
+ await generateVersions(mergedVersions, parentConfig.outputDir);
788
+ Object.keys(versions).forEach(async (key) => {
789
+ const versionConfig = versions[key];
790
+ const mergedConfig = {
791
+ ...parentConfig,
792
+ ...versionConfig,
793
+ };
794
+ await generateApiDocs(mergedConfig, targetDocsPluginId);
795
+ });
796
+ }
797
+ } else if (!versions[versionId]) {
798
+ console.error(
799
+ chalk.red(
800
+ `Version ID '${versionId}' does not exist in OpenAPI docs versions config.`
801
+ )
802
+ );
803
+ } else {
804
+ const versionConfig = versions[versionId];
805
+ const mergedConfig = {
806
+ ...parentConfig,
807
+ ...versionConfig,
808
+ };
809
+ await generateVersions(mergedVersions, parentConfig.outputDir);
810
+ await generateApiDocs(mergedConfig, targetDocsPluginId);
811
+ }
812
+ });
813
+
814
+ cli
815
+ .command(`clean-api-docs`)
816
+ .description(
817
+ `Clears the generated OpenAPI docs MDX files and sidebar.ts (if enabled).`
818
+ )
819
+ .usage("<id>")
820
+ .arguments("<id>")
821
+ .option("-p, --plugin-id <plugin>", "OpenAPI docs plugin ID.")
822
+ .option("--all-versions", "Clean all versions.")
823
+ .action(async (id, instance) => {
824
+ const options = instance.opts();
825
+ const pluginId = options.pluginId;
826
+ const allVersions = options.allVersions;
827
+ const pluginInstances = getPluginInstances(plugins);
828
+ let targetConfig: any;
829
+ if (pluginId) {
830
+ try {
831
+ const pluginConfig = getPluginConfig(plugins, pluginId);
832
+ targetConfig = pluginConfig.config ?? {};
833
+ } catch {
834
+ console.error(
835
+ chalk.red(`OpenAPI docs plugin ID '${pluginId}' not found.`)
836
+ );
837
+ return;
838
+ }
839
+ } else {
840
+ if (pluginInstances.length > 1) {
841
+ console.error(
842
+ chalk.red(
843
+ "OpenAPI docs plugin ID must be specified when more than one plugin instance exists."
844
+ )
845
+ );
846
+ return;
847
+ }
848
+ targetConfig = config;
849
+ }
850
+ if (id === "all") {
851
+ if (targetConfig[id]) {
852
+ console.error(
853
+ chalk.red(
854
+ "Can't use id 'all' for OpenAPI docs configuration key."
855
+ )
856
+ );
857
+ } else {
858
+ Object.keys(targetConfig).forEach(async function (key) {
859
+ await cleanApiDocs(targetConfig[key]);
860
+ if (allVersions) {
861
+ await cleanAllVersions(targetConfig[key]);
862
+ }
863
+ });
864
+ }
865
+ } else {
866
+ await cleanApiDocs(targetConfig[id]);
867
+ if (allVersions) {
868
+ await cleanAllVersions(targetConfig[id]);
869
+ }
870
+ }
871
+ });
872
+
873
+ cli
874
+ .command(`clean-api-docs:version`)
875
+ .description(
876
+ `Clears the versioned, generated OpenAPI docs MDX files, versions.json and sidebar.ts (if enabled).`
877
+ )
878
+ .usage("<id:version>")
879
+ .arguments("<id:version>")
880
+ .option("-p, --plugin-id <plugin>", "OpenAPI docs plugin ID.")
881
+ .action(async (id, instance) => {
882
+ const options = instance.opts();
883
+ const pluginId = options.pluginId;
884
+ const pluginInstances = getPluginInstances(plugins);
885
+ let targetConfig: any;
886
+ if (pluginId) {
887
+ try {
888
+ const pluginConfig = getPluginConfig(plugins, pluginId);
889
+ targetConfig = pluginConfig.config ?? {};
890
+ } catch {
891
+ console.error(
892
+ chalk.red(`OpenAPI docs plugin ID '${pluginId}' not found.`)
893
+ );
894
+ return;
895
+ }
896
+ } else {
897
+ if (pluginInstances.length > 1) {
898
+ console.error(
899
+ chalk.red(
900
+ "OpenAPI docs plugin ID must be specified when more than one plugin instance exists."
901
+ )
902
+ );
903
+ return;
904
+ }
905
+ targetConfig = config;
906
+ }
907
+ const [parentId, versionId] = id.split(":");
908
+ const { versions } = targetConfig[parentId] as any;
909
+
910
+ const parentConfig = Object.assign({}, targetConfig[parentId]);
911
+ delete parentConfig.versions;
912
+
913
+ if (versionId === "all") {
914
+ if (versions[id]) {
915
+ chalk.red(
916
+ "Can't use id 'all' for OpenAPI docs versions configuration key."
917
+ );
918
+ } else {
919
+ await cleanVersions(parentConfig.outputDir);
920
+ Object.keys(versions).forEach(async (key) => {
921
+ const versionConfig = versions[key];
922
+ const mergedConfig = {
923
+ ...parentConfig,
924
+ ...versionConfig,
925
+ };
926
+ await cleanApiDocs(mergedConfig);
927
+ });
928
+ }
929
+ } else {
930
+ const versionConfig = versions[versionId];
931
+ const mergedConfig = {
932
+ ...parentConfig,
933
+ ...versionConfig,
934
+ };
935
+ await cleanApiDocs(mergedConfig);
936
+ }
937
+ });
938
+ },
939
+ };
940
+ }
941
+
942
+ pluginOpenAPIDocs.validateOptions = ({ options, validate }: any) => {
943
+ const validatedOptions = validate(OptionsSchema, options);
944
+ return validatedOptions;
945
+ };