UNPKG

oas

Version:

Comprehensive tooling for working with OpenAPI definitions

718 lines (708 loc) 27 kB
import { SchemaObject, OASDocument, DataForHAR, OperationObject, HttpMethods, SecurityRequirementObject, KeyedSecuritySchemeObject, SecurityType, TagObject, ParameterObject, MediaTypeObject, ResponseObject, PathItemObject, OAS31Document } from './types.js'; interface MediaTypeExample { description?: string; summary?: string; title?: string; value: unknown; } type ResponseExamples = { mediaTypes: Record<string, MediaTypeExample[]>; onlyHeaders?: boolean; status: string; }[]; type CallbackExamples = { example: ResponseExamples; expression: string; identifier: string; method: string; }[]; interface SchemaWrapper { $schema?: string; deprecatedProps?: SchemaWrapper; description?: string; label?: string; schema: SchemaObject; type: string; } /** * The order of this object determines how they will be sorted in the compiled JSON Schema * representation. * * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameter-object} * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object} */ declare const types: Record<keyof OASDocument, string>; interface getParametersAsJSONSchemaOptions { /** * Contains an object of user defined schema defaults. */ globalDefaults?: Record<string, unknown>; /** * If you wish to hide properties that are marked as being `readOnly`. */ hideReadOnlyProperties?: boolean; /** * If you wish to hide properties that are marked as being `writeOnly`. */ hideWriteOnlyProperties?: boolean; /** * If you wish to include discriminator mapping `$ref` components alongside your * `discriminator` in schemas. Defaults to `true`. */ includeDiscriminatorMappingRefs?: boolean; /** * If you want the output to be two objects: body (contains `body` and `formData` JSON * Schema) and metadata (contains `path`, `query`, `cookie`, and `header`). */ mergeIntoBodyAndMetadata?: boolean; /** * If you wish to **not** split out deprecated properties into a separate `deprecatedProps` * object. */ retainDeprecatedProperties?: boolean; /** * With a transformer you can transform any data within a given schema, like say if you want * to rewrite a potentially unsafe `title` that might be eventually used as a JS variable * name, just make sure to return your transformed schema. */ transformer?: (schema: SchemaObject) => SchemaObject; } declare function getParametersAsJSONSchema(operation: Operation, api: OASDocument, opts?: getParametersAsJSONSchemaOptions): SchemaWrapper[]; type RequestBodyExamples = { examples: MediaTypeExample[]; mediaType: string; }[]; type ExampleGroups = Record<string, { /** * Array of custom code samples that contain `correspondingExample` key. * Mutually exclusive of `request`. Note that if this object is present, * there may or may not be corresponding responses in the `response` object. */ customCodeSamples?: (Extensions['code-samples'][number] & { /** * The index in the originally defined `code-samples` array */ originalIndex: number; })[]; /** * Title of example group. This is derived from the `summary` field of one of * the operation's example objects. The precedence is as follows (from highest to lowest): * 1. The first custom code sample's `name` field. * 2. The first request parameter (e.g., cookie/header/path/query) example object that * contains a `summary` field * 3. The request body example object's `summary` field * 4. The response example object's `summary` field * * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#example-object} * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#example-object} */ name: string; /** * Object containing the example request data for the current example key. * Mutually exclusive of `customCodeSamples`. If `customCodeSamples` is present, * any request example definitions are ignored. */ request?: DataForHAR; /** * Object containing the example response data for the current example key. */ response?: { /** * The content type of the current example * * @example "application/json" * @example "text/plain" */ mediaType: string; /** * The entire response example object. The example value itself is contained * within `value`. * * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#example-object} * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#example-object} */ mediaTypeExample: MediaTypeExample; /** * The HTTP status code for the current response example * * @example "2xx" * @example "400" */ status: string; }; }>; declare class Operation { /** * Schema of the operation from the API Definition. */ schema: OperationObject; /** * OpenAPI API Definition that this operation originated from. */ api: OASDocument; /** * Path that this operation is targeted towards. */ path: string; /** * HTTP Method that this operation is targeted towards. */ method: HttpMethods; /** * The primary Content Type that this operation accepts. */ contentType: string; /** * An object with groups of all example definitions (body/header/query/path/response/etc.) */ exampleGroups: ExampleGroups; /** * Request body examples for this operation. */ requestBodyExamples: RequestBodyExamples; /** * Response examples for this operation. */ responseExamples: ResponseExamples; /** * Callback examples for this operation (if it has callbacks). */ callbackExamples: CallbackExamples; /** * Flattened out arrays of both request and response headers that are utilized on this operation. */ headers: { request: string[]; response: string[]; }; constructor(api: OASDocument, path: string, method: HttpMethods, operation: OperationObject); getSummary(): string; getDescription(): string; getContentType(): string; isFormUrlEncoded(): boolean; isMultipart(): boolean; isJson(): boolean; isXml(): boolean; /** * Checks if the current operation is a webhook or not. * */ isWebhook(): boolean; /** * Returns an array of all security requirements associated wtih this operation. If none are * defined at the operation level, the securities for the entire API definition are returned * (with an empty array as a final fallback). * */ getSecurity(): SecurityRequirementObject[]; /** * Retrieve a collection of grouped security schemes. The inner array determines AND-grouped * security schemes, the outer array determines OR-groups. * * @see {@link https://swagger.io/docs/specification/authentication/#multiple} * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-requirement-object} * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-requirement-object} * @param filterInvalid Optional flag that, when set to `true`, filters out invalid/nonexistent * security schemes, rather than returning `false`. */ getSecurityWithTypes(filterInvalid?: boolean): ((false | { security: KeyedSecuritySchemeObject; type: SecurityType; })[] | false)[]; /** * Retrieve an object where the keys are unique scheme types, and the values are arrays * containing each security scheme of that type. * */ prepareSecurity(): Record<SecurityType, KeyedSecuritySchemeObject[]>; getHeaders(): Operation['headers']; /** * Determine if the operation has an operation present in its schema. Note that if one is present * in the schema but is an empty string then this will return false. * */ hasOperationId(): boolean; /** * Get an `operationId` for this operation. If one is not present (it's not required by the spec!) * a hash of the path and method will be returned instead. * */ getOperationId(opts?: { /** * Generate a JS method-friendly operation ID when one isn't present. * * For backwards compatiblity reasons this option will be indefinitely supported however we * recommend using `friendlyCase` instead as it's a heavily improved version of this option. * * @see {opts.friendlyCase} * @deprecated */ camelCase?: boolean; /** * Generate a human-friendly, but still camelCase, operation ID when one isn't present. The * difference between this and `camelCase` is that this also ensure that consecutive words are * not present in the resulting ID. For example, for the endpoint `/candidate/{candidate}` will * return `getCandidateCandidate` for `camelCase` however `friendlyCase` will return * `getCandidate`. * * The reason this friendliness is just not a part of the `camelCase` option is because we have * a number of consumers of the old operation ID style and making that change there would a * breaking change that we don't have any easy way to resolve. */ friendlyCase?: boolean; }): string; /** * Return an array of all tags, and their metadata, that exist on this operation. * */ getTags(): TagObject[]; /** * Return is the operation is flagged as `deprecated` or not. * */ isDeprecated(): boolean; /** * Determine if the operation has any (non-request body) parameters. * */ hasParameters(): boolean; /** * Return the parameters (non-request body) on the operation. * */ getParameters(): ParameterObject[]; /** * Determine if this operation has any required parameters. * */ hasRequiredParameters(): boolean; /** * Convert the operation into an array of JSON Schema schemas for each available type of * parameter available on the operation. * */ getParametersAsJSONSchema(opts?: getParametersAsJSONSchemaOptions): SchemaWrapper[]; /** * Get a single response for this status code, formatted as JSON schema. * * @param statusCode Status code to pull a JSON Schema response for. */ getResponseAsJSONSchema(statusCode: number | string, opts?: { /** * If you wish to include discriminator mapping `$ref` components alongside your * `discriminator` in schemas. Defaults to `true`. */ includeDiscriminatorMappingRefs?: boolean; /** * With a transformer you can transform any data within a given schema, like say if you want * to rewrite a potentially unsafe `title` that might be eventually used as a JS variable * name, just make sure to return your transformed schema. */ transformer?: (schema: SchemaObject) => SchemaObject; }): SchemaObject; /** * Get an array of all valid response status codes for this operation. * */ getResponseStatusCodes(): string[]; /** * Determine if the operation has any request bodies. * */ hasRequestBody(): boolean; /** * Retrieve the list of all available media types that the operations request body can accept. * * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object} * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object} */ getRequestBodyMediaTypes(): string[]; /** * Determine if this operation has a required request body. * */ hasRequiredRequestBody(): boolean; /** * Retrieve a specific request body content schema off this operation. * * If no media type is supplied this will return either the first available JSON-like request * body, or the first available if there are no JSON-like media types present. When this return * comes back it's in the form of an array with the first key being the selected media type, * followed by the media type object in question. * * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object} * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object} * @param mediaType Specific request body media type to retrieve if present. */ getRequestBody(mediaType?: string): MediaTypeObject | false | [string, MediaTypeObject, ...string[]]; /** * Retrieve an array of request body examples that this operation has. * */ getRequestBodyExamples(): RequestBodyExamples; /** * Return a specific response out of the operation by a given HTTP status code. * * @param statusCode Status code to pull a response object for. */ getResponseByStatusCode(statusCode: number | string): ResponseObject | boolean; /** * Retrieve an array of response examples that this operation has. * */ getResponseExamples(): ResponseExamples; /** * Determine if the operation has callbacks. * */ hasCallbacks(): boolean; /** * Retrieve a specific callback. * * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object} * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object} * @param identifier Callback identifier to look for. * @param expression Callback expression to look for. * @param method HTTP Method on the callback to look for. */ getCallback(identifier: string, expression: string, method: HttpMethods): Callback | false; /** * Retrieve an array of operations created from each callback. * */ getCallbacks(): (Callback | false)[] | false; /** * Retrieve an array of callback examples that this operation has. * */ getCallbackExamples(): CallbackExamples; /** * Determine if a given a custom specification extension exists within the operation. * * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions} * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions} * @param extension Specification extension to lookup. */ hasExtension(extension: string): boolean; /** * Retrieve a custom specification extension off of the operation. * * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions} * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions} * @param extension Specification extension to lookup. * * @deprecated Use `oas.getExtension(extension, operation)` instead. */ getExtension(extension: string | keyof Extensions): any; /** * Returns an object with groups of all example definitions (body/header/query/path/response/etc.). * The examples are grouped by their key when defined via the `examples` map. * * Any custom code samples defined via the `x-readme.code-samples` extension are returned, * regardless of if they have a matching response example. * * For standard OAS request parameter (e.g., body/header/query/path/etc.) examples, * they are only present in the return object if they have a corresponding response example * (i.e., a response example with the same key in the `examples` map). */ getExampleGroups(): ExampleGroups; } declare class Callback extends Operation { /** * The identifier that this callback is set to. */ identifier: string; /** * The parent path item object that this Callback exists within. */ parentSchema: PathItemObject; constructor(oas: OASDocument, path: string, method: HttpMethods, operation: OperationObject, identifier: string, parentPathItem: PathItemObject); /** * Return the primary identifier for this callback. * * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object} * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object} */ getIdentifier(): string; getSummary(): string; getDescription(): string; getParameters(): ParameterObject[]; } declare class Webhook extends Operation { /** * OpenAPI API Definition that this webhook originated from. */ api: OAS31Document; getSummary(): string; getDescription(): string; } /** * Enables custom-written code samples to be set for your operations. Use this if you have specific * formatting that may not be followed by the auto-generated code samples. Custom code samples are * treated as static content. * * This extension only be placed at the operation level. * * @defaultValue [] * @see {@link https://docs.readme.com/main/docs/openapi-extensions#custom-code-samples} * @example * { * "x-readme": { * "code-samples": [ * { * "language": "curl", * "code": "curl -X POST https://api.example.com/v2/alert", * "name": "Custom cURL snippet", * "install": "brew install curl" * }, * { * "language": "php", * "code": "<?php echo \"This is our custom PHP code snippet.\"; ?>", * "name": "Custom PHP snippet" * } * ] * } * } */ declare const CODE_SAMPLES = "code-samples"; /** * Disables the API Explorer's "Try It" button, preventing users from making API requests from * within your docs. Users will still be able to fill out any entry fields (path or query * parameters, etc.), and code snippets will be auto-generated based on the user's input, however * to interact with your API the user will need to copy the code snippet and execute it outside of * your docs. * * This **does not** disable your API Reference documentation. * * @defaultValue true * @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-the-api-explorer} * @example * { * "x-readme": { * "explorer-enabled": true * } * } */ declare const EXPLORER_ENABLED = "explorer-enabled"; /** * Adds static headers to add to each request. Use this when there are specific headers unique to * your API. * * @defaultValue [] * @see {@link https://docs.readme.com/main/docs/openapi-extensions#static-headers} * @example * { * "x-readme": { * "headers": [ * { * "key": "X-Static-Header-One", * "value": "owlbert" * }, * { * "key": "X-Static-Header-Two", * "value": "owlivia" * } * ] * } * } */ declare const HEADERS = "headers"; /** * Disables API requests from the API Explorer's "Try It" button from being sent into our [API * Metrics](https://readme.com/metrics) for you and your users. Additionally on any API endpoint * that this is disabled on your users will not see lists or graphs of previous requests they've * made against that API endpoint — either through the API Explorer's interactivity or through one * of our [Metrics SDKs](https://docs.readme.com/main/docs/api-metrics-setup) (if you have those * installed on your API). * * @defaultValue true * @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-api-metrics} * @example * { * "x-readme": { * "metrics-defaults": false * } * } */ declare const METRICS_ENABLED = "metrics-enabled"; /** * Configuration options for OAuth flows in the API Explorer. * * @defaultValue {} * @see {@link https://docs.readme.com/main/docs/openapi-extensions#oauth-options} * @example * { * "x-readme": { * "oauth-options": { * "scopeSeparator": ",", * "useInsecureClientAuthentication": true * } * } * } */ declare const OAUTH_OPTIONS = "oauth-options"; /** * Controls the order of parameters on your API Reference pages. * * Your custom ordering **must** contain all of our available parameter types: * * - `path`: Path parameters * - `query`: Query parameters * - `body`: Non-`application/x-www-form-urlencoded` request body payloads * - `cookie`: Cookie parameters * - `form`: `application/x-www-form-urlencoded` request body payloads * - `header`: Header parameters * * @defaultValue ['path', 'query', 'body', 'cookie', 'form', 'header'] * @see {@link https://docs.readme.com/main/docs/openapi-extensions#parameter-ordering} * @example * { * "x-readme": { * "parameter-ordering": ['path', 'query', 'header', 'cookie', 'body', 'form'] * } * } */ declare const PARAMETER_ORDERING = "parameter-ordering"; /** * Toggles the CORS proxy used when making API requests from within your docs (via the "Try It" * button). If your API is already set up to return CORS headers, you can safely disable this * feature. * * Disabling the CORS proxy will make the request directly from the user's browser and will prevent * [Metrics](https://docs.readme.com/main/docs/getting-started-with-metrics) data from being logged * by us unless [Metrics have already set up on your backend](https://docs.readme.com/main/docs/api-metrics-setup). * * @defaultValue true * @see {@link https://docs.readme.com/main/docs/openapi-extensions#cors-proxy-enabled} * @example * { * "x-readme": { * "proxy-enabled": true * } * } */ declare const PROXY_ENABLED = "proxy-enabled"; /** * Toggles what languages are shown by default for code samples in the API Explorer. This only * affects what languages are initially shown to the user; if the user picks another language from * the three-dot menu, that language and the respective auto-generated code snippet will also appear * as an option in the API Explorer. * * @defaultValue ['shell', 'node', 'ruby', 'php', 'python', 'java', 'csharp'] * @see {@link https://docs.readme.com/main/docs/openapi-extensions#code-sample-languages} * @example * { * "x-readme": { * "samples-languages": ["shell", "node", "ruby", "javascript", "python"] * } * } */ declare const SAMPLES_LANGUAGES = "samples-languages"; /** * Toggles if you will see code snippets for ReadMe's SDK code generator tool `api`. * * @defaultValue true * @see {@link https://api.readme.dev} * @example * { * "x-readme": { * "simple-mode": false * } * } */ declare const SIMPLE_MODE = "simple-mode"; /** * If `true`, tags are generated from the file top-down. If `false`, we sort the tags * based off the `tags` array in the OAS file. * * @defaultValue false * @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-tag-sorting} * @example * { * "x-readme": { * "disable-tag-sorting": true * } * } */ declare const DISABLE_TAG_SORTING = "disable-tag-sorting"; interface Extensions { [CODE_SAMPLES]: { /** * Custom code snippet * @example "curl -X POST https://api.example.com/v2/alert" */ code: string; /** * Corresponding response example * @see {@link https://docs.readme.com/main/docs/openapi-extensions#corresponding-response-examples} */ correspondingExample?: string; /** * Library installation instructions * @example "brew install httpie" * @example "npm install node-fetch@2 --save" */ install?: string; /** * Language for syntax highlighting * @example shell */ language: string; /** * Optional title for code sample * @example "Custom cURL snippet" */ name?: string; }[]; [DISABLE_TAG_SORTING]: boolean; [EXPLORER_ENABLED]: boolean; [HEADERS]: Record<string, number | string>[]; [METRICS_ENABLED]: boolean; [OAUTH_OPTIONS]: { /** * Scope separator for passing scopes. This value will be URL-encoded. * * @example "," * @example "+" * @default " " * @see {@link https://datatracker.ietf.org/doc/html/rfc6749#section-3.3} Scope separators information from OAuth 2.0 specification */ scopeSeparator?: string; /** * When enabled, the client credentials (i.e., `client_id` and `client_secret`) are sent in the request body (NOT recommended). * When disabled (the default), client credentials are sent using the HTTP Basic Authentication scheme. * * This is applicable for all requests to the token endpoint. * * @see {@link https://datatracker.ietf.org/doc/html/rfc6749#section-2.3.1} * @see {@link https://datatracker.ietf.org/doc/html/rfc6749#section-3.2} * * @example true * @default false */ useInsecureClientAuthentication?: boolean; }; [PARAMETER_ORDERING]: ('body' | 'cookie' | 'form' | 'header' | 'path' | 'query')[]; [PROXY_ENABLED]: boolean; [SAMPLES_LANGUAGES]: string[]; [SIMPLE_MODE]: boolean; } declare const extensionDefaults: Extensions; /** * Determing if an OpenAPI definition has an extension set in its root schema. * */ declare function hasRootExtension(extension: string | keyof Extensions, api: OASDocument): boolean; /** * Retrieve a custom specification extension off of the API definition. * */ declare function getExtension(extension: string | keyof Extensions, api: OASDocument, operation?: Operation): any; /** * Validate that the data for an instanceof our `PARAMETER_ORDERING` extension is properly * configured. * * @private */ declare function validateParameterOrdering(ordering: (typeof extensionDefaults)[typeof PARAMETER_ORDERING] | undefined, extension: string): void; export { Callback as C, DISABLE_TAG_SORTING as D, type Extensions as E, HEADERS as H, METRICS_ENABLED as M, Operation as O, PARAMETER_ORDERING as P, type SchemaWrapper as S, Webhook as W, getParametersAsJSONSchema as a, CODE_SAMPLES as b, EXPLORER_ENABLED as c, OAUTH_OPTIONS as d, PROXY_ENABLED as e, SAMPLES_LANGUAGES as f, type getParametersAsJSONSchemaOptions as g, SIMPLE_MODE as h, extensionDefaults as i, hasRootExtension as j, getExtension as k, types as t, validateParameterOrdering as v };