UNPKG

openapi-zod-client-yohoji

Version:

[![Screenshot 2022-11-12 at 18 52 25](https://user-images.githubusercontent.com/47224540/201487856-ffc4c862-6f31-4de1-8ef1-3981fabf3416.png)](https://openapi-zod-client.vercel.app/)

1,402 lines (1,353 loc) 115 kB
'use strict'; var path = require('node:path'); var server = require('pastable/server'); var tsPattern = require('ts-pattern'); var handlebars = require('handlebars'); var prettier = require('prettier'); var parserTypescript = require('prettier/parser-typescript'); var tanu = require('tanu'); var whence = require('whence'); var openapi3Ts = require('openapi3-ts'); function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n["default"] = e; return Object.freeze(n); } var path__default = /*#__PURE__*/_interopDefault(path); var prettier__default = /*#__PURE__*/_interopDefault(prettier); var parserTypescript__default = /*#__PURE__*/_interopDefault(parserTypescript); function _regeneratorRuntime() { _regeneratorRuntime = function () { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function (obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function (skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function () { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function (exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function (type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function (record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function (finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, catch: function (tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function (iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } var asComponentSchema = function asComponentSchema(name) { return "#/components/schemas/".concat(name); }; function normalizeString(text) { var prefixed = prefixStringStartingWithNumberIfNeeded(text); return prefixed.normalize("NFKD") // The normalize() using NFKD method returns the Unicode Normalization Form of a given string. .trim() // Remove whitespace from both sides of a string (optional) .replace(/\s+/g, "_") // Replace spaces with _ .replace(/-+/g, "_") // Replace - with _ .replace(/[^\w\-]+/g, "_") // Remove all non-word chars .replace(/--+/g, "-"); // Replace multiple - with single - } var wrapWithQuotesIfNeeded = function wrapWithQuotesIfNeeded(str) { if (/^[a-zA-Z]\w*$/.test(str)) { return str; } return "\"".concat(str, "\""); }; var prefixStringStartingWithNumberIfNeeded = function prefixStringStartingWithNumberIfNeeded(str) { var firstAsNumber = Number(str[0]); if (typeof firstAsNumber === "number" && !Number.isNaN(firstAsNumber)) { return "_" + str; } return str; }; var pathParamWithBracketsRegex = /({\w+})/g; var wordPrecededByNonWordCharacter = /[^\w\-]+/g; var pathParamToVariableName = function pathParamToVariableName(name) { // Replace all underscores with # to preserve them when doing snakeToCamel var preserveUnderscore = name.replaceAll("_", "#"); return server.snakeToCamel(preserveUnderscore.replaceAll("-", "_")).replaceAll("#", "_"); }; var matcherRegex = /{(\b\w+(?:-\w+)*\b)}/g; var replaceHyphenatedPath = function replaceHyphenatedPath(path) { var matches = path.match(matcherRegex); if (matches === null) { return path.replaceAll(matcherRegex, ":$1"); } matches.forEach(function (match) { var replacement = pathParamToVariableName(match.replaceAll(matcherRegex, ":$1")); path = path.replaceAll(match, replacement); }); return path; }; /** @example turns `/media-objects/{id}` into `MediaObjectsId` */ var pathToVariableName = function pathToVariableName(path) { return server.capitalize(server.kebabToCamel(path).replaceAll("/", "")) // /media-objects/{id} -> MediaObjects{id} .replace(pathParamWithBracketsRegex, function (group) { return server.capitalize(group.slice(1, -1)); }) // {id} -> Id .replace(wordPrecededByNonWordCharacter, "_"); }; // "/robots.txt" -> "/robots_txt" var isPrimitiveType$1 = function isPrimitiveType(type) { return primitiveTypeList$1.includes(type); }; var primitiveTypeList$1 = ["string", "number", "integer", "boolean", "null"]; var escapeControlCharacters = function escapeControlCharacters(str) { return str.replace(/\t/g, "\\t") // U+0009 .replace(/\n/g, "\\n") // U+000A .replace(/\r/g, "\\r") // U+000D .replace(/([\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\uFFFE\uFFFF])/g, function (_m, p1) { var dec = p1.codePointAt(); var hex = dec.toString(16); // eslint-disable-next-line sonarjs/no-nested-template-literals if (dec <= 0xff) return "\\x".concat("00".concat(hex).slice(-2)); // eslint-disable-next-line sonarjs/no-nested-template-literals return "\\u".concat("0000".concat(hex).slice(-4)); }).replace(/\//g, "\\/"); }; var toBoolean = function toBoolean(value, defaultValue) { return tsPattern.match(value)["with"](tsPattern.P.string.regex(/^false$/i), false, function () { return false; })["with"](tsPattern.P.string.regex(/^true$/i), true, function () { return true; }).otherwise(function () { return defaultValue; }); }; function _defineProperty(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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _arrayLikeToArray(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 _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(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(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var getHandlebars = function getHandlebars() { var instance = handlebars.create(); instance.registerHelper("ifeq", function (a, b, options) { if (a === b) { // @ts-expect-error return options.fn(this); } // @ts-expect-error return options.inverse(this); }); instance.registerHelper("ifNotEmptyObj", function (obj, options) { if (_typeof(obj) === "object" && Object.keys(obj).length > 0) { // @ts-expect-error return options.fn(this); } // @ts-expect-error return options.inverse(this); }); instance.registerHelper("toCamelCase", function (input) { // Check if input string is already in camelCase if (/^[a-z][a-zA-Z0-9]*$/.test(input)) { return input; } var words = input.split(/[\s_-]/); return words.map(function (word, index) { if (index === 0) { return word.toLowerCase(); } return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); }).join(""); }); return instance; }; /** @see https://github.dev/stephenh/ts-poet/blob/5ea0dbb3c9f1f4b0ee51a54abb2d758102eda4a2/src/Code.ts#L231 */ function maybePretty(input, options) { try { return prettier__default["default"].format(input.trim(), _objectSpread2({ parser: "typescript", plugins: [parserTypescript__default["default"]] }, options)); } catch (_unused) { return input; // assume it's invalid syntax and ignore } } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function () {}; return { s: F, n: function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function (e) { throw e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function () { it = it.call(o); }, n: function () { var step = it.next(); normalCompletion = step.done; return step; }, e: function (e) { didErr = true; err = e; }, f: function () { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(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 _nonIterableRest() { 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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } // taken from // https://github.dev/metadevpro/openapi3-ts/blob/a62ff445207af599f591532ef776e671c456cc37/src/model/OpenApi.ts#L261-L269 // to avoid the runtime dependency on `openapi3-ts` // which itself depends on `yaml` import (which use CJS `require` and thus can't be imported in a ESM module) /** * A type guard to check if the given value is a `ReferenceObject`. * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types * * @param obj The value to check. */ function isReferenceObject(obj) { return obj != null && Object.prototype.hasOwnProperty.call(obj, "$ref"); } var getOpenApiDependencyGraph = function getOpenApiDependencyGraph(schemaRef, getSchemaByRef) { var visitedsRefs = {}; var refsDependencyGraph = {}; var visit = function visit(schema, fromRef) { if (!schema) return; if (isReferenceObject(schema)) { if (!refsDependencyGraph[fromRef]) { refsDependencyGraph[fromRef] = new Set(); } refsDependencyGraph[fromRef].add(schema.$ref); if (visitedsRefs[schema.$ref]) return; visitedsRefs[fromRef] = true; visit(getSchemaByRef(schema.$ref), schema.$ref); return; } if (schema.allOf) { var _iterator = _createForOfIteratorHelper(schema.allOf), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var allOf = _step.value; visit(allOf, fromRef); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return; } if (schema.oneOf) { var _iterator2 = _createForOfIteratorHelper(schema.oneOf), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var oneOf = _step2.value; visit(oneOf, fromRef); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return; } if (schema.anyOf) { var _iterator3 = _createForOfIteratorHelper(schema.anyOf), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var anyOf = _step3.value; visit(anyOf, fromRef); } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return; } if (schema.type === "array") { if (!schema.items) return; return void visit(schema.items, fromRef); } if (schema.type === "object" || schema.properties || schema.additionalProperties) { if (schema.properties) { for (var property in schema.properties) { visit(schema.properties[property], fromRef); } } if (schema.additionalProperties && _typeof(schema.additionalProperties) === "object") { visit(schema.additionalProperties, fromRef); } } }; schemaRef.forEach(function (ref) { return visit(getSchemaByRef(ref), ref); }); var deepDependencyGraph = {}; var visitedsDeepRefs = {}; schemaRef.forEach(function (ref) { var deps = refsDependencyGraph[ref]; if (!deps) return; if (!deepDependencyGraph[ref]) { deepDependencyGraph[ref] = new Set(); } var visit = function visit(dep) { deepDependencyGraph[ref].add(dep); if (refsDependencyGraph[dep] && ref !== dep) { refsDependencyGraph[dep].forEach(function (transitive) { if (visitedsDeepRefs[ref + "__" + transitive]) return; visitedsDeepRefs[ref + "__" + transitive] = true; visit(transitive); }); } }; deps.forEach(function (dep) { return visit(dep); }); }); return { refsDependencyGraph: refsDependencyGraph, deepDependencyGraph: deepDependencyGraph }; }; var autocorrectRef = function autocorrectRef(ref) { return ref[1] === "/" ? ref : "#/" + ref.slice(1); }; var makeSchemaResolver = function makeSchemaResolver(doc) { // both used for debugging purpose // eslint-disable-next-line sonarjs/no-unused-collection var nameByRef = new Map(); // eslint-disable-next-line sonarjs/no-unused-collection var refByName = new Map(); var byRef = new Map(); var byNormalized = new Map(); var getSchemaByRef = function getSchemaByRef(ref) { var _get; // #components -> #/components var correctRef = autocorrectRef(ref); var split = correctRef.split("/"); // "#/components/schemas/Something.jsonld" -> #/components/schemas var path = split.slice(1, -1).join("/"); var map = (_get = server.get(doc, path.replace("#/", "").replace("#", "").replaceAll("/", "."))) !== null && _get !== void 0 ? _get : {}; // "#/components/schemas/Something.jsonld" -> "Something.jsonld" var name = split[split.length - 1]; var normalized = normalizeString(name); nameByRef.set(correctRef, normalized); refByName.set(normalized, correctRef); var infos = { ref: correctRef, name: name, normalized: normalized }; byRef.set(infos.ref, infos); byNormalized.set(infos.normalized, infos); // doc.components.schemas["Something.jsonld"] return map[name]; }; return { getSchemaByRef: getSchemaByRef, resolveRef: function resolveRef(ref) { return byRef.get(autocorrectRef(ref)); }, resolveSchemaName: function resolveSchemaName(normalized) { return byNormalized.get(normalized); } }; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var complexityByType = function complexityByType(schema) { var type = schema.type; if (!type) return 0; return tsPattern.match(type)["with"]("string", function () { return 1; })["with"]("number", function () { return 1; })["with"]("integer", function () { return 1; })["with"]("boolean", function () { return 1; })["with"]("null", function () { return 1; }).otherwise(function () { return 0; }); }; var complexityByComposite = function complexityByComposite(from) { if (!from) return 0; return tsPattern.match(from)["with"]("oneOf", function () { return 2; })["with"]("anyOf", function () { return 3; })["with"]("allOf", function () { return 2; })["with"]("enum", function () { return 1; })["with"]("array", function () { return 1; })["with"]("record", function () { return 1; })["with"]("empty-object", function () { return 1; })["with"]("object", function () { return 2; }).otherwise(function () { return 0; }); }; function getSchemaComplexity(_ref) { var current = _ref.current, schema = _ref.schema; if (!schema) return current; if (isReferenceObject(schema)) return current + 2; if (Array.isArray(schema.type)) { if (schema.type.length === 1) { return complexityByComposite("oneOf") + getSchemaComplexity({ current: current, schema: _objectSpread2(_objectSpread2({}, schema), {}, { type: schema.type[0] }) }); } return current + complexityByComposite("oneOf") + server.getSum(schema.type.map(function (prop) { return getSchemaComplexity({ current: 0, schema: _objectSpread2(_objectSpread2({}, schema), {}, { type: prop }) }); })); } if (schema.type === "null") { return current + complexityByType(_objectSpread2(_objectSpread2({}, schema), {}, { type: "null" })); } if (schema.oneOf) { if (schema.oneOf.length === 1) { return complexityByComposite("oneOf") + getSchemaComplexity({ current: current, schema: schema.oneOf[0] }); } return current + complexityByComposite("oneOf") + server.getSum(schema.oneOf.map(function (prop) { return getSchemaComplexity({ current: 0, schema: prop }); })); } // anyOf = oneOf but with 1 or more = `T extends oneOf ? T | T[] : never` if (schema.anyOf) { if (schema.anyOf.length === 1) { return complexityByComposite("anyOf") + getSchemaComplexity({ current: current, schema: schema.anyOf[0] }); } return current + complexityByComposite("anyOf") + server.getSum(schema.anyOf.map(function (prop) { return getSchemaComplexity({ current: 0, schema: prop }); })); } if (schema.allOf) { if (schema.allOf.length === 1) { return complexityByComposite("allOf") + getSchemaComplexity({ current: current, schema: schema.allOf[0] }); } return current + complexityByComposite("allOf") + server.getSum(schema.allOf.map(function (prop) { return getSchemaComplexity({ current: 0, schema: prop }); })); } if (!schema.type) return current; if (isPrimitiveType$1(schema.type)) { if (schema["enum"]) { return current + complexityByType(schema) + complexityByComposite("enum") + server.getSum(schema["enum"].map(function (prop) { return getSchemaComplexity({ current: 0, schema: prop }); })); } return current + complexityByType(schema); } if (schema.type === "array") { if (schema.items) { return complexityByComposite("array") + getSchemaComplexity({ current: current, schema: schema.items }); } return complexityByComposite("array") + getSchemaComplexity({ current: current, schema: undefined }); } if (schema.type === "object" || schema.properties || schema.additionalProperties) { if (schema.additionalProperties) { if (schema.additionalProperties === true) { return complexityByComposite("record") + getSchemaComplexity({ current: current, schema: undefined }); } return complexityByComposite("record") + getSchemaComplexity({ current: current, schema: schema.additionalProperties }); } if (schema.properties) { var props = Object.values(schema.properties); return current + complexityByComposite("object") + server.getSum(props.map(function (prop) { return getSchemaComplexity({ current: 0, schema: prop }); })); } return complexityByComposite("empty-object") + getSchemaComplexity({ current: current, schema: undefined }); } return current; } var CodeMeta = /*#__PURE__*/function () { function CodeMeta(schema, ctx) { var _meta$referencedBy; var meta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; _classCallCheck(this, CodeMeta); _defineProperty(this, "children", []); this.schema = schema; this.ctx = ctx; if (isReferenceObject(schema)) { this.ref = schema.$ref; } // @ts-expect-error this.meta = _objectSpread2({}, meta); this.meta.referencedBy = _toConsumableArray((_meta$referencedBy = meta === null || meta === void 0 ? void 0 : meta.referencedBy) !== null && _meta$referencedBy !== void 0 ? _meta$referencedBy : []); if (this.ref) { this.meta.referencedBy.push(this); } } _createClass(CodeMeta, [{ key: "codeString", get: function get() { if (this.code) return this.code; return this.ctx ? this.ctx.resolver.resolveRef(this.ref).normalized : this.ref; } }, { key: "complexity", get: function get() { return getSchemaComplexity({ current: 0, schema: this.schema }); } }, { key: "assign", value: function assign(code) { this.code = code; return this; } }, { key: "inherit", value: function inherit(parent) { if (parent) { parent.children.push(this); } return this; } }, { key: "toString", value: function toString() { return this.codeString; } }, { key: "toJSON", value: function toJSON() { return this.codeString; } }]); return CodeMeta; }(); var isBrokenAllOfItem = function isBrokenAllOfItem(item) { if (!openapi3Ts.isReferenceObject(item) && !!item.required && !item.type && !item.properties && !(item !== null && item !== void 0 && item.allOf) && !(item !== null && item !== void 0 && item.anyOf) && !item.oneOf) { return true; } return false; }; function inferRequiredSchema(schema) { if (!schema.allOf) { throw new Error("function inferRequiredSchema is specialized to handle item with required only in an allOf array."); } var _schema$allOf$reduce = schema.allOf.reduce(function (acc, cur) { if (isBrokenAllOfItem(cur)) { var _acc$; var required = cur.required; (_acc$ = acc[0]).push.apply(_acc$, _toConsumableArray(required !== null && required !== void 0 ? required : [])); } else { acc[1].push(cur); } return acc; }, [[], []]), _schema$allOf$reduce2 = _slicedToArray(_schema$allOf$reduce, 2), standaloneRequisites = _schema$allOf$reduce2[0], noRequiredOnlyAllof = _schema$allOf$reduce2[1]; var composedRequiredSchema = { properties: standaloneRequisites.reduce(function (acc, cur) { acc[cur] = { // type: "unknown" as SchemaObject["type"], }; return acc; }, {}), type: "object", required: standaloneRequisites }; return { noRequiredOnlyAllof: noRequiredOnlyAllof, composedRequiredSchema: composedRequiredSchema, patchRequiredSchemaInLoop: function patchRequiredSchemaInLoop(prop, resolver) { if (openapi3Ts.isReferenceObject(prop)) { var refType = resolver.getSchemaByRef(prop.$ref); if (refType) { composedRequiredSchema.required.forEach(function (required) { var _refType$properties$r, _refType$properties; composedRequiredSchema.properties[required] = (_refType$properties$r = refType === null || refType === void 0 ? void 0 : (_refType$properties = refType.properties) === null || _refType$properties === void 0 ? void 0 : _refType$properties[required]) !== null && _refType$properties$r !== void 0 ? _refType$properties$r : {}; }); } } else { var _prop$properties; var properties = (_prop$properties = prop["properties"]) !== null && _prop$properties !== void 0 ? _prop$properties : {}; composedRequiredSchema.required.forEach(function (required) { if (properties[required]) { var _properties$required; composedRequiredSchema.properties[required] = (_properties$required = properties[required]) !== null && _properties$required !== void 0 ? _properties$required : {}; } }); } } }; } /** * @see https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schemaObject * @see https://github.com/colinhacks/zod */ var circularRef = ""; // eslint-disable-next-line sonarjs/cognitive-complexity function getZodSchema(_ref) { var _options$schemaRefine, _options$schemaRefine2; var $schema = _ref.schema, ctx = _ref.ctx, inheritedMeta = _ref.meta, options = _ref.options; if (!$schema) { throw new Error("Schema is required"); } var schema = (_options$schemaRefine = options === null || options === void 0 ? void 0 : (_options$schemaRefine2 = options.schemaRefiner) === null || _options$schemaRefine2 === void 0 ? void 0 : _options$schemaRefine2.call(options, $schema, inheritedMeta)) !== null && _options$schemaRefine !== void 0 ? _options$schemaRefine : $schema; var code = new CodeMeta(schema, ctx, inheritedMeta); var meta = { parent: code.inherit(inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.parent), referencedBy: _toConsumableArray(code.meta.referencedBy) }; var refsPath = code.meta.referencedBy.slice(0, -1).map(function (prev) { return ctx ? ctx.resolver.resolveRef(prev.ref).normalized : prev.ref; }); if (isReferenceObject(schema)) { var _ctx$resolver$resolve; if (!ctx) throw new Error("Context is required"); var schemaName = (_ctx$resolver$resolve = ctx.resolver.resolveRef(schema.$ref)) === null || _ctx$resolver$resolve === void 0 ? void 0 : _ctx$resolver$resolve.normalized; // circular(=recursive) reference if (refsPath.length > 1 && refsPath.includes(schemaName)) { circularRef = code.ref; return code.assign(ctx.zodSchemaByName[code.ref]); } var result = ctx.zodSchemaByName[schema.$ref]; if (!result) { var actualSchema = ctx.resolver.getSchemaByRef(schema.$ref); if (!actualSchema) { throw new Error("Schema ".concat(schema.$ref, " not found")); } result = getZodSchema({ schema: actualSchema, ctx: ctx, meta: meta, options: options }).toString(); } if (ctx.zodSchemaByName[schemaName]) { return code; } ctx.zodSchemaByName[schemaName] = result; return code; } if (Array.isArray(schema.type)) { if (schema.type.length === 1) { return getZodSchema({ schema: _objectSpread2(_objectSpread2({}, schema), {}, { type: schema.type[0] }), ctx: ctx, meta: meta, options: options }); } return code.assign("z.union([".concat(schema.type.map(function (prop) { return getZodSchema({ schema: _objectSpread2(_objectSpread2({}, schema), {}, { type: prop }), ctx: ctx, meta: meta, options: options }); }).join(", "), "])")); } if (schema.type === "null") { return code.assign("z.null()"); } if (schema.oneOf) { var _schema$oneOf; if (schema.oneOf.length === 1) { var _type = getZodSchema({ schema: schema.oneOf[0], ctx: ctx, meta: meta, options: options }); return code.assign(_type.toString()); } /* when there are multiple allOf we are unable to use a discriminatedUnion as this library adds an * 'z.and' to the schema that it creates which breaks type inference */ var hasMultipleAllOf = (_schema$oneOf = schema.oneOf) === null || _schema$oneOf === void 0 ? void 0 : _schema$oneOf.some(function (obj) { return openapi3Ts.isSchemaObject(obj) && ((obj === null || obj === void 0 ? void 0 : obj.allOf) || []).length > 1; }); if (schema.discriminator && !hasMultipleAllOf) { var propertyName = schema.discriminator.propertyName; var discriminatedUnionOptions = schema.oneOf.map(function (prop) { return getZodSchema({ schema: prop, ctx: ctx, meta: meta, options: options }); }); var isCircularDiscriminatedUnion = discriminatedUnionOptions.some(function (t) { return t.ref === circularRef; }); if (isCircularDiscriminatedUnion) { return code.assign("z.union([".concat(discriminatedUnionOptions.join(", "), "])")); } return code.assign("\n z.discriminatedUnion(\"".concat(propertyName, "\", [").concat(discriminatedUnionOptions.join(", "), "])\n ")); } return code.assign("z.union([".concat(schema.oneOf.map(function (prop) { return getZodSchema({ schema: prop, ctx: ctx, meta: meta, options: options }); }).join(", "), "])")); } // anyOf = oneOf but with 1 or more = `T extends oneOf ? T | T[] : never` if (schema.anyOf) { if (schema.anyOf.length === 1) { var _type2 = getZodSchema({ schema: schema.anyOf[0], ctx: ctx, meta: meta, options: options }); return code.assign(_type2.toString()); } var types = schema.anyOf.map(function (prop) { return getZodSchema({ schema: prop, ctx: ctx, meta: meta, options: options }); }).map(function (type) { if ("type" in type.schema) { if (Array.isArray(type.schema.type)) ; else { var _schemaType = type.schema.type.toLowerCase(); !isPrimitiveType$1(_schemaType); } } return type.toString(); }).join(", "); return code.assign("z.union([".concat(types, "])")); } if (schema.allOf) { if (schema.allOf.length === 1) { var _type3 = getZodSchema({ schema: schema.allOf[0], ctx: ctx, meta: meta, options: options }); return code.assign(_type3.toString()); } var _inferRequiredSchema = inferRequiredSchema(schema), patchRequiredSchemaInLoop = _inferRequiredSchema.patchRequiredSchemaInLoop, noRequiredOnlyAllof = _inferRequiredSchema.noRequiredOnlyAllof, composedRequiredSchema = _inferRequiredSchema.composedRequiredSchema; var _types = noRequiredOnlyAllof.map(function (prop) { var zodSchema = getZodSchema({ schema: prop, ctx: ctx, meta: meta, options: options }); (ctx === null || ctx === void 0 ? void 0 : ctx.resolver) && patchRequiredSchemaInLoop(prop, ctx.resolver); return zodSchema; }); if (composedRequiredSchema.required.length) { _types.push(getZodSchema({ schema: composedRequiredSchema, ctx: ctx, meta: meta, options: options })); } var first = _types.at(0); var rest = _types.slice(1).map(function (type) { return "and(".concat(type.toString(), ")"); }).join("."); return code.assign("".concat(first.toString(), ".").concat(rest)); } var schemaType = schema.type ? schema.type.toLowerCase() : undefined; if (schemaType && isPrimitiveType$1(schemaType)) { if (schema["enum"]) { if (schemaType === "string") { if (schema["enum"].length === 1) { var value = schema["enum"][0]; var valueString = value === null ? "null" : "\"".concat(value, "\""); return code.assign("z.literal(".concat(valueString, ")")); } // eslint-disable-next-line sonarjs/no-nested-template-literals return code.assign("z.enum([".concat(schema["enum"].map(function (value) { return value === null ? "null" : "\"".concat(value, "\""); }).join(", "), "])")); } if (schema["enum"].some(function (e) { return typeof e === "string"; })) { return code.assign("z.never()"); } if (schema["enum"].length === 1) { var _value = schema["enum"][0]; return code.assign("z.literal(".concat(_value === null ? "null" : _value, ")")); } return code.assign( // eslint-disable-next-line sonarjs/no-nested-template-literals "z.union([".concat(schema["enum"].map(function (value) { return "z.literal(".concat(value === null ? "null" : value, ")"); }).join(", "), "])")); } return code.assign(tsPattern.match(schemaType)["with"]("integer", function () { return "z.number()"; })["with"]("string", function () { return tsPattern.match(schema.format)["with"]("binary", function () { return "z.instanceof(File)"; }).otherwise(function () { return "z.string()"; }); }).otherwise(function (type) { return "z.".concat(type, "()"); })); } var readonly = options !== null && options !== void 0 && options.allReadonly ? ".readonly()" : ""; if (schemaType === "array") { if (schema.items) { return code.assign("z.array(".concat(getZodSchema({ schema: schema.items, ctx: ctx, meta: meta, options: options }).toString()).concat(getZodChain({ schema: schema.items, meta: _objectSpread2(_objectSpread2({}, meta), {}, { isRequired: true }), options: options }), ")").concat(readonly)); } return code.assign("z.array(z.any())".concat(readonly)); } if (schemaType === "object" || schema.properties || schema.additionalProperties) { var _schema$required; // additional properties default to true if additionalPropertiesDefaultValue not provided var additionalPropsD