@openapi-generator-plus/plain-documentation-generator
Version:
An OpenAPI Generator Plus template for generating plain documentation
248 lines (247 loc) • 12.9 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createGenerator = void 0;
const types_1 = require("@openapi-generator-plus/types");
const path_1 = __importDefault(require("path"));
const handlebars_1 = __importDefault(require("handlebars"));
const handlebars_templates_1 = require("@openapi-generator-plus/handlebars-templates");
const java_like_generator_helper_1 = require("@openapi-generator-plus/java-like-generator-helper");
const generator_common_1 = require("@openapi-generator-plus/generator-common");
const less_utils_1 = require("./less-utils");
const static_utils_1 = require("./static-utils");
const fs_1 = require("fs");
function computeCustomTemplatesPath(configPath, customTemplatesPath) {
if (configPath) {
return path_1.default.resolve(path_1.default.dirname(configPath), customTemplatesPath);
}
else {
return customTemplatesPath;
}
}
function toSafeTypeForComposing(nativeType) {
if (/[^a-zA-Z0-9_.[\]]/.test(nativeType)) {
return `(${nativeType})`;
}
else {
return nativeType;
}
}
const createGenerator = (config, context) => {
const javaLikeContext = Object.assign(Object.assign({}, context), { defaultConstantStyle: "snake" /* ConstantStyle.allCapsSnake */, defaultEnumMemberStyle: "preserve" /* EnumMemberStyle.preserve */ });
const customTemplates = (0, generator_common_1.configString)(config, 'customTemplates', undefined);
const operationsConfig = (0, generator_common_1.configObject)(config, 'operations', {});
if (operationsConfig.navStyle === undefined) {
operationsConfig.navStyle = 'name';
}
if (operationsConfig.exclude === undefined) {
operationsConfig.exclude = [];
}
const generatorOptions = Object.assign(Object.assign({}, (0, java_like_generator_helper_1.options)(config, javaLikeContext)), { customTemplatesPath: customTemplates && computeCustomTemplatesPath(config.configPath, customTemplates), operations: operationsConfig });
const aCommonGenerator = (0, generator_common_1.commonGenerator)(config, context);
return Object.assign(Object.assign(Object.assign(Object.assign({}, context.baseGenerator(config, context)), aCommonGenerator), (0, java_like_generator_helper_1.javaLikeGenerator)(config, javaLikeContext)), { generatorType: () => types_1.CodegenGeneratorType.DOCUMENTATION, toIdentifier: (name) => name, toLiteral: (value, options) => {
if (value === undefined) {
const defaultValue = context.generator().defaultValue(options);
if (defaultValue === null) {
return null;
}
return defaultValue.literalValue;
}
return `${value}`;
}, toNativeType: (options) => {
const { type, format } = options;
if (type === 'string') {
if (format) {
return new context.NativeType(format, {
serializedType: 'string',
});
}
}
else if (type === 'integer') {
if (format) {
return new context.NativeType(format, {
serializedType: 'number',
});
}
else {
return new context.NativeType(type, {
serializedType: 'number',
});
}
}
return new context.NativeType(type);
}, toEnumMemberName: (name) => name, toNativeObjectType: function (options) {
const { scopedName } = options;
let modelName = '';
for (const name of scopedName) {
modelName += `.${context.generator().toClassName(name)}`;
}
return new context.NativeType(modelName.substring(1));
}, toNativeArrayType: (options) => {
const { componentNativeType } = options;
return new context.NativeType(`${toSafeTypeForComposing(componentNativeType.nativeType)}[]`);
}, toNativeMapType: (options) => {
const { keyNativeType, componentNativeType } = options;
return new context.NativeType(`{ [name: ${keyNativeType}]: ${componentNativeType} }`);
}, nativeTypeUsageTransformer: ({ nullable }) => ({
default: function (nativeType, nativeTypeString) {
if (nullable) {
return `${toSafeTypeForComposing(nativeTypeString)} | null`;
}
return nativeTypeString;
},
/* We don't transform the concrete type as the concrete type is never null; we use it to make new objects */
concreteType: null,
}), defaultValue: () => {
return null;
}, initialValue: () => {
return null;
}, toOperationGroupName: (name) => {
return name;
}, operationGroupingStrategy: () => {
return context.operationGroupingStrategies.addToGroupsByTagOrPath;
}, allOfStrategy: () => types_1.CodegenAllOfStrategy.NATIVE, anyOfStrategy: () => types_1.CodegenAnyOfStrategy.NATIVE, oneOfStrategy: () => types_1.CodegenOneOfStrategy.NATIVE, supportsInheritance: () => false, supportsMultipleInheritance: () => false, nativeCompositionCanBeScope: () => true, nativeComposedSchemaRequiresName: () => false, nativeComposedSchemaRequiresObjectLikeOrWrapper: () => false, interfaceCanBeNested: () => true, watchPaths: () => {
const result = [path_1.default.resolve(__dirname, '..', 'templates')];
result.push(path_1.default.resolve(__dirname, '..', 'less'));
result.push(path_1.default.resolve(__dirname, '..', 'static'));
if (generatorOptions.customTemplatesPath) {
result.push(generatorOptions.customTemplatesPath);
}
return result;
}, cleanPathPatterns: () => {
return [
'index.html',
'static/**',
'main.css',
'custom.css',
];
}, templateRootContext: () => {
return Object.assign(Object.assign(Object.assign({}, aCommonGenerator.templateRootContext()), generatorOptions), { generatorClass: '@openapi-generator-plus/plain-documentation-generator' });
}, postProcessDocument(doc) {
var _a;
/* Apply excludes on operations */
for (let i = 0; i < doc.groups.length; i++) {
const group = doc.groups[i];
for (let j = 0; j < group.operations.length; j++) {
const op = group.operations[j];
for (const exclude of ((_a = generatorOptions.operations) === null || _a === void 0 ? void 0 : _a.exclude) || []) {
if (op.fullPath.match(new RegExp(exclude))) {
group.operations.splice(j, 1);
j--;
break;
}
}
}
if (group.operations.length === 0) {
doc.groups.splice(i, 1);
i--;
}
}
}, exportTemplates: async (outputPath, doc) => {
const hbs = handlebars_1.default.create();
(0, handlebars_templates_1.registerStandardHelpers)(hbs, context);
hbs.registerHelper('eachSorted', function (context, options) {
if (!context) {
return options.inverse(this);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let collection;
if (context instanceof Map) {
collection = [...context.values()];
}
else if (Array.isArray(context)) {
collection = context;
}
else if (typeof context === 'object') {
collection = [];
for (const key in context) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
collection.push(context[key]);
}
}
else {
collection = [context];
}
let result = '';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
for (const item of collection.sort(function (a, b) {
var _a;
if (a === b) {
return 0;
}
if (typeof a === 'string' && typeof b === 'string') {
return a.localeCompare(b);
}
else if (typeof a === 'number' && typeof b === 'number') {
return a < b ? -1 : a > b ? 1 : 0;
}
else if (typeof a === 'object' && typeof b === 'object') {
if (a === null) {
return 1;
}
else if (b === null) {
return -1;
}
if ((0, types_1.isCodegenOperation)(a) && (0, types_1.isCodegenOperation)(b)) {
/* Sort CodegenOperations first by http method */
const result = (0, generator_common_1.compareHttpMethods)(a.httpMethod, b.httpMethod);
if (result !== 0) {
return result;
}
if (((_a = generatorOptions.operations) === null || _a === void 0 ? void 0 : _a.navStyle) === 'full-path') {
if (a.fullPath && b.fullPath) {
return a.fullPath.localeCompare(b.fullPath);
}
}
}
if (a.name && b.name) {
return a.name.localeCompare(b.name);
}
return 0;
}
else {
return 0;
}
})) {
result += options.fn(item);
}
return result;
});
hbs.registerHelper('htmlId', function (value) {
if (value !== undefined) {
return `${value}`.replace(/[^-a-zA-Z0-9_]+/g, '_').replace(/^_+/, '').replace(/_+$/, '');
}
else {
return value;
}
});
await (0, handlebars_templates_1.loadTemplates)(path_1.default.resolve(__dirname, '..', 'templates'), hbs);
if (generatorOptions.customTemplatesPath) {
await (0, handlebars_templates_1.loadTemplates)(generatorOptions.customTemplatesPath, hbs);
}
const rootContext = context.generator().templateRootContext();
if (!outputPath.endsWith('/')) {
outputPath += '/';
}
await (0, handlebars_templates_1.emit)('index', path_1.default.join(outputPath, 'index.html'), Object.assign(Object.assign({}, rootContext), doc), true, hbs);
await (0, less_utils_1.emit)(path_1.default.resolve(__dirname, '../less', 'style.less'), path_1.default.join(outputPath, 'static/css/main.css'));
await fs_1.promises.writeFile(path_1.default.join(outputPath, 'custom.css'), '', {});
if (generatorOptions.customTemplatesPath) {
const customLessPath = path_1.default.resolve(generatorOptions.customTemplatesPath, 'less/custom.less');
if ((0, fs_1.existsSync)(customLessPath)) {
await (0, less_utils_1.emit)(customLessPath, path_1.default.join(outputPath, 'static/css/custom.css'));
}
}
await (0, static_utils_1.copyContents)(path_1.default.resolve(__dirname, '..', 'static'), path_1.default.join(outputPath, 'static'));
if (generatorOptions.customTemplatesPath) {
const customStaticPath = path_1.default.resolve(generatorOptions.customTemplatesPath, 'static');
if ((0, fs_1.existsSync)(customStaticPath)) {
await (0, static_utils_1.copyContents)(customStaticPath, path_1.default.join(outputPath, 'static'));
}
}
} });
};
exports.createGenerator = createGenerator;
exports.default = exports.createGenerator;