UNPKG

openapi-modifier

Version:

This package allows you to automate the process of modifying OpenAPI specifications by applying a set of predefined rules

237 lines (236 loc) 9.87 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.mergeConfigs = exports.checkIsValidConfig = exports.getAbsoluteConfigPath = exports.findConfigFile = exports.defaultConfig = void 0; const zod_1 = require("zod"); const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const yaml_1 = __importDefault(require("yaml")); const configSchema = zod_1.z .object({ logger: zod_1.z .object({ verbose: zod_1.z.boolean().optional(), minLevel: zod_1.z.number().optional(), }) .strict() .optional(), input: zod_1.z.string().optional(), output: zod_1.z.string().optional(), pipeline: zod_1.z .array(zod_1.z .object({ rule: zod_1.z.string(), disabled: zod_1.z.boolean().optional(), config: zod_1.z.any().optional(), }) .strict()) .optional(), }) .strict(); const defaultConfig = {}; exports.defaultConfig = defaultConfig; const createConfigLogger = (baseLogger) => { return baseLogger.clone('config'); }; function diagnosticTSFile(logger, fileNames, options) { // see: https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API#a-minimal-compiler const ts = require('typescript'); let program = ts.createProgram(fileNames, Object.assign(Object.assign({}, options), { noEmit: true })); let emitResult = program.emit(); let allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); allDiagnostics.forEach((diagnostic) => { if (diagnostic.file) { let { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); logger.warning(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); } else { logger.warning(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')); } }); return !(allDiagnostics === null || allDiagnostics === void 0 ? void 0 : allDiagnostics.length); } const getAbsoluteConfigPath = (configPath) => { return path_1.default.isAbsolute(configPath) ? configPath : path_1.default.resolve(process.cwd(), configPath); }; exports.getAbsoluteConfigPath = getAbsoluteConfigPath; const findConfigFile = (baseLogger, configPath) => __awaiter(void 0, void 0, void 0, function* () { const logger = createConfigLogger(baseLogger); const absoluteConfigPath = getAbsoluteConfigPath(configPath); const configFileExtension = path_1.default.extname(configPath) || null; switch (configFileExtension) { case '.yaml': case '.yml': { let configContent = ''; try { const configBuffer = fs_1.default.readFileSync(absoluteConfigPath); configContent = configBuffer.toString(); } catch (error) { if (error instanceof Error) { logger.error(error, `Not found config file: ${absoluteConfigPath}`); } throw error; } try { return yaml_1.default.parse(configContent); } catch (error) { if (error instanceof Error) { logger.error(error, `Parse config: ${configContent}`); } throw error; } break; } case '.json': { let configContent = ''; try { const configBuffer = fs_1.default.readFileSync(absoluteConfigPath); configContent = configBuffer.toString(); } catch (error) { if (error instanceof Error) { logger.error(error, `Not found config file: ${absoluteConfigPath}`); } throw error; } try { return JSON.parse(configContent); } catch (error) { if (error instanceof Error) { logger.error(error, `Parse config: ${configContent}`); } throw error; } break; } case '.js': { try { const processorImport = yield Promise.resolve(`${absoluteConfigPath}`).then(s => __importStar(require(s))); return processorImport.default; } catch (error) { if (error instanceof Error) { logger.error(error, `Failed to proccess config file: ${absoluteConfigPath}`); } throw error; } break; } case '.ts': { const isValidTSFile = diagnosticTSFile(logger, [absoluteConfigPath], {}); if (!isValidTSFile) { const error = new Error('Not valid TS config file!'); logger.error(error, `Failed to proccess config file: ${absoluteConfigPath}`); throw error; } let configContent = ''; try { const configBuffer = fs_1.default.readFileSync(absoluteConfigPath); configContent = configBuffer.toString(); } catch (error) { if (error instanceof Error) { logger.error(error, `Not found config file: ${absoluteConfigPath}`); } throw error; } const absoluteCompiledConfigPath = `${absoluteConfigPath.slice(0, -2)}cjs`; const ts = require('typescript'); try { // see: https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API#a-simple-transform-function let result = ts.transpileModule(configContent, { compilerOptions: { module: ts.ModuleKind.CommonJS } }); fs_1.default.writeFileSync(absoluteCompiledConfigPath, result.outputText); const processorImport = yield Promise.resolve(`${absoluteCompiledConfigPath}`).then(s => __importStar(require(s))); return processorImport.default; } catch (error) { if (error instanceof Error) { logger.error(error, `Failed to proccess config file: ${absoluteConfigPath}`); } throw error; } finally { if (fs_1.default.existsSync(absoluteCompiledConfigPath)) { fs_1.default.unlinkSync(absoluteCompiledConfigPath); } } break; } default: { const error = new Error(` Not processable config file extension! Config path: ${absoluteConfigPath} `); logger.error(error); throw error; } } }); exports.findConfigFile = findConfigFile; const checkIsValidConfig = (baseLogger, config) => { const logger = createConfigLogger(baseLogger); try { configSchema.parse(config); return true; } catch (error) { if (error instanceof Error) { logger.error(error, `Not valid config: ${JSON.stringify(config || {})}`); } throw error; } }; exports.checkIsValidConfig = checkIsValidConfig; const mergeConfigs = (baseLogger, ...configs) => { const logger = createConfigLogger(baseLogger); try { return configs.reduce((acc, config) => { return Object.assign(Object.assign(Object.assign({}, acc), config), { logger: Object.assign(Object.assign({}, acc.logger), config.logger), pipeline: [...(acc.pipeline || []), ...(config.pipeline || [])] }); }, {}); } catch (error) { if (error instanceof Error) { logger.error(error, `Failed to merge configs: ${JSON.stringify(configs || [])}`); } throw error; } }; exports.mergeConfigs = mergeConfigs;