https://project.mdnd-it.cc/work_packages/94
This commit is contained in:
2025-08-23 04:25:28 +02:00
parent 725516ad6c
commit 19cfa031d0
25823 changed files with 1095587 additions and 2801760 deletions
@@ -0,0 +1,439 @@
import { OpenAPI } from "openapi-types";
export = SwaggerParser;
/**
* This is the default export of Swagger Parser. You can creates instances of this class using new SwaggerParser(), or you can just call its static methods.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html
*/
declare class SwaggerParser {
/**
* The `api` property is the parsed/bundled/dereferenced OpenAPI definition. This is the same value that is passed to the callback function (or Promise) when calling the parse, bundle, or dereference methods.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#api
*/
public api: OpenAPI.Document;
/**
* The $refs property is a `$Refs` object, which lets you access all of the externally-referenced files in the OpenAPI definition, as well as easily get and set specific values in the OpenAPI definition using JSON pointers.
*
* This is the same value that is passed to the callback function (or Promise) when calling the `resolve` method.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#refs
*/
public $refs: SwaggerParser.$Refs;
/**
* Parses, dereferences, and validates the given Swagger API.
* Depending on the options, validation can include JSON Schema validation and/or Swagger Spec validation.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#validateapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the dereferenced OpenAPI definition
*/
public validate(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public validate(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public validate(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public validate(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public validate(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public validate(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* Parses, dereferences, and validates the given Swagger API.
* Depending on the options, validation can include JSON Schema validation and/or Swagger Spec validation.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#validateapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the dereferenced OpenAPI definition
*/
public static validate(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public static validate(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static validate(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static validate(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public static validate(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public static validate(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* Dereferences all `$ref` pointers in the OpenAPI definition, replacing each reference with its resolved value. This results in an API definition that does not contain any `$ref` pointers. Instead, it's a normal JavaScript object tree that can easily be crawled and used just like any other JavaScript object. This is great for programmatic usage, especially when using tools that don't understand JSON references.
*
* The dereference method maintains object reference equality, meaning that all `$ref` pointers that point to the same object will be replaced with references to the same object. Again, this is great for programmatic usage, but it does introduce the risk of circular references, so be careful if you intend to serialize the API definition using `JSON.stringify()`. Consider using the bundle method instead, which does not create circular references.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#dereferenceapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the dereferenced OpenAPI definition
*/
public dereference(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public dereference(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public dereference(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public dereference(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public dereference(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public dereference(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* Dereferences all `$ref` pointers in the OpenAPI definition, replacing each reference with its resolved value. This results in an API definition that does not contain any `$ref` pointers. Instead, it's a normal JavaScript object tree that can easily be crawled and used just like any other JavaScript object. This is great for programmatic usage, especially when using tools that don't understand JSON references.
*
* The dereference method maintains object reference equality, meaning that all `$ref` pointers that point to the same object will be replaced with references to the same object. Again, this is great for programmatic usage, but it does introduce the risk of circular references, so be careful if you intend to serialize the API definition using `JSON.stringify()`. Consider using the bundle method instead, which does not create circular references.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#dereferenceapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the dereferenced OpenAPI definition
*/
public static dereference(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public static dereference(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static dereference(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static dereference(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public static dereference(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public static dereference(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* Bundles all referenced files/URLs into a single API definition that only has internal `$ref` pointers. This lets you split-up your API definition however you want while you're building it, but easily combine all those files together when it's time to package or distribute the API definition to other people. The resulting API definition size will be small, since it will still contain internal JSON references rather than being fully-dereferenced.
*
* This also eliminates the risk of circular references, so the API definition can be safely serialized using `JSON.stringify()`.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#bundleapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the bundled API definition object
*/
public bundle(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public bundle(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public bundle(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public bundle(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public bundle(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public bundle(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* Bundles all referenced files/URLs into a single API definition that only has internal `$ref` pointers. This lets you split-up your API definition however you want while you're building it, but easily combine all those files together when it's time to package or distribute the API definition to other people. The resulting API definition size will be small, since it will still contain internal JSON references rather than being fully-dereferenced.
*
* This also eliminates the risk of circular references, so the API definition can be safely serialized using `JSON.stringify()`.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#bundleapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the bundled API definition object
*/
public static bundle(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public static bundle(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static bundle(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static bundle(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public static bundle(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public static bundle(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* *This method is used internally by other methods, such as `bundle` and `dereference`. You probably won't need to call this method yourself.*
*
* Parses the given OpenAPI definition file (in JSON or YAML format), and returns it as a JavaScript object. This method `does not` resolve `$ref` pointers or dereference anything. It simply parses one file and returns it.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#parseapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. The path can be absolute or relative. In Node, the path is relative to `process.cwd()`. In the browser, it's relative to the URL of the page.
* @param options (optional)
* @param callback (optional) A callback that will receive the parsed OpenAPI definition object, or an error
*/
public parse(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public parse(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public parse(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public parse(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public parse(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public parse(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* *This method is used internally by other methods, such as `bundle` and `dereference`. You probably won't need to call this method yourself.*
*
* Parses the given OpenAPI definition file (in JSON or YAML format), and returns it as a JavaScript object. This method `does not` resolve `$ref` pointers or dereference anything. It simply parses one file and returns it.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#parseapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. The path can be absolute or relative. In Node, the path is relative to `process.cwd()`. In the browser, it's relative to the URL of the page.
* @param options (optional)
* @param callback (optional) A callback that will receive the parsed OpenAPI definition object, or an error
*/
public static parse(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public static parse(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static parse(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static parse(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public static parse(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public static parse(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* *This method is used internally by other methods, such as `bundle` and `dereference`. You probably won't need to call this method yourself.*
*
* Resolves all JSON references (`$ref` pointers) in the given OpenAPI definition file. If it references any other files/URLs, then they will be downloaded and resolved as well. This method **does not** dereference anything. It simply gives you a `$Refs` object, which is a map of all the resolved references and their values.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#resolveapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive a `$Refs` object
*/
public resolve(api: string | OpenAPI.Document, callback: SwaggerParser.$RefsCallback): void;
public resolve(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.$RefsCallback): void;
public resolve(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.$RefsCallback): void;
public resolve(api: string | OpenAPI.Document): Promise<SwaggerParser.$Refs>;
public resolve(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<SwaggerParser.$Refs>;
public resolve(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<SwaggerParser.$Refs>;
/**
* *This method is used internally by other methods, such as `bundle` and `dereference`. You probably won't need to call this method yourself.*
*
* Resolves all JSON references (`$ref` pointers) in the given OpenAPI definition file. If it references any other files/URLs, then they will be downloaded and resolved as well. This method **does not** dereference anything. It simply gives you a `$Refs` object, which is a map of all the resolved references and their values.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#resolveapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive a `$Refs` object
*/
public static resolve(api: string | OpenAPI.Document, callback: SwaggerParser.$RefsCallback): void;
public static resolve(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.$RefsCallback): void;
public static resolve(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.$RefsCallback): void;
public static resolve(api: string | OpenAPI.Document): Promise<SwaggerParser.$Refs>;
public static resolve(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<SwaggerParser.$Refs>;
public static resolve(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<SwaggerParser.$Refs>;
}
// eslint-disable-next-line no-redeclare
declare namespace SwaggerParser {
export type ApiCallback = (err: Error | null, api?: OpenAPI.Document) => any;
export type $RefsCallback = (err: Error | null, $refs?: $Refs) => any;
/**
* See https://apitools.dev/swagger-parser/docs/options.html
*/
export interface Options {
/**
* The `parse` options determine how different types of files will be parsed.
*
* JSON Schema `$Ref` Parser comes with built-in JSON, YAML, plain-text, and binary parsers, any of which you can configure or disable. You can also add your own custom parsers if you want.
*/
parse?: {
json?: ParserOptions | boolean;
yaml?: ParserOptions | boolean;
text?: (ParserOptions & { encoding?: string }) | boolean;
[key: string]: ParserOptions | boolean | undefined;
};
/**
* The `resolve` options control how Swagger Parser will resolve file paths and URLs, and how those files will be read/downloaded.
*
* JSON Schema `$Ref` Parser comes with built-in support for HTTP and HTTPS, as well as support for local files (when running in Node.js). You can configure or disable either of these built-in resolvers. You can also add your own custom resolvers if you want.
*/
resolve?: {
/**
* Determines whether external $ref pointers will be resolved. If this option is disabled, then external `$ref` pointers will simply be ignored.
*/
external?: boolean;
file?: Partial<ResolverOptions> | boolean;
http?: HTTPResolverOptions | boolean;
};
/**
* The `dereference` options control how JSON Schema `$Ref` Parser will dereference `$ref` pointers within the JSON schema.
*/
dereference?: {
/**
* Determines whether circular `$ref` pointers are handled.
*
* If set to `false`, then a `ReferenceError` will be thrown if the schema contains any circular references.
*
* If set to `"ignore"`, then circular references will simply be ignored. No error will be thrown, but the `$Refs.circular` property will still be set to `true`.
*/
circular?: boolean | "ignore";
};
/**
* The `validate` options control how Swagger Parser will validate the API.
*/
validate?: {
/**
* If set to `false`, then validating against the Swagger 2.0 Schema or OpenAPI 3.0 Schema is disabled.
*/
schema?: boolean;
/**
* If set to `false`, then validating against the Swagger 2.0 Specification is disabled.
*/
spec?: boolean;
};
}
export interface HTTPResolverOptions extends Partial<ResolverOptions> {
/**
* You can specify any HTTP headers that should be sent when downloading files. For example, some servers may require you to set the `Accept` or `Referrer` header.
*/
headers?: object;
/**
* The amount of time (in milliseconds) to wait for a response from the server when downloading files. The default is 5 seconds.
*/
timeout?: number;
/**
* The maximum number of HTTP redirects to follow per file. The default is 5. To disable automatic following of redirects, set this to zero.
*/
redirects?: number;
/**
* Set this to `true` if you're downloading files from a CORS-enabled server that requires authentication
*/
withCredentials?: boolean;
}
/**
* JSON Schema `$Ref` Parser comes with built-in resolvers for HTTP and HTTPS URLs, as well as local filesystem paths (when running in Node.js). You can add your own custom resolvers to support additional protocols, or even replace any of the built-in resolvers with your own custom implementation.
*
* See https://apitools.dev/json-schema-ref-parser/docs/plugins/resolvers.html
*/
export interface ResolverOptions {
/**
* All resolvers have an order property, even the built-in resolvers. If you don't specify an order property, then your resolver will run last. Specifying `order: 1`, like we did in this example, will make your resolver run first. Or you can squeeze your resolver in-between some of the built-in resolvers. For example, `order: 101` would make it run after the file resolver, but before the HTTP resolver. You can see the order of all the built-in resolvers by looking at their source code.
*
* The order property and canRead property are related to each other. For each file that Swagger Parser needs to resolve, it first determines which resolvers can read that file by checking their canRead property. If only one resolver matches a file, then only that one resolver is called, regardless of its order. If multiple resolvers match a file, then those resolvers are tried in order until one of them successfully reads the file. Once a resolver successfully reads the file, the rest of the resolvers are skipped.
*/
order?: number;
/**
* The `canRead` property tells JSON Schema `$Ref` Parser what kind of files your resolver can read. In this example, we've simply specified a regular expression that matches "mogodb://" URLs, but we could have used a simple boolean, or even a function with custom logic to determine which files to resolve. Here are examples of each approach:
*/
canRead: boolean | RegExp | string | string[] | ((file: FileInfo) => boolean);
/**
* This is where the real work of a resolver happens. The `read` method accepts the same file info object as the `canRead` function, but rather than returning a boolean value, the `read` method should return the contents of the file. The file contents should be returned in as raw a form as possible, such as a string or a byte array. Any further parsing or processing should be done by parsers.
*
* Unlike the `canRead` function, the `read` method can also be asynchronous. This might be important if your resolver needs to read data from a database or some other external source. You can return your asynchronous value using either an ES6 Promise or a Node.js-style error-first callback. Of course, if your resolver has the ability to return its data synchronously, then that's fine too. Here are examples of all three approaches:
*/
read(
file: FileInfo,
callback?: (error: Error | null, data: string | null) => any
): string | Buffer | Promise<string | Buffer>;
}
export interface ParserOptions {
/**
* Parsers run in a specific order, relative to other parsers. For example, a parser with `order: 5` will run before a parser with `order: 10`. If a parser is unable to successfully parse a file, then the next parser is tried, until one succeeds or they all fail.
*
* You can change the order in which parsers run, which is useful if you know that most of your referenced files will be a certain type, or if you add your own custom parser that you want to run first.
*/
order?: number;
/**
* All of the built-in parsers allow empty files by default. The JSON and YAML parsers will parse empty files as `undefined`. The text parser will parse empty files as an empty string. The binary parser will parse empty files as an empty byte array.
*
* You can set `allowEmpty: false` on any parser, which will cause an error to be thrown if a file empty.
*/
allowEmpty?: boolean;
/**
* Determines which parsers will be used for which files.
*
* A regular expression can be used to match files by their full path. A string (or array of strings) can be used to match files by their file extension. Or a function can be used to perform more complex matching logic. See the custom parser docs for details.
*/
canParse?: boolean | RegExp | string | string[] | ((file: FileInfo) => boolean);
}
/**
* JSON Schema `$Ref` Parser supports plug-ins, such as resolvers and parsers. These plug-ins can have methods such as `canRead()`, `read()`, `canParse()`, and `parse()`. All of these methods accept the same object as their parameter: an object containing information about the file being read or parsed.
*
* The file info object currently only consists of a few properties, but it may grow in the future if plug-ins end up needing more information.
*
* See https://apitools.dev/json-schema-ref-parser/docs/plugins/file-info-object.html
*/
export interface FileInfo {
/**
* The full URL of the file. This could be any type of URL, including "http://", "https://", "file://", "ftp://", "mongodb://", or even a local filesystem path (when running in Node.js).
*/
url: string;
/**
* The lowercase file extension, such as ".json", ".yaml", ".txt", etc.
*/
extension: string;
/**
* The raw file contents, in whatever form they were returned by the resolver that read the file.
*/
data: string | Buffer;
}
/**
* When you call the resolve method, the value that gets passed to the callback function (or Promise) is a $Refs object. This same object is accessible via the parser.$refs property of SwaggerParser objects.
*
* This object is a map of JSON References and their resolved values. It also has several convenient helper methods that make it easy for you to navigate and manipulate the JSON References.
*
* See https://apitools.dev/swagger-parser/docs/refs.html
*/
export class $Refs {
/**
* This property is true if the API definition contains any circular references. You may want to check this property before serializing the dereferenced API definition as JSON, since JSON.stringify() does not support circular references by default.
*
* See https://apitools.dev/swagger-parser/docs/refs.html#circular
*/
public circular: boolean;
/**
* Returns the paths/URLs of all the files in your API definition (including the main API definition file).
*
* See https://apitools.dev/swagger-parser/docs/refs.html#pathstypes
*
* @param types (optional) Optionally only return certain types of paths ("file", "http", etc.)
*/
public paths(...types: string[]): string[]
/**
* Returns a map of paths/URLs and their correspond values.
*
* See https://apitools.dev/swagger-parser/docs/refs.html#valuestypes
*
* @param types (optional) Optionally only return values from certain locations ("file", "http", etc.)
*/
public values(...types: string[]): { [url: string]: any }
/**
* Returns `true` if the given path exists in the OpenAPI definition; otherwise, returns `false`
*
* See https://apitools.dev/swagger-parser/docs/refs.html#existsref
*
* @param $ref The JSON Reference path, optionally with a JSON Pointer in the hash
*/
public exists($ref: string): boolean
/**
* Gets the value at the given path in the OpenAPI definition. Throws an error if the path does not exist.
*
* See https://apitools.dev/swagger-parser/docs/refs.html#getref
*
* @param $ref The JSON Reference path, optionally with a JSON Pointer in the hash
*/
public get($ref: string): any
/**
* Sets the value at the given path in the OpenAPI definition. If the property, or any of its parents, don't exist, they will be created.
*
* @param $ref The JSON Reference path, optionally with a JSON Pointer in the hash
* @param value The value to assign. Can be anything (object, string, number, etc.)
*/
public set($ref: string, value: any): void
}
}
@@ -0,0 +1,187 @@
/* eslint-disable no-unused-vars */
"use strict";
const validateSchema = require("./validators/schema");
const validateSpec = require("./validators/spec");
const normalizeArgs = require("@apidevtools/json-schema-ref-parser/lib/normalize-args");
const util = require("./util");
const Options = require("./options");
const maybe = require("call-me-maybe");
const { ono } = require("@jsdevtools/ono");
const $RefParser = require("@apidevtools/json-schema-ref-parser");
const dereference = require("@apidevtools/json-schema-ref-parser/lib/dereference");
module.exports = SwaggerParser;
/**
* This class parses a Swagger 2.0 or 3.0 API, resolves its JSON references and their resolved values,
* and provides methods for traversing, dereferencing, and validating the API.
*
* @class
* @augments $RefParser
*/
function SwaggerParser () {
$RefParser.apply(this, arguments);
}
util.inherits(SwaggerParser, $RefParser);
SwaggerParser.parse = $RefParser.parse;
SwaggerParser.resolve = $RefParser.resolve;
SwaggerParser.bundle = $RefParser.bundle;
SwaggerParser.dereference = $RefParser.dereference;
/**
* Alias {@link $RefParser#schema} as {@link SwaggerParser#api}
*/
Object.defineProperty(SwaggerParser.prototype, "api", {
configurable: true,
enumerable: true,
get () {
return this.schema;
}
});
/**
* Parses the given Swagger API.
* This method does not resolve any JSON references.
* It just reads a single file in JSON or YAML format, and parse it as a JavaScript object.
*
* @param {string} [path] - The file path or URL of the JSON schema
* @param {object} [api] - The Swagger API object. This object will be used instead of reading from `path`.
* @param {ParserOptions} [options] - Options that determine how the API is parsed
* @param {Function} [callback] - An error-first callback. The second parameter is the parsed API object.
* @returns {Promise} - The returned promise resolves with the parsed API object.
*/
SwaggerParser.prototype.parse = async function (path, api, options, callback) {
let args = normalizeArgs(arguments);
args.options = new Options(args.options);
try {
let schema = await $RefParser.prototype.parse.call(this, args.path, args.schema, args.options);
if (schema.swagger) {
// Verify that the parsed object is a Swagger API
if (schema.swagger === undefined || schema.info === undefined || schema.paths === undefined) {
throw ono.syntax(`${args.path || args.schema} is not a valid Swagger API definition`);
}
else if (typeof schema.swagger === "number") {
// This is a very common mistake, so give a helpful error message
throw ono.syntax('Swagger version number must be a string (e.g. "2.0") not a number.');
}
else if (typeof schema.info.version === "number") {
// This is a very common mistake, so give a helpful error message
throw ono.syntax('API version number must be a string (e.g. "1.0.0") not a number.');
}
else if (schema.swagger !== "2.0") {
throw ono.syntax(`Unrecognized Swagger version: ${schema.swagger}. Expected 2.0`);
}
}
else {
let supportedVersions = ["3.0.0", "3.0.1", "3.0.2", "3.0.3"];
// Verify that the parsed object is a Openapi API
if (schema.openapi === undefined || schema.info === undefined || schema.paths === undefined) {
throw ono.syntax(`${args.path || args.schema} is not a valid Openapi API definition`);
}
else if (typeof schema.openapi === "number") {
// This is a very common mistake, so give a helpful error message
throw ono.syntax('Openapi version number must be a string (e.g. "3.0.0") not a number.');
}
else if (typeof schema.info.version === "number") {
// This is a very common mistake, so give a helpful error message
throw ono.syntax('API version number must be a string (e.g. "1.0.0") not a number.');
}
else if (supportedVersions.indexOf(schema.openapi) === -1) {
throw ono.syntax(
`Unsupported OpenAPI version: ${schema.openapi}. ` +
`Swagger Parser only supports versions ${supportedVersions.join(", ")}`
);
}
}
// Looks good!
return maybe(args.callback, Promise.resolve(schema));
}
catch (err) {
return maybe(args.callback, Promise.reject(err));
}
};
/**
* Parses, dereferences, and validates the given Swagger API.
* Depending on the options, validation can include JSON Schema validation and/or Swagger Spec validation.
*
* @param {string} [path] - The file path or URL of the JSON schema
* @param {object} [api] - The Swagger API object. This object will be used instead of reading from `path`.
* @param {ParserOptions} [options] - Options that determine how the API is parsed, dereferenced, and validated
* @param {Function} [callback] - An error-first callback. The second parameter is the parsed API object.
* @returns {Promise} - The returned promise resolves with the parsed API object.
*/
SwaggerParser.validate = function (path, api, options, callback) {
let Class = this; // eslint-disable-line consistent-this
let instance = new Class();
return instance.validate.apply(instance, arguments);
};
/**
* Parses, dereferences, and validates the given Swagger API.
* Depending on the options, validation can include JSON Schema validation and/or Swagger Spec validation.
*
* @param {string} [path] - The file path or URL of the JSON schema
* @param {object} [api] - The Swagger API object. This object will be used instead of reading from `path`.
* @param {ParserOptions} [options] - Options that determine how the API is parsed, dereferenced, and validated
* @param {Function} [callback] - An error-first callback. The second parameter is the parsed API object.
* @returns {Promise} - The returned promise resolves with the parsed API object.
*/
SwaggerParser.prototype.validate = async function (path, api, options, callback) {
let me = this;
let args = normalizeArgs(arguments);
args.options = new Options(args.options);
// ZSchema doesn't support circular objects, so don't dereference circular $refs yet
// (see https://github.com/zaggino/z-schema/issues/137)
let circular$RefOption = args.options.dereference.circular;
args.options.validate.schema && (args.options.dereference.circular = "ignore");
try {
await this.dereference(args.path, args.schema, args.options);
// Restore the original options, now that we're done dereferencing
args.options.dereference.circular = circular$RefOption;
if (args.options.validate.schema) {
// Validate the API against the Swagger schema
// NOTE: This is safe to do, because we haven't dereferenced circular $refs yet
validateSchema(me.api);
if (me.$refs.circular) {
if (circular$RefOption === true) {
// The API has circular references,
// so we need to do a second-pass to fully-dereference it
dereference(me, args.options);
}
else if (circular$RefOption === false) {
// The API has circular references, and they're not allowed, so throw an error
throw ono.reference("The API contains circular references");
}
}
}
if (args.options.validate.spec) {
// Validate the API against the Swagger spec
validateSpec(me.api);
}
return maybe(args.callback, Promise.resolve(me.schema));
}
catch (err) {
return maybe(args.callback, Promise.reject(err));
}
};
/**
* The Swagger object
* https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swagger-object
*
* @typedef {{swagger: string, info: {}, paths: {}}} SwaggerObject
*/
@@ -0,0 +1,35 @@
"use strict";
const $RefParserOptions = require("@apidevtools/json-schema-ref-parser/lib/options");
const schemaValidator = require("./validators/schema");
const specValidator = require("./validators/spec");
const util = require("util");
module.exports = ParserOptions;
/**
* Options that determine how Swagger APIs are parsed, resolved, dereferenced, and validated.
*
* @param {object|ParserOptions} [_options] - Overridden options
* @class
* @augments $RefParserOptions
*/
function ParserOptions (_options) {
$RefParserOptions.call(this, ParserOptions.defaults);
$RefParserOptions.apply(this, arguments);
}
ParserOptions.defaults = {
/**
* Determines how the API definition will be validated.
*
* You can add additional validators of your own, replace an existing one with
* your own implemenation, or disable any validator by setting it to false.
*/
validate: {
schema: schemaValidator,
spec: specValidator,
},
};
util.inherits(ParserOptions, $RefParserOptions);
@@ -0,0 +1,11 @@
"use strict";
const util = require("util");
exports.format = util.format;
exports.inherits = util.inherits;
/**
* Regular Expression that matches Swagger path params.
*/
exports.swaggerParamRegExp = /\{([^/}]+)}/g;
@@ -0,0 +1,70 @@
"use strict";
const util = require("../util");
const { ono } = require("@jsdevtools/ono");
const ZSchema = require("z-schema");
const { openapi } = require("@apidevtools/openapi-schemas");
module.exports = validateSchema;
let zSchema = initializeZSchema();
/**
* Validates the given Swagger API against the Swagger 2.0 or 3.0 schema.
*
* @param {SwaggerObject} api
*/
function validateSchema (api) {
// Choose the appropriate schema (Swagger or OpenAPI)
let schema = api.swagger ? openapi.v2 : openapi.v3;
// Validate against the schema
let isValid = zSchema.validate(api, schema);
if (!isValid) {
let err = zSchema.getLastError();
let message = "Swagger schema validation failed. \n" + formatZSchemaError(err.details);
throw ono.syntax(err, { details: err.details }, message);
}
}
/**
* Performs one-time initialization logic to prepare for Swagger Schema validation.
*/
function initializeZSchema () {
// HACK: Delete the OpenAPI schema IDs because ZSchema can't resolve them
delete openapi.v2.id;
delete openapi.v3.id;
// The OpenAPI 3.0 schema uses "uri-reference" formats.
// Assume that any non-whitespace string is valid.
ZSchema.registerFormat("uri-reference", (value) => value.trim().length > 0);
// Configure ZSchema
return new ZSchema({
breakOnFirstError: true,
noExtraKeywords: true,
ignoreUnknownFormats: false,
reportPathAsArray: true
});
}
/**
* Z-Schema validation errors are a nested tree structure.
* This function crawls that tree and builds an error message string.
*
* @param {object[]} errors - The Z-Schema error details
* @param {string} [indent] - The whitespace used to indent the error message
* @returns {string}
*/
function formatZSchemaError (errors, indent) {
indent = indent || " ";
let message = "";
for (let error of errors) {
message += util.format(`${indent}${error.message} at #/${error.path.join("/")}\n`);
if (error.inner) {
message += formatZSchemaError(error.inner, indent + " ");
}
}
return message;
}
@@ -0,0 +1,344 @@
"use strict";
const util = require("../util");
const { ono } = require("@jsdevtools/ono");
const swaggerMethods = require("@apidevtools/swagger-methods");
const primitiveTypes = ["array", "boolean", "integer", "number", "string"];
const schemaTypes = ["array", "boolean", "integer", "number", "string", "object", "null", undefined];
module.exports = validateSpec;
/**
* Validates parts of the Swagger 2.0 spec that aren't covered by the Swagger 2.0 JSON Schema.
*
* @param {SwaggerObject} api
*/
function validateSpec (api) {
if (api.openapi) {
// We don't (yet) support validating against the OpenAPI spec
return;
}
let paths = Object.keys(api.paths || {});
let operationIds = [];
for (let pathName of paths) {
let path = api.paths[pathName];
let pathId = "/paths" + pathName;
if (path && pathName.indexOf("/") === 0) {
validatePath(api, path, pathId, operationIds);
}
}
let definitions = Object.keys(api.definitions || {});
for (let definitionName of definitions) {
let definition = api.definitions[definitionName];
let definitionId = "/definitions/" + definitionName;
validateRequiredPropertiesExist(definition, definitionId);
}
}
/**
* Validates the given path.
*
* @param {SwaggerObject} api - The entire Swagger API object
* @param {object} path - A Path object, from the Swagger API
* @param {string} pathId - A value that uniquely identifies the path
* @param {string} operationIds - An array of collected operationIds found in other paths
*/
function validatePath (api, path, pathId, operationIds) {
for (let operationName of swaggerMethods) {
let operation = path[operationName];
let operationId = pathId + "/" + operationName;
if (operation) {
let declaredOperationId = operation.operationId;
if (declaredOperationId) {
if (operationIds.indexOf(declaredOperationId) === -1) {
operationIds.push(declaredOperationId);
}
else {
throw ono.syntax(`Validation failed. Duplicate operation id '${declaredOperationId}'`);
}
}
validateParameters(api, path, pathId, operation, operationId);
let responses = Object.keys(operation.responses || {});
for (let responseName of responses) {
let response = operation.responses[responseName];
let responseId = operationId + "/responses/" + responseName;
validateResponse(responseName, (response || {}), responseId);
}
}
}
}
/**
* Validates the parameters for the given operation.
*
* @param {SwaggerObject} api - The entire Swagger API object
* @param {object} path - A Path object, from the Swagger API
* @param {string} pathId - A value that uniquely identifies the path
* @param {object} operation - An Operation object, from the Swagger API
* @param {string} operationId - A value that uniquely identifies the operation
*/
function validateParameters (api, path, pathId, operation, operationId) {
let pathParams = path.parameters || [];
let operationParams = operation.parameters || [];
// Check for duplicate path parameters
try {
checkForDuplicates(pathParams);
}
catch (e) {
throw ono.syntax(e, `Validation failed. ${pathId} has duplicate parameters`);
}
// Check for duplicate operation parameters
try {
checkForDuplicates(operationParams);
}
catch (e) {
throw ono.syntax(e, `Validation failed. ${operationId} has duplicate parameters`);
}
// Combine the path and operation parameters,
// with the operation params taking precedence over the path params
let params = pathParams.reduce((combinedParams, value) => {
let duplicate = combinedParams.some((param) => {
return param.in === value.in && param.name === value.name;
});
if (!duplicate) {
combinedParams.push(value);
}
return combinedParams;
}, operationParams.slice());
validateBodyParameters(params, operationId);
validatePathParameters(params, pathId, operationId);
validateParameterTypes(params, api, operation, operationId);
}
/**
* Validates body and formData parameters for the given operation.
*
* @param {object[]} params - An array of Parameter objects
* @param {string} operationId - A value that uniquely identifies the operation
*/
function validateBodyParameters (params, operationId) {
let bodyParams = params.filter((param) => { return param.in === "body"; });
let formParams = params.filter((param) => { return param.in === "formData"; });
// There can only be one "body" parameter
if (bodyParams.length > 1) {
throw ono.syntax(
`Validation failed. ${operationId} has ${bodyParams.length} body parameters. Only one is allowed.`,
);
}
else if (bodyParams.length > 0 && formParams.length > 0) {
// "body" params and "formData" params are mutually exclusive
throw ono.syntax(
`Validation failed. ${operationId} has body parameters and formData parameters. Only one or the other is allowed.`,
);
}
}
/**
* Validates path parameters for the given path.
*
* @param {object[]} params - An array of Parameter objects
* @param {string} pathId - A value that uniquely identifies the path
* @param {string} operationId - A value that uniquely identifies the operation
*/
function validatePathParameters (params, pathId, operationId) {
// Find all {placeholders} in the path string
let placeholders = pathId.match(util.swaggerParamRegExp) || [];
// Check for duplicates
for (let i = 0; i < placeholders.length; i++) {
for (let j = i + 1; j < placeholders.length; j++) {
if (placeholders[i] === placeholders[j]) {
throw ono.syntax(
`Validation failed. ${operationId} has multiple path placeholders named ${placeholders[i]}`);
}
}
}
params = params.filter((param) => { return param.in === "path"; });
for (let param of params) {
if (param.required !== true) {
throw ono.syntax(
"Validation failed. Path parameters cannot be optional. " +
`Set required=true for the "${param.name}" parameter at ${operationId}`,
);
}
let match = placeholders.indexOf("{" + param.name + "}");
if (match === -1) {
throw ono.syntax(
`Validation failed. ${operationId} has a path parameter named "${param.name}", ` +
`but there is no corresponding {${param.name}} in the path string`
);
}
placeholders.splice(match, 1);
}
if (placeholders.length > 0) {
throw ono.syntax(`Validation failed. ${operationId} is missing path parameter(s) for ${placeholders}`);
}
}
/**
* Validates data types of parameters for the given operation.
*
* @param {object[]} params - An array of Parameter objects
* @param {object} api - The entire Swagger API object
* @param {object} operation - An Operation object, from the Swagger API
* @param {string} operationId - A value that uniquely identifies the operation
*/
function validateParameterTypes (params, api, operation, operationId) {
for (let param of params) {
let parameterId = operationId + "/parameters/" + param.name;
let schema, validTypes;
switch (param.in) {
case "body":
schema = param.schema;
validTypes = schemaTypes;
break;
case "formData":
schema = param;
validTypes = primitiveTypes.concat("file");
break;
default:
schema = param;
validTypes = primitiveTypes;
}
validateSchema(schema, parameterId, validTypes);
validateRequiredPropertiesExist(schema, parameterId);
if (schema.type === "file") {
// "file" params must consume at least one of these MIME types
let formData = /multipart\/(.*\+)?form-data/;
let urlEncoded = /application\/(.*\+)?x-www-form-urlencoded/;
let consumes = operation.consumes || api.consumes || [];
let hasValidMimeType = consumes.some((consume) => {
return formData.test(consume) || urlEncoded.test(consume);
});
if (!hasValidMimeType) {
throw ono.syntax(
`Validation failed. ${operationId} has a file parameter, so it must consume multipart/form-data ` +
"or application/x-www-form-urlencoded",
);
}
}
}
}
/**
* Checks the given parameter list for duplicates, and throws an error if found.
*
* @param {object[]} params - An array of Parameter objects
*/
function checkForDuplicates (params) {
for (let i = 0; i < params.length - 1; i++) {
let outer = params[i];
for (let j = i + 1; j < params.length; j++) {
let inner = params[j];
if (outer.name === inner.name && outer.in === inner.in) {
throw ono.syntax(`Validation failed. Found multiple ${outer.in} parameters named "${outer.name}"`);
}
}
}
}
/**
* Validates the given response object.
*
* @param {string} code - The HTTP response code (or "default")
* @param {object} response - A Response object, from the Swagger API
* @param {string} responseId - A value that uniquely identifies the response
*/
function validateResponse (code, response, responseId) {
if (code !== "default" && (code < 100 || code > 599)) {
throw ono.syntax(`Validation failed. ${responseId} has an invalid response code (${code})`);
}
let headers = Object.keys(response.headers || {});
for (let headerName of headers) {
let header = response.headers[headerName];
let headerId = responseId + "/headers/" + headerName;
validateSchema(header, headerId, primitiveTypes);
}
if (response.schema) {
let validTypes = schemaTypes.concat("file");
if (validTypes.indexOf(response.schema.type) === -1) {
throw ono.syntax(
`Validation failed. ${responseId} has an invalid response schema type (${response.schema.type})`);
}
else {
validateSchema(response.schema, responseId + "/schema", validTypes);
}
}
}
/**
* Validates the given Swagger schema object.
*
* @param {object} schema - A Schema object, from the Swagger API
* @param {string} schemaId - A value that uniquely identifies the schema object
* @param {string[]} validTypes - An array of the allowed schema types
*/
function validateSchema (schema, schemaId, validTypes) {
if (validTypes.indexOf(schema.type) === -1) {
throw ono.syntax(
`Validation failed. ${schemaId} has an invalid type (${schema.type})`);
}
if (schema.type === "array" && !schema.items) {
throw ono.syntax(`Validation failed. ${schemaId} is an array, so it must include an "items" schema`);
}
}
/**
* Validates that the declared properties of the given Swagger schema object actually exist.
*
* @param {object} schema - A Schema object, from the Swagger API
* @param {string} schemaId - A value that uniquely identifies the schema object
*/
function validateRequiredPropertiesExist (schema, schemaId) {
/**
* Recursively collects all properties of the schema and its ancestors. They are added to the props object.
*/
function collectProperties (schemaObj, props) {
if (schemaObj.properties) {
for (let property in schemaObj.properties) {
if (schemaObj.properties.hasOwnProperty(property)) {
props[property] = schemaObj.properties[property];
}
}
}
if (schemaObj.allOf) {
for (let parent of schemaObj.allOf) {
collectProperties(parent, props);
}
}
}
if (schema.required && Array.isArray(schema.required)) {
let props = {};
collectProperties(schema, props);
for (let requiredProperty of schema.required) {
if (!props[requiredProperty]) {
throw ono.syntax(
`Validation failed. Property '${requiredProperty}' listed as required but does not exist in '${schemaId}'`
);
}
}
}
}