UNPKG

oas

Version:

Comprehensive tooling for working with OpenAPI definitions

584 lines (573 loc) 26.4 kB
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } function _optionalChainDelete(ops) { const result = _optionalChain(ops); return result == null ? true : result; } var _class; var _chunkW6GBV2JTcjs = require('../chunk-W6GBV2JT.cjs'); var _chunk2X4PY2BScjs = require('../chunk-2X4PY2BS.cjs'); require('../chunk-AYA3UT4L.cjs'); var _chunk3MTU2ESPcjs = require('../chunk-3MTU2ESP.cjs'); // src/reducer/index.ts var _jsonpointer = require('jsonpointer'); var _jsonpointer2 = _interopRequireDefault(_jsonpointer); var OpenAPIReducer = (_class = class _OpenAPIReducer { /** * A collection of `$ref` pointers that are used within our reduced API definition. This is used * to ensure that all referenced schemas are retained in our resulting API definition. Not * retaining them would result in an invalid OpenAPI definition. */ __init() {this.$refs = /* @__PURE__ */ new Set()} /** * A collection of OpenAPI tags that are used within our reduced API definition. */ __init2() {this.usedTags = /* @__PURE__ */ new Set()} /** * A collection of OpenAPI paths and operations that are cross-referenced from any other paths * and operations that we are reducing. This collection is used in order to ensure that those * schemas are retained with our resulting API definition. Not retaining them would result in an * invalid OpenAPI definition. */ __init3() {this.retainPathMethods = /* @__PURE__ */ new Set()} /** * A collection of OpenAPI webhook names and methods that are cross-referenced from any other * schemas. This collection, like `retainPathMethods`, is used in order to ensure that those * schemas are retained with our resulting API definition. Not retaining them would result in an * invalid OpenAPI definition. */ __init4() {this.retainWebhookMethods = /* @__PURE__ */ new Set()} /** * An array of OpenAPI tags to reduce down to. */ __init5() {this.tagsToReduceBy = []} /** * A collection of OpenAPI paths and operations to reduce down to. */ __init6() {this.pathsToReduceBy = {}} /** * A collection of OpenAPI webhooks to reduce down to. */ __init7() {this.webhooksToReduceBy = {}} __init8() {this.hasTagsToReduceBy = false} __init9() {this.hasPathsToReduceBy = false} __init10() {this.hasWebhooksToReduceBy = false} constructor(definition) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);_class.prototype.__init4.call(this);_class.prototype.__init5.call(this);_class.prototype.__init6.call(this);_class.prototype.__init7.call(this);_class.prototype.__init8.call(this);_class.prototype.__init9.call(this);_class.prototype.__init10.call(this); this.definition = structuredClone(definition); } /** * Initialize a new instance of the `OpenAPIReducer`. The reducer allows you to reduce an OpenAPI * definition down to only the information necessary to fulfill a specific set of tags, paths, * operations, and webhooks. * * OpenAPI reduction can be helpful not only to isolate and troubleshoot issues with large API * definitions, but also to compress a large API definition down to a manageable size containing * a specific set of items. * * All OpenAPI definitions reduced will still be fully functional and valid OpenAPI definitions. * * @param definition An OpenAPI definition to reduce. */ static init(definition) { return new _OpenAPIReducer(definition); } /** * Mark an OpenAPI tag to be included in our reduced API definition. Tag casing does not matter. * * @param tag The tag to mark for reduction. */ byTag(tag) { this.tagsToReduceBy.push(tag.toLowerCase()); return this; } /** * Mark an entire OpenAPI path, and all methods that it contains, to be included in your reduced * API definition. Path casing does not matter. * * @param path The path to mark for reduction. */ byPath(path) { this.pathsToReduceBy[path.toLowerCase()] = "*"; return this; } /** * Mark a single OpenAPI operation to be included in your reduced API definition. If the path * that this operation is a part of utilizes common parameters, those will be automatically * included. Path and method casing does not matter. * * Note that if you previously called `.byPath()` to reduce an entire path down, calling * `.byOperation()` will override that to just reduce this specific method (or this plus * subsequent calls to `.byOperation()`). * * @param path The path that the operation is a part of. * @param method The HTTP method of the operation to mark for reduction. * */ byOperation(path, method) { const pathLC = path.toLowerCase(); const methodLC = method.toLowerCase(); if (this.pathsToReduceBy[pathLC] && Array.isArray(this.pathsToReduceBy[pathLC])) { this.pathsToReduceBy[pathLC].push(methodLC); } else { this.pathsToReduceBy[pathLC] = [methodLC]; } return this; } byWebhook(webhookName, method) { const nameLC = webhookName.toLowerCase(); if (!method) { this.webhooksToReduceBy[nameLC] = "*"; return this; } const methodLC = method.toLowerCase(); if (this.webhooksToReduceBy[nameLC] && Array.isArray(this.webhooksToReduceBy[nameLC])) { this.webhooksToReduceBy[nameLC].push(methodLC); } else { this.webhooksToReduceBy[nameLC] = [methodLC]; } return this; } /** * Reduce the current OpenAPI definition down to the configured filters. * */ reduce() { if (!this.definition.openapi) { throw new Error("Sorry, only OpenAPI definitions are supported."); } this.hasPathsToReduceBy = Boolean(Object.keys(this.pathsToReduceBy).length); this.hasWebhooksToReduceBy = Boolean(Object.keys(this.webhooksToReduceBy).length); this.hasTagsToReduceBy = Boolean(this.tagsToReduceBy.length); if ("security" in this.definition) { Object.values(this.definition.security || {}).forEach((sec) => { Object.keys(sec).forEach((scheme) => { this.$refs.add(`#/components/securitySchemes/${scheme}`); }); }); } this.walkPaths(); this.walkWebhooks(); this.$refs.forEach(($ref) => { this.accumulateUsedRefs(this.definition, this.$refs, $ref); }); this.$refs.forEach((ref) => { const usedPathRef = this.parsePathRef(ref); if (usedPathRef) { this.retainPathMethods.add(`${usedPathRef.path.toLowerCase()}|${usedPathRef.method.toLowerCase()}`); } const usedWebhookRef = this.parseWebhookRef(ref); if (usedWebhookRef) { this.retainWebhookMethods.add(`${usedWebhookRef.name.toLowerCase()}|${usedWebhookRef.method.toLowerCase()}`); } }); this.reducePaths(); this.reduceWebhooks(); const hasPaths = Boolean(this.definition.paths && Object.keys(this.definition.paths).length); const hasWebhooks = Boolean( "webhooks" in this.definition && this.definition.webhooks && Object.keys(this.definition.webhooks).length ); if (!hasPaths && !hasWebhooks) { throw new Error( "All paths and webhooks in the API definition were removed. Did you supply the right path, operation, or webhook to reduce by?" ); } if ("components" in this.definition) { Object.keys(this.definition.components || {}).forEach((componentType) => { Object.keys(_optionalChain([this, 'access', _ => _.definition, 'access', _2 => _2.components, 'optionalAccess', _3 => _3[componentType]]) || {}).forEach((component) => { const refIsUsed = this.$refs.has(`#/components/${componentType}/${component}`) || Array.from(this.$refs).some((ref) => { return ref.startsWith(`#/components/${componentType}/${component}/`); }); if (!refIsUsed) { _optionalChainDelete([this, 'access', _4 => _4.definition, 'access', _5 => _5.components, 'optionalAccess', _6 => _6[componentType], 'optionalAccess', _7 => delete _7[component]]); } }); if (!Object.keys(_optionalChain([this, 'access', _8 => _8.definition, 'access', _9 => _9.components, 'optionalAccess', _10 => _10[componentType]]) || {}).length) { _optionalChainDelete([this, 'access', _11 => _11.definition, 'access', _12 => _12.components, 'optionalAccess', _13 => delete _13[componentType]]); } }); if (!Object.keys(this.definition.components || {}).length) { delete this.definition.components; } } if ("tags" in this.definition) { this.definition.tags = (_nullishCoalesce(this.definition.tags, () => ( []))).filter((tag) => { return Boolean(tag) && this.usedTags.has(tag.name); }); if (!_optionalChain([this, 'access', _14 => _14.definition, 'access', _15 => _15.tags, 'optionalAccess', _16 => _16.length])) { delete this.definition.tags; } } return this.definition; } /** * Recursively process a `$ref` pointer and accumulate any other `$ref` pointers that it or its * children use. This handles circular references by skipping `$ref` pointers we have already seen. * Additionally when a `$ref` points to `#/paths` we record the used path + method so we can * retain cross-operation references within the reduced definition. * * @param schema JSON Schema object to look for and accumulate any `$ref` pointers that it may have. * @param $refs Known set of `$ref` pointers. * @param $ref `$ref` pointer to fetch a schema from out of the supplied schema. */ accumulateUsedRefs(schema, $refs, $ref) { const pathRef = this.parsePathRef($ref); if (pathRef) { this.retainPathMethods.add(`${pathRef.path.toLowerCase()}|${pathRef.method.toLowerCase()}`); } const webhookRef = this.parseWebhookRef($ref); if (webhookRef) { this.retainWebhookMethods.add(`${webhookRef.name.toLowerCase()}|${webhookRef.method.toLowerCase()}`); } let $refSchema; if (typeof $ref === "string") $refSchema = _jsonpointer2.default.get(schema, $ref.substring(1)); if ($refSchema === void 0) { return; } this.queryForRefPointers($refSchema).forEach(({ value: currRef }) => { const foundRef = this.toRefString(currRef); if (!foundRef) { return; } if ($refs.has(foundRef)) { return; } $refs.add(foundRef); this.accumulateUsedRefs(schema, $refs, foundRef); }); } /** * Query a JSON Schema object for any `$ref` pointers using JSONPath and return any pointers that * exist. * * @see {@link https://datatracker.ietf.org/doc/html/rfc9535} * @param schema JSON Schema object to look for any `$ref` pointers within it. */ queryForRefPointers(schema) { return _chunkW6GBV2JTcjs.query.call(void 0, ["$..['$ref']"], schema); } /** * Normalize a value from a `jsonpath-plus` `$ref` query to a `$ref` pointer because JSONPath * queries may return the property value or the parent. * */ toRefString(value) { if (typeof value === "string") { return value; } else if (value && typeof value === "object" && "$ref" in value && typeof value.$ref === "string") { return value.$ref; } return null; } /** * If the given `$ref` points into a path (e.g. `#/paths/~1anything/post/...`), return the path * and method so the reducer can ultimately retain cross-operation references. * */ parsePathRef($ref) { if (typeof $ref !== "string" || !$ref.startsWith("#/paths/")) { return null; } const match = $ref.match(/^#\/paths\/([^/]+)\/([^/]+)(?:\/|$)/); if (match) { const pathSegment = match[1]; const method = match[2]; if (pathSegment && method) { return { path: _chunk2X4PY2BScjs.decodePointer.call(void 0, pathSegment), method }; } } return null; } /** * If the given `$ref` points into webhooks (e.g. `#/webhooks/newBooking/post/...`), return the * webhook name and method so the reducer can retain cross-referenced webhook operations. * */ parseWebhookRef($ref) { if (typeof $ref !== "string" || !$ref.startsWith("#/webhooks/")) { return null; } const match = $ref.match(/^#\/webhooks\/([^/]+)\/([^/]+)(?:\/|$)/); if (match) { const webhookName = match[1]; const method = match[2]; if (webhookName && method) { return { name: _chunk2X4PY2BScjs.decodePointer.call(void 0, webhookName), method }; } } return null; } /** * Walk through the `paths` in our OpenAPI definition and reduce down any that we know we do not * want to keep and accumulate any `$ref` pointers that we find that may be cross-referenced in * paths, webhooks, operations, and schemas that we _do_ want to keep. * */ walkPaths() { if (!("paths" in this.definition) || !this.definition.paths) { return; } Object.keys(this.definition.paths).forEach((path) => { const pathLC = path.toLowerCase(); if (this.hasWebhooksToReduceBy && !this.hasPathsToReduceBy) { _optionalChainDelete([this, 'access', _17 => _17.definition, 'access', _18 => _18.paths, 'optionalAccess', _19 => delete _19[path]]); return; } if (this.hasPathsToReduceBy) { if (!(pathLC in this.pathsToReduceBy)) { _optionalChainDelete([this, 'access', _20 => _20.definition, 'access', _21 => _21.paths, 'optionalAccess', _22 => delete _22[path]]); return; } } Object.keys(_optionalChain([this, 'access', _23 => _23.definition, 'access', _24 => _24.paths, 'optionalAccess', _25 => _25[path]]) || {}).forEach((method) => { if (method === "parameters" || !_chunk2X4PY2BScjs.supportedMethods.includes(method.toLowerCase())) { return; } if (this.hasPathsToReduceBy) { if (this.pathsToReduceBy[pathLC] !== "*" && Array.isArray(this.pathsToReduceBy[pathLC]) && !this.pathsToReduceBy[pathLC].includes(method.toLowerCase())) { return; } } const operation = _optionalChain([this, 'access', _26 => _26.definition, 'access', _27 => _27.paths, 'optionalAccess', _28 => _28[path], 'optionalAccess', _29 => _29[method]]); if (!operation) { throw new Error(`Operation \`${method} ${path}\` not found`); } if (this.hasTagsToReduceBy) { if (!(operation.tags || []).filter((tag) => this.tagsToReduceBy.includes(tag.toLowerCase())).length) { return; } } (operation.tags || []).forEach((tag) => { this.usedTags.add(tag); }); const pathLevelParams = _optionalChain([this, 'access', _30 => _30.definition, 'access', _31 => _31.paths, 'optionalAccess', _32 => _32[path], 'optionalAccess', _33 => _33.parameters]); if (pathLevelParams) { this.queryForRefPointers(pathLevelParams).forEach(({ value: ref }) => { const refStr = this.toRefString(ref); if (!refStr) { return; } this.$refs.add(refStr); this.accumulateUsedRefs(this.definition, this.$refs, refStr); }); } this.queryForRefPointers(operation).forEach(({ value: ref }) => { const refStr = this.toRefString(ref); if (!refStr) { return; } this.$refs.add(refStr); const pathRef = this.parsePathRef(refStr); if (pathRef) { this.retainPathMethods.add(`${pathRef.path.toLowerCase()}|${pathRef.method.toLowerCase()}`); } this.accumulateUsedRefs(this.definition, this.$refs, refStr); }); Object.values(operation.security || {}).forEach((sec) => { Object.keys(sec).forEach((scheme) => { this.$refs.add(`#/components/securitySchemes/${scheme}`); }); }); }); }); } /** * Walk through the `webhooks` in our OpenAPI definition and reduce down any that we know we do * not want to keep and accumulate any `$ref` pointers that we find that may be cross-referenced * in paths, operations, and schemas that we _do_ want to keep. * */ walkWebhooks() { if (!_chunk3MTU2ESPcjs.isOpenAPI31.call(void 0, this.definition)) { return; } else if (!("webhooks" in this.definition) || !this.definition.webhooks) { return; } const definition = this.definition; Object.keys(definition.webhooks || {}).forEach((webhookName) => { const nameLC = webhookName.toLowerCase(); if (this.hasWebhooksToReduceBy && !(nameLC in this.webhooksToReduceBy)) { return; } const webhook = _optionalChain([definition, 'access', _34 => _34.webhooks, 'optionalAccess', _35 => _35[webhookName]]); if (!webhook || typeof webhook !== "object") { return; } Object.keys(webhook).forEach((method) => { if (method === "parameters" || !_chunk2X4PY2BScjs.supportedMethods.includes(method.toLowerCase())) { return; } if (this.hasWebhooksToReduceBy) { const methodFilter = this.webhooksToReduceBy[nameLC]; if (methodFilter !== "*" && Array.isArray(methodFilter) && !methodFilter.includes(method.toLowerCase())) { return; } } if (_chunk3MTU2ESPcjs.isRef.call(void 0, webhook)) { return; } const operation = webhook[method]; if (!operation) { return; } if (this.hasTagsToReduceBy) { if (!(operation.tags || []).filter((tag) => this.tagsToReduceBy.includes(tag.toLowerCase())).length) { return; } } (operation.tags || []).forEach((tag) => { this.usedTags.add(tag); }); if (webhook.parameters) { this.queryForRefPointers(webhook.parameters).forEach(({ value: ref }) => { const refStr = this.toRefString(ref); if (!refStr) { return; } this.$refs.add(refStr); this.accumulateUsedRefs(definition, this.$refs, refStr); }); } this.queryForRefPointers(operation).forEach(({ value: ref }) => { const refStr = this.toRefString(ref); if (!refStr) { return; } this.$refs.add(refStr); const pathRef = this.parsePathRef(refStr); if (pathRef) { this.retainPathMethods.add(`${pathRef.path.toLowerCase()}|${pathRef.method.toLowerCase()}`); } const webhookRef = this.parseWebhookRef(refStr); if (webhookRef) { this.retainWebhookMethods.add(`${webhookRef.name.toLowerCase()}|${webhookRef.method.toLowerCase()}`); } this.accumulateUsedRefs(definition, this.$refs, refStr); }); Object.values(operation.security || {}).forEach((sec) => { Object.keys(sec).forEach((scheme) => { this.$refs.add(`#/components/securitySchemes/${scheme}`); }); }); }); }); } /** * Prune back our `paths` object in the OpenAPI definition to only include paths that we want to * preserve. * */ reducePaths() { if (!("paths" in this.definition) || !this.definition.paths) { return; } Object.keys(this.definition.paths).forEach((path) => { const pathLC = path.toLowerCase(); if (this.hasPathsToReduceBy && !(pathLC in this.pathsToReduceBy)) { _optionalChainDelete([this, 'access', _36 => _36.definition, 'access', _37 => _37.paths, 'optionalAccess', _38 => delete _38[path]]); return; } Object.keys(_optionalChain([this, 'access', _39 => _39.definition, 'access', _40 => _40.paths, 'optionalAccess', _41 => _41[path]]) || {}).forEach((method) => { const methodLC = method.toLowerCase(); if (method === "parameters" || !_chunk2X4PY2BScjs.supportedMethods.includes(methodLC)) { return; } const retainedByRef = this.retainPathMethods.has(`${pathLC}|${methodLC}`) || Array.from(this.$refs).some((ref) => { const pathRef = this.parsePathRef(ref); return _optionalChain([pathRef, 'optionalAccess', _42 => _42.path, 'access', _43 => _43.toLowerCase, 'call', _44 => _44()]) === pathLC && _optionalChain([pathRef, 'optionalAccess', _45 => _45.method, 'access', _46 => _46.toLowerCase, 'call', _47 => _47()]) === methodLC; }); if (methodLC !== "parameters") { if (this.hasPathsToReduceBy) { if (!retainedByRef && this.pathsToReduceBy[pathLC] !== "*" && Array.isArray(this.pathsToReduceBy[pathLC]) && !this.pathsToReduceBy[pathLC].includes(methodLC)) { _optionalChainDelete([this, 'access', _48 => _48.definition, 'access', _49 => _49.paths, 'optionalAccess', _50 => _50[path], 'optionalAccess', _51 => delete _51[method]]); return; } } } const operation = _optionalChain([this, 'access', _52 => _52.definition, 'access', _53 => _53.paths, 'optionalAccess', _54 => _54[path], 'optionalAccess', _55 => _55[method]]); if (!operation) { throw new Error(`Operation \`${method} ${path}\` not found`); } if (this.hasTagsToReduceBy) { if (!(operation.tags || []).filter((tag) => this.tagsToReduceBy.includes(tag.toLowerCase())).length) { if (!retainedByRef) { _optionalChainDelete([this, 'access', _56 => _56.definition, 'access', _57 => _57.paths, 'optionalAccess', _58 => _58[path], 'optionalAccess', _59 => delete _59[method]]); } return; } } if ("tags" in operation) { _optionalChain([operation, 'access', _60 => _60.tags, 'optionalAccess', _61 => _61.forEach, 'call', _62 => _62((tag) => { this.usedTags.add(tag); })]); } if ("security" in operation) { Object.values(operation.security || {}).forEach((sec) => { Object.keys(sec).forEach((scheme) => { this.$refs.add(`#/components/securitySchemes/${scheme}`); }); }); } }); if (!Object.keys(_optionalChain([this, 'access', _63 => _63.definition, 'access', _64 => _64.paths, 'optionalAccess', _65 => _65[path]]) || {}).length) { _optionalChainDelete([this, 'access', _66 => _66.definition, 'access', _67 => _67.paths, 'optionalAccess', _68 => delete _68[path]]); } }); if (!Object.keys(this.definition.paths || {}).length) { if (!(this.definition.webhooks && Object.keys(this.definition.webhooks).length)) { throw new Error( "All paths in the API definition were removed. Did you supply the right path name to reduce by?" ); } delete this.definition.paths; } } /** * Prune back our `webhooks` object in the OpenAPI definition to only include webhooks that we * want to preserve. * */ reduceWebhooks() { if (!_chunk3MTU2ESPcjs.isOpenAPI31.call(void 0, this.definition)) { return; } else if (!("webhooks" in this.definition) || !this.definition.webhooks) { return; } const definition = this.definition; Object.keys(definition.webhooks || {}).forEach((webhookName) => { const nameLC = webhookName.toLowerCase(); if (this.hasWebhooksToReduceBy && !(nameLC in this.webhooksToReduceBy)) { const retainedByRef = Array.from(this.retainWebhookMethods).some( (key) => key.startsWith(`${nameLC}|`) || key === `${nameLC}|` ); if (!retainedByRef) { _optionalChainDelete([definition, 'access', _69 => _69.webhooks, 'optionalAccess', _70 => delete _70[webhookName]]); return; } } const webhook = _optionalChain([definition, 'access', _71 => _71.webhooks, 'optionalAccess', _72 => _72[webhookName]]); if (!webhook || typeof webhook !== "object") { return; } if (_chunk3MTU2ESPcjs.isRef.call(void 0, webhook)) { return; } Object.keys(webhook).forEach((method) => { const methodLC = method.toLowerCase(); if (method === "parameters" || !_chunk2X4PY2BScjs.supportedMethods.includes(methodLC)) { return; } const retainedByRef = this.retainWebhookMethods.has(`${nameLC}|${methodLC}`); if (this.hasWebhooksToReduceBy && !retainedByRef) { const methodFilter = this.webhooksToReduceBy[nameLC]; if (methodFilter !== "*" && Array.isArray(methodFilter) && !methodFilter.includes(methodLC)) { if (!_optionalChain([definition, 'access', _73 => _73.webhooks, 'optionalAccess', _74 => _74[webhookName]]) || _chunk3MTU2ESPcjs.isRef.call(void 0, _optionalChain([definition, 'access', _75 => _75.webhooks, 'optionalAccess', _76 => _76[webhookName]]))) { return; } _optionalChainDelete([definition, 'access', _77 => _77.webhooks, 'optionalAccess', _78 => _78[webhookName], 'optionalAccess', _79 => delete _79[method]]); } } }); if (!Object.keys(_optionalChain([definition, 'access', _80 => _80.webhooks, 'optionalAccess', _81 => _81[webhookName]]) || {}).length) { _optionalChainDelete([definition, 'access', _82 => _82.webhooks, 'optionalAccess', _83 => delete _83[webhookName]]); } }); if (definition.webhooks && !Object.keys(definition.webhooks).length) { delete definition.webhooks; } } }, _class); exports.OpenAPIReducer = OpenAPIReducer; //# sourceMappingURL=index.cjs.map