oas 28.6.2 → 28.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/analyzer/index.cjs +6 -6
  2. package/dist/analyzer/index.js +4 -4
  3. package/dist/{chunk-6VA5PEAW.cjs → chunk-3IRCRFDX.cjs} +34 -28
  4. package/dist/chunk-3IRCRFDX.cjs.map +1 -0
  5. package/dist/{chunk-DKWZF6ZJ.js → chunk-AFEHY5RG.js} +3 -3
  6. package/dist/{chunk-3GXXYRQ6.js → chunk-C3GC3WSK.js} +33 -27
  7. package/dist/chunk-C3GC3WSK.js.map +1 -0
  8. package/dist/{chunk-UI7OWREK.js → chunk-CCR5GBJV.js} +84 -4
  9. package/dist/{chunk-UI7OWREK.js.map → chunk-CCR5GBJV.js.map} +1 -1
  10. package/dist/{chunk-4DBNE7RJ.cjs → chunk-LNQ2I4RW.cjs} +1 -1
  11. package/dist/{chunk-4DBNE7RJ.cjs.map → chunk-LNQ2I4RW.cjs.map} +1 -1
  12. package/dist/{chunk-W3LSKLU6.js → chunk-LV26LN7C.js} +1 -1
  13. package/dist/{chunk-W3LSKLU6.js.map → chunk-LV26LN7C.js.map} +1 -1
  14. package/dist/{chunk-47YGVG2J.cjs → chunk-OSHPUFYW.cjs} +101 -21
  15. package/dist/chunk-OSHPUFYW.cjs.map +1 -0
  16. package/dist/{chunk-D7V2DDZ5.cjs → chunk-WN7KLBGW.cjs} +21 -21
  17. package/dist/{chunk-D7V2DDZ5.cjs.map → chunk-WN7KLBGW.cjs.map} +1 -1
  18. package/dist/index.cjs +5 -5
  19. package/dist/index.js +4 -4
  20. package/dist/operation/index.cjs +4 -4
  21. package/dist/operation/index.js +3 -3
  22. package/dist/operation/lib/get-parameters-as-json-schema.cjs +2 -2
  23. package/dist/operation/lib/get-parameters-as-json-schema.js +1 -1
  24. package/dist/utils.cjs +5 -3
  25. package/dist/utils.cjs.map +1 -1
  26. package/dist/utils.d.cts +16 -1
  27. package/dist/utils.d.ts +16 -1
  28. package/dist/utils.js +4 -2
  29. package/package.json +4 -4
  30. package/dist/chunk-3GXXYRQ6.js.map +0 -1
  31. package/dist/chunk-47YGVG2J.cjs.map +0 -1
  32. package/dist/chunk-6VA5PEAW.cjs.map +0 -1
  33. /package/dist/{chunk-DKWZF6ZJ.js.map → chunk-AFEHY5RG.js.map} +0 -0
package/dist/utils.js CHANGED
@@ -1,15 +1,17 @@
1
1
  import {
2
2
  findSchemaDefinition,
3
3
  supportedMethods
4
- } from "./chunk-W3LSKLU6.js";
4
+ } from "./chunk-LV26LN7C.js";
5
5
  import {
6
+ getParameterContentType,
6
7
  matches_mimetype_default,
7
8
  types
8
- } from "./chunk-3GXXYRQ6.js";
9
+ } from "./chunk-C3GC3WSK.js";
9
10
  import "./chunk-NBQXNFZT.js";
10
11
  import "./chunk-L3V5TF63.js";
11
12
  export {
12
13
  findSchemaDefinition,
14
+ getParameterContentType,
13
15
  types as jsonSchemaTypes,
14
16
  matches_mimetype_default as matchesMimeType,
15
17
  supportedMethods
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oas",
3
- "version": "28.6.2",
3
+ "version": "28.7.0",
4
4
  "description": "Comprehensive tooling for working with OpenAPI definitions",
5
5
  "license": "MIT",
6
6
  "author": "ReadMe <support@readme.io> (https://readme.com)",
@@ -87,7 +87,7 @@
87
87
  "watch": "tsc --watch"
88
88
  },
89
89
  "dependencies": {
90
- "@readme/openapi-parser": "^5.3.1",
90
+ "@readme/openapi-parser": "^5.4.0",
91
91
  "@types/json-schema": "^7.0.11",
92
92
  "json-schema-merge-allof": "^0.8.1",
93
93
  "jsonpath-plus": "^10.0.0",
@@ -98,7 +98,7 @@
98
98
  "remove-undefined-objects": "^7.0.0"
99
99
  },
100
100
  "devDependencies": {
101
- "@readme/oas-examples": "^7.1.2",
101
+ "@readme/oas-examples": "^7.2.0",
102
102
  "@types/json-schema-merge-allof": "^0.6.5",
103
103
  "@types/memoizee": "^0.4.12",
104
104
  "@types/node": "^22.14.0",
@@ -107,5 +107,5 @@
107
107
  "vitest": "^4.0.8"
108
108
  },
109
109
  "prettier": "@readme/standards/prettier",
110
- "gitHead": "c9763db0343f1c33ff2ed70d70039fa189502c58"
110
+ "gitHead": "866765a738dd4114d6e31a0b5bb6b021d04d778f"
111
111
  }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/clone-object.ts","../src/lib/helpers.ts","../src/lib/matches-mimetype.ts","../src/lib/openapi-to-json-schema.ts","../src/operation/lib/get-parameters-as-json-schema.ts"],"sourcesContent":["export function cloneObject<T>(obj: T): T {\n if (typeof obj === 'undefined') {\n return undefined;\n }\n\n return JSON.parse(JSON.stringify(obj));\n}\n","import type { SchemaObject } from '../types.js';\n\nexport function hasSchemaType(schema: SchemaObject, discriminator: 'array' | 'object'): boolean {\n if (Array.isArray(schema.type)) {\n return schema.type.includes(discriminator);\n }\n\n return schema.type === discriminator;\n}\n\nexport function isObject(val: unknown): val is Record<string, unknown> {\n return typeof val === 'object' && val !== null && !Array.isArray(val);\n}\n\nexport function isPrimitive(val: unknown): val is boolean | number | string {\n return typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean';\n}\n","function matchesMediaType(types: string[], mediaType: string): boolean {\n return types.some(type => {\n return mediaType.indexOf(type) > -1;\n });\n}\n\n// biome-ignore lint/style/noDefaultExport: This is safe for now.\nexport default {\n formUrlEncoded: (mimeType: string): boolean => {\n return matchesMediaType(['application/x-www-form-urlencoded'], mimeType);\n },\n\n json: (contentType: string): boolean => {\n return matchesMediaType(\n ['application/json', 'application/x-json', 'text/json', 'text/x-json', '+json'],\n contentType,\n );\n },\n\n multipart: (contentType: string): boolean => {\n return matchesMediaType(\n ['multipart/mixed', 'multipart/related', 'multipart/form-data', 'multipart/alternative'],\n contentType,\n );\n },\n\n wildcard: (contentType: string): boolean => {\n return contentType === '*/*';\n },\n\n xml: (contentType: string): boolean => {\n return matchesMediaType(\n [\n 'application/xml',\n 'application/xml-external-parsed-entity',\n 'application/xml-dtd',\n 'text/xml',\n 'text/xml-external-parsed-entity',\n '+xml',\n ],\n contentType,\n );\n },\n};\n","import type { JSONSchema7TypeName } from 'json-schema';\nimport type { OpenAPIV3_1 } from 'openapi-types';\nimport type { JSONSchema, OASDocument, RequestBodyObject, SchemaObject } from '../types.js';\n\nimport mergeJSONSchemaAllOf from 'json-schema-merge-allof';\nimport jsonpointer from 'jsonpointer';\nimport removeUndefinedObjects from 'remove-undefined-objects';\n\nimport { isOpenAPI30, isRef, isSchema } from '../types.js';\nimport { hasSchemaType, isObject, isPrimitive } from './helpers.js';\n\n/**\n * This list has been pulled from `openapi-schema-to-json-schema` but been slightly modified to fit\n * within the constraints in which ReadMe uses the output from this library in schema form\n * rendering as while properties like `readOnly` aren't represented within JSON Schema, we support\n * it within that library's handling of OpenAPI-friendly JSON Schema.\n *\n * @see {@link https://github.com/openapi-contrib/openapi-schema-to-json-schema/blob/main/src/consts.ts}\n */\nconst UNSUPPORTED_SCHEMA_PROPS = [\n 'example', // OpenAPI supports `example` but we're mapping it to `examples` in this library.\n 'externalDocs',\n 'xml',\n] as const;\n\nexport interface toJSONSchemaOptions {\n /**\n * Whether or not to extend descriptions with a list of any present enums.\n */\n addEnumsToDescriptions?: boolean;\n\n /**\n * Current location within the schema -- this is a JSON pointer.\n */\n currentLocation?: string;\n\n /**\n * Object containing a global set of defaults that we should apply to schemas that match it.\n */\n globalDefaults?: Record<string, unknown>;\n\n /**\n * If you wish to hide properties that are marked as being `readOnly`.\n */\n hideReadOnlyProperties?: boolean;\n\n /**\n * If you wish to hide properties that are marked as being `writeOnly`.\n */\n hideWriteOnlyProperties?: boolean;\n\n /**\n * Is this schema the child of a polymorphic `allOf` schema?\n */\n isPolymorphicAllOfChild?: boolean;\n\n /**\n * Array of parent `default` schemas to utilize when attempting to path together schema defaults.\n */\n prevDefaultSchemas?: SchemaObject[];\n\n /**\n * Array of parent `example` schemas to utilize when attempting to path together schema examples.\n */\n prevExampleSchemas?: SchemaObject[];\n\n /**\n * A function that's called anytime a (circular) `$ref` is found.\n */\n refLogger?: (ref: string, type: 'discriminator' | 'ref') => void;\n\n /**\n * With a transformer you can transform any data within a given schema, like say if you want\n * to rewrite a potentially unsafe `title` that might be eventually used as a JS variable\n * name, just make sure to return your transformed schema.\n */\n transformer?: (schema: SchemaObject) => SchemaObject;\n}\n\n/**\n * Encode a string to be used as a JSON pointer.\n *\n * @see {@link https://tools.ietf.org/html/rfc6901}\n * @param str String to encode into string that can be used as a JSON pointer.\n */\nfunction encodePointer(str: string) {\n return str.replace('~', '~0').replace('/', '~1');\n}\n\nexport function getSchemaVersionString(schema: SchemaObject, api: OASDocument): string {\n // If we're not on OpenAPI 3.1+ then we should fall back to the default schema version.\n if (isOpenAPI30(api)) {\n // This should remain as an HTTP url, not HTTPS.\n return 'http://json-schema.org/draft-04/schema#';\n }\n\n /**\n * If the schema indicates the version, prefer that.\n *\n * We use `as` here because the schema *should* be an OAS 3.1 schema due to the `isOpenAPI30` check\n * above.\n */\n if ((schema as OpenAPIV3_1.SchemaObject).$schema) {\n return (schema as OpenAPIV3_1.SchemaObject).$schema;\n }\n\n // If the user defined a global schema version on their OAS document, prefer that.\n if (api.jsonSchemaDialect) {\n return api.jsonSchemaDialect;\n }\n\n return 'https://json-schema.org/draft/2020-12/schema#';\n}\n\nfunction isPolymorphicSchema(schema: SchemaObject): boolean {\n return 'allOf' in schema || 'anyOf' in schema || 'oneOf' in schema;\n}\n\nfunction isRequestBodySchema(schema: unknown): schema is RequestBodyObject {\n return 'content' in (schema as RequestBodyObject);\n}\n\n/**\n * Given a JSON pointer, a type of property to look for, and an array of schemas do a reverse\n * search through them until we find the JSON pointer, or part of it, within the array.\n *\n * This function will allow you to take a pointer like `/tags/name` and return back `buster` from\n * the following array:\n *\n * ```\n * [\n * {\n * example: {id: 20}\n * },\n * {\n * examples: {\n * distinctName: {\n * tags: {name: 'buster'}\n * }\n * }\n * }\n * ]\n * ```\n *\n * As with most things however, this is not without its quirks! If a deeply nested property shares\n * the same name as an example that's further up the stack (like `tags.id` and an example for `id`),\n * there's a chance that it'll be misidentified as having an example and receive the wrong value.\n *\n * That said, any example is usually better than no example though, so while it's quirky behavior\n * it shouldn't raise immediate cause for alarm.\n *\n * @see {@link https://tools.ietf.org/html/rfc6901}\n * @param property Specific type of schema property to look for a value for.\n * @param pointer JSON pointer to search for an example for.\n * @param schemas Array of previous schemas we've found relating to this pointer.\n */\nfunction searchForValueByPropAndPointer(\n property: 'default' | 'example',\n pointer: string,\n schemas: toJSONSchemaOptions['prevDefaultSchemas'] | toJSONSchemaOptions['prevExampleSchemas'] = [],\n) {\n if (!schemas.length || !pointer.length) {\n return undefined;\n }\n\n const locSplit = pointer.split('/').filter(Boolean).reverse();\n const pointers = [];\n\n let point = '';\n for (let i = 0; i < locSplit.length; i += 1) {\n point = `/${locSplit[i]}${point}`;\n pointers.push(point);\n }\n\n let foundValue: any;\n const rev = [...schemas].reverse();\n\n for (let i = 0; i < pointers.length; i += 1) {\n for (let ii = 0; ii < rev.length; ii += 1) {\n let schema = rev[ii];\n\n if (property === 'example') {\n if ('example' in schema) {\n schema = schema.example;\n } else {\n if (!Array.isArray(schema.examples) || !schema.examples.length) {\n continue;\n }\n\n // Prevent us from crashing if `examples` is a completely empty object.\n schema = [...schema.examples].shift();\n }\n } else {\n schema = schema.default;\n }\n\n try {\n foundValue = jsonpointer.get(schema, pointers[i]);\n } catch {\n // If the schema we're looking at is `{obj: null}` and our pointer is `/obj/propertyName`\n // `jsonpointer` will throw an error. If that happens, we should silently catch and toss it\n // and return no example.\n }\n\n if (foundValue !== undefined) {\n break;\n }\n }\n\n if (foundValue !== undefined) {\n break;\n }\n }\n\n return foundValue;\n}\n\n/**\n * Given an OpenAPI-flavored JSON Schema, make an effort to modify it so it's shaped more towards\n * stock JSON Schema.\n *\n * Why do this?\n *\n * 1. OpenAPI 3.0.x supports its own flavor of JSON Schema that isn't fully compatible with most\n * JSON Schema tooling (like `@readme/oas-form` or `@rjsf/core`).\n * 2. While validating an OpenAPI definition will prevent corrupted or improper schemas from\n * occuring, we have a lot of legacy schemas in ReadMe that were ingested before we had proper\n * validation in place, and as a result have some API definitions that will not pass validation\n * right now. In addition to reshaping OAS-JSON Schema into JSON Schema this library will also\n * fix these improper schemas: things like `type: object` having `items` instead of `properties`,\n * or `type: array` missing `items`.\n * 3. To ease the burden of polymorphic handling on our form rendering engine we make an attempt\n * to merge `allOf` schemas here.\n * 4. Additionally due to OpenAPI 3.0.x not supporting JSON Schema, in order to support the\n * `example` keyword that OAS supports, we need to do some work in here to remap it into\n * `examples`. However, since all we care about in respect to examples for usage within\n * `@readme/oas-form`, we're only retaining primitives. This *slightly* deviates from JSON\n * Schema in that JSON Schema allows for any schema to be an example, but since\n * `@readme/oas-form` can only actually **render** primitives, that's what we're retaining.\n * 5. Though OpenAPI 3.1 does support full JSON Schema, this library should be able to handle it\n * without any problems.\n *\n * And why use this over `@openapi-contrib/openapi-schema-to-json-schema`? Fortunately and\n * unfortunately we've got a lot of API definitions in our database that aren't currently valid so\n * we need to have a lot of bespoke handling for odd quirks, typos, and missing declarations that\n * might be present.\n *\n * @todo add support for `schema: false` and `not` cases.\n * @see {@link https://json-schema.org/draft/2019-09/json-schema-validation.html}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schema-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object}\n * @param data OpenAPI Schema Object to convert to pure JSON Schema.\n */\nexport function toJSONSchema(data: SchemaObject | boolean, opts: toJSONSchemaOptions = {}): SchemaObject {\n let schema = data === true ? {} : { ...data };\n const schemaAdditionalProperties = isSchema(schema) ? schema.additionalProperties : null;\n\n const {\n addEnumsToDescriptions,\n currentLocation,\n globalDefaults,\n hideReadOnlyProperties,\n hideWriteOnlyProperties,\n isPolymorphicAllOfChild,\n prevDefaultSchemas,\n prevExampleSchemas,\n refLogger,\n transformer,\n } = {\n addEnumsToDescriptions: false,\n currentLocation: '',\n globalDefaults: {},\n hideReadOnlyProperties: false,\n hideWriteOnlyProperties: false,\n isPolymorphicAllOfChild: false,\n prevDefaultSchemas: [] as toJSONSchemaOptions['prevDefaultSchemas'],\n prevExampleSchemas: [] as toJSONSchemaOptions['prevExampleSchemas'],\n refLogger: () => true,\n transformer: (s: SchemaObject) => s,\n ...opts,\n };\n\n // If this schema contains a `$ref`, it's circular and we shouldn't try to resolve it. Just\n // return and move along.\n if (isRef(schema)) {\n refLogger(schema.$ref, 'ref');\n\n return transformer({\n $ref: schema.$ref,\n });\n }\n\n // If we don't have a set type, but are dealing with an `anyOf`, `oneOf`, or `allOf`\n // representation let's run through them and make sure they're good.\n if (isSchema(schema, isPolymorphicAllOfChild)) {\n // If this is an `allOf` schema we should make an attempt to merge so as to ease the burden on\n // the tooling that ingests these schemas.\n if ('allOf' in schema && Array.isArray(schema.allOf)) {\n try {\n schema = mergeJSONSchemaAllOf(schema as JSONSchema, {\n ignoreAdditionalProperties: true,\n resolvers: {\n // `merge-json-schema-allof` by default takes the first `description` when you're\n // merging an `allOf` but because generally when you're merging two schemas together\n // with an `allOf` you want data in the subsequent schemas to be applied to the first\n // and `description` should be a part of that.\n description: (obj: string[]) => {\n return obj.slice(-1)[0];\n },\n\n // `merge-json-schema-allof` doesn't support merging enum arrays but since that's a\n // safe and simple operation as enums always contain primitives we can handle it\n // ourselves with a custom resolver.\n enum: (obj: unknown[]) => {\n let arr: unknown[] = [];\n obj.forEach(e => {\n arr = arr.concat(e);\n });\n\n return arr;\n },\n\n // for any unknown keywords (e.g., `example`, `format`, `x-readme-ref-name`),\n // we fallback to using the title resolver (which uses the first value found).\n // https://github.com/mokkabonna/json-schema-merge-allof/blob/ea2e48ee34415022de5a50c236eb4793a943ad11/src/index.js#L292\n // https://github.com/mokkabonna/json-schema-merge-allof/blob/ea2e48ee34415022de5a50c236eb4793a943ad11/README.md?plain=1#L147\n defaultResolver: mergeJSONSchemaAllOf.options.resolvers.title,\n } as unknown,\n }) as SchemaObject;\n } catch {\n // If we can't merge the `allOf` for whatever reason (like if one item is a `string` and\n // the other is a `object`) then we should completely remove it from the schema and continue\n // with whatever we've got. Why? If we don't, any tooling that's ingesting this will need\n // to account for the incompatible `allOf` and it may be subject to more breakages than\n // just not having it present would be.\n const { ...schemaWithoutAllOf } = schema;\n schema = schemaWithoutAllOf as SchemaObject;\n delete schema.allOf;\n }\n\n // If after merging the `allOf` this schema still contains a `$ref` then it's circular and\n // we shouldn't do anything else.\n if (isRef(schema)) {\n refLogger(schema.$ref, 'ref');\n\n return transformer({\n $ref: schema.$ref,\n });\n }\n }\n\n ['anyOf', 'oneOf'].forEach((polyType: 'anyOf' | 'oneOf') => {\n if (polyType in schema && Array.isArray(schema[polyType])) {\n schema[polyType].forEach((item, idx) => {\n const polyOptions: toJSONSchemaOptions = {\n addEnumsToDescriptions,\n currentLocation: `${currentLocation}/${idx}`,\n globalDefaults,\n hideReadOnlyProperties,\n hideWriteOnlyProperties,\n isPolymorphicAllOfChild: false,\n prevDefaultSchemas,\n prevExampleSchemas,\n refLogger,\n transformer,\n };\n\n // When `properties` or `items` are present alongside a polymorphic schema instead of\n // letting whatever JSON Schema interpreter is handling these constructed schemas we can\n // guide its hand a bit by manually transforming it into an inferred `allOf` of the\n // `properties` + the polymorph schema.\n //\n // This `allOf` schema will be merged together when fed through `toJSONSchema`.\n if ('properties' in schema) {\n schema[polyType][idx] = toJSONSchema(\n { required: schema.required, allOf: [item, { properties: schema.properties }] } as SchemaObject,\n polyOptions,\n );\n } else if ('items' in schema) {\n schema[polyType][idx] = toJSONSchema(\n { allOf: [item, { items: schema.items }] } as SchemaObject,\n polyOptions,\n );\n } else {\n schema[polyType][idx] = toJSONSchema(item as SchemaObject, polyOptions);\n }\n\n // Ensure that we don't have any invalid `required` booleans lying around.\n if (\n isObject(schema[polyType][idx]) &&\n 'required' in (schema[polyType][idx] as SchemaObject) &&\n typeof (schema[polyType][idx] as SchemaObject).required === 'boolean'\n ) {\n delete (schema[polyType][idx] as SchemaObject).required;\n }\n });\n }\n });\n\n if ('discriminator' in schema) {\n if ('mapping' in schema.discriminator && typeof schema.discriminator.mapping === 'object') {\n // Discriminator mappings aren't written as traditional `$ref` pointers so in order to log\n // them to the supplied `refLogger`.\n const mapping = schema.discriminator.mapping;\n Object.keys(mapping).forEach(k => {\n refLogger(mapping[k], 'discriminator');\n });\n }\n }\n }\n\n // If this schema is malformed for some reason, let's do our best to repair it.\n if (!('type' in schema) && !isPolymorphicSchema(schema) && !isRequestBodySchema(schema)) {\n if ('properties' in schema) {\n schema.type = 'object';\n } else if ('items' in schema) {\n schema.type = 'array';\n } else {\n // If there's still no `type` on the schema we should leave it alone because we don't have a\n // great way to know if it's part of a nested schema that should, and couldn't be merged,\n // into another, or it's just purely malformed.\n //\n // Whatever tooling that ingests the generated schema should handle it however it needs to.\n }\n }\n\n if ('type' in schema) {\n // `nullable` isn't a thing in JSON Schema but it was in OpenAPI 3.0 so we should retain and\n // translate it into something that's compatible with JSON Schema.\n if ('nullable' in schema) {\n if (schema.nullable) {\n if (Array.isArray(schema.type)) {\n schema.type.push('null');\n } else if (schema.type !== null && schema.type !== 'null') {\n schema.type = [schema.type, 'null'];\n }\n }\n\n delete schema.nullable;\n }\n\n if (schema.type === null) {\n // `type: null` is possible in JSON Schema but we're translating it to a string version\n // so we don't need to worry about asserting nullish types in our implementations of this\n // generated schema.\n schema.type = 'null';\n } else if (Array.isArray(schema.type)) {\n if (schema.type.includes(null)) {\n schema.type[schema.type.indexOf(null)] = 'null';\n }\n\n schema.type = Array.from(new Set(schema.type));\n\n // We don't need `type: [<type>]` when we can just as easily make it `type: <type>`.\n if (schema.type.length === 1) {\n schema.type = schema.type.shift();\n } else if (schema.type.includes('array') || schema.type.includes('boolean') || schema.type.includes('object')) {\n // If we have a `null` type but there's only two types present then we can remove `null`\n // as an option and flag the whole schema as `nullable`.\n const isNullable = schema.type.includes('null');\n\n if (schema.type.length === 2 && isNullable) {\n // If this is `array | null` or `object | null` then we don't need to do anything.\n } else {\n // If this mixed type has non-primitives then we for convenience of our implementation\n // we're moving them into a `oneOf`.\n const nonPrimitives: any[] = [];\n\n // Because arrays, booleans, and objects are not compatible with any other schem type\n // other than null we're moving them into an isolated `oneOf`, and as such want to take\n // with it its specific properties that may be present on our current schema.\n Object.entries({\n // https://json-schema.org/understanding-json-schema/reference/array.html\n array: [\n 'additionalItems',\n 'contains',\n 'items',\n 'maxContains',\n 'maxItems',\n 'minContains',\n 'minItems',\n 'prefixItems',\n 'uniqueItems',\n ],\n\n // https://json-schema.org/understanding-json-schema/reference/boolean.html\n boolean: [\n // Booleans don't have any boolean-specific properties.\n ],\n\n // https://json-schema.org/understanding-json-schema/reference/object.html\n object: [\n 'additionalProperties',\n 'maxProperties',\n 'minProperties',\n 'nullable',\n 'patternProperties',\n 'properties',\n 'propertyNames',\n 'required',\n ],\n }).forEach(([typeKey, keywords]) => {\n if (!schema.type.includes(typeKey as JSONSchema7TypeName)) {\n return;\n }\n\n const reducedSchema: any = removeUndefinedObjects({\n type: isNullable ? [typeKey, 'null'] : typeKey,\n\n allowEmptyValue: (schema as any).allowEmptyValue ?? undefined,\n deprecated: schema.deprecated ?? undefined,\n description: schema.description ?? undefined,\n readOnly: schema.readOnly ?? undefined,\n title: schema.title ?? undefined,\n writeOnly: schema.writeOnly ?? undefined,\n });\n\n keywords.forEach((t: keyof SchemaObject) => {\n if (t in schema) {\n reducedSchema[t] = schema[t];\n delete schema[t];\n }\n });\n\n nonPrimitives.push(reducedSchema);\n });\n\n schema.type = schema.type.filter(t => t !== 'array' && t !== 'boolean' && t !== 'object');\n if (schema.type.length === 1) {\n schema.type = schema.type.shift();\n }\n\n // Because we may have encountered a fully mixed non-primitive type like `array | object`\n // we only want to retain the existing schema object if we still have types remaining\n // in it.\n if (schema.type.length > 1) {\n schema = { oneOf: [schema, ...nonPrimitives] };\n } else {\n schema = { oneOf: nonPrimitives };\n }\n }\n }\n }\n }\n\n if (isSchema(schema, isPolymorphicAllOfChild)) {\n if ('default' in schema && isObject(schema.default)) {\n prevDefaultSchemas.push({ default: schema.default });\n }\n\n // JSON Schema doesn't support OpenAPI-style examples so we need to reshape them a bit.\n if ('example' in schema) {\n // Only bother adding primitive examples.\n if (isPrimitive(schema.example)) {\n schema.examples = [schema.example];\n } else if (Array.isArray(schema.example)) {\n schema.examples = schema.example.filter(example => isPrimitive(example));\n if (!schema.examples.length) {\n delete schema.examples;\n }\n } else {\n prevExampleSchemas.push({ example: schema.example });\n }\n\n delete schema.example;\n } else if ('examples' in schema) {\n let reshapedExamples = false;\n if (typeof schema.examples === 'object' && !Array.isArray(schema.examples)) {\n const examples: unknown[] = [];\n Object.keys(schema.examples).forEach(name => {\n const example = schema.examples[name as unknown as number];\n if ('$ref' in example) {\n // no-op because any `$ref` example here after dereferencing is circular so we should\n // ignore it\n refLogger(example.$ref, 'ref');\n } else if ('value' in example) {\n if (isPrimitive(example.value)) {\n examples.push(example.value);\n reshapedExamples = true;\n } else if (Array.isArray(example.value) && isPrimitive(example.value[0])) {\n examples.push(example.value[0]);\n reshapedExamples = true;\n } else {\n // If this example is neither a primitive or an array we should dump it into the\n // `prevExampleSchemas` array because we might be able to extract an example from it\n // further downstream.\n prevExampleSchemas.push({\n example: example.value,\n });\n }\n }\n });\n\n if (examples.length) {\n reshapedExamples = true;\n schema.examples = examples;\n }\n } else if (Array.isArray(schema.examples) && isPrimitive(schema.examples[0])) {\n // We haven't reshaped `examples` here, but since it's in a state that's preferrable to us\n // let's keep it around.\n reshapedExamples = true;\n }\n\n if (!reshapedExamples) {\n delete schema.examples;\n }\n }\n\n // If we didn't have any immediately defined examples, let's search backwards and see if we can\n // find one. But as we're only looking for primitive example, only try to search for one if\n // we're dealing with a primitive schema.\n if (!hasSchemaType(schema, 'array') && !hasSchemaType(schema, 'object') && !schema.examples) {\n const foundExample = searchForValueByPropAndPointer('example', currentLocation, prevExampleSchemas);\n if (foundExample) {\n // We can only really deal with primitives, so only promote those as the found example if\n // it is.\n if (isPrimitive(foundExample) || (Array.isArray(foundExample) && isPrimitive(foundExample[0]))) {\n schema.examples = [foundExample];\n }\n }\n }\n\n if (hasSchemaType(schema, 'array')) {\n if ('items' in schema) {\n if (!Array.isArray(schema.items) && Object.keys(schema.items).length === 1 && isRef(schema.items)) {\n // `items` contains a `$ref`, so since it's circular we should do a no-op here and log\n // and ignore it.\n refLogger(schema.items.$ref, 'ref');\n } else if (schema.items !== true) {\n // Run through the arrays contents and clean them up.\n schema.items = toJSONSchema(schema.items as SchemaObject, {\n addEnumsToDescriptions,\n currentLocation: `${currentLocation}/0`,\n globalDefaults,\n hideReadOnlyProperties,\n hideWriteOnlyProperties,\n prevExampleSchemas,\n refLogger,\n transformer,\n });\n\n // If we have a non-array `required` entry in our `items` schema then it's invalid and we\n // should remove it. We only support non-array boolean `required` properties inside object\n // properties.\n if (isObject(schema.items) && 'required' in schema.items && !Array.isArray(schema.items.required)) {\n delete schema.items.required;\n }\n }\n } else if ('properties' in schema || 'additionalProperties' in schema) {\n // This is a fix to handle cases where someone may have typod `items` as `properties` on an\n // array. Since throwing a complete failure isn't ideal, we can see that they meant for the\n // type to be `object`, so we can do our best to shape the data into what they were\n // intending it to be.\n schema.type = 'object';\n } else {\n // This is a fix to handle cases where we have a malformed array with no `items` property\n // present.\n (schema as any).items = {};\n }\n } else if (hasSchemaType(schema, 'object')) {\n if ('properties' in schema) {\n Object.keys(schema.properties).forEach(prop => {\n if (\n Array.isArray(schema.properties[prop]) ||\n (typeof schema.properties[prop] === 'object' && schema.properties[prop] !== null)\n ) {\n const newPropSchema = toJSONSchema(schema.properties[prop] as SchemaObject, {\n addEnumsToDescriptions,\n currentLocation: `${currentLocation}/${encodePointer(prop)}`,\n globalDefaults,\n hideReadOnlyProperties,\n hideWriteOnlyProperties,\n prevDefaultSchemas,\n prevExampleSchemas,\n refLogger,\n transformer,\n });\n\n // If this property is read or write only then we should fully hide it from its parent schema.\n let propShouldBeUpdated = true;\n if ((hideReadOnlyProperties || hideWriteOnlyProperties) && !Object.keys(newPropSchema).length) {\n // We should only delete this schema if it wasn't already empty though. We do this\n // because we (un)fortunately have handling in our API Explorer form system for\n // schemas that are devoid of any `type` declaration.\n if (Object.keys(schema.properties[prop]).length > 0) {\n delete schema.properties[prop];\n propShouldBeUpdated = false;\n }\n }\n\n if (propShouldBeUpdated) {\n schema.properties[prop] = newPropSchema;\n\n /**\n * JSON Schema does not have any support for `required: <boolean>` but because some\n * of our users do this, and it does not throw OpenAPI validation errors thanks to\n * some extremely loose typings around `schema` in the official JSON Schema\n * definitions that the OAI offers, we're opting to support these users and upgrade\n * their invalid `required` definitions into ones that our tooling can interpret.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/schemas/v3.1/schema.json#L1114-L1121}\n */\n if (\n isObject(newPropSchema) &&\n 'required' in newPropSchema &&\n typeof newPropSchema.required === 'boolean' &&\n newPropSchema.required === true\n ) {\n if ('required' in schema && Array.isArray(schema.required)) {\n schema.required.push(prop);\n } else {\n schema.required = [prop];\n }\n\n delete (schema.properties[prop] as SchemaObject).required;\n }\n }\n }\n });\n\n // If we want to hide all readOnly or writeOnly properites and it happens to be that this\n // object was comprised of only those then we shouldn't render this object.\n if (hideReadOnlyProperties || hideWriteOnlyProperties) {\n if (!Object.keys(schema.properties).length) {\n return transformer({});\n }\n }\n }\n\n if (typeof schemaAdditionalProperties === 'object' && schemaAdditionalProperties !== null) {\n // If this `additionalProperties` is completely empty and devoid of any sort of schema,\n // treat it as such. Otherwise let's recurse into it and see if we can sort it out.\n if (\n !('type' in schemaAdditionalProperties) &&\n !('$ref' in schemaAdditionalProperties) &&\n // We know it will be a schema object because it's dereferenced\n !isPolymorphicSchema(schemaAdditionalProperties as SchemaObject)\n ) {\n schema.additionalProperties = true;\n } else {\n // We know it will be a schema object because it's dereferenced\n schema.additionalProperties = toJSONSchema(schemaAdditionalProperties as SchemaObject, {\n addEnumsToDescriptions,\n currentLocation,\n globalDefaults,\n hideReadOnlyProperties,\n hideWriteOnlyProperties,\n prevDefaultSchemas,\n prevExampleSchemas,\n refLogger,\n transformer,\n });\n }\n }\n\n // Since neither `properties` and `additionalProperties` are actually required to be present\n // on an object, since we construct this schema work to build up a form we still need\n // *something* for the user to enter in for this object so we'll add back in\n // `additionalProperties` for that.\n if (!isPolymorphicSchema(schema) && !('properties' in schema) && !('additionalProperties' in schema)) {\n schema.additionalProperties = true;\n }\n }\n }\n\n /**\n * Users can pass in parameter defaults via JWT User Data. We're checking to see if the defaults\n * being passed in exist on endpoints via jsonpointer\n *\n * @see {@link https://docs.readme.com/docs/passing-data-to-jwt}\n */\n if (\n isSchema(schema, isPolymorphicAllOfChild) &&\n globalDefaults &&\n Object.keys(globalDefaults).length > 0 &&\n currentLocation\n ) {\n try {\n const userJwtDefault = jsonpointer.get(globalDefaults, currentLocation);\n if (userJwtDefault) {\n schema.default = userJwtDefault;\n }\n } catch {\n // If jsonpointer returns an error, we won't show any defaults for that path.\n }\n }\n\n // Only add a default value if we actually have one.\n if ('default' in schema && typeof schema.default !== 'undefined') {\n if (hasSchemaType(schema, 'object')) {\n // Defaults for `object` and types have been dereferenced into their children schemas already\n // above so we don't need to preserve this default anymore.\n delete schema.default;\n } else if (\n ('allowEmptyValue' in schema && schema.allowEmptyValue && schema.default === '') ||\n schema.default !== ''\n ) {\n // If we have `allowEmptyValue` present, and the default is actually an empty string, let it\n // through as it's allowed.\n } else {\n // If the default is empty and we don't want to allowEmptyValue, we need to remove the\n // default.\n delete schema.default;\n }\n } else if (prevDefaultSchemas.length) {\n const foundDefault = searchForValueByPropAndPointer('default', currentLocation, prevDefaultSchemas);\n\n // We shouldn't ever set an object default out of the parent lineage tree defaults because\n // the contents of that object will be set on the schema that they're a part of. Setting\n // that object as well would result us in duplicating the defaults for that schema in two\n // places.\n if (\n isPrimitive(foundDefault) ||\n foundDefault === null ||\n (Array.isArray(foundDefault) && hasSchemaType(schema, 'array'))\n ) {\n schema.default = foundDefault;\n }\n }\n\n if (isSchema(schema, isPolymorphicAllOfChild) && 'enum' in schema && Array.isArray(schema.enum)) {\n // Enums should not have duplicated items as those will break AJV validation.\n // If we ever target ES6 for typescript we can drop this array.from.\n // https://stackoverflow.com/questions/33464504/using-spread-syntax-and-new-set-with-typescript/56870548\n schema.enum = Array.from(new Set(schema.enum));\n\n // If we want to add enums to descriptions (like in the case of response JSON Schema)\n // generation we need to convert them into a list of Markdown tilda'd strings. We're also\n // filtering away empty and falsy strings here because adding empty `` blocks to the description\n // will serve nobody any good.\n if (addEnumsToDescriptions) {\n const enums = schema.enum\n .filter(v => v !== undefined && (typeof v !== 'string' || v.trim() !== ''))\n .map(str => `\\`${str}\\``)\n .join(' ');\n\n if (enums.length) {\n if ('description' in schema) {\n schema.description += `\\n\\n${enums}`;\n } else {\n schema.description = enums;\n }\n }\n }\n }\n\n // Clean up any remaining `items` or `properties` schema fragments lying around if there's also\n // polymorphism present.\n if ('anyOf' in schema || 'oneOf' in schema) {\n if ('properties' in schema) {\n delete schema.properties;\n }\n\n if ('items' in schema) {\n delete schema.items;\n }\n }\n\n // Remove unsupported JSON Schema props.\n for (let i = 0; i < UNSUPPORTED_SCHEMA_PROPS.length; i += 1) {\n // Using the as here because the purpose is to delete keys we don't expect, so of course the\n // typing won't work\n delete (schema as Record<string, unknown>)[UNSUPPORTED_SCHEMA_PROPS[i]];\n }\n\n // If we want to hide any `readOnly` or `writeOnly` schemas, and this one is that, then we\n // shouldn't return anything.\n if (hideReadOnlyProperties && 'readOnly' in schema && schema.readOnly === true) {\n return {};\n } else if (hideWriteOnlyProperties && 'writeOnly' in schema && schema.writeOnly === true) {\n return {};\n }\n\n return transformer(schema);\n}\n","import type { OpenAPIV3_1 } from 'openapi-types';\nimport type { toJSONSchemaOptions } from '../../lib/openapi-to-json-schema.js';\nimport type { ComponentsObject, ExampleObject, OASDocument, ParameterObject, SchemaObject } from '../../types.js';\nimport type { Operation } from '../index.js';\n\nimport { getExtension, PARAMETER_ORDERING } from '../../extensions.js';\nimport { cloneObject } from '../../lib/clone-object.js';\nimport { isPrimitive } from '../../lib/helpers.js';\nimport matchesMimetype from '../../lib/matches-mimetype.js';\nimport { getSchemaVersionString, toJSONSchema } from '../../lib/openapi-to-json-schema.js';\n\nexport interface SchemaWrapper {\n $schema?: string;\n deprecatedProps?: SchemaWrapper;\n description?: string;\n label?: string;\n schema: SchemaObject;\n type: string;\n}\n\n/**\n * The order of this object determines how they will be sorted in the compiled JSON Schema\n * representation.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameter-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object}\n */\nexport const types: Record<keyof OASDocument, string> = {\n path: 'Path Params',\n query: 'Query Params',\n body: 'Body Params',\n cookie: 'Cookie Params',\n formData: 'Form Data',\n header: 'Headers',\n metadata: 'Metadata', // This a special type reserved for https://npm.im/api\n};\n\nexport interface getParametersAsJSONSchemaOptions {\n /**\n * Contains an object of user defined schema defaults.\n */\n globalDefaults?: Record<string, unknown>;\n\n /**\n * If you wish to hide properties that are marked as being `readOnly`.\n */\n hideReadOnlyProperties?: boolean;\n\n /**\n * If you wish to hide properties that are marked as being `writeOnly`.\n */\n hideWriteOnlyProperties?: boolean;\n\n /**\n * If you wish to include discriminator mapping `$ref` components alongside your\n * `discriminator` in schemas. Defaults to `true`.\n */\n includeDiscriminatorMappingRefs?: boolean;\n\n /**\n * If you want the output to be two objects: body (contains `body` and `formData` JSON\n * Schema) and metadata (contains `path`, `query`, `cookie`, and `header`).\n */\n mergeIntoBodyAndMetadata?: boolean;\n\n /**\n * If you wish to **not** split out deprecated properties into a separate `deprecatedProps`\n * object.\n */\n retainDeprecatedProperties?: boolean;\n\n /**\n * With a transformer you can transform any data within a given schema, like say if you want\n * to rewrite a potentially unsafe `title` that might be eventually used as a JS variable\n * name, just make sure to return your transformed schema.\n */\n transformer?: (schema: SchemaObject) => SchemaObject;\n}\n\nexport function getParametersAsJSONSchema(\n operation: Operation,\n api: OASDocument,\n opts?: getParametersAsJSONSchemaOptions,\n): SchemaWrapper[] {\n let hasCircularRefs = false;\n let hasDiscriminatorMappingRefs = false;\n\n function refLogger(ref: string, type: 'discriminator' | 'ref') {\n if (type === 'ref') {\n hasCircularRefs = true;\n } else {\n hasDiscriminatorMappingRefs = true;\n }\n }\n\n function getDeprecated(schema: SchemaObject, type: string) {\n // If we wish to retain deprecated properties then we shouldn't split them out into the\n // `deprecatedProps` object.\n if (opts.retainDeprecatedProperties) {\n return null;\n }\n\n // If there's no properties, bail\n if (!schema || !schema.properties) return null;\n\n // Clone the original schema so this doesn't interfere with it\n const deprecatedBody = cloneObject(schema);\n\n // Booleans are not valid for required in draft 4, 7 or 2020. Not sure why the typing thinks\n // they are.\n const requiredParams = (schema.required || []) as string[];\n\n // Find all top-level deprecated properties from the schema - required and readOnly params are\n // excluded.\n const allDeprecatedProps: Record<string, SchemaObject> = {};\n\n Object.keys(deprecatedBody.properties).forEach(key => {\n const deprecatedProp = deprecatedBody.properties[key] as SchemaObject;\n if (deprecatedProp.deprecated && !requiredParams.includes(key) && !deprecatedProp.readOnly) {\n allDeprecatedProps[key] = deprecatedProp;\n }\n });\n\n // We know this is the right type. todo: don't use as\n (deprecatedBody.properties as Record<string, SchemaObject>) = allDeprecatedProps;\n const deprecatedSchema = toJSONSchema(deprecatedBody, {\n globalDefaults: opts.globalDefaults,\n hideReadOnlyProperties: opts.hideReadOnlyProperties,\n hideWriteOnlyProperties: opts.hideWriteOnlyProperties,\n prevExampleSchemas: [],\n refLogger,\n transformer: opts.transformer,\n });\n\n // Check if the schema wasn't created or there's no deprecated properties\n if (Object.keys(deprecatedSchema).length === 0 || Object.keys(deprecatedSchema.properties).length === 0) {\n return null;\n }\n\n // Remove deprecated properties from the original schema\n // Not using the clone here becuase we WANT this to affect the original\n Object.keys(schema.properties).forEach(key => {\n // We know this will always be a SchemaObject\n if ((schema.properties[key] as SchemaObject).deprecated && !requiredParams.includes(key)) {\n delete schema.properties[key];\n }\n });\n\n return {\n type,\n schema: isPrimitive(deprecatedSchema)\n ? deprecatedSchema\n : {\n ...deprecatedSchema,\n $schema: getSchemaVersionString(deprecatedSchema, api),\n },\n };\n }\n\n /**\n *\n */\n function transformRequestBody(): SchemaWrapper {\n const requestBody = operation.getRequestBody();\n if (!requestBody || !Array.isArray(requestBody)) return null;\n\n const [mediaType, mediaTypeObject, description] = requestBody;\n const type = mediaType === 'application/x-www-form-urlencoded' ? 'formData' : 'body';\n\n // If this schema is completely empty, don't bother processing it.\n if (!mediaTypeObject.schema || !Object.keys(mediaTypeObject.schema).length) {\n return null;\n }\n\n const prevExampleSchemas: toJSONSchemaOptions['prevExampleSchemas'] = [];\n if ('example' in mediaTypeObject) {\n prevExampleSchemas.push({ example: mediaTypeObject.example });\n } else if ('examples' in mediaTypeObject) {\n prevExampleSchemas.push({\n examples: Object.values(mediaTypeObject.examples)\n .map((example: ExampleObject) => example.value)\n .filter(val => val !== undefined),\n });\n }\n\n // We're cloning the request schema because we've had issues with request schemas that were\n // dereferenced being processed multiple times because their component is also processed.\n const requestSchema = cloneObject(mediaTypeObject.schema);\n\n const cleanedSchema = toJSONSchema(requestSchema, {\n globalDefaults: opts.globalDefaults,\n hideReadOnlyProperties: opts.hideReadOnlyProperties,\n hideWriteOnlyProperties: opts.hideWriteOnlyProperties,\n prevExampleSchemas,\n refLogger,\n transformer: opts.transformer,\n });\n\n // If this schema is **still** empty, don't bother returning it.\n if (!Object.keys(cleanedSchema).length) {\n return null;\n }\n\n return {\n type,\n label: types[type],\n schema: isPrimitive(cleanedSchema)\n ? cleanedSchema\n : {\n ...cleanedSchema,\n $schema: getSchemaVersionString(cleanedSchema, api),\n },\n deprecatedProps: getDeprecated(cleanedSchema, type),\n ...(description ? { description } : {}),\n };\n }\n\n function transformComponents(): ComponentsObject {\n if (!('components' in api)) {\n return false;\n }\n\n const components: Partial<ComponentsObject> = {\n ...Object.keys(api.components)\n .map(componentType => ({ [componentType]: {} }))\n .reduce((prev, next) => Object.assign(prev, next), {}),\n };\n\n Object.keys(api.components).forEach((componentType: keyof ComponentsObject) => {\n if (typeof api.components[componentType] === 'object' && !Array.isArray(api.components[componentType])) {\n Object.keys(api.components[componentType]).forEach(schemaName => {\n const componentSchema = cloneObject(api.components[componentType][schemaName]);\n components[componentType][schemaName] = toJSONSchema(componentSchema as SchemaObject, {\n globalDefaults: opts.globalDefaults,\n hideReadOnlyProperties: opts.hideReadOnlyProperties,\n hideWriteOnlyProperties: opts.hideWriteOnlyProperties,\n refLogger,\n transformer: opts.transformer,\n });\n });\n }\n });\n\n // If none of our above component type placeholders got used let's clean them up.\n Object.keys(components).forEach((componentType: keyof ComponentsObject) => {\n if (!Object.keys(components[componentType]).length) {\n delete components[componentType];\n }\n });\n\n return components;\n }\n\n function transformParameters(): SchemaWrapper[] {\n const operationParams = operation.getParameters();\n\n const transformed = Object.keys(types)\n .map(type => {\n const required: string[] = [];\n\n // This `as` actually *could* be a ref, but we don't want refs to pass through here, so\n // `.in` will never match `type`\n const parameters = operationParams.filter(param => (param as ParameterObject).in === type);\n if (parameters.length === 0) {\n return null;\n }\n\n const properties = parameters.reduce((prev: Record<string, SchemaObject>, current: ParameterObject) => {\n let schema: SchemaObject = {};\n if ('schema' in current) {\n const currentSchema: SchemaObject = current.schema ? cloneObject(current.schema) : {};\n\n if (current.example) {\n // `example` can be present outside of the `schema` block so if it's there we should\n // pull it in so it can be handled and returned if it's valid.\n currentSchema.example = current.example;\n } else if (current.examples) {\n // `examples` isn't actually supported here in OAS 3.0, but we might as well support\n // it because `examples` is JSON Schema and that's fully supported in OAS 3.1.\n currentSchema.examples = current.examples as unknown as unknown[];\n }\n\n if (current.deprecated) currentSchema.deprecated = current.deprecated;\n\n const interimSchema = toJSONSchema(currentSchema, {\n currentLocation: `/${current.name}`,\n globalDefaults: opts.globalDefaults,\n hideReadOnlyProperties: opts.hideReadOnlyProperties,\n hideWriteOnlyProperties: opts.hideWriteOnlyProperties,\n refLogger,\n transformer: opts.transformer,\n });\n\n schema = isPrimitive(interimSchema)\n ? interimSchema\n : {\n ...interimSchema,\n\n // Note: this applies a `$schema` version to each field in the larger schema\n // object. It's not really **correct** but it's what we have to do because\n // there's a chance that the end user has indicated the schemas are different.\n $schema: getSchemaVersionString(currentSchema, api),\n };\n } else if ('content' in current && typeof current.content === 'object') {\n const contentKeys = Object.keys(current.content);\n if (contentKeys.length) {\n let contentType: string;\n if (contentKeys.length === 1) {\n contentType = contentKeys[0];\n } else {\n // We should always try to prioritize `application/json` over any other possible\n // content that might be present on this schema.\n const jsonLikeContentTypes = contentKeys.filter(k => matchesMimetype.json(k));\n if (jsonLikeContentTypes.length) {\n contentType = jsonLikeContentTypes[0];\n } else {\n contentType = contentKeys[0];\n }\n }\n\n if (typeof current.content[contentType] === 'object' && 'schema' in current.content[contentType]) {\n const currentSchema: SchemaObject = current.content[contentType].schema\n ? cloneObject(current.content[contentType].schema)\n : {};\n\n if (current.example) {\n // `example` can be present outside of the `schema` block so if it's there we\n // should pull it in so it can be handled and returned if it's valid.\n currentSchema.example = current.example;\n } else if (current.examples) {\n // `examples` isn't actually supported here in OAS 3.0, but we might as well\n // support it because `examples` is JSON Schema and that's fully supported in OAS\n // 3.1.\n currentSchema.examples = current.examples as unknown as unknown[];\n }\n\n if (current.deprecated) currentSchema.deprecated = current.deprecated;\n\n const interimSchema = toJSONSchema(currentSchema, {\n currentLocation: `/${current.name}`,\n globalDefaults: opts.globalDefaults,\n hideReadOnlyProperties: opts.hideReadOnlyProperties,\n hideWriteOnlyProperties: opts.hideWriteOnlyProperties,\n refLogger,\n transformer: opts.transformer,\n });\n\n schema = isPrimitive(interimSchema)\n ? interimSchema\n : {\n ...interimSchema,\n\n // Note: this applies a `$schema` version to each field in the larger schema\n // object. It's not really **correct** but it's what we have to do because\n // there's a chance that the end user has indicated the schemas are different.\n $schema: getSchemaVersionString(currentSchema, api),\n };\n }\n }\n }\n\n // Parameter descriptions don't exist in `current.schema` so `constructSchema` will never\n // have access to it.\n if (current.description) {\n if (!isPrimitive(schema)) {\n schema.description = current.description;\n }\n }\n\n prev[current.name] = schema;\n\n if (current.required) {\n required.push(current.name);\n }\n\n return prev;\n }, {});\n\n // This typing is technically WRONG :( but it's the best we can do for now.\n const schema: OpenAPIV3_1.SchemaObject = {\n type: 'object',\n properties: properties as Record<string, OpenAPIV3_1.SchemaObject>,\n required,\n };\n\n return {\n type,\n label: types[type],\n schema,\n deprecatedProps: getDeprecated(schema, type),\n };\n })\n .filter(Boolean);\n\n if (!opts.mergeIntoBodyAndMetadata) {\n return transformed;\n } else if (!transformed.length) {\n return [];\n }\n\n // If we want to merge parameters into a single metadata entry then we need to pull all\n // available schemas and `deprecatedProps` (if we don't want to retain them via the\n // `retainDeprecatedProps` option) under one roof.\n const deprecatedProps = transformed.map(r => r.deprecatedProps?.schema || null).filter(Boolean);\n return [\n {\n type: 'metadata',\n label: types.metadata,\n schema: {\n allOf: transformed.map(r => r.schema),\n } as SchemaObject,\n deprecatedProps: deprecatedProps.length\n ? {\n type: 'metadata',\n schema: {\n allOf: deprecatedProps,\n } as SchemaObject,\n }\n : null,\n },\n ];\n }\n\n // If this operation neither has any parameters or a request body then we should return null\n // because there won't be any JSON Schema.\n if (!operation.hasParameters() && !operation.hasRequestBody()) {\n return null;\n }\n\n // `metadata` is `api` SDK specific, is not a part of the `PARAMETER_ORDERING` extension, and\n // should always be sorted last. We also define `formData` as `form` in the extension because\n // we don't want folks to have to deal with casing issues so we need to rewrite it to `formData`.\n const typeKeys = (getExtension(PARAMETER_ORDERING, api, operation) as string[]).map(k => k.toLowerCase());\n typeKeys[typeKeys.indexOf('form')] = 'formData';\n typeKeys.push('metadata');\n\n const jsonSchema = [transformRequestBody()].concat(...transformParameters()).filter(Boolean);\n\n // We should only include `components`, or even bother transforming components into JSON Schema,\n // if we either have circular refs or if we have discriminator mapping refs somewhere and want to\n // include them.\n const shouldIncludeComponents =\n hasCircularRefs || (hasDiscriminatorMappingRefs && opts.includeDiscriminatorMappingRefs);\n\n const components = shouldIncludeComponents ? transformComponents() : false;\n\n return jsonSchema\n .map(group => {\n /**\n * Since this library assumes that the schema has already been dereferenced, adding every\n * component here that **isn't** circular adds a ton of bloat so it'd be cool if `components`\n * was just the remaining `$ref` pointers that are still being referenced.\n *\n * @todo\n */\n if (components && shouldIncludeComponents) {\n // Fixing typing and confused version mismatches\n (group.schema.components as ComponentsObject) = components;\n }\n\n // Delete deprecatedProps if it's null on the schema.\n if (!group.deprecatedProps) delete group.deprecatedProps;\n\n return group;\n })\n .sort((a, b) => {\n return typeKeys.indexOf(a.type) - typeKeys.indexOf(b.type);\n });\n}\n"],"mappings":";;;;;;;;;;;AAAO,SAAS,YAAe,KAAW;AACxC,MAAI,OAAO,QAAQ,aAAa;AAC9B,WAAO;AAAA,EACT;AAEA,SAAO,KAAK,MAAM,KAAK,UAAU,GAAG,CAAC;AACvC;;;ACJO,SAAS,cAAc,QAAsB,eAA4C;AAC9F,MAAI,MAAM,QAAQ,OAAO,IAAI,GAAG;AAC9B,WAAO,OAAO,KAAK,SAAS,aAAa;AAAA,EAC3C;AAEA,SAAO,OAAO,SAAS;AACzB;AAEO,SAAS,SAAS,KAA8C;AACrE,SAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,CAAC,MAAM,QAAQ,GAAG;AACtE;AAEO,SAAS,YAAY,KAAgD;AAC1E,SAAO,OAAO,QAAQ,YAAY,OAAO,QAAQ,YAAY,OAAO,QAAQ;AAC9E;;;AChBA,SAAS,iBAAiBA,QAAiB,WAA4B;AACrE,SAAOA,OAAM,KAAK,UAAQ;AACxB,WAAO,UAAU,QAAQ,IAAI,IAAI;AAAA,EACnC,CAAC;AACH;AAGA,IAAO,2BAAQ;AAAA,EACb,gBAAgB,CAAC,aAA8B;AAC7C,WAAO,iBAAiB,CAAC,mCAAmC,GAAG,QAAQ;AAAA,EACzE;AAAA,EAEA,MAAM,CAAC,gBAAiC;AACtC,WAAO;AAAA,MACL,CAAC,oBAAoB,sB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;AAAA,UACN,QAAQ;AAAA,YACN,OAAO;AAAA,UACT;AAAA,QACF,IACA;AAAA,MACN;AAAA,IACF;AAAA,EACF;AAIA,MAAI,CAAC,UAAU,cAAc,KAAK,CAAC,UAAU,eAAe,GAAG;AAC7D,WAAO;AAAA,EACT;AAKA,QAAM,WAAY,aAAa,oBAAoB,KAAK,SAAS,EAAe,IAAI,OAAK,EAAE,YAAY,CAAC;AACxG,WAAS,SAAS,QAAQ,MAAM,CAAC,IAAI;AACrC,WAAS,KAAK,UAAU;AAExB,QAAM,aAAa,CAAC,qBAAqB,CAAC,EAAE,OAAO,GAAG,oBAAoB,CAAC,EAAE,OAAO,OAAO;AAK3F,QAAM,0BACJ,mBAAoB,+BAA+B,KAAK;AAE1D,QAAM,aAAa,0BAA0B,oBAAoB,IAAI;AAErE,SAAO,WACJ,IAAI,WAAS;AAQZ,QAAI,cAAc,yBAAyB;AAEzC,MAAC,MAAM,OAAO,aAAkC;AAAA,IAClD;AAGA,QAAI,CAAC,MAAM,gBAAiB,QAAO,MAAM;AAEzC,WAAO;AAAA,EACT,CAAC,EACA,KAAK,CAAC,GAAG,MAAM;AACd,WAAO,SAAS,QAAQ,EAAE,IAAI,IAAI,SAAS,QAAQ,EAAE,IAAI;AAAA,EAC3D,CAAC;AACL;","names":["types","components","schema"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas/dist/chunk-47YGVG2J.cjs","../src/index.ts","../src/lib/build-discriminator-one-of.ts","../src/lib/get-auth.ts","../src/lib/get-user-variable.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACVA,uDAA4B;AAC5B,8CAAoC;ADYpC;AACA;AEpBA,SAAS,mCA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ACgB,MAAA;AACN,QAAA;AACZ,MAAA;AACF,IAAA;AACF,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAS2B,EAAA;AACb,IAAA;AACL,MAAA;AACN,IAAA;AACH,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,EAAA;AACY,IAAA;AACQ,MAAA;AAClB,IAAA;AAEY,IAAA;AACd,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQE,EAAA;AAeS,IAAA;AACI,MAAA;AACG,QAAA;AACb,MAAA;AACH,IAAA;AAES,IAAA;AACI,MAAA;AACK,QAAA;AACf,MAAA;AACH,IAAA;AAEmB,IAAA;AAMb,IAAA;AAEO,IAAA;AAKJ,IAAA;AACS,MAAA;AAMA,QAAA;AAIZ,UAAA;AACF,QAAA;AAES,QAAA;AAIF,UAAA;AACP,QAAA;AAEgB,QAAA;AACjB,MAAA;AACH,IAAA;AAEM,IAAA;AAE0B,IAAA;AACrB,MAAA;AAAA;AAEG,QAAA;AACZ,MAAA;AACa,MAAA;AAAA;AAAA;AAGD,QAAA;AAEG,QAAA;AAKE,UAAA;AACf,QAAA;AACF,MAAA;AAEO,IAAA;AACM,MAAA;AAIP,MAAA;AACF,QAAA;AACF,MAAA;AAEgB,MAAA;AACX,MAAA;AACS,QAAA;AACF,QAAA;AAAA;AAEK,QAAA;AACjB,MAAA;AAGa,MAAA;AACH,QAAA;AACV,MAAA;AAEU,IAAA;AACE,MAAA;AACb,IAAA;AACL,EAAA;AACF;ADvPwB;AACA;AACA;AACA","file":"/Users/erunion/code/readme/oas/packages/oas/dist/chunk-47YGVG2J.cjs","sourcesContent":[null,"import type { OpenAPIV3_1 } from 'openapi-types';\nimport type { Match, ParamData } from 'path-to-regexp';\nimport type { Extensions } from './extensions.js';\nimport type {\n AuthForHAR,\n HttpMethods,\n OASDocument,\n OperationObject,\n PathsObject,\n SchemaObject,\n ServerObject,\n Servers,\n ServerVariable,\n ServerVariablesObject,\n User,\n} from './types.js';\n\nimport { dereference } from '@readme/openapi-parser';\nimport { match, pathToRegexp } from 'path-to-regexp';\n\nimport {\n CODE_SAMPLES,\n extensionDefaults,\n getExtension,\n HEADERS,\n hasRootExtension,\n OAUTH_OPTIONS,\n PARAMETER_ORDERING,\n SAMPLES_LANGUAGES,\n validateParameterOrdering,\n} from './extensions.js';\nimport { buildDiscriminatorOneOf, findDiscriminatorChildren } from './lib/build-discriminator-one-of.js';\nimport { getAuth } from './lib/get-auth.js';\nimport getUserVariable from './lib/get-user-variable.js';\nimport { isPrimitive } from './lib/helpers.js';\nimport { Operation, Webhook } from './operation/index.js';\nimport { findSchemaDefinition, supportedMethods } from './utils.js';\n\ninterface PathMatch {\n match?: Match<ParamData>;\n operation: PathsObject;\n url: {\n method?: HttpMethods;\n nonNormalizedPath: string;\n origin: string;\n path: string;\n slugs: Record<string, string>;\n };\n}\ntype PathMatches = PathMatch[];\n\nconst SERVER_VARIABLE_REGEX = /{([-_a-zA-Z0-9:.[\\]]+)}/g;\n\nfunction ensureProtocol(url: string) {\n // Add protocol to urls starting with // e.g. //example.com\n // This is because httpsnippet throws a HARError when it doesnt have a protocol\n if (url.match(/^\\/\\//)) {\n return `https:${url}`;\n }\n\n // Add protocol to urls with no // within them\n // This is because httpsnippet throws a HARError when it doesnt have a protocol\n if (!url.match(/\\/\\//)) {\n return `https://${url}`;\n }\n\n return url;\n}\n\nfunction stripTrailingSlash(url: string) {\n if (url[url.length - 1] === '/') {\n return url.slice(0, -1);\n }\n\n return url;\n}\n\n/**\n * Normalize a OpenAPI server URL by ensuring that it has a proper HTTP protocol and doesn't have a\n * trailing slash.\n *\n * @param api The API definition that we're processing.\n * @param selected The index of the `servers` array in the API definition that we want to normalize.\n */\nfunction normalizedUrl(api: OASDocument, selected: number) {\n const exampleDotCom = 'https://example.com';\n let url: string;\n try {\n url = api.servers[selected].url;\n // This is to catch the case where servers = [{}]\n if (!url) throw new Error('no url');\n\n // Stripping the '/' off the end\n url = stripTrailingSlash(url);\n\n // Check if the URL is just a path a missing an origin, for example `/api/v3`. If so, then make\n // `example.com` the origin to avoid it becoming something invalid like `https:///api/v3`.\n // RM-1044\n if (url.startsWith('/') && !url.startsWith('//')) {\n const urlWithOrigin = new URL(exampleDotCom);\n urlWithOrigin.pathname = url;\n url = urlWithOrigin.href;\n }\n } catch {\n url = exampleDotCom;\n }\n\n return ensureProtocol(url);\n}\n\n/**\n * With a URL that may contain server variables, transform those server variables into regex that\n * we can query against.\n *\n * For example, when given `https://{region}.node.example.com/v14` this will return back:\n *\n * https://([-_a-zA-Z0-9:.[\\\\]]+).node.example.com/v14\n *\n * @param url URL to transform\n */\nfunction transformUrlIntoRegex(url: string) {\n return stripTrailingSlash(url.replace(SERVER_VARIABLE_REGEX, '([-_a-zA-Z0-9:.[\\\\]]+)'));\n}\n\n/**\n * Normalize a path so that we can use it with `path-to-regexp` to do operation lookups.\n *\n * @param path Path to normalize.\n */\nfunction normalizePath(path: string) {\n return (\n path\n // This regex transforms `{pathParam}` into `:pathParam` so we can regex against it. We're\n // also handling quirks here like if there's an optional proceeding or trailing curly bracket\n // (`{{pathParam}` or `{pathParam}}`) as any unescaped curlys, which would be present in\n // `:pathParam}`, will throw a regex exception.\n .replace(/({?){(.*?)}(}?)/g, (str, ...args) => {\n // If a path contains a path parameter with hyphens, like `:dlc-release`, when it's regexd\n // with `path-to-regexp` it match against the `:dlc` portion of the parameter, breaking all\n // matching against the full path.\n //\n // For example on `/games/:game/dlc/:dlc-release` the regex that's actually used to search\n // against a path like `/games/destiny-2/dlc/witch-queen` is the following:\n // /^\\/games(?:\\/([^\\/#\\?]+?))\\/dlc(?:\\/([^\\/#\\?]+?))-release[\\/#\\?]?$/i\n //\n // However if `:dlc-release` is rewritten to `:dlcrelease` we end up with a functional\n // regex: /^\\/games(?:\\/([^\\/#\\?]+?))\\/dlc(?:\\/([^\\/#\\?]+?))[\\/#\\?]?$/i.\n return `:${args[1].replace('-', '')}`;\n })\n\n // In addition to transforming `{pathParam}` into `:pathParam` we also need to escape cases\n // where a non-variabled colon is next to a variabled-colon because if we don't then\n // `path-to-regexp` won't be able to correct identify where the variable starts.\n //\n // For example if the URL is `/post/:param1::param2` we'll be escaping it to\n // `/post/:param1\\::param2`.\n .replace(/::/, '\\\\::')\n\n // We also need to escape question marks too because they're treated as regex modifiers.\n .split('?')[0]\n );\n}\n\n/**\n * Generate path matches for a given path and origin on a set of OpenAPI path objects.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#paths-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#paths-object}\n * @param paths The OpenAPI Paths Object to process.\n * @param pathName Path to look for a match.\n * @param origin The origin that we're matching against.\n */\nfunction generatePathMatches(paths: PathsObject, pathName: string, origin: string) {\n const prunedPathName = pathName.split('?')[0];\n return (\n Object.keys(paths)\n .map(path => {\n const cleanedPath = normalizePath(path);\n\n let matchResult: PathMatch['match'];\n try {\n const matchStatement = match(cleanedPath, { decode: decodeURIComponent });\n matchResult = matchStatement(prunedPathName);\n } catch {\n // If path matching fails for whatever reason (maybe they have a malformed path parameter)\n // then we shouldn't also fail.\n return false;\n }\n\n const slugs: Record<string, string> = {};\n\n if (matchResult && Object.keys(matchResult.params).length) {\n Object.keys(matchResult.params).forEach(param => {\n slugs[`:${param}`] = (matchResult.params as Record<string, string>)[param];\n });\n }\n\n return {\n url: {\n origin,\n path: cleanedPath.replace(/\\\\::/, '::'),\n nonNormalizedPath: path,\n slugs,\n },\n operation: paths[path] as PathsObject,\n match: matchResult,\n } satisfies PathMatch;\n })\n .filter(Boolean) as PathMatches\n ).filter(p => p.match);\n}\n\n/**\n * @param pathMatches Array of path matches to filter down.\n * @param targetMethod HTTP method to look for.\n * @returns Filtered down path matches.\n */\nfunction filterPathMethods(pathMatches: PathMatches, targetMethod: HttpMethods) {\n const regExp = pathToRegexp(targetMethod);\n return pathMatches\n .map(p => {\n const captures = Object.keys(p.operation).filter(r => regExp.regexp.exec(r));\n\n if (captures.length) {\n const method = captures[0];\n p.url.method = method.toUpperCase() as HttpMethods;\n\n return {\n url: p.url,\n operation: p.operation[method],\n };\n }\n\n return false;\n })\n .filter(Boolean) as { operation: OperationObject; url: PathMatch['url'] }[];\n}\n\n/**\n * @param pathMatches URL and PathsObject matches to narrow down to find a target path.\n * @returns An object containing matches that were discovered in the API definition.\n */\nfunction findTargetPath(pathMatches: { operation: PathsObject; url: PathMatch['url'] }[]) {\n let minCount = Object.keys(pathMatches[0].url.slugs).length;\n let operation: {\n operation: PathsObject;\n url: PathMatch['url'];\n };\n\n for (let m = 0; m < pathMatches.length; m += 1) {\n const selection = pathMatches[m];\n const paramCount = Object.keys(selection.url.slugs).length;\n if (paramCount <= minCount) {\n minCount = paramCount;\n operation = selection;\n }\n }\n\n return operation;\n}\n\n// biome-ignore lint/style/noDefaultExport: This is fine for now.\nexport default class Oas {\n /**\n * An OpenAPI API Definition.\n */\n api: OASDocument;\n\n /**\n * The current user that we should use when pulling auth tokens from security schemes.\n */\n user: User;\n\n /**\n * Internal storage array that the library utilizes to keep track of the times the\n * {@see Oas.dereference} has been called so that if you initiate multiple promises they'll all\n * end up returning the same data set once the initial dereference call completed.\n */\n protected promises: {\n reject: any;\n resolve: any;\n }[];\n\n /**\n * Internal storage array that the library utilizes to keep track of its `dereferencing` state so\n * it doesn't initiate multiple dereferencing processes.\n */\n protected dereferencing: {\n circularRefs: string[];\n complete: boolean;\n processing: boolean;\n };\n\n /**\n * @param oas An OpenAPI definition.\n * @param user The information about a user that we should use when pulling auth tokens from\n * security schemes.\n */\n constructor(oas: OASDocument | string, user?: User) {\n if (typeof oas === 'string') {\n this.api = (JSON.parse(oas) || {}) as OASDocument;\n } else {\n this.api = oas || ({} as OASDocument);\n }\n\n this.user = user || {};\n\n this.promises = [];\n this.dereferencing = {\n processing: false,\n complete: false,\n circularRefs: [],\n };\n }\n\n /**\n * This will initialize a new instance of the `Oas` class. This method is useful if you're using\n * Typescript and are attempting to supply an untyped JSON object into `Oas` as it will force-type\n * that object to an `OASDocument` for you.\n *\n * @param oas An OpenAPI definition.\n * @param user The information about a user that we should use when pulling auth tokens from\n * security schemes.\n */\n static init(oas: OASDocument | Record<string, unknown>, user?: User): Oas {\n return new Oas(oas as OASDocument, user);\n }\n\n /**\n * Retrieve the OpenAPI version that this API definition is targeted for.\n */\n getVersion(): string {\n if (this.api.openapi) {\n return this.api.openapi;\n }\n\n throw new Error('Unable to recognize what specification version this API definition conforms to.');\n }\n\n /**\n * Retrieve the current OpenAPI API Definition.\n *\n */\n getDefinition(): OASDocument {\n return this.api;\n }\n\n url(selected = 0, variables?: ServerVariable): string {\n const url = normalizedUrl(this.api, selected);\n return this.replaceUrl(url, variables || this.defaultVariables(selected)).trim();\n }\n\n variables(selected = 0): ServerVariablesObject {\n let variables: ServerVariablesObject;\n try {\n variables = this.api.servers[selected].variables;\n if (!variables) throw new Error('no variables');\n } catch {\n variables = {};\n }\n\n return variables;\n }\n\n defaultVariables(selected = 0): ServerVariable {\n const variables = this.variables(selected);\n const defaults: ServerVariable = {};\n\n Object.keys(variables).forEach(key => {\n defaults[key] = getUserVariable(this.user, key) || variables[key].default || '';\n });\n\n return defaults;\n }\n\n splitUrl(selected = 0): (\n | {\n /**\n * A unique key, where the `value` is concatenated to its index\n */\n key: string;\n type: 'text';\n value: string;\n }\n | {\n /**\n * An optional description for the server variable.\n *\n * @see {@link https://spec.openapis.org/oas/v3.1.0#fixed-fields-4}\n */\n description?: string;\n\n /**\n * An enumeration of string values to be used if the substitution options are from a limited set.\n *\n * @see {@link https://spec.openapis.org/oas/v3.1.0#fixed-fields-4}\n */\n enum?: string[];\n\n /**\n * A unique key, where the `value` is concatenated to its index\n */\n key: string;\n type: 'variable';\n value: string;\n }\n )[] {\n const url = normalizedUrl(this.api, selected);\n const variables = this.variables(selected);\n\n return url\n .split(/({.+?})/)\n .filter(Boolean)\n .map((part, i) => {\n const isVariable = part.match(/[{}]/);\n const value = part.replace(/[{}]/g, '');\n // To ensure unique keys, we're going to create a key\n // with the value concatenated to its index.\n const key = `${value}-${i}`;\n\n if (!isVariable) {\n return {\n type: 'text',\n value,\n key,\n };\n }\n\n const variable = variables?.[value];\n\n return {\n type: 'variable',\n value,\n key,\n description: variable?.description,\n enum: variable?.enum,\n };\n });\n }\n\n /**\n * With a fully composed server URL, run through our list of known OAS servers and return back\n * which server URL was selected along with any contained server variables split out.\n *\n * For example, if you have an OAS server URL of `https://{name}.example.com:{port}/{basePath}`,\n * and pass in `https://buster.example.com:3000/pet` to this function, you'll get back the\n * following:\n *\n * { selected: 0, variables: { name: 'buster', port: 3000, basePath: 'pet' } }\n *\n * Re-supplying this data to `oas.url()` should return the same URL you passed into this method.\n *\n * @param baseUrl A given URL to extract server variables out of.\n */\n splitVariables(baseUrl: string): Servers | false {\n const matchedServer = (this.api.servers || [])\n .map((server, i) => {\n const rgx = transformUrlIntoRegex(server.url);\n const found = new RegExp(rgx).exec(baseUrl);\n if (!found) {\n return false;\n }\n\n // While it'd be nice to use named regex groups to extract path parameters from the URL and\n // match them up with the variables that we have present in it, JS unfortunately doesn't\n // support having the groups duplicated. So instead of doing that we need to re-regex the\n // server URL, this time splitting on the path parameters -- this way we'll be able to\n // extract the parameter names and match them up with the matched server that we obtained\n // above.\n const variables: Record<string, number | string> = {};\n Array.from(server.url.matchAll(SERVER_VARIABLE_REGEX)).forEach((variable, y) => {\n variables[variable[1]] = found[y + 1];\n });\n\n return {\n selected: i,\n variables,\n };\n })\n .filter(Boolean);\n\n return matchedServer.length ? matchedServer[0] : false;\n }\n\n /**\n * Replace templated variables with supplied data in a given URL.\n *\n * There are a couple ways that this will utilize variable data:\n *\n * - Supplying a `variables` object. If this is supplied, this data will always take priority.\n * This incoming `variables` object can be two formats:\n * `{ variableName: { default: 'value' } }` and `{ variableName: 'value' }`. If the former is\n * present, that will take precedence over the latter.\n * - If the supplied `variables` object is empty or does not match the current template name,\n * we fallback to the data stored in `this.user` and attempt to match against that.\n * See `getUserVariable` for some more information on how this data is pulled from `this.user`.\n *\n * If no variables supplied match up with the template name, the template name will instead be\n * used as the variable data.\n *\n * @param url A URL to swap variables into.\n * @param variables An object containing variables to swap into the URL.\n */\n replaceUrl(url: string, variables: ServerVariable = {}): string {\n // When we're constructing URLs, server URLs with trailing slashes cause problems with doing\n // lookups, so if we have one here on, slice it off.\n return stripTrailingSlash(\n url.replace(SERVER_VARIABLE_REGEX, (original: string, key: string) => {\n if (key in variables) {\n const data = variables[key];\n if (typeof data === 'object') {\n if (!Array.isArray(data) && data !== null && 'default' in data) {\n return data.default as string;\n }\n } else {\n return data as string;\n }\n }\n\n const userVariable = getUserVariable(this.user, key);\n if (userVariable) {\n return userVariable as string;\n }\n\n return original;\n }),\n );\n }\n\n /**\n * Retrieve an Operation of Webhook class instance for a given path and method.\n *\n * @param path Path to lookup and retrieve.\n * @param method HTTP Method to retrieve on the path.\n */\n operation(\n path: string,\n method: HttpMethods,\n opts: {\n /**\n * If you prefer to first look for a webhook with this path and method.\n */\n isWebhook?: boolean;\n } = {},\n ): Operation {\n // If we're unable to locate an operation for this path+method combination within the API\n // definition, we should still set an empty schema on the operation in the `Operation` class\n // because if we don't trying to use any of the accessors on that class are going to fail as\n // `schema` will be `undefined`.\n let operation: OperationObject = {\n parameters: [],\n };\n\n if (opts.isWebhook) {\n const api = this.api as OpenAPIV3_1.Document;\n // Typecasting this to a `PathsObject` because we don't have `$ref` pointers here.\n if ((api?.webhooks[path] as PathsObject)?.[method]) {\n operation = (api.webhooks[path] as PathsObject)[method] as OperationObject;\n return new Webhook(api, path, method, operation);\n }\n }\n\n if (this?.api?.paths?.[path]?.[method]) {\n operation = this.api.paths[path][method];\n }\n\n return new Operation(this.api, path, method, operation);\n }\n\n findOperationMatches(url: string): PathMatches {\n const { origin, hostname } = new URL(url);\n const originRegExp = new RegExp(origin, 'i');\n const { servers, paths } = this.api;\n\n let pathName: string;\n let targetServer: ServerObject;\n let matchedServer: ServerObject;\n\n if (!servers || !servers.length) {\n // If this API definition doesn't have any servers set up let's treat it as if it were\n // https://example.com because that's the default origin we add in `normalizedUrl` under the\n // same circumstances. Without this we won't be able to match paths within what is otherwise\n // a valid OpenAPI definition.\n matchedServer = {\n url: 'https://example.com',\n };\n } else {\n matchedServer = servers.find(s => originRegExp.exec(this.replaceUrl(s.url, s.variables || {})));\n if (!matchedServer) {\n const hostnameRegExp = new RegExp(hostname);\n matchedServer = servers.find(s => hostnameRegExp.exec(this.replaceUrl(s.url, s.variables || {})));\n }\n }\n\n if (matchedServer) {\n // Instead of setting `url` directly against `matchedServer` we need to set it to an\n // intermediary object as directly modifying `matchedServer.url` will in turn update\n // `this.servers[idx].url` which we absolutely do not want to happen.\n targetServer = {\n ...matchedServer,\n url: this.replaceUrl(matchedServer.url, matchedServer.variables || {}),\n };\n\n [, pathName] = url.split(new RegExp(targetServer.url, 'i'));\n }\n\n // If we **still** haven't found a matching server, then the OAS server URL might have server\n // variables and we should loosen it up with regex to try to discover a matching path.\n //\n // For example if an OAS has `https://{region}.node.example.com/v14` set as its server URL, and\n // the `this.user` object has a `region` value of `us`, if we're trying to locate an operation\n // for https://eu.node.example.com/v14/api/esm we won't be able to because normally the users\n // `region` of `us` will be transposed in and we'll be trying to locate `eu.node.example.com`\n // in `us.node.example.com` -- which won't work.\n //\n // So what this does is transform `https://{region}.node.example.com/v14` into\n // `https://([-_a-zA-Z0-9[\\\\]]+).node.example.com/v14`, and from there we'll be able to match\n // https://eu.node.example.com/v14/api/esm and ultimately find the operation matches for\n // `/api/esm`.\n if (!matchedServer || !pathName) {\n const matchedServerAndPath = servers\n .map(server => {\n const rgx = transformUrlIntoRegex(server.url);\n const found = new RegExp(rgx).exec(url);\n if (!found) {\n return undefined;\n }\n\n return {\n matchedServer: server,\n pathName: url.split(new RegExp(rgx)).slice(-1).pop(),\n };\n })\n .filter(Boolean);\n\n if (!matchedServerAndPath.length) {\n return undefined;\n }\n\n pathName = matchedServerAndPath[0].pathName;\n targetServer = {\n ...matchedServerAndPath[0].matchedServer,\n };\n }\n\n if (pathName === undefined) return undefined;\n if (pathName === '') pathName = '/';\n const annotatedPaths = generatePathMatches(paths, pathName, targetServer.url);\n if (!annotatedPaths.length) return undefined;\n\n return annotatedPaths;\n }\n\n /**\n * Discover an operation in an OAS from a fully-formed URL and HTTP method. Will return an object\n * containing a `url` object and another one for `operation`. This differs from `getOperation()`\n * in that it does not return an instance of the `Operation` class.\n *\n * @param url A full URL to look up.\n * @param method The cooresponding HTTP method to look up.\n */\n findOperation(url: string, method: HttpMethods): PathMatch {\n const annotatedPaths = this.findOperationMatches(url);\n if (!annotatedPaths) {\n return undefined;\n }\n\n const matches = filterPathMethods(annotatedPaths, method) as {\n operation: PathsObject;\n url: PathMatch['url']; // @fixme this should actually be an `OperationObject`.\n }[];\n if (!matches.length) return undefined;\n return findTargetPath(matches);\n }\n\n /**\n * Discover an operation in an OAS from a fully-formed URL without an HTTP method. Will return an\n * object containing a `url` object and another one for `operation`.\n *\n * @param url A full URL to look up.\n */\n findOperationWithoutMethod(url: string): PathMatch {\n const annotatedPaths = this.findOperationMatches(url);\n if (!annotatedPaths) {\n return undefined;\n }\n return findTargetPath(annotatedPaths);\n }\n\n /**\n * Retrieve an operation in an OAS from a fully-formed URL and HTTP method. Differs from\n * `findOperation` in that while this method will return an `Operation` instance,\n * `findOperation()` does not.\n *\n * @param url A full URL to look up.\n * @param method The cooresponding HTTP method to look up.\n */\n getOperation(url: string, method: HttpMethods): Operation {\n const op = this.findOperation(url, method);\n if (op === undefined) {\n return undefined;\n }\n\n return this.operation(op.url.nonNormalizedPath, method);\n }\n\n /**\n * Retrieve an operation in an OAS by an `operationId`.\n *\n * If an operation does not have an `operationId` one will be generated in place, using the\n * default behavior of `Operation.getOperationId()`, and then asserted against your query.\n *\n * Note that because `operationId`s are unique that uniqueness does include casing so the ID\n * you are looking for will be asserted as an exact match.\n *\n * @see {Operation.getOperationId()}\n * @param id The `operationId` to look up.\n */\n getOperationById(id: string): Operation | Webhook {\n let found: Operation | Webhook;\n\n Object.values(this.getPaths()).forEach(operations => {\n if (found) return;\n found = Object.values(operations).find(operation => operation.getOperationId() === id);\n });\n\n if (found) {\n return found;\n }\n\n Object.entries(this.getWebhooks()).forEach(([, webhooks]) => {\n if (found) return;\n found = Object.values(webhooks).find(webhook => webhook.getOperationId() === id);\n });\n\n return found;\n }\n\n /**\n * With an object of user information, retrieve the appropriate API auth keys from the current\n * OAS definition.\n *\n * @see {@link https://docs.readme.com/docs/passing-data-to-jwt}\n * @param user User\n * @param selectedApp The user app to retrieve an auth key for.\n */\n getAuth(user: User, selectedApp?: number | string): AuthForHAR {\n if (!this.api?.components?.securitySchemes) {\n return {};\n }\n\n return getAuth(this.api, user, selectedApp);\n }\n\n /**\n * Returns the `paths` object that exists in this API definition but with every `method` mapped\n * to an instance of the `Operation` class.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#openapi-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}\n */\n getPaths(): Record<string, Record<HttpMethods, Operation | Webhook>> {\n /**\n * Because a path doesn't need to contain a keyed-object of HTTP methods, we should exclude\n * anything from within the paths object that isn't a known HTTP method.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#fixed-fields-7}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#fixed-fields-7}\n */\n const paths: Record<string, Record<HttpMethods, Operation | Webhook>> = {};\n\n Object.keys(this.api.paths ? this.api.paths : []).forEach(path => {\n // If this is a specification extension then we should ignore it.\n if (path.startsWith('x-')) {\n return;\n }\n\n paths[path] = {} as Record<HttpMethods, Operation | Webhook>;\n\n // Though this library is generally unaware of `$ref` pointers we're making a singular\n // exception with this accessor out of convenience.\n if ('$ref' in this.api.paths[path]) {\n this.api.paths[path] = findSchemaDefinition(this.api.paths[path].$ref, this.api);\n }\n\n Object.keys(this.api.paths[path]).forEach((method: HttpMethods) => {\n if (!supportedMethods.includes(method)) return;\n\n paths[path][method] = this.operation(path, method);\n });\n });\n\n return paths;\n }\n\n /**\n * Returns the `webhooks` object that exists in this API definition but with every `method`\n * mapped to an instance of the `Webhook` class.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#openapi-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}\n */\n getWebhooks(): Record<string, Record<HttpMethods, Webhook>> {\n const webhooks: Record<string, Record<HttpMethods, Webhook>> = {};\n const api = this.api as OpenAPIV3_1.Document;\n\n Object.keys(api.webhooks ? api.webhooks : []).forEach(id => {\n webhooks[id] = {} as Record<HttpMethods, Webhook>;\n Object.keys(api.webhooks[id]).forEach((method: HttpMethods) => {\n webhooks[id][method] = this.operation(id, method, { isWebhook: true }) as Webhook;\n });\n });\n\n return webhooks;\n }\n\n /**\n * Return an array of all tag names that exist on this API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#openapi-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}\n * @param setIfMissing If a tag is not present on an operation that operations path will be added\n * into the list of tags returned.\n */\n getTags(setIfMissing = false): string[] {\n const allTags = new Set<string>();\n\n const oasTags =\n this.api.tags?.map(tag => {\n return tag.name;\n }) || [];\n\n const disableTagSorting = getExtension('disable-tag-sorting', this.api);\n\n Object.entries(this.getPaths()).forEach(([path, operations]) => {\n Object.values(operations).forEach(operation => {\n const tags = operation.getTags();\n if (setIfMissing && !tags.length) {\n allTags.add(path);\n return;\n }\n\n tags.forEach(tag => {\n allTags.add(tag.name);\n });\n });\n });\n\n Object.entries(this.getWebhooks()).forEach(([path, webhooks]) => {\n Object.values(webhooks).forEach(webhook => {\n const tags = webhook.getTags();\n if (setIfMissing && !tags.length) {\n allTags.add(path);\n return;\n }\n\n tags.forEach(tag => {\n allTags.add(tag.name);\n });\n });\n });\n\n // Tags that exist only on the endpoint\n const endpointTags: string[] = [];\n // Tags that the user has defined in the `tags` array\n const tagsArray: string[] = [];\n\n // Distinguish between which tags exist in the `tags` array and which tags\n // exist only at the endpoint level. For tags that exist only at the\n // endpoint level, we'll just tack that on to the end of the sorted tags.\n if (disableTagSorting) {\n return Array.from(allTags);\n }\n\n Array.from(allTags).forEach(tag => {\n if (oasTags.includes(tag)) {\n tagsArray.push(tag);\n } else {\n endpointTags.push(tag);\n }\n });\n\n let sortedTags = tagsArray.sort((a, b) => {\n return oasTags.indexOf(a) - oasTags.indexOf(b);\n });\n\n sortedTags = sortedTags.concat(endpointTags);\n\n return sortedTags;\n }\n\n /**\n * Determine if a given a custom specification extension exists within the API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}\n * @param extension Specification extension to lookup.\n */\n hasExtension(extension: string): boolean {\n return hasRootExtension(extension, this.api);\n }\n\n /**\n * Retrieve a custom specification extension off of the API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}\n * @param extension Specification extension to lookup.\n */\n getExtension(extension: string | keyof Extensions, operation?: Operation): any {\n return getExtension(extension, this.api, operation);\n }\n\n /**\n * Determine if a given OpenAPI custom extension is valid or not.\n *\n * @see {@link https://docs.readme.com/docs/openapi-extensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}\n * @param extension Specification extension to validate.\n * @throws\n */\n validateExtension(extension: keyof Extensions): void {\n if (this.hasExtension('x-readme')) {\n const data = this.getExtension('x-readme') as Extensions;\n if (typeof data !== 'object' || Array.isArray(data) || data === null) {\n throw new TypeError('\"x-readme\" must be of type \"Object\"');\n }\n\n if (extension in data) {\n if ([CODE_SAMPLES, HEADERS, PARAMETER_ORDERING, SAMPLES_LANGUAGES].includes(extension)) {\n if (!Array.isArray(data[extension])) {\n throw new TypeError(`\"x-readme.${extension}\" must be of type \"Array\"`);\n }\n\n if (extension === PARAMETER_ORDERING) {\n validateParameterOrdering(data[extension], `x-readme.${extension}`);\n }\n } else if (extension === OAUTH_OPTIONS) {\n if (typeof data[extension] !== 'object') {\n throw new TypeError(`\"x-readme.${extension}\" must be of type \"Object\"`);\n }\n } else if (typeof data[extension] !== 'boolean') {\n throw new TypeError(`\"x-readme.${extension}\" must be of type \"Boolean\"`);\n }\n }\n }\n\n // If the extension isn't grouped under `x-readme`, we need to look for them with `x-` prefixes.\n if (this.hasExtension(`x-${extension}`)) {\n const data = this.getExtension(`x-${extension}`);\n if ([CODE_SAMPLES, HEADERS, PARAMETER_ORDERING, SAMPLES_LANGUAGES].includes(extension)) {\n if (!Array.isArray(data)) {\n throw new TypeError(`\"x-${extension}\" must be of type \"Array\"`);\n }\n\n if (extension === PARAMETER_ORDERING) {\n validateParameterOrdering(data, `x-${extension}`);\n }\n } else if (extension === OAUTH_OPTIONS) {\n if (typeof data !== 'object') {\n throw new TypeError(`\"x-${extension}\" must be of type \"Object\"`);\n }\n } else if (typeof data !== 'boolean') {\n throw new TypeError(`\"x-${extension}\" must be of type \"Boolean\"`);\n }\n }\n }\n\n /**\n * Validate all of our custom or known OpenAPI extensions, throwing exceptions when necessary.\n *\n * @see {@link https://docs.readme.com/docs/openapi-extensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}\n */\n validateExtensions(): void {\n Object.keys(extensionDefaults).forEach((extension: keyof Extensions) => {\n this.validateExtension(extension);\n });\n }\n\n /**\n * Retrieve any circular `$ref` pointers that maybe present within the API definition.\n *\n * This method requires that you first dereference the definition.\n *\n * @see Oas.dereference\n */\n getCircularReferences(): string[] {\n if (!this.dereferencing.complete) {\n throw new Error('#dereference() must be called first in order for this method to obtain circular references.');\n }\n\n return this.dereferencing.circularRefs;\n }\n\n /**\n * Dereference the current OAS definition so it can be parsed free of worries of `$ref` schemas\n * and circular structures.\n *\n */\n async dereference(\n opts: {\n /**\n * A callback method can be supplied to be called when dereferencing is complete. Used for\n * debugging that the multi-promise handling within this method works.\n *\n * @private\n */\n cb?: () => void;\n\n /**\n * Preserve component schema names within themselves as a `title`.\n */\n preserveRefAsJSONSchemaTitle?: boolean;\n } = { preserveRefAsJSONSchemaTitle: false },\n ): Promise<(typeof this.promises)[] | boolean> {\n if (this.dereferencing.complete) {\n return new Promise(resolve => {\n resolve(true);\n });\n }\n\n if (this.dereferencing.processing) {\n return new Promise((resolve, reject) => {\n this.promises.push({ resolve, reject });\n });\n }\n\n this.dereferencing.processing = true;\n\n // Discriminator Phase 1: Find discriminator schemas and their children before dereferencing (allOf $refs are resolved\n // during dereferencing). For schemas with a discriminator using allOf inheritance, we build a\n // oneOf array from the discovered child schemas so consumers can see the polymorphic options.\n // (see https://spec.openapis.org/oas/v3.0.0.html#fixed-fields-20)\n const discriminatorChildrenMap = findDiscriminatorChildren(this.api);\n\n const { api, promises } = this;\n\n // Because referencing will eliminate any lineage back to the original `$ref`, information that\n // we might need at some point, we should run through all available component schemas and denote\n // what their name is so that when dereferencing happens below those names will be preserved.\n if (api?.components?.schemas && typeof api.components.schemas === 'object') {\n Object.keys(api.components.schemas).forEach(schemaName => {\n // As of OpenAPI 3.1 component schemas can be primitives or arrays. If this happens then we\n // shouldn't try to add `title` or `x-readme-ref-name` properties because we can't. We'll\n // have some data loss on these schemas but as they aren't objects they likely won't be used\n // in ways that would require needing a `title` or `x-readme-ref-name` anyways.\n if (\n isPrimitive(api.components.schemas[schemaName]) ||\n Array.isArray(api.components.schemas[schemaName]) ||\n api.components.schemas[schemaName] === null\n ) {\n return;\n }\n\n if (opts.preserveRefAsJSONSchemaTitle) {\n // This may result in some data loss if there's already a `title` present, but in the case\n // where we want to generate code for the API definition (see http://npm.im/api), we'd\n // prefer to retain original reference name as a title for any generated types.\n (api.components.schemas[schemaName] as SchemaObject).title = schemaName;\n }\n\n (api.components.schemas[schemaName] as SchemaObject)['x-readme-ref-name'] = schemaName;\n });\n }\n\n const circularRefs: Set<string> = new Set();\n\n return dereference<OASDocument>(api, {\n resolve: {\n // We shouldn't be resolving external pointers at this point so just ignore them.\n external: false,\n },\n dereference: {\n // If circular `$refs` are ignored they'll remain in the OAS as `$ref: String`, otherwise\n // `$ref‘ just won't exist. This allows us to do easy circular reference detection.\n circular: 'ignore',\n\n onCircular: (path: string) => {\n // The circular references that are coming out of `json-schema-ref-parser` are prefixed\n // with the schema path (file path, URL, whatever) that the schema exists in. Because\n // we don't care about this information for this reporting mechanism, and only the\n // `$ref` pointer, we're removing it.\n circularRefs.add(`#${path.split('#')[1]}`);\n },\n },\n })\n .then((dereferenced: OASDocument) => {\n this.api = dereferenced;\n\n // Discriminator Phase 2: Build oneOf arrays for discriminator schemas using dereferenced child schemas.\n // This must be done after dereferencing so we have the fully resolved child schemas.\n if (discriminatorChildrenMap && discriminatorChildrenMap.size > 0) {\n buildDiscriminatorOneOf(this.api, discriminatorChildrenMap);\n }\n\n this.promises = promises;\n this.dereferencing = {\n processing: false,\n complete: true,\n // We need to convert our `Set` to an array in order to match the typings.\n circularRefs: [...circularRefs],\n };\n\n // Used for debugging that dereferencing promise awaiting works.\n if (opts.cb) {\n opts.cb();\n }\n })\n .then(() => {\n return this.promises.map(deferred => deferred.resolve());\n });\n }\n}\n","import type { DiscriminatorChildrenMap, DiscriminatorObject, OASDocument, SchemaObject } from '../types.js';\n\nimport { isRef } from '../types.js';\nimport { cloneObject } from './clone-object.js';\n\n/**\n * Determines if a schema has a discriminator but is missing oneOf/anyOf polymorphism.\n *\n * @param schema Schema to check.\n * @returns If the schema has a discriminator but no oneOf/anyOf.\n */\nfunction hasDiscriminatorWithoutPolymorphism(schema: SchemaObject): boolean {\n if (!schema || typeof schema !== 'object') return false;\n if (!('discriminator' in schema)) return false;\n if ('oneOf' in schema || 'anyOf' in schema) return false;\n return true;\n}\n\n/**\n * Checks if a schema's allOf contains a $ref to a specific schema name.\n *\n * @param schema Schema to check.\n * @param targetSchemaName The schema name to look for (e.g., 'Pet').\n * @returns If the schema's allOf contains a $ref to the target schema.\n */\nfunction allOfReferencesSchema(schema: SchemaObject, targetSchemaName: string): boolean {\n if (!schema || typeof schema !== 'object') return false;\n if (!('allOf' in schema) || !Array.isArray(schema.allOf)) return false;\n\n return schema.allOf.some(item => {\n if (isRef(item)) {\n // Check if the $ref points to the target schema\n // Format: #/components/schemas/SchemaName\n const refParts = item.$ref.split('/');\n const refSchemaName = refParts[refParts.length - 1];\n return refSchemaName === targetSchemaName;\n }\n return false;\n });\n}\n\n/**\n * Phase 1: Before dereferencing, identify discriminator schemas and their children via allOf\n * inheritance. Returns a mapping that can be used after dereferencing.\n *\n * We don't add oneOf here because that would create circular references\n * (Pet → Cat → Pet via allOf) which would break dereferencing.\n *\n * @param api The OpenAPI definition to process (before dereferencing).\n * @returns A map of discriminator schema names to their child schema names.\n */\nexport function findDiscriminatorChildren(api: OASDocument): DiscriminatorChildrenMap {\n const childrenMap: DiscriminatorChildrenMap = new Map();\n\n if (!api?.components?.schemas || typeof api.components.schemas !== 'object') {\n return childrenMap;\n }\n\n const schemas = api.components.schemas as Record<string, SchemaObject>;\n const schemaNames = Object.keys(schemas);\n\n // Find all schemas with discriminator but no oneOf/anyOf\n const discriminatorSchemas: string[] = schemaNames.filter(name => {\n return hasDiscriminatorWithoutPolymorphism(schemas[name]);\n });\n\n // For each discriminator schema, record child schema names\n for (const baseName of discriminatorSchemas) {\n const baseSchema = schemas[baseName] as SchemaObject & { discriminator: DiscriminatorObject };\n const discriminator = baseSchema.discriminator;\n\n let childSchemaNames: string[] | undefined;\n\n // If there's already a mapping defined, use that\n if (discriminator.mapping && typeof discriminator.mapping === 'object') {\n const mappingRefs = Object.values(discriminator.mapping);\n if (mappingRefs.length > 0) {\n // Extract schema names from refs like \"#/components/schemas/Cat\"\n childSchemaNames = mappingRefs.map(ref => {\n const parts = ref.split('/');\n return parts[parts.length - 1];\n });\n }\n }\n\n // Otherwise, scan for schemas that extend this base via allOf\n if (!childSchemaNames || childSchemaNames.length === 0) {\n childSchemaNames = schemaNames.filter(name => {\n if (name === baseName) return false;\n return allOfReferencesSchema(schemas[name], baseName);\n });\n }\n\n // Store child schema names in the map\n if (childSchemaNames.length > 0) {\n childrenMap.set(baseName, childSchemaNames);\n }\n }\n\n return childrenMap;\n}\n\n/**\n * Phase 2: After dereferencing, build oneOf arrays for discriminator schemas using the\n * dereferenced child schemas.\n *\n * @param api The OpenAPI definition to process (after dereferencing).\n * @param childrenMap The mapping of discriminator schemas to their children (from findDiscriminatorChildren).\n */\nexport function buildDiscriminatorOneOf(api: OASDocument, childrenMap: DiscriminatorChildrenMap): void {\n // Early exit if there are no component schemas or no mappings\n if (!api?.components?.schemas || typeof api.components.schemas !== 'object') {\n return;\n }\n if (childrenMap.size === 0) {\n return;\n }\n\n const schemas = api.components.schemas as Record<string, SchemaObject>;\n\n // Build oneOf for each discriminator schema\n for (const [schemaName, childNames] of childrenMap) {\n const schema = schemas[schemaName];\n if (!schema) continue;\n\n // Build oneOf from dereferenced child schemas\n const oneOf: SchemaObject[] = [];\n for (const childName of childNames) {\n if (schemas[childName]) {\n // Clone the schema to avoid circular reference issues\n oneOf.push(cloneObject(schemas[childName]));\n }\n }\n\n if (oneOf.length > 0) {\n (schema as Record<string, unknown>).oneOf = oneOf;\n }\n }\n}\n","import type { AuthForHAR, KeyedSecuritySchemeObject, OASDocument, SecuritySchemeObject, User } from '../types.js';\n\ntype authKey = unknown | { password: number | string; user: number | string } | null;\n\n/**\n * @param user User to retrieve retrieve an auth key for.\n * @param scheme The type of security scheme that we want a key for.\n */\nfunction getKey(user: User, scheme: KeyedSecuritySchemeObject): authKey {\n switch (scheme.type) {\n case 'oauth2':\n case 'apiKey':\n return user[scheme._key] || user.apiKey || scheme['x-default'] || null;\n\n case 'http':\n if (scheme.scheme === 'basic') {\n return user[scheme._key] || { user: user.user || null, pass: user.pass || null };\n }\n\n if (scheme.scheme === 'bearer') {\n return user[scheme._key] || user.apiKey || scheme['x-default'] || null;\n }\n return null;\n\n default:\n return null;\n }\n}\n\n/**\n * Retrieve auth keys for a specific security scheme for a given user for a specific \"app\" that\n * they have configured.\n *\n * For `scheme` we're typing it to a union of `SecurityScheme` and `any` because we have handling\n * and tests for an unknown or unrecognized `type` and though it's not possible with the\n * `SecurityScheme.type` to be unrecognized it may still be possible to get an unrecognized scheme\n * with this method in the wild as we have API definitions in our database that were ingested\n * before we had good validation in place.\n *\n * @param user User\n * @param scheme Security scheme to get auth keys for.\n * @param selectedApp The user app to retrieve an auth key for.\n */\nexport function getByScheme(\n user: User,\n scheme = {} as KeyedSecuritySchemeObject,\n selectedApp?: number | string,\n): authKey {\n if (user?.keys?.length) {\n if (selectedApp) {\n return getKey(\n user.keys.find(key => key.name === selectedApp),\n scheme,\n );\n }\n\n return getKey(user.keys[0], scheme);\n }\n\n return getKey(user, scheme);\n}\n\n/**\n * Retrieve auth keys for an API definition from a given user for a specific \"app\" that they have\n * configured.\n *\n * @param api API definition\n * @param user User\n * @param selectedApp The user app to retrieve an auth key for.\n */\nexport function getAuth(api: OASDocument, user: User, selectedApp?: number | string): AuthForHAR {\n return Object.keys(api?.components?.securitySchemes || {})\n .map(scheme => {\n return {\n [scheme]: getByScheme(\n user,\n {\n // This sucks but since we dereference we'll never have a `$ref` pointer here with a\n // `ReferenceObject` type.\n ...(api.components.securitySchemes[scheme] as SecuritySchemeObject),\n _key: scheme,\n },\n selectedApp,\n ),\n };\n })\n .reduce((prev, next) => Object.assign(prev, next), {});\n}\n","import type { User } from '../types.js';\n\n/**\n * Retrieve a user variable off of a given user.\n *\n * @see {@link https://docs.readme.com/docs/passing-data-to-jwt}\n * @param user The user to get a user variable for.\n * @param property The name of the variable to retrieve.\n * @param selectedApp The user app to retrieve an auth key for.\n */\n// biome-ignore lint/style/noDefaultExport: This is safe for now.\nexport default function getUserVariable(user: User, property: string, selectedApp?: number | string): unknown {\n let key = user;\n\n if ('keys' in user && Array.isArray(user.keys) && user.keys.length) {\n if (selectedApp) {\n key = user.keys.find(k => k.name === selectedApp);\n } else {\n key = user.keys[0];\n }\n }\n\n return key[property] || user[property] || null;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas/dist/chunk-6VA5PEAW.cjs","../src/lib/clone-object.ts","../src/lib/helpers.ts","../src/lib/matches-mimetype.ts","../src/lib/openapi-to-json-schema.ts","../src/operation/lib/get-parameters-as-json-schema.ts"],"names":["types","components","schema"],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACVO,SAAS,WAAA,CAAe,GAAA,EAAW;AACxC,EAAA,GAAA,CAAI,OAAO,IAAA,IAAQ,WAAA,EAAa;AAC9B,IAAA,OAAO,KAAA,CAAA;AAAA,EACT;AAEA,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,SAAA,CAAU,GAAG,CAAC,CAAA;AACvC;ADWA;AACA;AEhBO,SAAS,aAAA,CAAc,MAAA,EAAsB,aAAA,EAA4C;AAC9F,EAAA,GAAA,CAAI,KAAA,CAAM,OAAA,CAAQ,MAAA,CAAO,IAAI,CAAA,EAAG;AAC9B,IAAA,OAAO,MAAA,CAAO,IAAA,CAAK,QAAA,CAAS,aAAa,CAAA;AAAA,EAC3C;AAEA,EAAA,OAAO,MAAA,CAAO,KAAA,IAAS,aAAA;AACzB;AAEO,SAAS,QAAA,CAAS,GAAA,EAA8C;AACrE,EAAA,OAAO,OAAO,IAAA,IAAQ,SAAA,GAAY,IAAA,IAAQ,KAAA,GAAQ,CAAC,KAA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AAA;AACF,cAAA;AAEY,cAAA;AAEN,cAAA;AACJ,gBAAA;AACA,gBAAA;AACA,gBAAA;AACA,gBAAA;AACA,gBAAA;AACA,gBAAA;AACD,cAAA;AAEQ,cAAA;AAGA,gBAAA;AAAA;AAAA;AAAA;AAKM,gBAAA;AACX,cAAA;AACN,YAAA;AACF,UAAA;AACF,QAAA;AAIY,QAAA;AACOC,UAAAA;AACR,YAAA;AACT,UAAA;AACF,QAAA;AAEiB,QAAA;AAEL,QAAA;AACI,UAAA;AAChB,QAAA;AAEO,QAAA;AACJ,MAAA;AAGoC,MAAA;AACjC,QAAA;AACN,QAAA;AACA,QAAA;AACF,MAAA;AAEO,MAAA;AACL,QAAA;AACiB,QAAA;AACjB,QAAA;AACiB,QAAA;AACnB,MAAA;AAEa,IAAA;AAEP,IAAA;AACD,MAAA;AACe,IAAA;AACd,MAAA;AACV,IAAA;AAKwB,IAAA;AACjB,IAAA;AACL,MAAA;AACQ,QAAA;AACO,QAAA;AACL,QAAA;AACC,UAAA;AACT,QAAA;AACiB,QAAA;AAEL,UAAA;AACE,UAAA;AACC,YAAA;AACT,UAAA;AAEF,QAAA;AACN,MAAA;AACF,IAAA;AACF,EAAA;AAIe,EAAA;AACN,IAAA;AACT,EAAA;AAKkB,EAAA;AACQ,EAAA;AACF,EAAA;AAEJ,EAAA;AAKd,EAAA;AAGa,EAAA;AAGZ,EAAA;AAQe,IAAA;AAEF,MAAA;AAChB,IAAA;AAGW,IAAA;AAEJ,IAAA;AAEO,EAAA;AACU,IAAA;AACzB,EAAA;AACL;ALmW4B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/erunion/code/readme/oas/packages/oas/dist/chunk-6VA5PEAW.cjs","sourcesContent":[null,"export function cloneObject<T>(obj: T): T {\n if (typeof obj === 'undefined') {\n return undefined;\n }\n\n return JSON.parse(JSON.stringify(obj));\n}\n","import type { SchemaObject } from '../types.js';\n\nexport function hasSchemaType(schema: SchemaObject, discriminator: 'array' | 'object'): boolean {\n if (Array.isArray(schema.type)) {\n return schema.type.includes(discriminator);\n }\n\n return schema.type === discriminator;\n}\n\nexport function isObject(val: unknown): val is Record<string, unknown> {\n return typeof val === 'object' && val !== null && !Array.isArray(val);\n}\n\nexport function isPrimitive(val: unknown): val is boolean | number | string {\n return typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean';\n}\n","function matchesMediaType(types: string[], mediaType: string): boolean {\n return types.some(type => {\n return mediaType.indexOf(type) > -1;\n });\n}\n\n// biome-ignore lint/style/noDefaultExport: This is safe for now.\nexport default {\n formUrlEncoded: (mimeType: string): boolean => {\n return matchesMediaType(['application/x-www-form-urlencoded'], mimeType);\n },\n\n json: (contentType: string): boolean => {\n return matchesMediaType(\n ['application/json', 'application/x-json', 'text/json', 'text/x-json', '+json'],\n contentType,\n );\n },\n\n multipart: (contentType: string): boolean => {\n return matchesMediaType(\n ['multipart/mixed', 'multipart/related', 'multipart/form-data', 'multipart/alternative'],\n contentType,\n );\n },\n\n wildcard: (contentType: string): boolean => {\n return contentType === '*/*';\n },\n\n xml: (contentType: string): boolean => {\n return matchesMediaType(\n [\n 'application/xml',\n 'application/xml-external-parsed-entity',\n 'application/xml-dtd',\n 'text/xml',\n 'text/xml-external-parsed-entity',\n '+xml',\n ],\n contentType,\n );\n },\n};\n","import type { JSONSchema7TypeName } from 'json-schema';\nimport type { OpenAPIV3_1 } from 'openapi-types';\nimport type { JSONSchema, OASDocument, RequestBodyObject, SchemaObject } from '../types.js';\n\nimport mergeJSONSchemaAllOf from 'json-schema-merge-allof';\nimport jsonpointer from 'jsonpointer';\nimport removeUndefinedObjects from 'remove-undefined-objects';\n\nimport { isOpenAPI30, isRef, isSchema } from '../types.js';\nimport { hasSchemaType, isObject, isPrimitive } from './helpers.js';\n\n/**\n * This list has been pulled from `openapi-schema-to-json-schema` but been slightly modified to fit\n * within the constraints in which ReadMe uses the output from this library in schema form\n * rendering as while properties like `readOnly` aren't represented within JSON Schema, we support\n * it within that library's handling of OpenAPI-friendly JSON Schema.\n *\n * @see {@link https://github.com/openapi-contrib/openapi-schema-to-json-schema/blob/main/src/consts.ts}\n */\nconst UNSUPPORTED_SCHEMA_PROPS = [\n 'example', // OpenAPI supports `example` but we're mapping it to `examples` in this library.\n 'externalDocs',\n 'xml',\n] as const;\n\nexport interface toJSONSchemaOptions {\n /**\n * Whether or not to extend descriptions with a list of any present enums.\n */\n addEnumsToDescriptions?: boolean;\n\n /**\n * Current location within the schema -- this is a JSON pointer.\n */\n currentLocation?: string;\n\n /**\n * Object containing a global set of defaults that we should apply to schemas that match it.\n */\n globalDefaults?: Record<string, unknown>;\n\n /**\n * If you wish to hide properties that are marked as being `readOnly`.\n */\n hideReadOnlyProperties?: boolean;\n\n /**\n * If you wish to hide properties that are marked as being `writeOnly`.\n */\n hideWriteOnlyProperties?: boolean;\n\n /**\n * Is this schema the child of a polymorphic `allOf` schema?\n */\n isPolymorphicAllOfChild?: boolean;\n\n /**\n * Array of parent `default` schemas to utilize when attempting to path together schema defaults.\n */\n prevDefaultSchemas?: SchemaObject[];\n\n /**\n * Array of parent `example` schemas to utilize when attempting to path together schema examples.\n */\n prevExampleSchemas?: SchemaObject[];\n\n /**\n * A function that's called anytime a (circular) `$ref` is found.\n */\n refLogger?: (ref: string, type: 'discriminator' | 'ref') => void;\n\n /**\n * With a transformer you can transform any data within a given schema, like say if you want\n * to rewrite a potentially unsafe `title` that might be eventually used as a JS variable\n * name, just make sure to return your transformed schema.\n */\n transformer?: (schema: SchemaObject) => SchemaObject;\n}\n\n/**\n * Encode a string to be used as a JSON pointer.\n *\n * @see {@link https://tools.ietf.org/html/rfc6901}\n * @param str String to encode into string that can be used as a JSON pointer.\n */\nfunction encodePointer(str: string) {\n return str.replace('~', '~0').replace('/', '~1');\n}\n\nexport function getSchemaVersionString(schema: SchemaObject, api: OASDocument): string {\n // If we're not on OpenAPI 3.1+ then we should fall back to the default schema version.\n if (isOpenAPI30(api)) {\n // This should remain as an HTTP url, not HTTPS.\n return 'http://json-schema.org/draft-04/schema#';\n }\n\n /**\n * If the schema indicates the version, prefer that.\n *\n * We use `as` here because the schema *should* be an OAS 3.1 schema due to the `isOpenAPI30` check\n * above.\n */\n if ((schema as OpenAPIV3_1.SchemaObject).$schema) {\n return (schema as OpenAPIV3_1.SchemaObject).$schema;\n }\n\n // If the user defined a global schema version on their OAS document, prefer that.\n if (api.jsonSchemaDialect) {\n return api.jsonSchemaDialect;\n }\n\n return 'https://json-schema.org/draft/2020-12/schema#';\n}\n\nfunction isPolymorphicSchema(schema: SchemaObject): boolean {\n return 'allOf' in schema || 'anyOf' in schema || 'oneOf' in schema;\n}\n\nfunction isRequestBodySchema(schema: unknown): schema is RequestBodyObject {\n return 'content' in (schema as RequestBodyObject);\n}\n\n/**\n * Given a JSON pointer, a type of property to look for, and an array of schemas do a reverse\n * search through them until we find the JSON pointer, or part of it, within the array.\n *\n * This function will allow you to take a pointer like `/tags/name` and return back `buster` from\n * the following array:\n *\n * ```\n * [\n * {\n * example: {id: 20}\n * },\n * {\n * examples: {\n * distinctName: {\n * tags: {name: 'buster'}\n * }\n * }\n * }\n * ]\n * ```\n *\n * As with most things however, this is not without its quirks! If a deeply nested property shares\n * the same name as an example that's further up the stack (like `tags.id` and an example for `id`),\n * there's a chance that it'll be misidentified as having an example and receive the wrong value.\n *\n * That said, any example is usually better than no example though, so while it's quirky behavior\n * it shouldn't raise immediate cause for alarm.\n *\n * @see {@link https://tools.ietf.org/html/rfc6901}\n * @param property Specific type of schema property to look for a value for.\n * @param pointer JSON pointer to search for an example for.\n * @param schemas Array of previous schemas we've found relating to this pointer.\n */\nfunction searchForValueByPropAndPointer(\n property: 'default' | 'example',\n pointer: string,\n schemas: toJSONSchemaOptions['prevDefaultSchemas'] | toJSONSchemaOptions['prevExampleSchemas'] = [],\n) {\n if (!schemas.length || !pointer.length) {\n return undefined;\n }\n\n const locSplit = pointer.split('/').filter(Boolean).reverse();\n const pointers = [];\n\n let point = '';\n for (let i = 0; i < locSplit.length; i += 1) {\n point = `/${locSplit[i]}${point}`;\n pointers.push(point);\n }\n\n let foundValue: any;\n const rev = [...schemas].reverse();\n\n for (let i = 0; i < pointers.length; i += 1) {\n for (let ii = 0; ii < rev.length; ii += 1) {\n let schema = rev[ii];\n\n if (property === 'example') {\n if ('example' in schema) {\n schema = schema.example;\n } else {\n if (!Array.isArray(schema.examples) || !schema.examples.length) {\n continue;\n }\n\n // Prevent us from crashing if `examples` is a completely empty object.\n schema = [...schema.examples].shift();\n }\n } else {\n schema = schema.default;\n }\n\n try {\n foundValue = jsonpointer.get(schema, pointers[i]);\n } catch {\n // If the schema we're looking at is `{obj: null}` and our pointer is `/obj/propertyName`\n // `jsonpointer` will throw an error. If that happens, we should silently catch and toss it\n // and return no example.\n }\n\n if (foundValue !== undefined) {\n break;\n }\n }\n\n if (foundValue !== undefined) {\n break;\n }\n }\n\n return foundValue;\n}\n\n/**\n * Given an OpenAPI-flavored JSON Schema, make an effort to modify it so it's shaped more towards\n * stock JSON Schema.\n *\n * Why do this?\n *\n * 1. OpenAPI 3.0.x supports its own flavor of JSON Schema that isn't fully compatible with most\n * JSON Schema tooling (like `@readme/oas-form` or `@rjsf/core`).\n * 2. While validating an OpenAPI definition will prevent corrupted or improper schemas from\n * occuring, we have a lot of legacy schemas in ReadMe that were ingested before we had proper\n * validation in place, and as a result have some API definitions that will not pass validation\n * right now. In addition to reshaping OAS-JSON Schema into JSON Schema this library will also\n * fix these improper schemas: things like `type: object` having `items` instead of `properties`,\n * or `type: array` missing `items`.\n * 3. To ease the burden of polymorphic handling on our form rendering engine we make an attempt\n * to merge `allOf` schemas here.\n * 4. Additionally due to OpenAPI 3.0.x not supporting JSON Schema, in order to support the\n * `example` keyword that OAS supports, we need to do some work in here to remap it into\n * `examples`. However, since all we care about in respect to examples for usage within\n * `@readme/oas-form`, we're only retaining primitives. This *slightly* deviates from JSON\n * Schema in that JSON Schema allows for any schema to be an example, but since\n * `@readme/oas-form` can only actually **render** primitives, that's what we're retaining.\n * 5. Though OpenAPI 3.1 does support full JSON Schema, this library should be able to handle it\n * without any problems.\n *\n * And why use this over `@openapi-contrib/openapi-schema-to-json-schema`? Fortunately and\n * unfortunately we've got a lot of API definitions in our database that aren't currently valid so\n * we need to have a lot of bespoke handling for odd quirks, typos, and missing declarations that\n * might be present.\n *\n * @todo add support for `schema: false` and `not` cases.\n * @see {@link https://json-schema.org/draft/2019-09/json-schema-validation.html}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schema-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object}\n * @param data OpenAPI Schema Object to convert to pure JSON Schema.\n */\nexport function toJSONSchema(data: SchemaObject | boolean, opts: toJSONSchemaOptions = {}): SchemaObject {\n let schema = data === true ? {} : { ...data };\n const schemaAdditionalProperties = isSchema(schema) ? schema.additionalProperties : null;\n\n const {\n addEnumsToDescriptions,\n currentLocation,\n globalDefaults,\n hideReadOnlyProperties,\n hideWriteOnlyProperties,\n isPolymorphicAllOfChild,\n prevDefaultSchemas,\n prevExampleSchemas,\n refLogger,\n transformer,\n } = {\n addEnumsToDescriptions: false,\n currentLocation: '',\n globalDefaults: {},\n hideReadOnlyProperties: false,\n hideWriteOnlyProperties: false,\n isPolymorphicAllOfChild: false,\n prevDefaultSchemas: [] as toJSONSchemaOptions['prevDefaultSchemas'],\n prevExampleSchemas: [] as toJSONSchemaOptions['prevExampleSchemas'],\n refLogger: () => true,\n transformer: (s: SchemaObject) => s,\n ...opts,\n };\n\n // If this schema contains a `$ref`, it's circular and we shouldn't try to resolve it. Just\n // return and move along.\n if (isRef(schema)) {\n refLogger(schema.$ref, 'ref');\n\n return transformer({\n $ref: schema.$ref,\n });\n }\n\n // If we don't have a set type, but are dealing with an `anyOf`, `oneOf`, or `allOf`\n // representation let's run through them and make sure they're good.\n if (isSchema(schema, isPolymorphicAllOfChild)) {\n // If this is an `allOf` schema we should make an attempt to merge so as to ease the burden on\n // the tooling that ingests these schemas.\n if ('allOf' in schema && Array.isArray(schema.allOf)) {\n try {\n schema = mergeJSONSchemaAllOf(schema as JSONSchema, {\n ignoreAdditionalProperties: true,\n resolvers: {\n // `merge-json-schema-allof` by default takes the first `description` when you're\n // merging an `allOf` but because generally when you're merging two schemas together\n // with an `allOf` you want data in the subsequent schemas to be applied to the first\n // and `description` should be a part of that.\n description: (obj: string[]) => {\n return obj.slice(-1)[0];\n },\n\n // `merge-json-schema-allof` doesn't support merging enum arrays but since that's a\n // safe and simple operation as enums always contain primitives we can handle it\n // ourselves with a custom resolver.\n enum: (obj: unknown[]) => {\n let arr: unknown[] = [];\n obj.forEach(e => {\n arr = arr.concat(e);\n });\n\n return arr;\n },\n\n // for any unknown keywords (e.g., `example`, `format`, `x-readme-ref-name`),\n // we fallback to using the title resolver (which uses the first value found).\n // https://github.com/mokkabonna/json-schema-merge-allof/blob/ea2e48ee34415022de5a50c236eb4793a943ad11/src/index.js#L292\n // https://github.com/mokkabonna/json-schema-merge-allof/blob/ea2e48ee34415022de5a50c236eb4793a943ad11/README.md?plain=1#L147\n defaultResolver: mergeJSONSchemaAllOf.options.resolvers.title,\n } as unknown,\n }) as SchemaObject;\n } catch {\n // If we can't merge the `allOf` for whatever reason (like if one item is a `string` and\n // the other is a `object`) then we should completely remove it from the schema and continue\n // with whatever we've got. Why? If we don't, any tooling that's ingesting this will need\n // to account for the incompatible `allOf` and it may be subject to more breakages than\n // just not having it present would be.\n const { ...schemaWithoutAllOf } = schema;\n schema = schemaWithoutAllOf as SchemaObject;\n delete schema.allOf;\n }\n\n // If after merging the `allOf` this schema still contains a `$ref` then it's circular and\n // we shouldn't do anything else.\n if (isRef(schema)) {\n refLogger(schema.$ref, 'ref');\n\n return transformer({\n $ref: schema.$ref,\n });\n }\n }\n\n ['anyOf', 'oneOf'].forEach((polyType: 'anyOf' | 'oneOf') => {\n if (polyType in schema && Array.isArray(schema[polyType])) {\n schema[polyType].forEach((item, idx) => {\n const polyOptions: toJSONSchemaOptions = {\n addEnumsToDescriptions,\n currentLocation: `${currentLocation}/${idx}`,\n globalDefaults,\n hideReadOnlyProperties,\n hideWriteOnlyProperties,\n isPolymorphicAllOfChild: false,\n prevDefaultSchemas,\n prevExampleSchemas,\n refLogger,\n transformer,\n };\n\n // When `properties` or `items` are present alongside a polymorphic schema instead of\n // letting whatever JSON Schema interpreter is handling these constructed schemas we can\n // guide its hand a bit by manually transforming it into an inferred `allOf` of the\n // `properties` + the polymorph schema.\n //\n // This `allOf` schema will be merged together when fed through `toJSONSchema`.\n if ('properties' in schema) {\n schema[polyType][idx] = toJSONSchema(\n { required: schema.required, allOf: [item, { properties: schema.properties }] } as SchemaObject,\n polyOptions,\n );\n } else if ('items' in schema) {\n schema[polyType][idx] = toJSONSchema(\n { allOf: [item, { items: schema.items }] } as SchemaObject,\n polyOptions,\n );\n } else {\n schema[polyType][idx] = toJSONSchema(item as SchemaObject, polyOptions);\n }\n\n // Ensure that we don't have any invalid `required` booleans lying around.\n if (\n isObject(schema[polyType][idx]) &&\n 'required' in (schema[polyType][idx] as SchemaObject) &&\n typeof (schema[polyType][idx] as SchemaObject).required === 'boolean'\n ) {\n delete (schema[polyType][idx] as SchemaObject).required;\n }\n });\n }\n });\n\n if ('discriminator' in schema) {\n if ('mapping' in schema.discriminator && typeof schema.discriminator.mapping === 'object') {\n // Discriminator mappings aren't written as traditional `$ref` pointers so in order to log\n // them to the supplied `refLogger`.\n const mapping = schema.discriminator.mapping;\n Object.keys(mapping).forEach(k => {\n refLogger(mapping[k], 'discriminator');\n });\n }\n }\n }\n\n // If this schema is malformed for some reason, let's do our best to repair it.\n if (!('type' in schema) && !isPolymorphicSchema(schema) && !isRequestBodySchema(schema)) {\n if ('properties' in schema) {\n schema.type = 'object';\n } else if ('items' in schema) {\n schema.type = 'array';\n } else {\n // If there's still no `type` on the schema we should leave it alone because we don't have a\n // great way to know if it's part of a nested schema that should, and couldn't be merged,\n // into another, or it's just purely malformed.\n //\n // Whatever tooling that ingests the generated schema should handle it however it needs to.\n }\n }\n\n if ('type' in schema) {\n // `nullable` isn't a thing in JSON Schema but it was in OpenAPI 3.0 so we should retain and\n // translate it into something that's compatible with JSON Schema.\n if ('nullable' in schema) {\n if (schema.nullable) {\n if (Array.isArray(schema.type)) {\n schema.type.push('null');\n } else if (schema.type !== null && schema.type !== 'null') {\n schema.type = [schema.type, 'null'];\n }\n }\n\n delete schema.nullable;\n }\n\n if (schema.type === null) {\n // `type: null` is possible in JSON Schema but we're translating it to a string version\n // so we don't need to worry about asserting nullish types in our implementations of this\n // generated schema.\n schema.type = 'null';\n } else if (Array.isArray(schema.type)) {\n if (schema.type.includes(null)) {\n schema.type[schema.type.indexOf(null)] = 'null';\n }\n\n schema.type = Array.from(new Set(schema.type));\n\n // We don't need `type: [<type>]` when we can just as easily make it `type: <type>`.\n if (schema.type.length === 1) {\n schema.type = schema.type.shift();\n } else if (schema.type.includes('array') || schema.type.includes('boolean') || schema.type.includes('object')) {\n // If we have a `null` type but there's only two types present then we can remove `null`\n // as an option and flag the whole schema as `nullable`.\n const isNullable = schema.type.includes('null');\n\n if (schema.type.length === 2 && isNullable) {\n // If this is `array | null` or `object | null` then we don't need to do anything.\n } else {\n // If this mixed type has non-primitives then we for convenience of our implementation\n // we're moving them into a `oneOf`.\n const nonPrimitives: any[] = [];\n\n // Because arrays, booleans, and objects are not compatible with any other schem type\n // other than null we're moving them into an isolated `oneOf`, and as such want to take\n // with it its specific properties that may be present on our current schema.\n Object.entries({\n // https://json-schema.org/understanding-json-schema/reference/array.html\n array: [\n 'additionalItems',\n 'contains',\n 'items',\n 'maxContains',\n 'maxItems',\n 'minContains',\n 'minItems',\n 'prefixItems',\n 'uniqueItems',\n ],\n\n // https://json-schema.org/understanding-json-schema/reference/boolean.html\n boolean: [\n // Booleans don't have any boolean-specific properties.\n ],\n\n // https://json-schema.org/understanding-json-schema/reference/object.html\n object: [\n 'additionalProperties',\n 'maxProperties',\n 'minProperties',\n 'nullable',\n 'patternProperties',\n 'properties',\n 'propertyNames',\n 'required',\n ],\n }).forEach(([typeKey, keywords]) => {\n if (!schema.type.includes(typeKey as JSONSchema7TypeName)) {\n return;\n }\n\n const reducedSchema: any = removeUndefinedObjects({\n type: isNullable ? [typeKey, 'null'] : typeKey,\n\n allowEmptyValue: (schema as any).allowEmptyValue ?? undefined,\n deprecated: schema.deprecated ?? undefined,\n description: schema.description ?? undefined,\n readOnly: schema.readOnly ?? undefined,\n title: schema.title ?? undefined,\n writeOnly: schema.writeOnly ?? undefined,\n });\n\n keywords.forEach((t: keyof SchemaObject) => {\n if (t in schema) {\n reducedSchema[t] = schema[t];\n delete schema[t];\n }\n });\n\n nonPrimitives.push(reducedSchema);\n });\n\n schema.type = schema.type.filter(t => t !== 'array' && t !== 'boolean' && t !== 'object');\n if (schema.type.length === 1) {\n schema.type = schema.type.shift();\n }\n\n // Because we may have encountered a fully mixed non-primitive type like `array | object`\n // we only want to retain the existing schema object if we still have types remaining\n // in it.\n if (schema.type.length > 1) {\n schema = { oneOf: [schema, ...nonPrimitives] };\n } else {\n schema = { oneOf: nonPrimitives };\n }\n }\n }\n }\n }\n\n if (isSchema(schema, isPolymorphicAllOfChild)) {\n if ('default' in schema && isObject(schema.default)) {\n prevDefaultSchemas.push({ default: schema.default });\n }\n\n // JSON Schema doesn't support OpenAPI-style examples so we need to reshape them a bit.\n if ('example' in schema) {\n // Only bother adding primitive examples.\n if (isPrimitive(schema.example)) {\n schema.examples = [schema.example];\n } else if (Array.isArray(schema.example)) {\n schema.examples = schema.example.filter(example => isPrimitive(example));\n if (!schema.examples.length) {\n delete schema.examples;\n }\n } else {\n prevExampleSchemas.push({ example: schema.example });\n }\n\n delete schema.example;\n } else if ('examples' in schema) {\n let reshapedExamples = false;\n if (typeof schema.examples === 'object' && !Array.isArray(schema.examples)) {\n const examples: unknown[] = [];\n Object.keys(schema.examples).forEach(name => {\n const example = schema.examples[name as unknown as number];\n if ('$ref' in example) {\n // no-op because any `$ref` example here after dereferencing is circular so we should\n // ignore it\n refLogger(example.$ref, 'ref');\n } else if ('value' in example) {\n if (isPrimitive(example.value)) {\n examples.push(example.value);\n reshapedExamples = true;\n } else if (Array.isArray(example.value) && isPrimitive(example.value[0])) {\n examples.push(example.value[0]);\n reshapedExamples = true;\n } else {\n // If this example is neither a primitive or an array we should dump it into the\n // `prevExampleSchemas` array because we might be able to extract an example from it\n // further downstream.\n prevExampleSchemas.push({\n example: example.value,\n });\n }\n }\n });\n\n if (examples.length) {\n reshapedExamples = true;\n schema.examples = examples;\n }\n } else if (Array.isArray(schema.examples) && isPrimitive(schema.examples[0])) {\n // We haven't reshaped `examples` here, but since it's in a state that's preferrable to us\n // let's keep it around.\n reshapedExamples = true;\n }\n\n if (!reshapedExamples) {\n delete schema.examples;\n }\n }\n\n // If we didn't have any immediately defined examples, let's search backwards and see if we can\n // find one. But as we're only looking for primitive example, only try to search for one if\n // we're dealing with a primitive schema.\n if (!hasSchemaType(schema, 'array') && !hasSchemaType(schema, 'object') && !schema.examples) {\n const foundExample = searchForValueByPropAndPointer('example', currentLocation, prevExampleSchemas);\n if (foundExample) {\n // We can only really deal with primitives, so only promote those as the found example if\n // it is.\n if (isPrimitive(foundExample) || (Array.isArray(foundExample) && isPrimitive(foundExample[0]))) {\n schema.examples = [foundExample];\n }\n }\n }\n\n if (hasSchemaType(schema, 'array')) {\n if ('items' in schema) {\n if (!Array.isArray(schema.items) && Object.keys(schema.items).length === 1 && isRef(schema.items)) {\n // `items` contains a `$ref`, so since it's circular we should do a no-op here and log\n // and ignore it.\n refLogger(schema.items.$ref, 'ref');\n } else if (schema.items !== true) {\n // Run through the arrays contents and clean them up.\n schema.items = toJSONSchema(schema.items as SchemaObject, {\n addEnumsToDescriptions,\n currentLocation: `${currentLocation}/0`,\n globalDefaults,\n hideReadOnlyProperties,\n hideWriteOnlyProperties,\n prevExampleSchemas,\n refLogger,\n transformer,\n });\n\n // If we have a non-array `required` entry in our `items` schema then it's invalid and we\n // should remove it. We only support non-array boolean `required` properties inside object\n // properties.\n if (isObject(schema.items) && 'required' in schema.items && !Array.isArray(schema.items.required)) {\n delete schema.items.required;\n }\n }\n } else if ('properties' in schema || 'additionalProperties' in schema) {\n // This is a fix to handle cases where someone may have typod `items` as `properties` on an\n // array. Since throwing a complete failure isn't ideal, we can see that they meant for the\n // type to be `object`, so we can do our best to shape the data into what they were\n // intending it to be.\n schema.type = 'object';\n } else {\n // This is a fix to handle cases where we have a malformed array with no `items` property\n // present.\n (schema as any).items = {};\n }\n } else if (hasSchemaType(schema, 'object')) {\n if ('properties' in schema) {\n Object.keys(schema.properties).forEach(prop => {\n if (\n Array.isArray(schema.properties[prop]) ||\n (typeof schema.properties[prop] === 'object' && schema.properties[prop] !== null)\n ) {\n const newPropSchema = toJSONSchema(schema.properties[prop] as SchemaObject, {\n addEnumsToDescriptions,\n currentLocation: `${currentLocation}/${encodePointer(prop)}`,\n globalDefaults,\n hideReadOnlyProperties,\n hideWriteOnlyProperties,\n prevDefaultSchemas,\n prevExampleSchemas,\n refLogger,\n transformer,\n });\n\n // If this property is read or write only then we should fully hide it from its parent schema.\n let propShouldBeUpdated = true;\n if ((hideReadOnlyProperties || hideWriteOnlyProperties) && !Object.keys(newPropSchema).length) {\n // We should only delete this schema if it wasn't already empty though. We do this\n // because we (un)fortunately have handling in our API Explorer form system for\n // schemas that are devoid of any `type` declaration.\n if (Object.keys(schema.properties[prop]).length > 0) {\n delete schema.properties[prop];\n propShouldBeUpdated = false;\n }\n }\n\n if (propShouldBeUpdated) {\n schema.properties[prop] = newPropSchema;\n\n /**\n * JSON Schema does not have any support for `required: <boolean>` but because some\n * of our users do this, and it does not throw OpenAPI validation errors thanks to\n * some extremely loose typings around `schema` in the official JSON Schema\n * definitions that the OAI offers, we're opting to support these users and upgrade\n * their invalid `required` definitions into ones that our tooling can interpret.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/schemas/v3.1/schema.json#L1114-L1121}\n */\n if (\n isObject(newPropSchema) &&\n 'required' in newPropSchema &&\n typeof newPropSchema.required === 'boolean' &&\n newPropSchema.required === true\n ) {\n if ('required' in schema && Array.isArray(schema.required)) {\n schema.required.push(prop);\n } else {\n schema.required = [prop];\n }\n\n delete (schema.properties[prop] as SchemaObject).required;\n }\n }\n }\n });\n\n // If we want to hide all readOnly or writeOnly properites and it happens to be that this\n // object was comprised of only those then we shouldn't render this object.\n if (hideReadOnlyProperties || hideWriteOnlyProperties) {\n if (!Object.keys(schema.properties).length) {\n return transformer({});\n }\n }\n }\n\n if (typeof schemaAdditionalProperties === 'object' && schemaAdditionalProperties !== null) {\n // If this `additionalProperties` is completely empty and devoid of any sort of schema,\n // treat it as such. Otherwise let's recurse into it and see if we can sort it out.\n if (\n !('type' in schemaAdditionalProperties) &&\n !('$ref' in schemaAdditionalProperties) &&\n // We know it will be a schema object because it's dereferenced\n !isPolymorphicSchema(schemaAdditionalProperties as SchemaObject)\n ) {\n schema.additionalProperties = true;\n } else {\n // We know it will be a schema object because it's dereferenced\n schema.additionalProperties = toJSONSchema(schemaAdditionalProperties as SchemaObject, {\n addEnumsToDescriptions,\n currentLocation,\n globalDefaults,\n hideReadOnlyProperties,\n hideWriteOnlyProperties,\n prevDefaultSchemas,\n prevExampleSchemas,\n refLogger,\n transformer,\n });\n }\n }\n\n // Since neither `properties` and `additionalProperties` are actually required to be present\n // on an object, since we construct this schema work to build up a form we still need\n // *something* for the user to enter in for this object so we'll add back in\n // `additionalProperties` for that.\n if (!isPolymorphicSchema(schema) && !('properties' in schema) && !('additionalProperties' in schema)) {\n schema.additionalProperties = true;\n }\n }\n }\n\n /**\n * Users can pass in parameter defaults via JWT User Data. We're checking to see if the defaults\n * being passed in exist on endpoints via jsonpointer\n *\n * @see {@link https://docs.readme.com/docs/passing-data-to-jwt}\n */\n if (\n isSchema(schema, isPolymorphicAllOfChild) &&\n globalDefaults &&\n Object.keys(globalDefaults).length > 0 &&\n currentLocation\n ) {\n try {\n const userJwtDefault = jsonpointer.get(globalDefaults, currentLocation);\n if (userJwtDefault) {\n schema.default = userJwtDefault;\n }\n } catch {\n // If jsonpointer returns an error, we won't show any defaults for that path.\n }\n }\n\n // Only add a default value if we actually have one.\n if ('default' in schema && typeof schema.default !== 'undefined') {\n if (hasSchemaType(schema, 'object')) {\n // Defaults for `object` and types have been dereferenced into their children schemas already\n // above so we don't need to preserve this default anymore.\n delete schema.default;\n } else if (\n ('allowEmptyValue' in schema && schema.allowEmptyValue && schema.default === '') ||\n schema.default !== ''\n ) {\n // If we have `allowEmptyValue` present, and the default is actually an empty string, let it\n // through as it's allowed.\n } else {\n // If the default is empty and we don't want to allowEmptyValue, we need to remove the\n // default.\n delete schema.default;\n }\n } else if (prevDefaultSchemas.length) {\n const foundDefault = searchForValueByPropAndPointer('default', currentLocation, prevDefaultSchemas);\n\n // We shouldn't ever set an object default out of the parent lineage tree defaults because\n // the contents of that object will be set on the schema that they're a part of. Setting\n // that object as well would result us in duplicating the defaults for that schema in two\n // places.\n if (\n isPrimitive(foundDefault) ||\n foundDefault === null ||\n (Array.isArray(foundDefault) && hasSchemaType(schema, 'array'))\n ) {\n schema.default = foundDefault;\n }\n }\n\n if (isSchema(schema, isPolymorphicAllOfChild) && 'enum' in schema && Array.isArray(schema.enum)) {\n // Enums should not have duplicated items as those will break AJV validation.\n // If we ever target ES6 for typescript we can drop this array.from.\n // https://stackoverflow.com/questions/33464504/using-spread-syntax-and-new-set-with-typescript/56870548\n schema.enum = Array.from(new Set(schema.enum));\n\n // If we want to add enums to descriptions (like in the case of response JSON Schema)\n // generation we need to convert them into a list of Markdown tilda'd strings. We're also\n // filtering away empty and falsy strings here because adding empty `` blocks to the description\n // will serve nobody any good.\n if (addEnumsToDescriptions) {\n const enums = schema.enum\n .filter(v => v !== undefined && (typeof v !== 'string' || v.trim() !== ''))\n .map(str => `\\`${str}\\``)\n .join(' ');\n\n if (enums.length) {\n if ('description' in schema) {\n schema.description += `\\n\\n${enums}`;\n } else {\n schema.description = enums;\n }\n }\n }\n }\n\n // Clean up any remaining `items` or `properties` schema fragments lying around if there's also\n // polymorphism present.\n if ('anyOf' in schema || 'oneOf' in schema) {\n if ('properties' in schema) {\n delete schema.properties;\n }\n\n if ('items' in schema) {\n delete schema.items;\n }\n }\n\n // Remove unsupported JSON Schema props.\n for (let i = 0; i < UNSUPPORTED_SCHEMA_PROPS.length; i += 1) {\n // Using the as here because the purpose is to delete keys we don't expect, so of course the\n // typing won't work\n delete (schema as Record<string, unknown>)[UNSUPPORTED_SCHEMA_PROPS[i]];\n }\n\n // If we want to hide any `readOnly` or `writeOnly` schemas, and this one is that, then we\n // shouldn't return anything.\n if (hideReadOnlyProperties && 'readOnly' in schema && schema.readOnly === true) {\n return {};\n } else if (hideWriteOnlyProperties && 'writeOnly' in schema && schema.writeOnly === true) {\n return {};\n }\n\n return transformer(schema);\n}\n","import type { OpenAPIV3_1 } from 'openapi-types';\nimport type { toJSONSchemaOptions } from '../../lib/openapi-to-json-schema.js';\nimport type { ComponentsObject, ExampleObject, OASDocument, ParameterObject, SchemaObject } from '../../types.js';\nimport type { Operation } from '../index.js';\n\nimport { getExtension, PARAMETER_ORDERING } from '../../extensions.js';\nimport { cloneObject } from '../../lib/clone-object.js';\nimport { isPrimitive } from '../../lib/helpers.js';\nimport matchesMimetype from '../../lib/matches-mimetype.js';\nimport { getSchemaVersionString, toJSONSchema } from '../../lib/openapi-to-json-schema.js';\n\nexport interface SchemaWrapper {\n $schema?: string;\n deprecatedProps?: SchemaWrapper;\n description?: string;\n label?: string;\n schema: SchemaObject;\n type: string;\n}\n\n/**\n * The order of this object determines how they will be sorted in the compiled JSON Schema\n * representation.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameter-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object}\n */\nexport const types: Record<keyof OASDocument, string> = {\n path: 'Path Params',\n query: 'Query Params',\n body: 'Body Params',\n cookie: 'Cookie Params',\n formData: 'Form Data',\n header: 'Headers',\n metadata: 'Metadata', // This a special type reserved for https://npm.im/api\n};\n\nexport interface getParametersAsJSONSchemaOptions {\n /**\n * Contains an object of user defined schema defaults.\n */\n globalDefaults?: Record<string, unknown>;\n\n /**\n * If you wish to hide properties that are marked as being `readOnly`.\n */\n hideReadOnlyProperties?: boolean;\n\n /**\n * If you wish to hide properties that are marked as being `writeOnly`.\n */\n hideWriteOnlyProperties?: boolean;\n\n /**\n * If you wish to include discriminator mapping `$ref` components alongside your\n * `discriminator` in schemas. Defaults to `true`.\n */\n includeDiscriminatorMappingRefs?: boolean;\n\n /**\n * If you want the output to be two objects: body (contains `body` and `formData` JSON\n * Schema) and metadata (contains `path`, `query`, `cookie`, and `header`).\n */\n mergeIntoBodyAndMetadata?: boolean;\n\n /**\n * If you wish to **not** split out deprecated properties into a separate `deprecatedProps`\n * object.\n */\n retainDeprecatedProperties?: boolean;\n\n /**\n * With a transformer you can transform any data within a given schema, like say if you want\n * to rewrite a potentially unsafe `title` that might be eventually used as a JS variable\n * name, just make sure to return your transformed schema.\n */\n transformer?: (schema: SchemaObject) => SchemaObject;\n}\n\nexport function getParametersAsJSONSchema(\n operation: Operation,\n api: OASDocument,\n opts?: getParametersAsJSONSchemaOptions,\n): SchemaWrapper[] {\n let hasCircularRefs = false;\n let hasDiscriminatorMappingRefs = false;\n\n function refLogger(ref: string, type: 'discriminator' | 'ref') {\n if (type === 'ref') {\n hasCircularRefs = true;\n } else {\n hasDiscriminatorMappingRefs = true;\n }\n }\n\n function getDeprecated(schema: SchemaObject, type: string) {\n // If we wish to retain deprecated properties then we shouldn't split them out into the\n // `deprecatedProps` object.\n if (opts.retainDeprecatedProperties) {\n return null;\n }\n\n // If there's no properties, bail\n if (!schema || !schema.properties) return null;\n\n // Clone the original schema so this doesn't interfere with it\n const deprecatedBody = cloneObject(schema);\n\n // Booleans are not valid for required in draft 4, 7 or 2020. Not sure why the typing thinks\n // they are.\n const requiredParams = (schema.required || []) as string[];\n\n // Find all top-level deprecated properties from the schema - required and readOnly params are\n // excluded.\n const allDeprecatedProps: Record<string, SchemaObject> = {};\n\n Object.keys(deprecatedBody.properties).forEach(key => {\n const deprecatedProp = deprecatedBody.properties[key] as SchemaObject;\n if (deprecatedProp.deprecated && !requiredParams.includes(key) && !deprecatedProp.readOnly) {\n allDeprecatedProps[key] = deprecatedProp;\n }\n });\n\n // We know this is the right type. todo: don't use as\n (deprecatedBody.properties as Record<string, SchemaObject>) = allDeprecatedProps;\n const deprecatedSchema = toJSONSchema(deprecatedBody, {\n globalDefaults: opts.globalDefaults,\n hideReadOnlyProperties: opts.hideReadOnlyProperties,\n hideWriteOnlyProperties: opts.hideWriteOnlyProperties,\n prevExampleSchemas: [],\n refLogger,\n transformer: opts.transformer,\n });\n\n // Check if the schema wasn't created or there's no deprecated properties\n if (Object.keys(deprecatedSchema).length === 0 || Object.keys(deprecatedSchema.properties).length === 0) {\n return null;\n }\n\n // Remove deprecated properties from the original schema\n // Not using the clone here becuase we WANT this to affect the original\n Object.keys(schema.properties).forEach(key => {\n // We know this will always be a SchemaObject\n if ((schema.properties[key] as SchemaObject).deprecated && !requiredParams.includes(key)) {\n delete schema.properties[key];\n }\n });\n\n return {\n type,\n schema: isPrimitive(deprecatedSchema)\n ? deprecatedSchema\n : {\n ...deprecatedSchema,\n $schema: getSchemaVersionString(deprecatedSchema, api),\n },\n };\n }\n\n /**\n *\n */\n function transformRequestBody(): SchemaWrapper {\n const requestBody = operation.getRequestBody();\n if (!requestBody || !Array.isArray(requestBody)) return null;\n\n const [mediaType, mediaTypeObject, description] = requestBody;\n const type = mediaType === 'application/x-www-form-urlencoded' ? 'formData' : 'body';\n\n // If this schema is completely empty, don't bother processing it.\n if (!mediaTypeObject.schema || !Object.keys(mediaTypeObject.schema).length) {\n return null;\n }\n\n const prevExampleSchemas: toJSONSchemaOptions['prevExampleSchemas'] = [];\n if ('example' in mediaTypeObject) {\n prevExampleSchemas.push({ example: mediaTypeObject.example });\n } else if ('examples' in mediaTypeObject) {\n prevExampleSchemas.push({\n examples: Object.values(mediaTypeObject.examples)\n .map((example: ExampleObject) => example.value)\n .filter(val => val !== undefined),\n });\n }\n\n // We're cloning the request schema because we've had issues with request schemas that were\n // dereferenced being processed multiple times because their component is also processed.\n const requestSchema = cloneObject(mediaTypeObject.schema);\n\n const cleanedSchema = toJSONSchema(requestSchema, {\n globalDefaults: opts.globalDefaults,\n hideReadOnlyProperties: opts.hideReadOnlyProperties,\n hideWriteOnlyProperties: opts.hideWriteOnlyProperties,\n prevExampleSchemas,\n refLogger,\n transformer: opts.transformer,\n });\n\n // If this schema is **still** empty, don't bother returning it.\n if (!Object.keys(cleanedSchema).length) {\n return null;\n }\n\n return {\n type,\n label: types[type],\n schema: isPrimitive(cleanedSchema)\n ? cleanedSchema\n : {\n ...cleanedSchema,\n $schema: getSchemaVersionString(cleanedSchema, api),\n },\n deprecatedProps: getDeprecated(cleanedSchema, type),\n ...(description ? { description } : {}),\n };\n }\n\n function transformComponents(): ComponentsObject {\n if (!('components' in api)) {\n return false;\n }\n\n const components: Partial<ComponentsObject> = {\n ...Object.keys(api.components)\n .map(componentType => ({ [componentType]: {} }))\n .reduce((prev, next) => Object.assign(prev, next), {}),\n };\n\n Object.keys(api.components).forEach((componentType: keyof ComponentsObject) => {\n if (typeof api.components[componentType] === 'object' && !Array.isArray(api.components[componentType])) {\n Object.keys(api.components[componentType]).forEach(schemaName => {\n const componentSchema = cloneObject(api.components[componentType][schemaName]);\n components[componentType][schemaName] = toJSONSchema(componentSchema as SchemaObject, {\n globalDefaults: opts.globalDefaults,\n hideReadOnlyProperties: opts.hideReadOnlyProperties,\n hideWriteOnlyProperties: opts.hideWriteOnlyProperties,\n refLogger,\n transformer: opts.transformer,\n });\n });\n }\n });\n\n // If none of our above component type placeholders got used let's clean them up.\n Object.keys(components).forEach((componentType: keyof ComponentsObject) => {\n if (!Object.keys(components[componentType]).length) {\n delete components[componentType];\n }\n });\n\n return components;\n }\n\n function transformParameters(): SchemaWrapper[] {\n const operationParams = operation.getParameters();\n\n const transformed = Object.keys(types)\n .map(type => {\n const required: string[] = [];\n\n // This `as` actually *could* be a ref, but we don't want refs to pass through here, so\n // `.in` will never match `type`\n const parameters = operationParams.filter(param => (param as ParameterObject).in === type);\n if (parameters.length === 0) {\n return null;\n }\n\n const properties = parameters.reduce((prev: Record<string, SchemaObject>, current: ParameterObject) => {\n let schema: SchemaObject = {};\n if ('schema' in current) {\n const currentSchema: SchemaObject = current.schema ? cloneObject(current.schema) : {};\n\n if (current.example) {\n // `example` can be present outside of the `schema` block so if it's there we should\n // pull it in so it can be handled and returned if it's valid.\n currentSchema.example = current.example;\n } else if (current.examples) {\n // `examples` isn't actually supported here in OAS 3.0, but we might as well support\n // it because `examples` is JSON Schema and that's fully supported in OAS 3.1.\n currentSchema.examples = current.examples as unknown as unknown[];\n }\n\n if (current.deprecated) currentSchema.deprecated = current.deprecated;\n\n const interimSchema = toJSONSchema(currentSchema, {\n currentLocation: `/${current.name}`,\n globalDefaults: opts.globalDefaults,\n hideReadOnlyProperties: opts.hideReadOnlyProperties,\n hideWriteOnlyProperties: opts.hideWriteOnlyProperties,\n refLogger,\n transformer: opts.transformer,\n });\n\n schema = isPrimitive(interimSchema)\n ? interimSchema\n : {\n ...interimSchema,\n\n // Note: this applies a `$schema` version to each field in the larger schema\n // object. It's not really **correct** but it's what we have to do because\n // there's a chance that the end user has indicated the schemas are different.\n $schema: getSchemaVersionString(currentSchema, api),\n };\n } else if ('content' in current && typeof current.content === 'object') {\n const contentKeys = Object.keys(current.content);\n if (contentKeys.length) {\n let contentType: string;\n if (contentKeys.length === 1) {\n contentType = contentKeys[0];\n } else {\n // We should always try to prioritize `application/json` over any other possible\n // content that might be present on this schema.\n const jsonLikeContentTypes = contentKeys.filter(k => matchesMimetype.json(k));\n if (jsonLikeContentTypes.length) {\n contentType = jsonLikeContentTypes[0];\n } else {\n contentType = contentKeys[0];\n }\n }\n\n if (typeof current.content[contentType] === 'object' && 'schema' in current.content[contentType]) {\n const currentSchema: SchemaObject = current.content[contentType].schema\n ? cloneObject(current.content[contentType].schema)\n : {};\n\n if (current.example) {\n // `example` can be present outside of the `schema` block so if it's there we\n // should pull it in so it can be handled and returned if it's valid.\n currentSchema.example = current.example;\n } else if (current.examples) {\n // `examples` isn't actually supported here in OAS 3.0, but we might as well\n // support it because `examples` is JSON Schema and that's fully supported in OAS\n // 3.1.\n currentSchema.examples = current.examples as unknown as unknown[];\n }\n\n if (current.deprecated) currentSchema.deprecated = current.deprecated;\n\n const interimSchema = toJSONSchema(currentSchema, {\n currentLocation: `/${current.name}`,\n globalDefaults: opts.globalDefaults,\n hideReadOnlyProperties: opts.hideReadOnlyProperties,\n hideWriteOnlyProperties: opts.hideWriteOnlyProperties,\n refLogger,\n transformer: opts.transformer,\n });\n\n schema = isPrimitive(interimSchema)\n ? interimSchema\n : {\n ...interimSchema,\n\n // Note: this applies a `$schema` version to each field in the larger schema\n // object. It's not really **correct** but it's what we have to do because\n // there's a chance that the end user has indicated the schemas are different.\n $schema: getSchemaVersionString(currentSchema, api),\n };\n }\n }\n }\n\n // Parameter descriptions don't exist in `current.schema` so `constructSchema` will never\n // have access to it.\n if (current.description) {\n if (!isPrimitive(schema)) {\n schema.description = current.description;\n }\n }\n\n prev[current.name] = schema;\n\n if (current.required) {\n required.push(current.name);\n }\n\n return prev;\n }, {});\n\n // This typing is technically WRONG :( but it's the best we can do for now.\n const schema: OpenAPIV3_1.SchemaObject = {\n type: 'object',\n properties: properties as Record<string, OpenAPIV3_1.SchemaObject>,\n required,\n };\n\n return {\n type,\n label: types[type],\n schema,\n deprecatedProps: getDeprecated(schema, type),\n };\n })\n .filter(Boolean);\n\n if (!opts.mergeIntoBodyAndMetadata) {\n return transformed;\n } else if (!transformed.length) {\n return [];\n }\n\n // If we want to merge parameters into a single metadata entry then we need to pull all\n // available schemas and `deprecatedProps` (if we don't want to retain them via the\n // `retainDeprecatedProps` option) under one roof.\n const deprecatedProps = transformed.map(r => r.deprecatedProps?.schema || null).filter(Boolean);\n return [\n {\n type: 'metadata',\n label: types.metadata,\n schema: {\n allOf: transformed.map(r => r.schema),\n } as SchemaObject,\n deprecatedProps: deprecatedProps.length\n ? {\n type: 'metadata',\n schema: {\n allOf: deprecatedProps,\n } as SchemaObject,\n }\n : null,\n },\n ];\n }\n\n // If this operation neither has any parameters or a request body then we should return null\n // because there won't be any JSON Schema.\n if (!operation.hasParameters() && !operation.hasRequestBody()) {\n return null;\n }\n\n // `metadata` is `api` SDK specific, is not a part of the `PARAMETER_ORDERING` extension, and\n // should always be sorted last. We also define `formData` as `form` in the extension because\n // we don't want folks to have to deal with casing issues so we need to rewrite it to `formData`.\n const typeKeys = (getExtension(PARAMETER_ORDERING, api, operation) as string[]).map(k => k.toLowerCase());\n typeKeys[typeKeys.indexOf('form')] = 'formData';\n typeKeys.push('metadata');\n\n const jsonSchema = [transformRequestBody()].concat(...transformParameters()).filter(Boolean);\n\n // We should only include `components`, or even bother transforming components into JSON Schema,\n // if we either have circular refs or if we have discriminator mapping refs somewhere and want to\n // include them.\n const shouldIncludeComponents =\n hasCircularRefs || (hasDiscriminatorMappingRefs && opts.includeDiscriminatorMappingRefs);\n\n const components = shouldIncludeComponents ? transformComponents() : false;\n\n return jsonSchema\n .map(group => {\n /**\n * Since this library assumes that the schema has already been dereferenced, adding every\n * component here that **isn't** circular adds a ton of bloat so it'd be cool if `components`\n * was just the remaining `$ref` pointers that are still being referenced.\n *\n * @todo\n */\n if (components && shouldIncludeComponents) {\n // Fixing typing and confused version mismatches\n (group.schema.components as ComponentsObject) = components;\n }\n\n // Delete deprecatedProps if it's null on the schema.\n if (!group.deprecatedProps) delete group.deprecatedProps;\n\n return group;\n })\n .sort((a, b) => {\n return typeKeys.indexOf(a.type) - typeKeys.indexOf(b.type);\n });\n}\n"]}