oas-normalize 12.1.0 → 13.0.1

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.
package/LICENSE CHANGED
@@ -1,6 +1,4 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 ReadMe
1
+ Copyright © 2025 ReadMe
4
2
 
5
3
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
4
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -107,7 +107,7 @@ try {
107
107
 
108
108
  #### Error Handling
109
109
 
110
- All thrown validation error messages that direct the user to the line(s) where their errors are present:
110
+ All errors will be thrown as a `ValidationError` exception with contextual error messages that direct the user to the line(s) where their errors are present:
111
111
 
112
112
  ```
113
113
  OpenAPI schema validation failed.
@@ -123,27 +123,33 @@ REQUIRED must have required property 'url'
123
123
  12 | ],
124
124
  ```
125
125
 
126
- However if you would like to programatically access this information the `SyntaxError` error that is thrown contains a `details` array of [AJV](https://npm.im/ajv) errors:
127
-
128
- ```json
129
- [
130
- {
131
- "instancePath": "/servers/0",
132
- "schemaPath": "#/required",
133
- "keyword": "required",
134
- "params": { "missingProperty": "url" },
135
- "message": "must have required property 'url'",
136
- },
137
- {
138
- "instancePath": "/servers/0",
139
- "schemaPath": "#/additionalProperties",
140
- "keyword": "additionalProperties",
141
- "params": { "additionalProperty": "urll" },
142
- "message": "must NOT have additional properties",
143
- },
144
- ];
126
+ If you also wish to treat certain errors as warnings you can do so by supplying your `.validate()` call with a [`@readme/openapi-parser`](https://npm.im/@readme/openapi-parser) ruleset:
127
+
128
+ ```ts
129
+ try {
130
+ const result = await oas.validate({
131
+ validate: {
132
+ rules: {
133
+ openapi: {
134
+ 'path-parameters-not-in-path': 'warning',
135
+ },
136
+ },
137
+ },
138
+ });
139
+
140
+ if (result.warnings.length) {
141
+ console.warn('🚸 The API is valid but has some warnings.');
142
+ console.warn(result.warnings);
143
+ } else {
144
+ console.log('🍭 The API is valid!');
145
+ }
146
+ } catch (err) {
147
+ console.error(err);
148
+ }
145
149
  ```
146
150
 
151
+ For full documentation on the available rulesets, as well as tooling to transform the the `.validate()` responses into a human-readable strings, check out the documentation for [`@readme/openapi-parser`](https://npm.im/@readme/openapi-parser).
152
+
147
153
  ### `.version()`
148
154
 
149
155
  Load and retrieve version information about a supplied API definition.
@@ -1,5 +1,6 @@
1
1
  // src/lib/utils.ts
2
2
  import YAML, { JSON_SCHEMA } from "js-yaml";
3
+ import { compileErrors } from "@readme/openapi-parser";
3
4
  function isBuffer(obj) {
4
5
  return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === "function" && !!obj.constructor.isBuffer(obj);
5
6
  }
@@ -79,6 +80,7 @@ export {
79
80
  isSwagger,
80
81
  stringToJSON,
81
82
  isAPIDefinition,
82
- getAPIDefinitionType
83
+ getAPIDefinitionType,
84
+ compileErrors
83
85
  };
84
- //# sourceMappingURL=chunk-J322YOXV.js.map
86
+ //# sourceMappingURL=chunk-EHNNEPCG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/utils.ts"],"sourcesContent":["import YAML, { JSON_SCHEMA } from 'js-yaml';\n\nexport { compileErrors } from '@readme/openapi-parser';\n\n/**\n * Determine if a given variable is a `Buffer`.\n *\n */\nexport function isBuffer(obj: any): boolean {\n return (\n obj != null &&\n obj.constructor != null &&\n typeof obj.constructor.isBuffer === 'function' &&\n !!obj.constructor.isBuffer(obj)\n );\n}\n\n/**\n * Deconstruct a URL into a payload for a `fetch` request.\n *\n */\nexport function prepareURL(url: string): { options: RequestInit; url: string } {\n const options: RequestInit = {};\n const u = new URL(url);\n\n // `fetch` doesn't support supplying basic auth credentials in the URL so we need to move them\n // into a header.\n if (u.username || u.password) {\n options.headers = {\n Authorization: `Basic ${btoa(`${u.username}:${u.password}`)}`,\n };\n\n u.username = '';\n u.password = '';\n }\n\n // Transform GitHub sources into their raw content URLs.\n if (u.host === 'github.com' && u.pathname.includes('/blob/')) {\n u.host = 'raw.githubusercontent.com';\n u.pathname = u.pathname.replace('/blob/', '/');\n }\n\n return {\n url: u.toString(),\n options,\n };\n}\n\n/**\n * Determine the type of a given variable. Returns `false` if unrecognized.\n *\n */\nexport function getType(obj: any): 'buffer' | 'json' | 'path' | 'string-json' | 'string-yaml' | 'url' | false {\n if (isBuffer(obj)) {\n return 'buffer';\n } else if (typeof obj === 'object') {\n return 'json';\n } else if (typeof obj === 'string') {\n if (obj.match(/\\s*{/)) {\n return 'string-json';\n } else if (obj.match(/\\n/)) {\n // Not sure about this...\n return 'string-yaml';\n } else if (obj.substring(0, 4) === 'http') {\n return 'url';\n }\n\n return 'path';\n }\n\n return false;\n}\n\n/**\n * Determine if a given schema if an OpenAPI definition.\n *\n */\nexport function isOpenAPI(schema: Record<string, unknown>): boolean {\n return !!schema.openapi;\n}\n\n/**\n * Determine if a given schema is a Postman collection.\n *\n * Unfortunately the Postman schema spec doesn't have anything like `openapi` or `swagger` for us\n * to look at but it does require that `info` and `item` be present and as `item` doesn't exist in\n * OpenAPI or Swagger we can use the combination of those two properties to determine if what we\n * have is a Postman collection.\n *\n * @see {@link https://schema.postman.com/json/collection/v2.0.0/collection.json}\n * @see {@link https://schema.postman.com/json/collection/v2.1.0/collection.json}\n */\nexport function isPostman(schema: Record<string, unknown>): boolean {\n return !!schema.info && !!schema.item;\n}\n\n/**\n * Determine if a given schema if an Swagger definition.\n *\n */\nexport function isSwagger(schema: Record<string, unknown>): boolean {\n return !!schema.swagger;\n}\n\n/**\n * Convert a YAML blob or stringified JSON object into a JSON object.\n *\n */\nexport function stringToJSON(string: Record<string, unknown> | string): Record<string, unknown> {\n if (typeof string === 'object') {\n return string;\n } else if (string.match(/^\\s*{/)) {\n // eslint-disable-next-line try-catch-failsafe/json-parse\n return JSON.parse(string);\n }\n\n return YAML.load(string, { schema: JSON_SCHEMA }) as Record<string, unknown>;\n}\n\n/**\n * Determine if a given schema is an API definition that we can support.\n *\n */\nexport function isAPIDefinition(schema: Record<string, unknown>): boolean {\n return isOpenAPI(schema) || isPostman(schema) || isSwagger(schema);\n}\n\n/**\n * Retrieve the type of API definition that a given schema is.\n *\n */\nexport function getAPIDefinitionType(schema: Record<string, unknown>): 'openapi' | 'postman' | 'swagger' | 'unknown' {\n if (isOpenAPI(schema)) {\n return 'openapi';\n } else if (isPostman(schema)) {\n return 'postman';\n } else if (isSwagger(schema)) {\n return 'swagger';\n }\n\n return 'unknown';\n}\n"],"mappings":";AAAA,OAAO,QAAQ,mBAAmB;AAElC,SAAS,qBAAqB;AAMvB,SAAS,SAAS,KAAmB;AAC1C,SACE,OAAO,QACP,IAAI,eAAe,QACnB,OAAO,IAAI,YAAY,aAAa,cACpC,CAAC,CAAC,IAAI,YAAY,SAAS,GAAG;AAElC;AAMO,SAAS,WAAW,KAAoD;AAC7E,QAAM,UAAuB,CAAC;AAC9B,QAAM,IAAI,IAAI,IAAI,GAAG;AAIrB,MAAI,EAAE,YAAY,EAAE,UAAU;AAC5B,YAAQ,UAAU;AAAA,MAChB,eAAe,SAAS,KAAK,GAAG,EAAE,QAAQ,IAAI,EAAE,QAAQ,EAAE,CAAC;AAAA,IAC7D;AAEA,MAAE,WAAW;AACb,MAAE,WAAW;AAAA,EACf;AAGA,MAAI,EAAE,SAAS,gBAAgB,EAAE,SAAS,SAAS,QAAQ,GAAG;AAC5D,MAAE,OAAO;AACT,MAAE,WAAW,EAAE,SAAS,QAAQ,UAAU,GAAG;AAAA,EAC/C;AAEA,SAAO;AAAA,IACL,KAAK,EAAE,SAAS;AAAA,IAChB;AAAA,EACF;AACF;AAMO,SAAS,QAAQ,KAAsF;AAC5G,MAAI,SAAS,GAAG,GAAG;AACjB,WAAO;AAAA,EACT,WAAW,OAAO,QAAQ,UAAU;AAClC,WAAO;AAAA,EACT,WAAW,OAAO,QAAQ,UAAU;AAClC,QAAI,IAAI,MAAM,MAAM,GAAG;AACrB,aAAO;AAAA,IACT,WAAW,IAAI,MAAM,IAAI,GAAG;AAE1B,aAAO;AAAA,IACT,WAAW,IAAI,UAAU,GAAG,CAAC,MAAM,QAAQ;AACzC,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAMO,SAAS,UAAU,QAA0C;AAClE,SAAO,CAAC,CAAC,OAAO;AAClB;AAaO,SAAS,UAAU,QAA0C;AAClE,SAAO,CAAC,CAAC,OAAO,QAAQ,CAAC,CAAC,OAAO;AACnC;AAMO,SAAS,UAAU,QAA0C;AAClE,SAAO,CAAC,CAAC,OAAO;AAClB;AAMO,SAAS,aAAa,QAAmE;AAC9F,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAO;AAAA,EACT,WAAW,OAAO,MAAM,OAAO,GAAG;AAEhC,WAAO,KAAK,MAAM,MAAM;AAAA,EAC1B;AAEA,SAAO,KAAK,KAAK,QAAQ,EAAE,QAAQ,YAAY,CAAC;AAClD;AAMO,SAAS,gBAAgB,QAA0C;AACxE,SAAO,UAAU,MAAM,KAAK,UAAU,MAAM,KAAK,UAAU,MAAM;AACnE;AAMO,SAAS,qBAAqB,QAAgF;AACnH,MAAI,UAAU,MAAM,GAAG;AACrB,WAAO;AAAA,EACT,WAAW,UAAU,MAAM,GAAG;AAC5B,WAAO;AAAA,EACT,WAAW,UAAU,MAAM,GAAG;AAC5B,WAAO;AAAA,EACT;AAEA,SAAO;AACT;","names":[]}
@@ -0,0 +1,12 @@
1
+ // src/lib/errors.ts
2
+ var ValidationError = class extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "ValidationError";
6
+ }
7
+ };
8
+
9
+ export {
10
+ ValidationError
11
+ };
12
+ //# sourceMappingURL=chunk-KGEOPSPH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/errors.ts"],"sourcesContent":["export class ValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ValidationError';\n }\n}\n"],"mappings":";AAAO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;","names":[]}
@@ -0,0 +1,12 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/lib/errors.ts
2
+ var ValidationError = class extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "ValidationError";
6
+ }
7
+ };
8
+
9
+
10
+
11
+ exports.ValidationError = ValidationError;
12
+ //# sourceMappingURL=chunk-SI6PKQOL.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas-normalize/dist/chunk-SI6PKQOL.cjs","../src/lib/errors.ts"],"names":[],"mappings":"AAAA;ACAO,IAAM,gBAAA,EAAN,MAAA,QAA8B,MAAM;AAAA,EACzC,WAAA,CAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,KAAA,EAAO,iBAAA;AAAA,EACd;AACF,CAAA;ADEA;AACA;AACE;AACF,0CAAC","file":"/Users/erunion/code/readme/oas/packages/oas-normalize/dist/chunk-SI6PKQOL.cjs","sourcesContent":[null,"export class ValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ValidationError';\n }\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/lib/utils.ts
2
2
  var _jsyaml = require('js-yaml'); var _jsyaml2 = _interopRequireDefault(_jsyaml);
3
+ var _openapiparser = require('@readme/openapi-parser');
3
4
  function isBuffer(obj) {
4
5
  return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === "function" && !!obj.constructor.isBuffer(obj);
5
6
  }
@@ -80,5 +81,6 @@ function getAPIDefinitionType(schema) {
80
81
 
81
82
 
82
83
 
83
- exports.isBuffer = isBuffer; exports.prepareURL = prepareURL; exports.getType = getType; exports.isOpenAPI = isOpenAPI; exports.isPostman = isPostman; exports.isSwagger = isSwagger; exports.stringToJSON = stringToJSON; exports.isAPIDefinition = isAPIDefinition; exports.getAPIDefinitionType = getAPIDefinitionType;
84
- //# sourceMappingURL=chunk-GZL345SR.cjs.map
84
+
85
+ exports.isBuffer = isBuffer; exports.prepareURL = prepareURL; exports.getType = getType; exports.isOpenAPI = isOpenAPI; exports.isPostman = isPostman; exports.isSwagger = isSwagger; exports.stringToJSON = stringToJSON; exports.isAPIDefinition = isAPIDefinition; exports.getAPIDefinitionType = getAPIDefinitionType; exports.compileErrors = _openapiparser.compileErrors;
86
+ //# sourceMappingURL=chunk-ZTTIELJH.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas-normalize/dist/chunk-ZTTIELJH.cjs","../src/lib/utils.ts"],"names":[],"mappings":"AAAA;ACAA,iFAAkC;AAElC,uDAA8B;AAMvB,SAAS,QAAA,CAAS,GAAA,EAAmB;AAC1C,EAAA,OACE,IAAA,GAAO,KAAA,GACP,GAAA,CAAI,YAAA,GAAe,KAAA,GACnB,OAAO,GAAA,CAAI,WAAA,CAAY,SAAA,IAAa,WAAA,GACpC,CAAC,CAAC,GAAA,CAAI,WAAA,CAAY,QAAA,CAAS,GAAG,CAAA;AAElC;AAMO,SAAS,UAAA,CAAW,GAAA,EAAoD;AAC7E,EAAA,MAAM,QAAA,EAAuB,CAAC,CAAA;AAC9B,EAAA,MAAM,EAAA,EAAI,IAAI,GAAA,CAAI,GAAG,CAAA;AAIrB,EAAA,GAAA,CAAI,CAAA,CAAE,SAAA,GAAY,CAAA,CAAE,QAAA,EAAU;AAC5B,IAAA,OAAA,CAAQ,QAAA,EAAU;AAAA,MAChB,aAAA,EAAe,CAAA,MAAA,EAAS,IAAA,CAAK,CAAA,EAAA;AAC/B,IAAA;AAEa,IAAA;AACA,IAAA;AACf,EAAA;AAGiC,EAAA;AACtB,IAAA;AACuB,IAAA;AAClC,EAAA;AAEO,EAAA;AACW,IAAA;AAChB,IAAA;AACF,EAAA;AACF;AAM8G;AACzF,EAAA;AACV,IAAA;AACiB,EAAA;AACjB,IAAA;AACiB,EAAA;AACD,IAAA;AACd,MAAA;AACmB,IAAA;AAEnB,MAAA;AACoB,IAAA;AACpB,MAAA;AACT,IAAA;AAEO,IAAA;AACT,EAAA;AAEO,EAAA;AACT;AAMoE;AAClD,EAAA;AAClB;AAaoE;AACjC,EAAA;AACnC;AAMoE;AAClD,EAAA;AAClB;AAMgG;AAC9D,EAAA;AACvB,IAAA;AACyB,EAAA;AAER,IAAA;AAC1B,EAAA;AAE2B,EAAA;AAC7B;AAM0E;AAC5C,EAAA;AAC9B;AAMqC;AACZ,EAAA;AACd,IAAA;AACqB,EAAA;AACrB,IAAA;AACqB,EAAA;AACrB,IAAA;AACT,EAAA;AAEO,EAAA;AACT;ADrEoC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/erunion/code/readme/oas/packages/oas-normalize/dist/chunk-ZTTIELJH.cjs","sourcesContent":[null,"import YAML, { JSON_SCHEMA } from 'js-yaml';\n\nexport { compileErrors } from '@readme/openapi-parser';\n\n/**\n * Determine if a given variable is a `Buffer`.\n *\n */\nexport function isBuffer(obj: any): boolean {\n return (\n obj != null &&\n obj.constructor != null &&\n typeof obj.constructor.isBuffer === 'function' &&\n !!obj.constructor.isBuffer(obj)\n );\n}\n\n/**\n * Deconstruct a URL into a payload for a `fetch` request.\n *\n */\nexport function prepareURL(url: string): { options: RequestInit; url: string } {\n const options: RequestInit = {};\n const u = new URL(url);\n\n // `fetch` doesn't support supplying basic auth credentials in the URL so we need to move them\n // into a header.\n if (u.username || u.password) {\n options.headers = {\n Authorization: `Basic ${btoa(`${u.username}:${u.password}`)}`,\n };\n\n u.username = '';\n u.password = '';\n }\n\n // Transform GitHub sources into their raw content URLs.\n if (u.host === 'github.com' && u.pathname.includes('/blob/')) {\n u.host = 'raw.githubusercontent.com';\n u.pathname = u.pathname.replace('/blob/', '/');\n }\n\n return {\n url: u.toString(),\n options,\n };\n}\n\n/**\n * Determine the type of a given variable. Returns `false` if unrecognized.\n *\n */\nexport function getType(obj: any): 'buffer' | 'json' | 'path' | 'string-json' | 'string-yaml' | 'url' | false {\n if (isBuffer(obj)) {\n return 'buffer';\n } else if (typeof obj === 'object') {\n return 'json';\n } else if (typeof obj === 'string') {\n if (obj.match(/\\s*{/)) {\n return 'string-json';\n } else if (obj.match(/\\n/)) {\n // Not sure about this...\n return 'string-yaml';\n } else if (obj.substring(0, 4) === 'http') {\n return 'url';\n }\n\n return 'path';\n }\n\n return false;\n}\n\n/**\n * Determine if a given schema if an OpenAPI definition.\n *\n */\nexport function isOpenAPI(schema: Record<string, unknown>): boolean {\n return !!schema.openapi;\n}\n\n/**\n * Determine if a given schema is a Postman collection.\n *\n * Unfortunately the Postman schema spec doesn't have anything like `openapi` or `swagger` for us\n * to look at but it does require that `info` and `item` be present and as `item` doesn't exist in\n * OpenAPI or Swagger we can use the combination of those two properties to determine if what we\n * have is a Postman collection.\n *\n * @see {@link https://schema.postman.com/json/collection/v2.0.0/collection.json}\n * @see {@link https://schema.postman.com/json/collection/v2.1.0/collection.json}\n */\nexport function isPostman(schema: Record<string, unknown>): boolean {\n return !!schema.info && !!schema.item;\n}\n\n/**\n * Determine if a given schema if an Swagger definition.\n *\n */\nexport function isSwagger(schema: Record<string, unknown>): boolean {\n return !!schema.swagger;\n}\n\n/**\n * Convert a YAML blob or stringified JSON object into a JSON object.\n *\n */\nexport function stringToJSON(string: Record<string, unknown> | string): Record<string, unknown> {\n if (typeof string === 'object') {\n return string;\n } else if (string.match(/^\\s*{/)) {\n // eslint-disable-next-line try-catch-failsafe/json-parse\n return JSON.parse(string);\n }\n\n return YAML.load(string, { schema: JSON_SCHEMA }) as Record<string, unknown>;\n}\n\n/**\n * Determine if a given schema is an API definition that we can support.\n *\n */\nexport function isAPIDefinition(schema: Record<string, unknown>): boolean {\n return isOpenAPI(schema) || isPostman(schema) || isSwagger(schema);\n}\n\n/**\n * Retrieve the type of API definition that a given schema is.\n *\n */\nexport function getAPIDefinitionType(schema: Record<string, unknown>): 'openapi' | 'postman' | 'swagger' | 'unknown' {\n if (isOpenAPI(schema)) {\n return 'openapi';\n } else if (isPostman(schema)) {\n return 'postman';\n } else if (isSwagger(schema)) {\n return 'swagger';\n }\n\n return 'unknown';\n}\n"]}
package/dist/index.cjs CHANGED
@@ -1,19 +1,26 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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; }
2
2
 
3
+ var _chunkSI6PKQOLcjs = require('./chunk-SI6PKQOL.cjs');
3
4
 
4
5
 
5
6
 
6
7
 
7
8
 
8
9
 
9
- var _chunkGZL345SRcjs = require('./chunk-GZL345SR.cjs');
10
+
11
+
12
+ var _chunkZTTIELJHcjs = require('./chunk-ZTTIELJH.cjs');
10
13
 
11
14
  // src/index.ts
12
15
  var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
13
- var _openapiparser = require('@readme/openapi-parser'); var _openapiparser2 = _interopRequireDefault(_openapiparser);
16
+ var _openapiparser = require('@readme/openapi-parser');
14
17
  var _postmantoopenapi = require('@readme/postman-to-openapi'); var _postmantoopenapi2 = _interopRequireDefault(_postmantoopenapi);
15
18
  var _swagger2openapi = require('swagger2openapi'); var _swagger2openapi2 = _interopRequireDefault(_swagger2openapi);
16
19
  var OASNormalize = class _OASNormalize {
20
+
21
+
22
+
23
+
17
24
  constructor(file, opts) {
18
25
  this.file = file;
19
26
  this.opts = {
@@ -21,7 +28,7 @@ var OASNormalize = class _OASNormalize {
21
28
  enablePaths: false,
22
29
  ...opts
23
30
  };
24
- this.type = _chunkGZL345SRcjs.getType.call(void 0, this.file);
31
+ this.type = _chunkZTTIELJHcjs.getType.call(void 0, this.file);
25
32
  this.cache = {
26
33
  load: false,
27
34
  bundle: false,
@@ -35,7 +42,7 @@ var OASNormalize = class _OASNormalize {
35
42
  async load() {
36
43
  if (this.cache.load) return this.cache.load;
37
44
  const resolve = (obj) => {
38
- const ret = _chunkGZL345SRcjs.stringToJSON.call(void 0, obj);
45
+ const ret = _chunkZTTIELJHcjs.stringToJSON.call(void 0, obj);
39
46
  this.cache.load = ret;
40
47
  return ret;
41
48
  };
@@ -47,7 +54,7 @@ var OASNormalize = class _OASNormalize {
47
54
  case "buffer":
48
55
  return resolve(this.file.toString());
49
56
  case "url":
50
- const { url, options } = _chunkGZL345SRcjs.prepareURL.call(void 0, this.file);
57
+ const { url, options } = _chunkZTTIELJHcjs.prepareURL.call(void 0, this.file);
51
58
  const resp = await fetch(url, options).then((res) => res.text());
52
59
  return resolve(resp);
53
60
  case "path":
@@ -75,13 +82,13 @@ var OASNormalize = class _OASNormalize {
75
82
  async bundle() {
76
83
  if (this.cache.bundle) return this.cache.bundle;
77
84
  return this.load().then((schema) => {
78
- if (_chunkGZL345SRcjs.isPostman.call(void 0, schema)) {
85
+ if (_chunkZTTIELJHcjs.isPostman.call(void 0, schema)) {
79
86
  return _OASNormalize.convertPostmanToOpenAPI(schema);
80
87
  }
81
88
  return schema;
82
- }).then((schema) => _openapiparser2.default.bundle(schema)).then((bundle) => {
83
- this.cache.bundle = bundle;
84
- return bundle;
89
+ }).then((schema) => _openapiparser.bundle.call(void 0, schema)).then((bundled) => {
90
+ this.cache.bundle = bundled;
91
+ return bundled;
85
92
  });
86
93
  }
87
94
  /**
@@ -91,11 +98,11 @@ var OASNormalize = class _OASNormalize {
91
98
  async deref() {
92
99
  if (this.cache.deref) return this.cache.deref;
93
100
  return this.load().then((schema) => {
94
- if (_chunkGZL345SRcjs.isPostman.call(void 0, schema)) {
101
+ if (_chunkZTTIELJHcjs.isPostman.call(void 0, schema)) {
95
102
  return _OASNormalize.convertPostmanToOpenAPI(schema);
96
103
  }
97
104
  return schema;
98
- }).then((schema) => _openapiparser2.default.dereference(schema)).then((dereferenced) => {
105
+ }).then((schema) => _openapiparser.dereference.call(void 0, schema)).then((dereferenced) => {
99
106
  this.cache.deref = dereferenced;
100
107
  return dereferenced;
101
108
  });
@@ -107,11 +114,11 @@ var OASNormalize = class _OASNormalize {
107
114
  async convert() {
108
115
  if (this.cache.convert) return this.cache.convert;
109
116
  return this.load().then(async (schema) => {
110
- return _chunkGZL345SRcjs.isPostman.call(void 0, schema) ? _OASNormalize.convertPostmanToOpenAPI(schema) : schema;
117
+ return _chunkZTTIELJHcjs.isPostman.call(void 0, schema) ? _OASNormalize.convertPostmanToOpenAPI(schema) : schema;
111
118
  }).then(async (schema) => {
112
- if (!_chunkGZL345SRcjs.isSwagger.call(void 0, schema) && !_chunkGZL345SRcjs.isOpenAPI.call(void 0, schema)) {
119
+ if (!_chunkZTTIELJHcjs.isSwagger.call(void 0, schema) && !_chunkZTTIELJHcjs.isOpenAPI.call(void 0, schema)) {
113
120
  throw new Error("The supplied API definition is unsupported.");
114
- } else if (_chunkGZL345SRcjs.isOpenAPI.call(void 0, schema)) {
121
+ } else if (_chunkZTTIELJHcjs.isOpenAPI.call(void 0, schema)) {
115
122
  return schema;
116
123
  }
117
124
  const baseVersion = parseInt(schema.swagger, 10);
@@ -130,25 +137,26 @@ var OASNormalize = class _OASNormalize {
130
137
  */
131
138
  async validate(opts = {}) {
132
139
  const parserOptions = opts.parser || {};
133
- if (!parserOptions.validate) {
134
- parserOptions.validate = {};
135
- }
136
- parserOptions.validate.colorizeErrors = this.opts.colorizeErrors;
140
+ if (!parserOptions.validate) parserOptions.validate = {};
141
+ if (!parserOptions.validate.errors) parserOptions.validate.errors = {};
142
+ parserOptions.validate.errors.colorize = this.opts.colorizeErrors;
137
143
  return this.load().then(async (schema) => {
138
- return _chunkGZL345SRcjs.isPostman.call(void 0, schema) ? _OASNormalize.convertPostmanToOpenAPI(schema) : schema;
144
+ return _chunkZTTIELJHcjs.isPostman.call(void 0, schema) ? _OASNormalize.convertPostmanToOpenAPI(schema) : schema;
139
145
  }).then(async (schema) => {
140
- if (!_chunkGZL345SRcjs.isSwagger.call(void 0, schema) && !_chunkGZL345SRcjs.isOpenAPI.call(void 0, schema)) {
141
- throw new Error("The supplied API definition is unsupported.");
142
- } else if (_chunkGZL345SRcjs.isSwagger.call(void 0, schema)) {
146
+ if (!_chunkZTTIELJHcjs.isSwagger.call(void 0, schema) && !_chunkZTTIELJHcjs.isOpenAPI.call(void 0, schema)) {
147
+ throw new (0, _chunkSI6PKQOLcjs.ValidationError)("The supplied API definition is unsupported.");
148
+ } else if (_chunkZTTIELJHcjs.isSwagger.call(void 0, schema)) {
143
149
  const baseVersion = parseInt(schema.swagger, 10);
144
150
  if (baseVersion === 1) {
145
- throw new Error("Swagger v1.2 is unsupported.");
151
+ throw new (0, _chunkSI6PKQOLcjs.ValidationError)("Swagger v1.2 is unsupported.");
146
152
  }
147
153
  }
148
154
  const clonedSchema = JSON.parse(JSON.stringify(schema));
149
- return _openapiparser2.default.validate(clonedSchema, parserOptions).then(() => {
150
- return true;
151
- });
155
+ const result = await _openapiparser.validate.call(void 0, clonedSchema, parserOptions);
156
+ if (!result.valid) {
157
+ throw new (0, _chunkSI6PKQOLcjs.ValidationError)(_openapiparser.compileErrors.call(void 0, result));
158
+ }
159
+ return result;
152
160
  });
153
161
  }
154
162
  /**
@@ -157,7 +165,7 @@ var OASNormalize = class _OASNormalize {
157
165
  */
158
166
  async version() {
159
167
  return this.load().then((schema) => {
160
- switch (_chunkGZL345SRcjs.getAPIDefinitionType.call(void 0, schema)) {
168
+ switch (_chunkZTTIELJHcjs.getAPIDefinitionType.call(void 0, schema)) {
161
169
  case "openapi":
162
170
  return {
163
171
  specification: "openapi",
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users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AAA,CAAE,IAAA,CAAK,CAAA,MAAA,EAAA,GAAU;AAChC,MAAA,OAAA,CAAc,oDAAA,MAA2B,CAAA,EAAG;AAAA,QAC1C,KAAK,SAAA;AACH,UAAA,OAAO;AAAA,YACL,aAAA,EAAe,SAAA;AAAA,YACf,OAAA,EAAU,MAAA,CAAyC;AAAA,UACrD,CAAA;AAAA,QAEF,KAAK,SAAA;AACH,UAAA,IAAI,QAAA,EAAU,SAAA;AACd,UAAA,GAAA,iBAAK,MAAA,2BAAQ,IAAA,6BAAiC,QAAA,EAAQ;AAIpD,YAAA,MAAM,MAAA,EAAA,iBAAS,MAAA,6BAAQ,MAAA,CAAA,CAAgC,MAAA,CAAO,KAAA;AAAA,cAC5D;AAAA,YACF,CAAA;AAEA,YAAA,GAAA,CAAI,KAAA,EAAO;AACT,cAAA,QAAA,EAAU,KAAA,CAAM,CAAC,CAAA;AAAA,YACnB;AAAA,UACF;AAEA,UAAA,OAAO;AAAA,YACL,aAAA,EAAe,SAAA;AAAA,YACf;AAAA,UACF,CAAA;AAAA,QAEF,KAAK,SAAA;AACH,UAAA,OAAO;AAAA,YACL,aAAA,EAAe,SAAA;AAAA,YACf,OAAA,EAAU,MAAA,CAAyC;AAAA,UACrD,CAAA;AAAA,QAEF,OAAA;AACE,UAAA,MAAM,IAAI,KAAA,CAAM,wBAAwB,CAAA;AAAA,MAC5C;AAAA,IACF,CAAC,CAAA;AAAA,EACH;AACF,CAAA;AD9EA;AACE;AACF,+BAAA","file":"/Users/erunion/code/readme/oas/packages/oas-normalize/dist/index.cjs","sourcesContent":[null,"import type { Options } from './lib/types.js';\nimport type { OpenAPI, OpenAPIV2, OpenAPIV3 } from 'openapi-types';\n\nimport fs from 'node:fs';\n\nimport openapiParser from '@readme/openapi-parser';\nimport postmanToOpenAPI from '@readme/postman-to-openapi';\nimport converter from 'swagger2openapi';\n\nimport * as utils from './lib/utils.js';\n\nexport default class OASNormalize {\n cache: {\n bundle?: OpenAPI.Document | false;\n convert?: OpenAPI.Document | false;\n deref?: OpenAPI.Document | false;\n load?: Record<string, unknown> | false;\n };\n\n file: any;\n\n opts: Options;\n\n type: ReturnType<typeof utils.getType>;\n\n constructor(file: any, opts?: Options) {\n this.file = file;\n this.opts = {\n colorizeErrors: false,\n enablePaths: false,\n ...opts,\n };\n\n this.type = utils.getType(this.file);\n\n this.cache = {\n load: false,\n bundle: false,\n deref: false,\n };\n }\n\n /**\n * Load and return the API definition that `oas-normalize` was initialized with.\n *\n */\n async load(): Promise<Record<string, unknown>> {\n if (this.cache.load) return this.cache.load;\n\n const resolve = (obj: Parameters<typeof utils.stringToJSON>[0]) => {\n const ret = utils.stringToJSON(obj);\n this.cache.load = ret;\n return ret;\n };\n\n switch (this.type) {\n case 'json':\n case 'string-json':\n case 'string-yaml':\n return resolve(this.file);\n\n case 'buffer':\n return resolve(this.file.toString());\n\n case 'url':\n const { url, options } = utils.prepareURL(this.file);\n const resp = await fetch(url, options).then(res => res.text());\n return resolve(resp);\n\n case 'path':\n // Load a local file\n if (!this.opts.enablePaths) {\n throw new Error('Use `opts.enablePaths` to enable accessing local files.');\n }\n\n const contents = fs.readFileSync(this.file).toString();\n if (!contents.trim()) {\n throw new Error('No file contents found.');\n }\n return resolve(contents);\n\n default:\n throw new Error('Could not load this file.');\n }\n }\n\n private static async convertPostmanToOpenAPI(schema: any) {\n return postmanToOpenAPI(JSON.stringify(schema), undefined, { outputFormat: 'json', replaceVars: true }).then(\n JSON.parse,\n );\n }\n\n /**\n * Bundle up the given API definition, resolving any external `$ref` pointers in the process.\n *\n */\n async bundle() {\n if (this.cache.bundle) return this.cache.bundle;\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to bundle we'll still\n // upconvert it to an OpenAPI definition file so our returned dataset is always one of\n // those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => openapiParser.bundle(schema))\n .then(bundle => {\n this.cache.bundle = bundle;\n return bundle;\n });\n }\n\n /**\n * Dereference the given API definition.\n *\n */\n async deref() {\n if (this.cache.deref) return this.cache.deref;\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to dereference we'll\n // still upconvert it to an OpenAPI definition file so our returned dataset is always one\n // of those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => openapiParser.dereference(schema))\n .then(dereferenced => {\n this.cache.deref = dereferenced;\n return dereferenced;\n });\n }\n\n /**\n * Convert a given API definition to OpenAPI if it is not already.\n *\n */\n async convert(): Promise<OpenAPI.Document> {\n if (this.cache.convert) return this.cache.convert;\n\n return this.load()\n .then(async schema => {\n // If we have a Postman collection we need to convert it to OpenAPI.\n return utils.isPostman(schema) ? OASNormalize.convertPostmanToOpenAPI(schema) : schema;\n })\n .then(async schema => {\n if (!utils.isSwagger(schema) && !utils.isOpenAPI(schema)) {\n throw new Error('The supplied API definition is unsupported.');\n } else if (utils.isOpenAPI(schema)) {\n return schema;\n }\n\n const baseVersion = parseInt(schema.swagger, 10);\n if (baseVersion === 1) {\n throw new Error('Swagger v1.2 is unsupported.');\n }\n\n return converter\n .convertObj(schema, { anchors: true })\n .then((options: { openapi: OpenAPI.Document }) => options.openapi);\n });\n }\n\n /**\n * Validate a given API definition.\n *\n * If supplied a Postman collection it will be converted to OpenAPI first and then run through\n * standard OpenAPI validation.\n *\n */\n async validate(\n opts: {\n parser?: openapiParser.Options;\n } = {},\n ): Promise<true> {\n const parserOptions = opts.parser || {};\n if (!parserOptions.validate) {\n parserOptions.validate = {};\n }\n\n parserOptions.validate.colorizeErrors = this.opts.colorizeErrors;\n\n return this.load()\n .then(async schema => {\n // Because we don't have something akin to `openapi-parser` for Postman collections we just\n // always convert them to OpenAPI.\n return utils.isPostman(schema) ? OASNormalize.convertPostmanToOpenAPI(schema) : schema;\n })\n .then(async schema => {\n if (!utils.isSwagger(schema) && !utils.isOpenAPI(schema)) {\n throw new Error('The supplied API definition is unsupported.');\n } else if (utils.isSwagger(schema)) {\n const baseVersion = parseInt(schema.swagger, 10);\n if (baseVersion === 1) {\n throw new Error('Swagger v1.2 is unsupported.');\n }\n }\n\n /**\n * `openapiParser.validate()` dereferences schemas at the same time as validation, mutating\n * the supplied parameter in the process, and does not give us an option to disable this.\n * As we already have a dereferencing method on this library, and this method just needs to\n * tell us if the API definition is valid or not, we need to clone the schema before\n * supplying it to `openapi-parser`.\n */\n // eslint-disable-next-line try-catch-failsafe/json-parse\n const clonedSchema = JSON.parse(JSON.stringify(schema));\n\n return openapiParser.validate(clonedSchema, parserOptions).then(() => {\n // The API definition, whatever its format or specification, is valid.\n return true;\n });\n });\n }\n\n /**\n * Retrieve OpenAPI, Swagger, or Postman version information about the supplied API definition.\n *\n */\n async version(): Promise<{ specification: 'openapi' | 'postman' | 'swagger'; version: string | 'unknown' }> {\n return this.load().then(schema => {\n switch (utils.getAPIDefinitionType(schema)) {\n case 'openapi':\n return {\n specification: 'openapi',\n version: (schema as unknown as OpenAPIV3.Document).openapi,\n };\n\n case 'postman':\n let version = 'unknown';\n if ((schema?.info as Record<string, string>)?.schema) {\n // Though `info.schema` is required by the Postman spec there's no strictness to its\n // contents so we'll do our best to extract a version out of this schema URL that they\n // seem to usually match. If not we'll fallback to treating it as an `unknown` version.\n const match = (schema?.info as Record<string, string>).schema.match(\n /http(s?):\\/\\/schema.getpostman.com\\/json\\/collection\\/v([0-9.]+)\\//,\n );\n\n if (match) {\n version = match[2];\n }\n }\n\n return {\n specification: 'postman',\n version,\n };\n\n case 'swagger':\n return {\n specification: 'swagger',\n version: (schema as unknown as OpenAPIV2.Document).swagger,\n };\n\n default:\n throw new Error('Unknown file detected.');\n }\n });\n }\n}\n"]}
1
+ {"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas-normalize/dist/index.cjs","../src/index.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAAA;AACA;AACE;AACA;AACA;AACA;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ACL;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,OAAA,CAAA,EAAsG;AAC1G,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,CAAA,CAAE,IAAA,CAAK,CAAA,MAAA,EAAA,GAAU;AAChC,MAAA,OAAA,CAAc,oDAAA,MAA2B,CAAA,EAAG;AAAA,QAC1C,KAAK,SAAA;AACH,UAAA,OAAO;AAAA,YACL,aAAA,EAAe,SAAA;AAAA,YACf,OAAA,EAAU,MAAA,CAAyC;AAAA,UACrD,CAAA;AAAA,QAEF,KAAK,SAAA;AACH,UAAA,IAAI,QAAA,EAAU,SAAA;AACd,UAAA,GAAA,iBAAK,MAAA,2BAAQ,IAAA,6BAAiC,QAAA,EAAQ;AAIpD,YAAA,MAAM,MAAA,EAAA,iBAAS,MAAA,6BAAQ,MAAA,CAAA,CAAgC,MAAA,CAAO,KAAA;AAAA,cAC5D;AAAA,YACF,CAAA;AAEA,YAAA,GAAA,CAAI,KAAA,EAAO;AACT,cAAA,QAAA,EAAU,KAAA,CAAM,CAAC,CAAA;AAAA,YACnB;AAAA,UACF;AAEA,UAAA,OAAO;AAAA,YACL,aAAA,EAAe,SAAA;AAAA,YACf;AAAA,UACF,CAAA;AAAA,QAEF,KAAK,SAAA;AACH,UAAA,OAAO;AAAA,YACL,aAAA,EAAe,SAAA;AAAA,YACf,OAAA,EAAU,MAAA,CAAyC;AAAA,UACrD,CAAA;AAAA,QAEF,OAAA;AACE,UAAA,MAAM,IAAI,KAAA,CAAM,wBAAwB,CAAA;AAAA,MAC5C;AAAA,IACF,CAAC,CAAA;AAAA,EACH;AACF,CAAA;AD1EA;AACE;AACF,+BAAA","file":"/Users/erunion/code/readme/oas/packages/oas-normalize/dist/index.cjs","sourcesContent":[null,"import type { Options } from './lib/types.js';\nimport type { ParserOptions, ValidationResult } from '@readme/openapi-parser';\nimport type { OpenAPI, OpenAPIV2, OpenAPIV3 } from 'openapi-types';\n\nimport fs from 'node:fs';\n\nimport { bundle, compileErrors, dereference, validate } from '@readme/openapi-parser';\nimport postmanToOpenAPI from '@readme/postman-to-openapi';\nimport converter from 'swagger2openapi';\n\nimport { ValidationError } from './lib/errors.js';\nimport * as utils from './lib/utils.js';\n\nexport default class OASNormalize {\n cache: {\n bundle?: OpenAPI.Document | false;\n convert?: OpenAPI.Document | false;\n deref?: OpenAPI.Document | false;\n load?: Record<string, unknown> | false;\n };\n\n file: any;\n\n opts: Options;\n\n type: ReturnType<typeof utils.getType>;\n\n constructor(file: any, opts?: Options) {\n this.file = file;\n this.opts = {\n colorizeErrors: false,\n enablePaths: false,\n ...opts,\n };\n\n this.type = utils.getType(this.file);\n\n this.cache = {\n load: false,\n bundle: false,\n deref: false,\n };\n }\n\n /**\n * Load and return the API definition that `oas-normalize` was initialized with.\n *\n */\n async load(): Promise<Record<string, unknown>> {\n if (this.cache.load) return this.cache.load;\n\n const resolve = (obj: Parameters<typeof utils.stringToJSON>[0]) => {\n const ret = utils.stringToJSON(obj);\n this.cache.load = ret;\n return ret;\n };\n\n switch (this.type) {\n case 'json':\n case 'string-json':\n case 'string-yaml':\n return resolve(this.file);\n\n case 'buffer':\n return resolve(this.file.toString());\n\n case 'url':\n const { url, options } = utils.prepareURL(this.file);\n const resp = await fetch(url, options).then(res => res.text());\n return resolve(resp);\n\n case 'path':\n // Load a local file\n if (!this.opts.enablePaths) {\n throw new Error('Use `opts.enablePaths` to enable accessing local files.');\n }\n\n const contents = fs.readFileSync(this.file).toString();\n if (!contents.trim()) {\n throw new Error('No file contents found.');\n }\n return resolve(contents);\n\n default:\n throw new Error('Could not load this file.');\n }\n }\n\n private static async convertPostmanToOpenAPI(schema: any) {\n return postmanToOpenAPI(JSON.stringify(schema), undefined, { outputFormat: 'json', replaceVars: true }).then(\n JSON.parse,\n );\n }\n\n /**\n * Bundle up the given API definition, resolving any external `$ref` pointers in the process.\n *\n */\n async bundle(): Promise<OpenAPI.Document> {\n if (this.cache.bundle) return this.cache.bundle;\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to bundle we'll still\n // upconvert it to an OpenAPI definition file so our returned dataset is always one of\n // those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => bundle(schema))\n .then(bundled => {\n this.cache.bundle = bundled;\n return bundled;\n });\n }\n\n /**\n * Dereference the given API definition.\n *\n */\n async deref(): Promise<OpenAPI.Document> {\n if (this.cache.deref) return this.cache.deref;\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to dereference we'll\n // still upconvert it to an OpenAPI definition file so our returned dataset is always one\n // of those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => dereference(schema))\n .then(dereferenced => {\n this.cache.deref = dereferenced;\n return dereferenced;\n });\n }\n\n /**\n * Convert a given API definition to OpenAPI if it is not already.\n *\n */\n async convert(): Promise<OpenAPI.Document> {\n if (this.cache.convert) return this.cache.convert;\n\n return this.load()\n .then(async schema => {\n // If we have a Postman collection we need to convert it to OpenAPI.\n return utils.isPostman(schema) ? OASNormalize.convertPostmanToOpenAPI(schema) : schema;\n })\n .then(async schema => {\n if (!utils.isSwagger(schema) && !utils.isOpenAPI(schema)) {\n throw new Error('The supplied API definition is unsupported.');\n } else if (utils.isOpenAPI(schema)) {\n return schema;\n }\n\n const baseVersion = parseInt(schema.swagger, 10);\n if (baseVersion === 1) {\n throw new Error('Swagger v1.2 is unsupported.');\n }\n\n return converter\n .convertObj(schema, { anchors: true })\n .then((options: { openapi: OpenAPI.Document }) => options.openapi);\n });\n }\n\n /**\n * Validate a given API definition.\n *\n * If supplied a Postman collection it will be converted to OpenAPI first and then run through\n * standard OpenAPI validation.\n *\n */\n async validate(\n opts: {\n parser?: ParserOptions;\n } = {},\n ): Promise<ValidationResult> {\n const parserOptions = opts.parser || {};\n if (!parserOptions.validate) parserOptions.validate = {};\n if (!parserOptions.validate.errors) parserOptions.validate.errors = {};\n\n parserOptions.validate.errors.colorize = this.opts.colorizeErrors;\n\n return this.load()\n .then(async schema => {\n // Because we don't have something akin to `openapi-parser` for Postman collections we just\n // always convert them to OpenAPI.\n return utils.isPostman(schema) ? OASNormalize.convertPostmanToOpenAPI(schema) : schema;\n })\n .then(async schema => {\n if (!utils.isSwagger(schema) && !utils.isOpenAPI(schema)) {\n throw new ValidationError('The supplied API definition is unsupported.');\n } else if (utils.isSwagger(schema)) {\n const baseVersion = parseInt(schema.swagger, 10);\n if (baseVersion === 1) {\n throw new ValidationError('Swagger v1.2 is unsupported.');\n }\n }\n\n /**\n * `OpenAPIParser.validate()` dereferences schemas at the same time as validation, mutating\n * the supplied parameter in the process, and does not give us an option to disable this.\n * As we already have a dereferencing method on this library, and this method just needs to\n * tell us if the API definition is valid or not, we need to clone the schema before\n * supplying it to `openapi-parser`.\n */\n // eslint-disable-next-line try-catch-failsafe/json-parse\n const clonedSchema = JSON.parse(JSON.stringify(schema));\n\n const result = await validate(clonedSchema, parserOptions);\n if (!result.valid) {\n throw new ValidationError(compileErrors(result));\n }\n\n // The API definition, whatever its format or specification, is valid.\n return result;\n });\n }\n\n /**\n * Retrieve OpenAPI, Swagger, or Postman version information about the supplied API definition.\n *\n */\n async version(): Promise<{ specification: 'openapi' | 'postman' | 'swagger'; version: string | 'unknown' }> {\n return this.load().then(schema => {\n switch (utils.getAPIDefinitionType(schema)) {\n case 'openapi':\n return {\n specification: 'openapi',\n version: (schema as unknown as OpenAPIV3.Document).openapi,\n };\n\n case 'postman':\n let version = 'unknown';\n if ((schema?.info as Record<string, string>)?.schema) {\n // Though `info.schema` is required by the Postman spec there's no strictness to its\n // contents so we'll do our best to extract a version out of this schema URL that they\n // seem to usually match. If not we'll fallback to treating it as an `unknown` version.\n const match = (schema?.info as Record<string, string>).schema.match(\n /http(s?):\\/\\/schema.getpostman.com\\/json\\/collection\\/v([0-9.]+)\\//,\n );\n\n if (match) {\n version = match[2];\n }\n }\n\n return {\n specification: 'postman',\n version,\n };\n\n case 'swagger':\n return {\n specification: 'swagger',\n version: (schema as unknown as OpenAPIV2.Document).swagger,\n };\n\n default:\n throw new Error('Unknown file detected.');\n }\n });\n }\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Options } from './lib/types.cjs';
2
+ import { ParserOptions, ValidationResult } from '@readme/openapi-parser';
2
3
  import { OpenAPI } from 'openapi-types';
3
- import openapiParser from '@readme/openapi-parser';
4
4
  import { getType } from './lib/utils.cjs';
5
5
 
6
6
  declare class OASNormalize {
@@ -24,12 +24,12 @@ declare class OASNormalize {
24
24
  * Bundle up the given API definition, resolving any external `$ref` pointers in the process.
25
25
  *
26
26
  */
27
- bundle(): Promise<OpenAPI.Document<{}>>;
27
+ bundle(): Promise<OpenAPI.Document>;
28
28
  /**
29
29
  * Dereference the given API definition.
30
30
  *
31
31
  */
32
- deref(): Promise<OpenAPI.Document<{}>>;
32
+ deref(): Promise<OpenAPI.Document>;
33
33
  /**
34
34
  * Convert a given API definition to OpenAPI if it is not already.
35
35
  *
@@ -43,8 +43,8 @@ declare class OASNormalize {
43
43
  *
44
44
  */
45
45
  validate(opts?: {
46
- parser?: openapiParser.Options;
47
- }): Promise<true>;
46
+ parser?: ParserOptions;
47
+ }): Promise<ValidationResult>;
48
48
  /**
49
49
  * Retrieve OpenAPI, Swagger, or Postman version information about the supplied API definition.
50
50
  *
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Options } from './lib/types.js';
2
+ import { ParserOptions, ValidationResult } from '@readme/openapi-parser';
2
3
  import { OpenAPI } from 'openapi-types';
3
- import openapiParser from '@readme/openapi-parser';
4
4
  import { getType } from './lib/utils.js';
5
5
 
6
6
  declare class OASNormalize {
@@ -24,12 +24,12 @@ declare class OASNormalize {
24
24
  * Bundle up the given API definition, resolving any external `$ref` pointers in the process.
25
25
  *
26
26
  */
27
- bundle(): Promise<OpenAPI.Document<{}>>;
27
+ bundle(): Promise<OpenAPI.Document>;
28
28
  /**
29
29
  * Dereference the given API definition.
30
30
  *
31
31
  */
32
- deref(): Promise<OpenAPI.Document<{}>>;
32
+ deref(): Promise<OpenAPI.Document>;
33
33
  /**
34
34
  * Convert a given API definition to OpenAPI if it is not already.
35
35
  *
@@ -43,8 +43,8 @@ declare class OASNormalize {
43
43
  *
44
44
  */
45
45
  validate(opts?: {
46
- parser?: openapiParser.Options;
47
- }): Promise<true>;
46
+ parser?: ParserOptions;
47
+ }): Promise<ValidationResult>;
48
48
  /**
49
49
  * Retrieve OpenAPI, Swagger, or Postman version information about the supplied API definition.
50
50
  *
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ import {
2
+ ValidationError
3
+ } from "./chunk-KGEOPSPH.js";
1
4
  import {
2
5
  getAPIDefinitionType,
3
6
  getType,
@@ -6,14 +9,18 @@ import {
6
9
  isSwagger,
7
10
  prepareURL,
8
11
  stringToJSON
9
- } from "./chunk-J322YOXV.js";
12
+ } from "./chunk-EHNNEPCG.js";
10
13
 
11
14
  // src/index.ts
12
15
  import fs from "node:fs";
13
- import openapiParser from "@readme/openapi-parser";
16
+ import { bundle, compileErrors, dereference, validate } from "@readme/openapi-parser";
14
17
  import postmanToOpenAPI from "@readme/postman-to-openapi";
15
18
  import converter from "swagger2openapi";
16
19
  var OASNormalize = class _OASNormalize {
20
+ cache;
21
+ file;
22
+ opts;
23
+ type;
17
24
  constructor(file, opts) {
18
25
  this.file = file;
19
26
  this.opts = {
@@ -79,9 +86,9 @@ var OASNormalize = class _OASNormalize {
79
86
  return _OASNormalize.convertPostmanToOpenAPI(schema);
80
87
  }
81
88
  return schema;
82
- }).then((schema) => openapiParser.bundle(schema)).then((bundle) => {
83
- this.cache.bundle = bundle;
84
- return bundle;
89
+ }).then((schema) => bundle(schema)).then((bundled) => {
90
+ this.cache.bundle = bundled;
91
+ return bundled;
85
92
  });
86
93
  }
87
94
  /**
@@ -95,7 +102,7 @@ var OASNormalize = class _OASNormalize {
95
102
  return _OASNormalize.convertPostmanToOpenAPI(schema);
96
103
  }
97
104
  return schema;
98
- }).then((schema) => openapiParser.dereference(schema)).then((dereferenced) => {
105
+ }).then((schema) => dereference(schema)).then((dereferenced) => {
99
106
  this.cache.deref = dereferenced;
100
107
  return dereferenced;
101
108
  });
@@ -130,25 +137,26 @@ var OASNormalize = class _OASNormalize {
130
137
  */
131
138
  async validate(opts = {}) {
132
139
  const parserOptions = opts.parser || {};
133
- if (!parserOptions.validate) {
134
- parserOptions.validate = {};
135
- }
136
- parserOptions.validate.colorizeErrors = this.opts.colorizeErrors;
140
+ if (!parserOptions.validate) parserOptions.validate = {};
141
+ if (!parserOptions.validate.errors) parserOptions.validate.errors = {};
142
+ parserOptions.validate.errors.colorize = this.opts.colorizeErrors;
137
143
  return this.load().then(async (schema) => {
138
144
  return isPostman(schema) ? _OASNormalize.convertPostmanToOpenAPI(schema) : schema;
139
145
  }).then(async (schema) => {
140
146
  if (!isSwagger(schema) && !isOpenAPI(schema)) {
141
- throw new Error("The supplied API definition is unsupported.");
147
+ throw new ValidationError("The supplied API definition is unsupported.");
142
148
  } else if (isSwagger(schema)) {
143
149
  const baseVersion = parseInt(schema.swagger, 10);
144
150
  if (baseVersion === 1) {
145
- throw new Error("Swagger v1.2 is unsupported.");
151
+ throw new ValidationError("Swagger v1.2 is unsupported.");
146
152
  }
147
153
  }
148
154
  const clonedSchema = JSON.parse(JSON.stringify(schema));
149
- return openapiParser.validate(clonedSchema, parserOptions).then(() => {
150
- return true;
151
- });
155
+ const result = await validate(clonedSchema, parserOptions);
156
+ if (!result.valid) {
157
+ throw new ValidationError(compileErrors(result));
158
+ }
159
+ return result;
152
160
  });
153
161
  }
154
162
  /**
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Options } from './lib/types.js';\nimport type { OpenAPI, OpenAPIV2, OpenAPIV3 } from 'openapi-types';\n\nimport fs from 'node:fs';\n\nimport openapiParser from '@readme/openapi-parser';\nimport postmanToOpenAPI from '@readme/postman-to-openapi';\nimport converter from 'swagger2openapi';\n\nimport * as utils from './lib/utils.js';\n\nexport default class OASNormalize {\n cache: {\n bundle?: OpenAPI.Document | false;\n convert?: OpenAPI.Document | false;\n deref?: OpenAPI.Document | false;\n load?: Record<string, unknown> | false;\n };\n\n file: any;\n\n opts: Options;\n\n type: ReturnType<typeof utils.getType>;\n\n constructor(file: any, opts?: Options) {\n this.file = file;\n this.opts = {\n colorizeErrors: false,\n enablePaths: false,\n ...opts,\n };\n\n this.type = utils.getType(this.file);\n\n this.cache = {\n load: false,\n bundle: false,\n deref: false,\n };\n }\n\n /**\n * Load and return the API definition that `oas-normalize` was initialized with.\n *\n */\n async load(): Promise<Record<string, unknown>> {\n if (this.cache.load) return this.cache.load;\n\n const resolve = (obj: Parameters<typeof utils.stringToJSON>[0]) => {\n const ret = utils.stringToJSON(obj);\n this.cache.load = ret;\n return ret;\n };\n\n switch (this.type) {\n case 'json':\n case 'string-json':\n case 'string-yaml':\n return resolve(this.file);\n\n case 'buffer':\n return resolve(this.file.toString());\n\n case 'url':\n const { url, options } = utils.prepareURL(this.file);\n const resp = await fetch(url, options).then(res => res.text());\n return resolve(resp);\n\n case 'path':\n // Load a local file\n if (!this.opts.enablePaths) {\n throw new Error('Use `opts.enablePaths` to enable accessing local files.');\n }\n\n const contents = fs.readFileSync(this.file).toString();\n if (!contents.trim()) {\n throw new Error('No file contents found.');\n }\n return resolve(contents);\n\n default:\n throw new Error('Could not load this file.');\n }\n }\n\n private static async convertPostmanToOpenAPI(schema: any) {\n return postmanToOpenAPI(JSON.stringify(schema), undefined, { outputFormat: 'json', replaceVars: true }).then(\n JSON.parse,\n );\n }\n\n /**\n * Bundle up the given API definition, resolving any external `$ref` pointers in the process.\n *\n */\n async bundle() {\n if (this.cache.bundle) return this.cache.bundle;\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to bundle we'll still\n // upconvert it to an OpenAPI definition file so our returned dataset is always one of\n // those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => openapiParser.bundle(schema))\n .then(bundle => {\n this.cache.bundle = bundle;\n return bundle;\n });\n }\n\n /**\n * Dereference the given API definition.\n *\n */\n async deref() {\n if (this.cache.deref) return this.cache.deref;\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to dereference we'll\n // still upconvert it to an OpenAPI definition file so our returned dataset is always one\n // of those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => openapiParser.dereference(schema))\n .then(dereferenced => {\n this.cache.deref = dereferenced;\n return dereferenced;\n });\n }\n\n /**\n * Convert a given API definition to OpenAPI if it is not already.\n *\n */\n async convert(): Promise<OpenAPI.Document> {\n if (this.cache.convert) return this.cache.convert;\n\n return this.load()\n .then(async schema => {\n // If we have a Postman collection we need to convert it to OpenAPI.\n return utils.isPostman(schema) ? OASNormalize.convertPostmanToOpenAPI(schema) : schema;\n })\n .then(async schema => {\n if (!utils.isSwagger(schema) && !utils.isOpenAPI(schema)) {\n throw new Error('The supplied API definition is unsupported.');\n } else if (utils.isOpenAPI(schema)) {\n return schema;\n }\n\n const baseVersion = parseInt(schema.swagger, 10);\n if (baseVersion === 1) {\n throw new Error('Swagger v1.2 is unsupported.');\n }\n\n return converter\n .convertObj(schema, { anchors: true })\n .then((options: { openapi: OpenAPI.Document }) => options.openapi);\n });\n }\n\n /**\n * Validate a given API definition.\n *\n * If supplied a Postman collection it will be converted to OpenAPI first and then run through\n * standard OpenAPI validation.\n *\n */\n async validate(\n opts: {\n parser?: openapiParser.Options;\n } = {},\n ): Promise<true> {\n const parserOptions = opts.parser || {};\n if (!parserOptions.validate) {\n parserOptions.validate = {};\n }\n\n parserOptions.validate.colorizeErrors = this.opts.colorizeErrors;\n\n return this.load()\n .then(async schema => {\n // Because we don't have something akin to `openapi-parser` for Postman collections we just\n // always convert them to OpenAPI.\n return utils.isPostman(schema) ? OASNormalize.convertPostmanToOpenAPI(schema) : schema;\n })\n .then(async schema => {\n if (!utils.isSwagger(schema) && !utils.isOpenAPI(schema)) {\n throw new Error('The supplied API definition is unsupported.');\n } else if (utils.isSwagger(schema)) {\n const baseVersion = parseInt(schema.swagger, 10);\n if (baseVersion === 1) {\n throw new Error('Swagger v1.2 is unsupported.');\n }\n }\n\n /**\n * `openapiParser.validate()` dereferences schemas at the same time as validation, mutating\n * the supplied parameter in the process, and does not give us an option to disable this.\n * As we already have a dereferencing method on this library, and this method just needs to\n * tell us if the API definition is valid or not, we need to clone the schema before\n * supplying it to `openapi-parser`.\n */\n // eslint-disable-next-line try-catch-failsafe/json-parse\n const clonedSchema = JSON.parse(JSON.stringify(schema));\n\n return openapiParser.validate(clonedSchema, parserOptions).then(() => {\n // The API definition, whatever its format or specification, is valid.\n return true;\n });\n });\n }\n\n /**\n * Retrieve OpenAPI, Swagger, or Postman version information about the supplied API definition.\n *\n */\n async version(): Promise<{ specification: 'openapi' | 'postman' | 'swagger'; version: string | 'unknown' }> {\n return this.load().then(schema => {\n switch (utils.getAPIDefinitionType(schema)) {\n case 'openapi':\n return {\n specification: 'openapi',\n version: (schema as unknown as OpenAPIV3.Document).openapi,\n };\n\n case 'postman':\n let version = 'unknown';\n if ((schema?.info as Record<string, string>)?.schema) {\n // Though `info.schema` is required by the Postman spec there's no strictness to its\n // contents so we'll do our best to extract a version out of this schema URL that they\n // seem to usually match. If not we'll fallback to treating it as an `unknown` version.\n const match = (schema?.info as Record<string, string>).schema.match(\n /http(s?):\\/\\/schema.getpostman.com\\/json\\/collection\\/v([0-9.]+)\\//,\n );\n\n if (match) {\n version = match[2];\n }\n }\n\n return {\n specification: 'postman',\n version,\n };\n\n case 'swagger':\n return {\n specification: 'swagger',\n version: (schema as unknown as OpenAPIV2.Document).swagger,\n };\n\n default:\n throw new Error('Un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C1G,WAAO,KAAK,KAAK,EAAE,KAAK,YAAU;AAChC,cAAc,qBAAqB,MAAM,GAAG;AAAA,QAC1C,KAAK;AACH,iBAAO;AAAA,YACL,eAAe;AAAA,YACf,SAAU,OAAyC;AAAA,UACrD;AAAA,QAEF,KAAK;AACH,cAAI,UAAU;AACd,cAAK,QAAQ,MAAiC,QAAQ;AAIpD,kBAAM,SAAS,QAAQ,MAAgC,OAAO;AAAA,cAC5D;AAAA,YACF;AAEA,gBAAI,OAAO;AACT,wBAAU,MAAM,CAAC;AAAA,YACnB;AAAA,UACF;AAEA,iBAAO;AAAA,YACL,eAAe;AAAA,YACf;AAAA,UACF;AAAA,QAEF,KAAK;AACH,iBAAO;AAAA,YACL,eAAe;AAAA,YACf,SAAU,OAAyC;AAAA,UACrD;AAAA,QAEF;AACE,gBAAM,IAAI,MAAM,wBAAwB;AAAA,MAC5C;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Options } from './lib/types.js';\nimport type { ParserOptions, ValidationResult } from '@readme/openapi-parser';\nimport type { OpenAPI, OpenAPIV2, OpenAPIV3 } from 'openapi-types';\n\nimport fs from 'node:fs';\n\nimport { bundle, compileErrors, dereference, validate } from '@readme/openapi-parser';\nimport postmanToOpenAPI from '@readme/postman-to-openapi';\nimport converter from 'swagger2openapi';\n\nimport { ValidationError } from './lib/errors.js';\nimport * as utils from './lib/utils.js';\n\nexport default class OASNormalize {\n cache: {\n bundle?: OpenAPI.Document | false;\n convert?: OpenAPI.Document | false;\n deref?: OpenAPI.Document | false;\n load?: Record<string, unknown> | false;\n };\n\n file: any;\n\n opts: Options;\n\n type: ReturnType<typeof utils.getType>;\n\n constructor(file: any, opts?: Options) {\n this.file = file;\n this.opts = {\n colorizeErrors: false,\n enablePaths: false,\n ...opts,\n };\n\n this.type = utils.getType(this.file);\n\n this.cache = {\n load: false,\n bundle: false,\n deref: false,\n };\n }\n\n /**\n * Load and return the API definition that `oas-normalize` was initialized with.\n *\n */\n async load(): Promise<Record<string, unknown>> {\n if (this.cache.load) return this.cache.load;\n\n const resolve = (obj: Parameters<typeof utils.stringToJSON>[0]) => {\n const ret = utils.stringToJSON(obj);\n this.cache.load = ret;\n return ret;\n };\n\n switch (this.type) {\n case 'json':\n case 'string-json':\n case 'string-yaml':\n return resolve(this.file);\n\n case 'buffer':\n return resolve(this.file.toString());\n\n case 'url':\n const { url, options } = utils.prepareURL(this.file);\n const resp = await fetch(url, options).then(res => res.text());\n return resolve(resp);\n\n case 'path':\n // Load a local file\n if (!this.opts.enablePaths) {\n throw new Error('Use `opts.enablePaths` to enable accessing local files.');\n }\n\n const contents = fs.readFileSync(this.file).toString();\n if (!contents.trim()) {\n throw new Error('No file contents found.');\n }\n return resolve(contents);\n\n default:\n throw new Error('Could not load this file.');\n }\n }\n\n private static async convertPostmanToOpenAPI(schema: any) {\n return postmanToOpenAPI(JSON.stringify(schema), undefined, { outputFormat: 'json', replaceVars: true }).then(\n JSON.parse,\n );\n }\n\n /**\n * Bundle up the given API definition, resolving any external `$ref` pointers in the process.\n *\n */\n async bundle(): Promise<OpenAPI.Document> {\n if (this.cache.bundle) return this.cache.bundle;\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to bundle we'll still\n // upconvert it to an OpenAPI definition file so our returned dataset is always one of\n // those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => bundle(schema))\n .then(bundled => {\n this.cache.bundle = bundled;\n return bundled;\n });\n }\n\n /**\n * Dereference the given API definition.\n *\n */\n async deref(): Promise<OpenAPI.Document> {\n if (this.cache.deref) return this.cache.deref;\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to dereference we'll\n // still upconvert it to an OpenAPI definition file so our returned dataset is always one\n // of those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => dereference(schema))\n .then(dereferenced => {\n this.cache.deref = dereferenced;\n return dereferenced;\n });\n }\n\n /**\n * Convert a given API definition to OpenAPI if it is not already.\n *\n */\n async convert(): Promise<OpenAPI.Document> {\n if (this.cache.convert) return this.cache.convert;\n\n return this.load()\n .then(async schema => {\n // If we have a Postman collection we need to convert it to OpenAPI.\n return utils.isPostman(schema) ? OASNormalize.convertPostmanToOpenAPI(schema) : schema;\n })\n .then(async schema => {\n if (!utils.isSwagger(schema) && !utils.isOpenAPI(schema)) {\n throw new Error('The supplied API definition is unsupported.');\n } else if (utils.isOpenAPI(schema)) {\n return schema;\n }\n\n const baseVersion = parseInt(schema.swagger, 10);\n if (baseVersion === 1) {\n throw new Error('Swagger v1.2 is unsupported.');\n }\n\n return converter\n .convertObj(schema, { anchors: true })\n .then((options: { openapi: OpenAPI.Document }) => options.openapi);\n });\n }\n\n /**\n * Validate a given API definition.\n *\n * If supplied a Postman collection it will be converted to OpenAPI first and then run through\n * standard OpenAPI validation.\n *\n */\n async validate(\n opts: {\n parser?: ParserOptions;\n } = {},\n ): Promise<ValidationResult> {\n const parserOptions = opts.parser || {};\n if (!parserOptions.validate) parserOptions.validate = {};\n if (!parserOptions.validate.errors) parserOptions.validate.errors = {};\n\n parserOptions.validate.errors.colorize = this.opts.colorizeErrors;\n\n return this.load()\n .then(async schema => {\n // Because we don't have something akin to `openapi-parser` for Postman collections we just\n // always convert them to OpenAPI.\n return utils.isPostman(schema) ? OASNormalize.convertPostmanToOpenAPI(schema) : schema;\n })\n .then(async schema => {\n if (!utils.isSwagger(schema) && !utils.isOpenAPI(schema)) {\n throw new ValidationError('The supplied API definition is unsupported.');\n } else if (utils.isSwagger(schema)) {\n const baseVersion = parseInt(schema.swagger, 10);\n if (baseVersion === 1) {\n throw new ValidationError('Swagger v1.2 is unsupported.');\n }\n }\n\n /**\n * `OpenAPIParser.validate()` dereferences schemas at the same time as validation, mutating\n * the supplied parameter in the process, and does not give us an option to disable this.\n * As we already have a dereferencing method on this library, and this method just needs to\n * tell us if the API definition is valid or not, we need to clone the schema before\n * supplying it to `openapi-parser`.\n */\n // eslint-disable-next-line try-catch-failsafe/json-parse\n const clonedSchema = JSON.parse(JSON.stringify(schema));\n\n const result = await validate(clonedSchema, parserOptions);\n if (!result.valid) {\n throw new ValidationError(compileErrors(result));\n }\n\n // The API definition, whatever its format or specification, is valid.\n return result;\n });\n }\n\n /**\n * Retrieve OpenAPI, Swagger, or Postman version information about the supplied API definition.\n *\n */\n async version(): Promise<{ specification: 'openapi' | 'postman' | 'swagger'; version: string | 'unknown' }> {\n return this.load().then(schema => {\n switch (utils.getAPIDefinitionType(schema)) {\n case 'openapi':\n return {\n specification: 'openapi',\n version: (schema as unknown as OpenAPIV3.Document).openapi,\n };\n\n case 'postman':\n let version = 'unknown';\n if ((schema?.info as Record<string, string>)?.schema) {\n // Though `info.schema` is required by the Postman spec there's no strictness to its\n // contents so we'll do our best to extract a version out of this schema URL that they\n // seem to usually match. If not we'll fallback to treating it as an `unknown` version.\n const match = (schema?.info as Record<string, string>).schema.match(\n /http(s?):\\/\\/schema.getpostman.com\\/json\\/collection\\/v([0-9.]+)\\//,\n );\n\n if (match) {\n version = match[2];\n }\n }\n\n return {\n specification: 'postman',\n version,\n };\n\n case 'swagger':\n return {\n specification: 'swagger',\n version: (schema as unknown as OpenAPIV2.Document).swagger,\n };\n\n default:\n throw new Error('Unknown file detected.');\n }\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAIA,OAAO,QAAQ;AAEf,SAAS,QAAQ,eAAe,aAAa,gBAAgB;AAC7D,OAAO,sBAAsB;AAC7B,OAAO,eAAe;AAKtB,IAAqB,eAArB,MAAqB,cAAa;AAAA,EAChC;AAAA,EAOA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA,YAAY,MAAW,MAAgB;AACrC,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,MACV,gBAAgB;AAAA,MAChB,aAAa;A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EF,KAAK;AACH,cAAI,UAAU;AACd,cAAK,QAAQ,MAAiC,QAAQ;AAIpD,kBAAM,SAAS,QAAQ,MAAgC,OAAO;AAAA,cAC5D;AAAA,YACF;AAEA,gBAAI,OAAO;AACT,wBAAU,MAAM,CAAC;AAAA,YACnB;AAAA,UACF;AAEA,iBAAO;AAAA,YACL,eAAe;AAAA,YACf;AAAA,UACF;AAAA,QAEF,KAAK;AACH,iBAAO;AAAA,YACL,eAAe;AAAA,YACf,SAAU,OAAyC;AAAA,UACrD;AAAA,QAEF;AACE,gBAAM,IAAI,MAAM,wBAAwB;AAAA,MAC5C;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
@@ -0,0 +1,7 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+ var _chunkSI6PKQOLcjs = require('../chunk-SI6PKQOL.cjs');
4
+
5
+
6
+ exports.ValidationError = _chunkSI6PKQOLcjs.ValidationError;
7
+ //# sourceMappingURL=errors.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas-normalize/dist/lib/errors.cjs"],"names":[],"mappings":"AAAA;AACE;AACF,yDAA8B;AAC9B;AACE;AACF,4DAAC","file":"/Users/erunion/code/readme/oas/packages/oas-normalize/dist/lib/errors.cjs"}
@@ -0,0 +1,5 @@
1
+ declare class ValidationError extends Error {
2
+ constructor(message: string);
3
+ }
4
+
5
+ export { ValidationError };
@@ -0,0 +1,5 @@
1
+ declare class ValidationError extends Error {
2
+ constructor(message: string);
3
+ }
4
+
5
+ export { ValidationError };
@@ -0,0 +1,7 @@
1
+ import {
2
+ ValidationError
3
+ } from "../chunk-KGEOPSPH.js";
4
+ export {
5
+ ValidationError
6
+ };
7
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -8,8 +8,8 @@
8
8
 
9
9
 
10
10
 
11
- var _chunkGZL345SRcjs = require('../chunk-GZL345SR.cjs');
12
11
 
12
+ var _chunkZTTIELJHcjs = require('../chunk-ZTTIELJH.cjs');
13
13
 
14
14
 
15
15
 
@@ -19,5 +19,7 @@ var _chunkGZL345SRcjs = require('../chunk-GZL345SR.cjs');
19
19
 
20
20
 
21
21
 
22
- exports.getAPIDefinitionType = _chunkGZL345SRcjs.getAPIDefinitionType; exports.getType = _chunkGZL345SRcjs.getType; exports.isAPIDefinition = _chunkGZL345SRcjs.isAPIDefinition; exports.isBuffer = _chunkGZL345SRcjs.isBuffer; exports.isOpenAPI = _chunkGZL345SRcjs.isOpenAPI; exports.isPostman = _chunkGZL345SRcjs.isPostman; exports.isSwagger = _chunkGZL345SRcjs.isSwagger; exports.prepareURL = _chunkGZL345SRcjs.prepareURL; exports.stringToJSON = _chunkGZL345SRcjs.stringToJSON;
22
+
23
+
24
+ exports.compileErrors = _chunkZTTIELJHcjs.compileErrors; exports.getAPIDefinitionType = _chunkZTTIELJHcjs.getAPIDefinitionType; exports.getType = _chunkZTTIELJHcjs.getType; exports.isAPIDefinition = _chunkZTTIELJHcjs.isAPIDefinition; exports.isBuffer = _chunkZTTIELJHcjs.isBuffer; exports.isOpenAPI = _chunkZTTIELJHcjs.isOpenAPI; exports.isPostman = _chunkZTTIELJHcjs.isPostman; exports.isSwagger = _chunkZTTIELJHcjs.isSwagger; exports.prepareURL = _chunkZTTIELJHcjs.prepareURL; exports.stringToJSON = _chunkZTTIELJHcjs.stringToJSON;
23
25
  //# sourceMappingURL=utils.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas-normalize/dist/lib/utils.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,4dAAC","file":"/Users/erunion/code/readme/oas/packages/oas-normalize/dist/lib/utils.cjs"}
1
+ {"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas-normalize/dist/lib/utils.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,qhBAAC","file":"/Users/erunion/code/readme/oas/packages/oas-normalize/dist/lib/utils.cjs"}
@@ -1,3 +1,5 @@
1
+ export { compileErrors } from '@readme/openapi-parser';
2
+
1
3
  /**
2
4
  * Determine if a given variable is a `Buffer`.
3
5
  *
@@ -8,14 +10,14 @@ declare function isBuffer(obj: any): boolean;
8
10
  *
9
11
  */
10
12
  declare function prepareURL(url: string): {
11
- url: string;
12
13
  options: RequestInit;
14
+ url: string;
13
15
  };
14
16
  /**
15
17
  * Determine the type of a given variable. Returns `false` if unrecognized.
16
18
  *
17
19
  */
18
- declare function getType(obj: any): false | "buffer" | "json" | "string-json" | "string-yaml" | "url" | "path";
20
+ declare function getType(obj: any): 'buffer' | 'json' | 'path' | 'string-json' | 'string-yaml' | 'url' | false;
19
21
  /**
20
22
  * Determine if a given schema if an OpenAPI definition.
21
23
  *
@@ -52,6 +54,6 @@ declare function isAPIDefinition(schema: Record<string, unknown>): boolean;
52
54
  * Retrieve the type of API definition that a given schema is.
53
55
  *
54
56
  */
55
- declare function getAPIDefinitionType(schema: Record<string, unknown>): "openapi" | "postman" | "swagger" | "unknown";
57
+ declare function getAPIDefinitionType(schema: Record<string, unknown>): 'openapi' | 'postman' | 'swagger' | 'unknown';
56
58
 
57
59
  export { getAPIDefinitionType, getType, isAPIDefinition, isBuffer, isOpenAPI, isPostman, isSwagger, prepareURL, stringToJSON };
@@ -1,3 +1,5 @@
1
+ export { compileErrors } from '@readme/openapi-parser';
2
+
1
3
  /**
2
4
  * Determine if a given variable is a `Buffer`.
3
5
  *
@@ -8,14 +10,14 @@ declare function isBuffer(obj: any): boolean;
8
10
  *
9
11
  */
10
12
  declare function prepareURL(url: string): {
11
- url: string;
12
13
  options: RequestInit;
14
+ url: string;
13
15
  };
14
16
  /**
15
17
  * Determine the type of a given variable. Returns `false` if unrecognized.
16
18
  *
17
19
  */
18
- declare function getType(obj: any): false | "buffer" | "json" | "string-json" | "string-yaml" | "url" | "path";
20
+ declare function getType(obj: any): 'buffer' | 'json' | 'path' | 'string-json' | 'string-yaml' | 'url' | false;
19
21
  /**
20
22
  * Determine if a given schema if an OpenAPI definition.
21
23
  *
@@ -52,6 +54,6 @@ declare function isAPIDefinition(schema: Record<string, unknown>): boolean;
52
54
  * Retrieve the type of API definition that a given schema is.
53
55
  *
54
56
  */
55
- declare function getAPIDefinitionType(schema: Record<string, unknown>): "openapi" | "postman" | "swagger" | "unknown";
57
+ declare function getAPIDefinitionType(schema: Record<string, unknown>): 'openapi' | 'postman' | 'swagger' | 'unknown';
56
58
 
57
59
  export { getAPIDefinitionType, getType, isAPIDefinition, isBuffer, isOpenAPI, isPostman, isSwagger, prepareURL, stringToJSON };
package/dist/lib/utils.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ compileErrors,
2
3
  getAPIDefinitionType,
3
4
  getType,
4
5
  isAPIDefinition,
@@ -8,8 +9,9 @@ import {
8
9
  isSwagger,
9
10
  prepareURL,
10
11
  stringToJSON
11
- } from "../chunk-J322YOXV.js";
12
+ } from "../chunk-EHNNEPCG.js";
12
13
  export {
14
+ compileErrors,
13
15
  getAPIDefinitionType,
14
16
  getType,
15
17
  isAPIDefinition,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oas-normalize",
3
- "version": "12.1.0",
3
+ "version": "13.0.1",
4
4
  "description": "Tooling for converting, validating, and parsing OpenAPI, Swagger, and Postman API definitions",
5
5
  "type": "module",
6
6
  "exports": {
@@ -8,6 +8,10 @@
8
8
  "require": "./dist/index.cjs",
9
9
  "import": "./dist/index.js"
10
10
  },
11
+ "./lib/errors": {
12
+ "require": "./dist/lib/errors.cjs",
13
+ "import": "./dist/lib/errors.js"
14
+ },
11
15
  "./lib/types": {
12
16
  "require": "./dist/lib/types.cjs",
13
17
  "import": "./dist/lib/types.js"
@@ -22,7 +26,7 @@
22
26
  "module": "dist/index.js",
23
27
  "types": "dist/index.d.cts",
24
28
  "engines": {
25
- "node": ">=18"
29
+ "node": ">=20"
26
30
  },
27
31
  "files": [
28
32
  "dist"
@@ -52,7 +56,7 @@
52
56
  "url": "https://github.com/readmeio/oas/issues"
53
57
  },
54
58
  "scripts": {
55
- "attw": "attw --pack --format table-flipped",
59
+ "attw": "attw --pack --format ascii --profile node16",
56
60
  "bench": "echo 'Please run benchmarks from the root!' && exit 1",
57
61
  "build": "tsup",
58
62
  "lint": "npm run lint:types && npm run lint:js",
@@ -64,22 +68,21 @@
64
68
  },
65
69
  "license": "MIT",
66
70
  "dependencies": {
67
- "@readme/openapi-parser": "^2.7.0",
71
+ "@readme/openapi-parser": "^3.0.1",
68
72
  "@readme/postman-to-openapi": "^4.1.0",
69
73
  "js-yaml": "^4.1.0",
70
74
  "openapi-types": "^12.1.3",
71
75
  "swagger2openapi": "^7.0.8"
72
76
  },
73
77
  "devDependencies": {
74
- "@readme/oas-examples": "^5.12.0",
78
+ "@readme/oas-examples": "^5.19.1",
75
79
  "@types/js-yaml": "^4.0.9",
76
80
  "@types/swagger2openapi": "^7.0.4",
77
81
  "eslint": "^8.57.0",
78
82
  "nock": "^14.0.0",
79
- "tsup": "^8.0.2",
80
83
  "typescript": "^5.1.6",
81
- "vitest": "^3.0.4"
84
+ "vitest": "^3.0.5"
82
85
  },
83
86
  "prettier": "@readme/eslint-config/prettier",
84
- "gitHead": "815ed445419978add2aaec344aa876f8914d9fb6"
87
+ "gitHead": "16b03c527ed95c026e5781bfb1840c7278361cb5"
85
88
  }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas-normalize/dist/chunk-GZL345SR.cjs","../src/lib/utils.ts"],"names":[],"mappings":"AAAA;ACAA,iFAAkC;AAM3B,SAAS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file":"/Users/erunion/code/readme/oas/packages/oas-normalize/dist/chunk-GZL345SR.cjs","sourcesContent":[null,"import YAML, { JSON_SCHEMA } from 'js-yaml';\n\n/**\n * Determine if a given variable is a `Buffer`.\n *\n */\nexport function isBuffer(obj: any) {\n return (\n obj != null &&\n obj.constructor != null &&\n typeof obj.constructor.isBuffer === 'function' &&\n !!obj.constructor.isBuffer(obj)\n );\n}\n\n/**\n * Deconstruct a URL into a payload for a `fetch` request.\n *\n */\nexport function prepareURL(url: string) {\n const options: RequestInit = {};\n const u = new URL(url);\n\n // `fetch` doesn't support supplying basic auth credentials in the URL so we need to move them\n // into a header.\n if (u.username || u.password) {\n options.headers = {\n Authorization: `Basic ${btoa(`${u.username}:${u.password}`)}`,\n };\n\n u.username = '';\n u.password = '';\n }\n\n // Transform GitHub sources into their raw content URLs.\n if (u.host === 'github.com' && u.pathname.includes('/blob/')) {\n u.host = 'raw.githubusercontent.com';\n u.pathname = u.pathname.replace('/blob/', '/');\n }\n\n return {\n url: u.toString(),\n options,\n };\n}\n\n/**\n * Determine the type of a given variable. Returns `false` if unrecognized.\n *\n */\nexport function getType(obj: any) {\n if (isBuffer(obj)) {\n return 'buffer';\n } else if (typeof obj === 'object') {\n return 'json';\n } else if (typeof obj === 'string') {\n if (obj.match(/\\s*{/)) {\n return 'string-json';\n } else if (obj.match(/\\n/)) {\n // Not sure about this...\n return 'string-yaml';\n } else if (obj.substring(0, 4) === 'http') {\n return 'url';\n }\n\n return 'path';\n }\n\n return false;\n}\n\n/**\n * Determine if a given schema if an OpenAPI definition.\n *\n */\nexport function isOpenAPI(schema: Record<string, unknown>) {\n return !!schema.openapi;\n}\n\n/**\n * Determine if a given schema is a Postman collection.\n *\n * Unfortunately the Postman schema spec doesn't have anything like `openapi` or `swagger` for us\n * to look at but it does require that `info` and `item` be present and as `item` doesn't exist in\n * OpenAPI or Swagger we can use the combination of those two properties to determine if what we\n * have is a Postman collection.\n *\n * @see {@link https://schema.postman.com/json/collection/v2.0.0/collection.json}\n * @see {@link https://schema.postman.com/json/collection/v2.1.0/collection.json}\n */\nexport function isPostman(schema: Record<string, unknown>): boolean {\n return !!schema.info && !!schema.item;\n}\n\n/**\n * Determine if a given schema if an Swagger definition.\n *\n */\nexport function isSwagger(schema: Record<string, unknown>) {\n return !!schema.swagger;\n}\n\n/**\n * Convert a YAML blob or stringified JSON object into a JSON object.\n *\n */\nexport function stringToJSON(string: Record<string, unknown> | string): Record<string, unknown> {\n if (typeof string === 'object') {\n return string;\n } else if (string.match(/^\\s*{/)) {\n // eslint-disable-next-line try-catch-failsafe/json-parse\n return JSON.parse(string);\n }\n\n return YAML.load(string, { schema: JSON_SCHEMA }) as Record<string, unknown>;\n}\n\n/**\n * Determine if a given schema is an API definition that we can support.\n *\n */\nexport function isAPIDefinition(schema: Record<string, unknown>) {\n return isOpenAPI(schema) || isPostman(schema) || isSwagger(schema);\n}\n\n/**\n * Retrieve the type of API definition that a given schema is.\n *\n */\nexport function getAPIDefinitionType(schema: Record<string, unknown>) {\n if (isOpenAPI(schema)) {\n return 'openapi';\n } else if (isPostman(schema)) {\n return 'postman';\n } else if (isSwagger(schema)) {\n return 'swagger';\n }\n\n return 'unknown';\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/utils.ts"],"sourcesContent":["import YAML, { JSON_SCHEMA } from 'js-yaml';\n\n/**\n * Determine if a given variable is a `Buffer`.\n *\n */\nexport function isBuffer(obj: any) {\n return (\n obj != null &&\n obj.constructor != null &&\n typeof obj.constructor.isBuffer === 'function' &&\n !!obj.constructor.isBuffer(obj)\n );\n}\n\n/**\n * Deconstruct a URL into a payload for a `fetch` request.\n *\n */\nexport function prepareURL(url: string) {\n const options: RequestInit = {};\n const u = new URL(url);\n\n // `fetch` doesn't support supplying basic auth credentials in the URL so we need to move them\n // into a header.\n if (u.username || u.password) {\n options.headers = {\n Authorization: `Basic ${btoa(`${u.username}:${u.password}`)}`,\n };\n\n u.username = '';\n u.password = '';\n }\n\n // Transform GitHub sources into their raw content URLs.\n if (u.host === 'github.com' && u.pathname.includes('/blob/')) {\n u.host = 'raw.githubusercontent.com';\n u.pathname = u.pathname.replace('/blob/', '/');\n }\n\n return {\n url: u.toString(),\n options,\n };\n}\n\n/**\n * Determine the type of a given variable. Returns `false` if unrecognized.\n *\n */\nexport function getType(obj: any) {\n if (isBuffer(obj)) {\n return 'buffer';\n } else if (typeof obj === 'object') {\n return 'json';\n } else if (typeof obj === 'string') {\n if (obj.match(/\\s*{/)) {\n return 'string-json';\n } else if (obj.match(/\\n/)) {\n // Not sure about this...\n return 'string-yaml';\n } else if (obj.substring(0, 4) === 'http') {\n return 'url';\n }\n\n return 'path';\n }\n\n return false;\n}\n\n/**\n * Determine if a given schema if an OpenAPI definition.\n *\n */\nexport function isOpenAPI(schema: Record<string, unknown>) {\n return !!schema.openapi;\n}\n\n/**\n * Determine if a given schema is a Postman collection.\n *\n * Unfortunately the Postman schema spec doesn't have anything like `openapi` or `swagger` for us\n * to look at but it does require that `info` and `item` be present and as `item` doesn't exist in\n * OpenAPI or Swagger we can use the combination of those two properties to determine if what we\n * have is a Postman collection.\n *\n * @see {@link https://schema.postman.com/json/collection/v2.0.0/collection.json}\n * @see {@link https://schema.postman.com/json/collection/v2.1.0/collection.json}\n */\nexport function isPostman(schema: Record<string, unknown>): boolean {\n return !!schema.info && !!schema.item;\n}\n\n/**\n * Determine if a given schema if an Swagger definition.\n *\n */\nexport function isSwagger(schema: Record<string, unknown>) {\n return !!schema.swagger;\n}\n\n/**\n * Convert a YAML blob or stringified JSON object into a JSON object.\n *\n */\nexport function stringToJSON(string: Record<string, unknown> | string): Record<string, unknown> {\n if (typeof string === 'object') {\n return string;\n } else if (string.match(/^\\s*{/)) {\n // eslint-disable-next-line try-catch-failsafe/json-parse\n return JSON.parse(string);\n }\n\n return YAML.load(string, { schema: JSON_SCHEMA }) as Record<string, unknown>;\n}\n\n/**\n * Determine if a given schema is an API definition that we can support.\n *\n */\nexport function isAPIDefinition(schema: Record<string, unknown>) {\n return isOpenAPI(schema) || isPostman(schema) || isSwagger(schema);\n}\n\n/**\n * Retrieve the type of API definition that a given schema is.\n *\n */\nexport function getAPIDefinitionType(schema: Record<string, unknown>) {\n if (isOpenAPI(schema)) {\n return 'openapi';\n } else if (isPostman(schema)) {\n return 'postman';\n } else if (isSwagger(schema)) {\n return 'swagger';\n }\n\n return 'unknown';\n}\n"],"mappings":";AAAA,OAAO,QAAQ,mBAAmB;AAM3B,SAAS,SAAS,KAAU;AACjC,SACE,OAAO,QACP,IAAI,eAAe,QACnB,OAAO,IAAI,YAAY,aAAa,cACpC,CAAC,CAAC,IAAI,YAAY,SAAS,GAAG;AAElC;AAMO,SAAS,WAAW,KAAa;AACtC,QAAM,UAAuB,CAAC;AAC9B,QAAM,IAAI,IAAI,IAAI,GAAG;AAIrB,MAAI,EAAE,YAAY,EAAE,UAAU;AAC5B,YAAQ,UAAU;AAAA,MAChB,eAAe,SAAS,KAAK,GAAG,EAAE,QAAQ,IAAI,EAAE,QAAQ,EAAE,CAAC;AAAA,IAC7D;AAEA,MAAE,WAAW;AACb,MAAE,WAAW;AAAA,EACf;AAGA,MAAI,EAAE,SAAS,gBAAgB,EAAE,SAAS,SAAS,QAAQ,GAAG;AAC5D,MAAE,OAAO;AACT,MAAE,WAAW,EAAE,SAAS,QAAQ,UAAU,GAAG;AAAA,EAC/C;AAEA,SAAO;AAAA,IACL,KAAK,EAAE,SAAS;AAAA,IAChB;AAAA,EACF;AACF;AAMO,SAAS,QAAQ,KAAU;AAChC,MAAI,SAAS,GAAG,GAAG;AACjB,WAAO;AAAA,EACT,WAAW,OAAO,QAAQ,UAAU;AAClC,WAAO;AAAA,EACT,WAAW,OAAO,QAAQ,UAAU;AAClC,QAAI,IAAI,MAAM,MAAM,GAAG;AACrB,aAAO;AAAA,IACT,WAAW,IAAI,MAAM,IAAI,GAAG;AAE1B,aAAO;AAAA,IACT,WAAW,IAAI,UAAU,GAAG,CAAC,MAAM,QAAQ;AACzC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