UNPKG

openapi-ts-mock-generator

Version:
470 lines 21.9 kB
"use strict"; function _array_like_to_array(arr, len) { if (len == null || len > arr.length) len = arr.length; for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i]; return arr2; } function _array_with_holes(arr) { if (Array.isArray(arr)) return arr; } function _define_property(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _iterable_to_array_limit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){ _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally{ try { if (!_n && _i["return"] != null) _i["return"](); } finally{ if (_d) throw _e; } } return _arr; } function _non_iterable_rest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _object_spread(target) { for(var i = 1; i < arguments.length; i++){ var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === "function") { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function(key) { _define_property(target, key, source[key]); }); } return target; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function(sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _object_spread_props(target, source) { source = source != null ? source : {}; if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function(key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _sliced_to_array(arr, i) { return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest(); } function _unsupported_iterable_to_array(o, minLen) { if (!o) return; if (typeof o === "string") return _array_like_to_array(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen); } var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = function(target, all) { for(var name in all)__defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = function(to, from, except, desc) { if (from && typeof from === "object" || typeof from === "function") { var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined; try { var _loop = function() { var key = _step.value; if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: function() { return from[key]; }, enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); }; for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop(); } catch (err) { _didIteratorError = true; _iteratorError = err; } finally{ try { if (!_iteratorNormalCompletion && _iterator.return != null) { _iterator.return(); } } finally{ if (_didIteratorError) { throw _iteratorError; } } } } return to; }; var __toESM = function(mod, isNodeMode, target) { return target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(// If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod); }; var __toCommonJS = function(mod) { return __copyProps(__defProp({}, "__esModule", { value: true }), mod); }; // src/parser.ts var parser_exports = {}; __export(parser_exports, { getRandomLengthArray: function() { return getRandomLengthArray; }, parseSchema: function() { return parseSchema; }, refSchemaParser: function() { return refSchemaParser; }, specialFakerParser: function() { return specialFakerParser; } }); module.exports = __toCommonJS(parser_exports); // src/defaults.ts var import_faker = require("@faker-js/faker"); var ARRAY_MIN_LENGTH = 1; var ARRAY_MAX_LENGTH = 3; var MIN_STRING_LENGTH = 3; var MAX_STRING_LENGTH = 20; var MIN_INTEGER = 1; var MAX_INTEGER = 1e5; var MIN_NUMBER = 0; var MAX_NUMBER = 100; var MIN_WORD_LENGTH = 0; var MAX_WORD_LENGTH = 3; var FAKER_SEED = 1; var faker = new import_faker.Faker({ locale: [ import_faker.ko ] }); faker.seed(FAKER_SEED); // src/writer.ts var import_swagger_parser = __toESM(require("@apidevtools/swagger-parser")); var import_change_case_all = require("change-case-all"); var import_generate = require("oazapfts/generate"); var toUnquotedJSON = function(param, options) { var _$_object_spread = _object_spread({ depth: 0, isStatic: false, singleLine: false }, options), depth = _$_object_spread.depth, isStatic = _$_object_spread.isStatic, singleLine = _$_object_spread.singleLine; var prefixSpace = " ".repeat(depth * 2); var lineBreak = singleLine ? "" : "\n"; if (param === null) { return "null"; } else if (Array.isArray(param)) { var results = param.map(function(elem) { return toUnquotedJSON(elem, _object_spread_props(_object_spread({}, options), { depth: depth + 1 })); }); var firstElementSpace = singleLine ? "" : " "; return [ "[", firstElementSpace + results.join(", "), "]" ].join(lineBreak + prefixSpace); } else if (typeof param === "object") { var firstElementSpace1 = singleLine ? " " : " "; var lastComma = singleLine ? ", " : ","; var results1 = Object.entries(param).map(function(param) { var _param = _sliced_to_array(param, 2), key = _param[0], value = _param[1]; return "".concat(firstElementSpace1).concat(key, ": ").concat(toUnquotedJSON(value, _object_spread_props(_object_spread({}, options), { depth: depth + 1 }))).concat(lastComma); }).join(lineBreak + prefixSpace); return [ "{", "".concat(results1), "}" ].join(lineBreak + prefixSpace); } else if (typeof param === "string" && isStatic === false && (param.startsWith("faker") || param.startsWith("Buffer.from(faker"))) { return param; } else if (typeof param === "string" && param.endsWith(" as const")) { return '"'.concat(param.slice(0, -" as const".length), '" as const'); } return JSON.stringify(param); }; var multiLineStr = function(str) { return str.replace(/\n/g, " ").replace(/\s+/g, " ").replace(/\s\./g, ".").trim(); }; // src/parser.ts var import_change_case_all2 = require("change-case-all"); var import_fs = require("fs"); var import_generate2 = require("oazapfts/generate"); var import_path = require("path"); var parseSchema = function(schemaValue, specialSchema, options) { var outputSchema = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {}; if ((0, import_generate2.isReference)(schemaValue)) { console.warn("can't parse reference schema", schemaValue, schemaValue.$ref); return; } if (schemaValue.type === "object") { if (schemaValue.properties === void 0) return {}; return Object.entries(schemaValue.properties).reduce(function(acc, param) { var _param = _sliced_to_array(param, 2), key = _param[0], field = _param[1]; acc[key] = parseSchema(field, specialSchema, options, outputSchema); return acc; }, {}); } else if (schemaValue.enum !== void 0) { var enumValue = options.isStatic ? faker.helpers.arrayElement(schemaValue.enum) : "faker.helpers.arrayElement<".concat(schemaValue.enum.map(function(item) { return '"'.concat(item, '"'); }).join(" | "), ">(").concat(toUnquotedJSON(schemaValue.enum, { depth: 0, isStatic: options.isStatic, singleLine: true }), ")"); if (options.isStatic && typeof enumValue === "string") return enumValue + " as const"; return enumValue; } else if (schemaValue.allOf !== void 0) { var allOfValue = schemaValue.allOf; return faker.helpers.arrayElement(allOfValue.map(function(field) { return parseSchema(field, specialSchema, options, outputSchema); })); } else if (schemaValue.anyOf !== void 0) { var anyOfValue = schemaValue.anyOf; return options.isStatic ? faker.helpers.arrayElement(anyOfValue.map(function(field) { return parseSchema(field, specialSchema, options, outputSchema); })) : multiLineStr("\n faker.helpers.arrayElement([\n ".concat(anyOfValue.map(function(field) { return toUnquotedJSON(parseSchema(field, specialSchema, options, {}), { depth: 0, isStatic: options.isStatic, singleLine: true }); }), "\n ])\n ")); } else if (schemaValue.oneOf !== void 0) { var oneOfValue = schemaValue.oneOf; return options.isStatic ? faker.helpers.arrayElement(oneOfValue.map(function(field) { return parseSchema(field, specialSchema, options, outputSchema); })) : multiLineStr("\n faker.helpers.arrayElement([\n ".concat(oneOfValue.map(function(field) { return toUnquotedJSON(parseSchema(field, specialSchema, options, {}), { depth: 0, isStatic: options.isStatic, singleLine: true }); }), "\n ])\n ")); } else if (schemaValue.type === "array") { if ("prefixItems" in schemaValue) { var length = faker.number.int({ min: schemaValue.minItems, max: schemaValue.maxItems }); return schemaValue.prefixItems.slice(0, length).map(function(field) { return parseSchema(field, specialSchema, options, outputSchema); }); } var arrayValue = schemaValue.items; return getRandomLengthArray(options.arrayMinLength, options.arrayMaxLength).map(function() { return parseSchema(arrayValue, specialSchema, options, outputSchema); }); } return valueGenerator(schemaValue, specialSchema, options.isStatic); }; var uuidToB64 = function(uuid) { var uuidBuffer = Buffer.from(uuid.replace(/-/g, ""), "hex"); var base64Uuid = uuidBuffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); return base64Uuid; }; var valueGenerator = function(schemaValue, specialSchema, isStatic) { var _schemaValue_title; var titleSpecial = specialSchema.titleSpecial, descriptionSpecial = specialSchema.descriptionSpecial; if (schemaValue.title && titleSpecial[schemaValue.title]) { return titleSpecial[schemaValue.title]; } else if (schemaValue.description && descriptionSpecial[schemaValue.description]) { return descriptionSpecial[schemaValue.description]; } if (schemaValue.type === "string" && schemaValue.format === "date-time") { return isStatic ? faker.date.between({ from: "2020-01-01T00:00:00.000Z", to: "2030-12-31T23:59:59.999Z" }).toISOString() : multiLineStr('\n faker.date.between({\n from: "2020-01-01T00:00:00.000Z",\n to: "2030-12-31T23:59:59.999Z",\n })\n .toISOString()\n '); } else if (schemaValue.type === "string" && schemaValue.format === "date") { return isStatic ? faker.date.between({ from: "2020-01-01T00:00:00.000Z", to: "2030-12-31T23:59:59.999Z" }).toISOString().split("T")[0] : multiLineStr('\n faker.date.between({\n from: "2020-01-01T00:00:00.000Z",\n to: "2030-12-31T23:59:59.999Z",\n })\n .toISOString()\n .split("T")[0]\n '); } else if (schemaValue.type === "string" && schemaValue.pattern) { return isStatic ? faker.helpers.fromRegExp(schemaValue.pattern) : "faker.helpers.fromRegExp(/".concat(schemaValue.pattern, "/)"); } else if (schemaValue.type === "string" && ((_schemaValue_title = schemaValue.title) === null || _schemaValue_title === void 0 ? void 0 : _schemaValue_title.toLowerCase()) === "b64uuid") { var baseUuid = faker.string.uuid(); return isStatic ? uuidToB64(baseUuid) : multiLineStr('\n Buffer.from(faker.string.uuid().replace(/-/g, ""), "hex")\n .toString("base64")\n .replace(/\\+/g, "-")\n .replace(/\\//g, "_")\n .replace(/=/g, "")\n '); } else if (schemaValue.type === "string") { var _schemaValue_maxLength, _schemaValue_minLength; var minLength = (_schemaValue_minLength = schemaValue.minLength) !== null && _schemaValue_minLength !== void 0 ? _schemaValue_minLength : Math.min(MIN_STRING_LENGTH, (_schemaValue_maxLength = schemaValue.maxLength) !== null && _schemaValue_maxLength !== void 0 ? _schemaValue_maxLength : MAX_STRING_LENGTH); var _schemaValue_minLength1, _schemaValue_maxLength1; var maxLength = (_schemaValue_maxLength1 = schemaValue.maxLength) !== null && _schemaValue_maxLength1 !== void 0 ? _schemaValue_maxLength1 : Math.max(MAX_STRING_LENGTH, (_schemaValue_minLength1 = schemaValue.minLength) !== null && _schemaValue_minLength1 !== void 0 ? _schemaValue_minLength1 : MIN_STRING_LENGTH); return isStatic ? faker.string.alphanumeric({ length: { min: minLength, max: maxLength } }) : multiLineStr("\n faker.string.alphanumeric({\n length: { min: ".concat(minLength, ", max: ").concat(maxLength, " },\n })\n ")); } else if (schemaValue.type === "integer") { return isStatic ? faker.number.int({ min: MIN_INTEGER, max: MAX_INTEGER }) : multiLineStr("\n faker.number.int({ min: ".concat(MIN_INTEGER, ", max: ").concat(MAX_INTEGER, " })\n ")); } else if (schemaValue.type === "number") { var _schemaValue_maximum, _schemaValue_minimum; var minNumber = (_schemaValue_minimum = schemaValue.minimum) !== null && _schemaValue_minimum !== void 0 ? _schemaValue_minimum : Math.min(MIN_NUMBER, (_schemaValue_maximum = schemaValue.maximum) !== null && _schemaValue_maximum !== void 0 ? _schemaValue_maximum : MAX_NUMBER); var _schemaValue_minimum1, _schemaValue_maximum1; var maxNumber = (_schemaValue_maximum1 = schemaValue.maximum) !== null && _schemaValue_maximum1 !== void 0 ? _schemaValue_maximum1 : Math.max(MAX_NUMBER, (_schemaValue_minimum1 = schemaValue.minimum) !== null && _schemaValue_minimum1 !== void 0 ? _schemaValue_minimum1 : MIN_NUMBER); return isStatic ? faker.number.float({ min: minNumber, max: maxNumber, fractionDigits: 2 }) : multiLineStr("\n faker.number.float({\n min: ".concat(minNumber, ",\n max: ").concat(maxNumber, ",\n fractionDigits: 2,\n })\n ")); } else if (schemaValue.type === "boolean") { return isStatic ? faker.datatype.boolean() : "faker.datatype.boolean()"; } else if (schemaValue.type === "null") { return null; } else if (Object.keys(schemaValue).length === 0) { return isStatic ? faker.word.words({ count: { min: MIN_WORD_LENGTH, max: MAX_WORD_LENGTH } }) : multiLineStr("\n faker.word.words({\n count: {\n min: ".concat(MIN_WORD_LENGTH, ",\n max: ").concat(MAX_WORD_LENGTH, ",\n },\n })\n ")); } return isStatic ? faker.word.adjective() : "faker.word.adjective()"; }; var getRandomLengthArray = function() { var min = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : ARRAY_MIN_LENGTH, max = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : ARRAY_MAX_LENGTH; var length = faker.number.int({ min: min, max: max }); return Array.from({ length: length }, function(_, i) { return i; }); }; var refSchemaParser = function(ref, refs) { var schemaName = (0, import_change_case_all2.pascalCase)(ref.replace("#/components/schemas/", "")); var schemaValue = refs.get(ref); return { name: schemaName, value: schemaValue }; }; var getFakerValue = function(value, options) { if ("value" in value) { return value.value; } if ("module" in value && "type" in value) { if (options.isStatic === false) { var fakerOption = "options" in value ? toUnquotedJSON(value.options, { depth: 0, isStatic: options.isStatic, singleLine: true }) : ""; return "faker.".concat(value.module, ".").concat(value.type, "(").concat(fakerOption, ")"); } var fakerModule = faker[value.module]; if (fakerModule === void 0) { console.warn("can't find faker module", fakerModule); return void 0; } var fakerFunc = fakerModule[value.type]; if (fakerFunc === void 0 || typeof fakerFunc !== "function") { console.warn("can't find faker function", fakerFunc); return void 0; } return "options" in value ? fakerFunc(value.options) : fakerFunc(); } return void 0; }; var specialFakerParser = function(options) { if (options.specialPath === void 0) return { titleSpecial: {}, descriptionSpecial: {} }; var _options_baseDir; var titlePath = (0, import_path.join)((_options_baseDir = options.baseDir) !== null && _options_baseDir !== void 0 ? _options_baseDir : "", options.specialPath, "titles.json"); var _options_baseDir1; var descPath = (0, import_path.join)((_options_baseDir1 = options.baseDir) !== null && _options_baseDir1 !== void 0 ? _options_baseDir1 : "", options.specialPath, "descriptions.json"); var titleSpecialKey = (0, import_fs.existsSync)(titlePath) ? JSON.parse((0, import_fs.readFileSync)(titlePath, "utf-8")) : {}; var descriptionSpecialKey = (0, import_fs.existsSync)(descPath) ? JSON.parse((0, import_fs.readFileSync)(descPath, "utf-8")) : {}; var titleSpecial = Object.entries(titleSpecialKey).reduce(function(acc, param) { var _param = _sliced_to_array(param, 2), key = _param[0], value = _param[1]; var fakerValue = getFakerValue(value, { isStatic: options.isStatic }); acc[key] = fakerValue; return acc; }, {}); var descriptionSpecial = Object.entries(descriptionSpecialKey).reduce(function(acc, param) { var _param = _sliced_to_array(param, 2), key = _param[0], value = _param[1]; var fakerValue = getFakerValue(value, { isStatic: options.isStatic }); acc[key] = fakerValue; return acc; }, {}); return { titleSpecial: titleSpecial, descriptionSpecial: descriptionSpecial }; }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { getRandomLengthArray: getRandomLengthArray, parseSchema: parseSchema, refSchemaParser: refSchemaParser, specialFakerParser: specialFakerParser }); //# sourceMappingURL=parser.js.map