UNPKG

openapi-ts-mock-generator

Version:
399 lines 18.7 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 __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; 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 __toCommonJS = function(mod) { return __copyProps(__defProp({}, "__esModule", { value: true }), mod); }; // src/parsers/schema-parser.ts var schema_parser_exports = {}; __export(schema_parser_exports, { parseSchema: function() { return parseSchema; }, refSchemaParser: function() { return refSchemaParser; }, valueGenerator: function() { return valueGenerator; } }); module.exports = __toCommonJS(schema_parser_exports); // src/core/config.ts var import_faker = require("@faker-js/faker"); 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/utils/string-utils.ts 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; }; // src/utils/code-utils.ts var toTypeScriptCode = function(param, options) { var _options_depth = options.depth, depth = _options_depth === void 0 ? 0 : _options_depth, isStatic = options.isStatic; var prefixSpace = " ".repeat(depth * 2); if (param === null) { return "null"; } if (Array.isArray(param)) { var results = param.map(function(elem) { return toTypeScriptCode(elem, _object_spread_props(_object_spread({}, options), { depth: depth + 1 })); }).join(",\n" + prefixSpace); return [ "[", results, "]" ].join("\n" + prefixSpace); } if (typeof param === "object") { var results1 = Object.entries(param).map(function(param) { var _param = _sliced_to_array(param, 2), key = _param[0], value = _param[1]; return generateObjectProperty(key, value, options, prefixSpace); }).join("\n" + prefixSpace); return [ "{", "".concat(results1), "}" ].join("\n" + prefixSpace); } if (typeof param === "string") { if (isStatic === false && (param.startsWith("faker") || param.startsWith("Buffer.from(faker"))) { return param; } if (param.endsWith(" as const")) { return '"'.concat(param.slice(0, -" as const".length), '" as const'); } } return JSON.stringify(param); }; var shouldApplyNullableExtension = function(value, isOptional) { if (!isOptional) return false; if (value === null) return true; if (typeof value === "string" && value.includes(",null")) { return true; } return false; }; var generateObjectProperty = function(key, value, options, prefixSpace) { var isOptional = options.isOptional, _options_depth = options.depth, depth = _options_depth === void 0 ? 0 : _options_depth; var shouldApplyNullable = shouldApplyNullableExtension(value, isOptional); var nullableTypeExtensionStart = shouldApplyNullable ? "...(faker.datatype.boolean() ? {\n".concat(prefixSpace) : ""; var nullableTypeExtensionEnd = shouldApplyNullable ? "\n".concat(prefixSpace, "} : {})") : ""; var propertyValue = toTypeScriptCode(value, _object_spread_props(_object_spread({}, options), { depth: depth + 1 })); return "".concat(nullableTypeExtensionStart).concat(prefixSpace).concat(key, ": ").concat(propertyValue).concat(nullableTypeExtensionEnd, ","); }; var compressCode = function(code) { return code.replace(/\n/g, " ").replace(/\s+/g, " ").replace(/\s\./g, ".").trim(); }; // src/utils/array-utils.ts var getRandomLengthArray = function() { var min = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 1, max = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 3; var length = faker.number.int({ min: min, max: max }); return Array.from({ length: length }, function(_, i) { return i; }); }; // src/parsers/schema-parser.ts var import_change_case_all = require("change-case-all"); var import_generate = require("oazapfts/generate"); var parseSchema = function(schemaValue, specialSchema, options) { var outputSchema = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {}; if ((0, import_generate.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(toTypeScriptCode(schemaValue.enum, _object_spread({ depth: 0 }, options)), ")"); 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); })) : compressCode("\n faker.helpers.arrayElement([\n ".concat(anyOfValue.map(function(field) { return toTypeScriptCode(parseSchema(field, specialSchema, options, {}), _object_spread({ depth: 0 }, options)); }), "\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); })) : compressCode("\n faker.helpers.arrayElement([\n ".concat(oneOfValue.map(function(field) { return toTypeScriptCode(parseSchema(field, specialSchema, options, {}), _object_spread({ depth: 0 }, options)); }), "\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); }; var refSchemaParser = function(ref, refs) { var schemaName = (0, import_change_case_all.pascalCase)(ref.replace("#/components/schemas/", "")); var schemaValue = refs.get(ref); return { name: schemaName, value: schemaValue }; }; var valueGenerator = function(schemaValue, specialSchema, options) { var _schemaValue_title; var isStatic = options.isStatic; 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() : compressCode('\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] : compressCode('\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) : compressCode('\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 } }) : compressCode("\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 }) : compressCode("\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 }) : compressCode("\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 } }) : compressCode("\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()"; }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { parseSchema: parseSchema, refSchemaParser: refSchemaParser, valueGenerator: valueGenerator }); //# sourceMappingURL=schema-parser.js.map