UNPKG

openapi-ts-json-schema

Version:

OpenAPI to JSON schema generator with TypeScript in mind

62 lines (61 loc) 2.83 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeTsJsonSchema = void 0; const comment_json_1 = require("comment-json"); const replaceInlinedRefsWithStringPlaceholder_1 = require("./replaceInlinedRefsWithStringPlaceholder"); const replacePlaceholdersWithImportedSchemas_1 = require("./replacePlaceholdersWithImportedSchemas"); const replacePlaceholdersWithRefs_1 = require("./replacePlaceholdersWithRefs"); const makeCircularRefReplacer_1 = require("./makeCircularRefReplacer"); const patchJsonSchema_1 = require("./patchJsonSchema"); const __1 = require("../"); async function makeTsJsonSchema({ metaData, schemaMetaDataMap, refHandling, schemaPatcher, $idMapper, }) { const { originalSchema, absoluteDirName, $id } = metaData; // "inline" refHandling doesn't need replacing inlined refs const schemaWithPlaceholders = refHandling === 'import' || refHandling === 'keep' ? (0, replaceInlinedRefsWithStringPlaceholder_1.replaceInlinedRefsWithStringPlaceholder)(originalSchema) : originalSchema; /** * Check if this schema is just a reference to another schema * Eg: _OTJS-START_/components/schemas/Foo_OTJS-END_ */ const isAlias = typeof schemaWithPlaceholders === 'string'; const patchedSchema = isAlias ? schemaWithPlaceholders : (0, patchJsonSchema_1.patchJsonSchema)(schemaWithPlaceholders, schemaPatcher); /** * Stringifying schema with "comment-json" instead of JSON.stringify * to generate inline comments for "inline" refHandling */ const stringifiedSchema = (0, comment_json_1.stringify)(patchedSchema, (0, makeCircularRefReplacer_1.makeCircularRefReplacer)(), 2); let tsSchema = ` const schema = ${stringifiedSchema} as const; export default schema;`; if (refHandling === 'import') { // Alias schema handling is a bit rough, right now if (isAlias) { tsSchema = ` const schema = ${stringifiedSchema}; export default schema;`; } tsSchema = (0, replacePlaceholdersWithImportedSchemas_1.replacePlaceholdersWithImportedSchemas)({ schemaAsText: tsSchema, absoluteDirName, schemaMetaDataMap, }); } if (refHandling === 'keep') { tsSchema = (0, replacePlaceholdersWithRefs_1.replacePlaceholdersWithRefs)({ schemaAsText: tsSchema, refMapper: $idMapper, }); } /** * Re-expose schema with $id as "with$id" */ tsSchema = tsSchema + '\n\n' + `const with$id = { $id: "${$id}", ...schema } as const`; tsSchema = tsSchema + '\n' + `export { with$id };`; const formattedSchema = await (0, __1.formatTypeScript)(tsSchema); return formattedSchema; } exports.makeTsJsonSchema = makeTsJsonSchema;