docusaurus-plugin-redoc
Version:
Redoc Plugin for DocusaurusV2
143 lines • 6.55 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadRedoclyConfig = void 0;
exports.default = redocPlugin;
exports.validateOptions = validateOptions;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const utils_1 = require("@docusaurus/utils");
const redoc_1 = require("redoc");
const openapi_core_1 = require("@redocly/openapi-core");
const options_1 = require("./options");
const loadSpec_1 = require("./loadSpec");
const loadRedoclyConfig_1 = require("./loadRedoclyConfig");
Object.defineProperty(exports, "loadRedoclyConfig", { enumerable: true, get: function () { return loadRedoclyConfig_1.loadRedoclyConfig; } });
// eslint-disable-next-line @typescript-eslint/no-var-requires
const version = require('../package.json').version;
function redocPlugin(context, opts) {
const { baseUrl } = context.siteConfig;
const options = { ...options_1.DEFAULT_OPTIONS, ...opts };
const { debug, spec, url: downloadUrl, config, themeId, normalizeUrl: normalizeDownloadUrl, } = options;
let url = downloadUrl;
const isSpecFile = fs_1.default.existsSync(spec);
const fileName = path_1.default.join('redocusaurus', `${options.id || 'api-spec'}.yaml`);
let filesToWatch = isSpecFile ? [path_1.default.resolve(spec)] : [];
if (debug) {
console.error('[REDOCUSAURUS_PLUGIN] Opts Input:', opts);
console.error('[REDOCUSAURUS_PLUGIN] Options:', options);
}
return {
name: 'docusaurus-plugin-redoc',
async loadContent() {
const redoclyConfig = await (0, loadRedoclyConfig_1.loadRedoclyConfig)(config);
if (redoclyConfig.configFile) {
filesToWatch.push(redoclyConfig.configFile);
}
let bundledSpec, problems;
if (!isSpecFile) {
// If spec is a remote url then add it as download url also as a default
url = url || spec;
if (debug) {
console.log('[REDOCUSAURUS_PLUGIN] bundling spec from url', spec);
}
({ bundle: bundledSpec, problems } = await (0, loadSpec_1.loadSpecWithConfig)(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
spec, redoclyConfig));
}
else {
// If local file
if (debug) {
console.log('[REDOCUSAURUS_PLUGIN] reading file: ', spec);
}
const fileBundle = await (0, openapi_core_1.bundle)({
ref: spec,
config: redoclyConfig,
});
({ bundle: bundledSpec, problems } = fileBundle);
filesToWatch = [path_1.default.resolve(spec), ...fileBundle.fileDependencies];
}
if (problems === null || problems === void 0 ? void 0 : problems.length) {
console.error('[REDOCUSAURUS_PLUGIN] errors while bundling spec', spec);
(0, openapi_core_1.formatProblems)(problems, {
totals: (0, openapi_core_1.getTotals)(problems),
version,
});
}
if (debug) {
console.log('[REDOCUSAURUS_PLUGIN] File Bundled');
}
// Pass again to loader to convert swagger to openapi
const converted = await (0, redoc_1.loadAndBundleSpec)(bundledSpec.parsed);
// If download url is not provided then use bundled yaml as a static file (see `postBuild`)
url = url || fileName;
return {
converted,
bundle: bundledSpec.parsed,
};
},
async contentLoaded({ content, actions }) {
const { createData, addRoute, setGlobalData } = actions;
if (!(content === null || content === void 0 ? void 0 : content.converted)) {
throw new Error(`[Redocusaurus] Spec could not be parsed: ${spec}`);
}
const data = {
url,
themeId,
isSpecFile,
normalizeUrl: normalizeDownloadUrl,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
spec: content.converted,
};
setGlobalData(data);
if (options.route) {
const routePath = options.route.startsWith('/')
? options.route.slice(1)
: options.route;
const specProps = await createData(`redocApiSpecV1.2-${options.id || '1'}.json`, JSON.stringify(data));
const layoutProps = await createData(`redocApiLayoutV1-${options.id || '1'}.json`, JSON.stringify(options.layout));
const modules = {
specProps,
layoutProps,
};
const routeOptions = {
modules,
component: '@theme/ApiDoc',
exact: true,
path: (0, utils_1.normalizeUrl)([baseUrl, routePath]),
};
if (debug) {
console.error('[REDOCUSAURUS_PLUGIN] Route:', routeOptions);
}
addRoute(routeOptions);
}
},
async postBuild({ content }) {
if (!isSpecFile || downloadUrl) {
return;
}
// Create a static file from bundled spec
const staticFile = path_1.default.join(context.outDir, fileName);
const dir = path_1.default.dirname(staticFile);
if (!fs_1.default.existsSync(dir)) {
fs_1.default.mkdirSync(dir);
}
if (debug) {
console.error('[REDOCUSAURUS_PLUGIN] creating static bundle copy for download', staticFile);
}
// create bundled url
const bundledYaml = (0, openapi_core_1.stringifyYaml)(content.bundle || content.converted);
fs_1.default.writeFileSync(staticFile, bundledYaml);
},
getPathsToWatch() {
return filesToWatch;
},
};
}
function validateOptions({ options, validate, }) {
const validatedOptions = validate(options_1.PluginOptionSchema, options);
return validatedOptions;
}
//# sourceMappingURL=index.js.map