api 6.1.1 → 7.0.0-alpha.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.
Files changed (69) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +0 -12
  3. package/dist/bin.js +3 -3
  4. package/dist/{cli/codegen → codegen}/index.js +4 -4
  5. package/dist/{cli/codegen → codegen}/language.js +4 -3
  6. package/dist/codegen/languages/typescript/util.d.ts +10 -0
  7. package/dist/{cli/codegen → codegen}/languages/typescript/util.js +5 -6
  8. package/dist/{cli/codegen → codegen}/languages/typescript.d.ts +12 -12
  9. package/dist/{cli/codegen → codegen}/languages/typescript.js +75 -75
  10. package/dist/{cli/commands → commands}/index.js +3 -3
  11. package/dist/{cli/commands → commands}/install.js +37 -34
  12. package/dist/fetcher.d.ts +8 -9
  13. package/dist/fetcher.js +15 -15
  14. package/dist/{cli/lib → lib}/prompt.js +3 -3
  15. package/dist/{cli/logger.js → logger.js} +3 -3
  16. package/dist/packageInfo.d.ts +1 -1
  17. package/dist/packageInfo.js +2 -2
  18. package/dist/{cli/storage.d.ts → storage.d.ts} +5 -4
  19. package/dist/{cli/storage.js → storage.js} +39 -36
  20. package/package.json +14 -32
  21. package/src/bin.ts +1 -1
  22. package/src/{cli/codegen → codegen}/language.ts +3 -2
  23. package/src/{cli/codegen → codegen}/languages/typescript/util.ts +1 -1
  24. package/src/{cli/codegen → codegen}/languages/typescript.ts +31 -32
  25. package/src/{cli/commands → commands}/install.ts +1 -1
  26. package/src/fetcher.ts +4 -5
  27. package/src/packageInfo.ts +1 -1
  28. package/src/{cli/storage.ts → storage.ts} +13 -9
  29. package/tsconfig.json +3 -13
  30. package/dist/cache.d.ts +0 -68
  31. package/dist/cache.js +0 -198
  32. package/dist/cli/codegen/languages/typescript/util.d.ts +0 -20
  33. package/dist/core/errors/fetchError.d.ts +0 -12
  34. package/dist/core/errors/fetchError.js +0 -36
  35. package/dist/core/getJSONSchemaDefaults.d.ts +0 -14
  36. package/dist/core/getJSONSchemaDefaults.js +0 -61
  37. package/dist/core/index.d.ts +0 -40
  38. package/dist/core/index.js +0 -168
  39. package/dist/core/parseResponse.d.ts +0 -6
  40. package/dist/core/parseResponse.js +0 -71
  41. package/dist/core/prepareAuth.d.ts +0 -5
  42. package/dist/core/prepareAuth.js +0 -84
  43. package/dist/core/prepareParams.d.ts +0 -21
  44. package/dist/core/prepareParams.js +0 -425
  45. package/dist/core/prepareServer.d.ts +0 -10
  46. package/dist/core/prepareServer.js +0 -47
  47. package/dist/index.d.ts +0 -6
  48. package/dist/index.js +0 -259
  49. package/src/.sink.d.ts +0 -1
  50. package/src/cache.ts +0 -193
  51. package/src/core/errors/fetchError.ts +0 -31
  52. package/src/core/getJSONSchemaDefaults.ts +0 -74
  53. package/src/core/index.ts +0 -148
  54. package/src/core/parseResponse.ts +0 -26
  55. package/src/core/prepareAuth.ts +0 -109
  56. package/src/core/prepareParams.ts +0 -415
  57. package/src/core/prepareServer.ts +0 -48
  58. package/src/index.ts +0 -203
  59. package/src/typings.d.ts +0 -2
  60. /package/dist/{cli/codegen → codegen}/index.d.ts +0 -0
  61. /package/dist/{cli/codegen → codegen}/language.d.ts +0 -0
  62. /package/dist/{cli/commands → commands}/index.d.ts +0 -0
  63. /package/dist/{cli/commands → commands}/install.d.ts +0 -0
  64. /package/dist/{cli/lib → lib}/prompt.d.ts +0 -0
  65. /package/dist/{cli/logger.d.ts → logger.d.ts} +0 -0
  66. /package/src/{cli/codegen → codegen}/index.ts +0 -0
  67. /package/src/{cli/commands → commands}/index.ts +0 -0
  68. /package/src/{cli/lib → lib}/prompt.ts +0 -0
  69. /package/src/{cli/logger.ts → logger.ts} +0 -0
package/dist/index.js DELETED
@@ -1,259 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
39
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
40
- if (ar || !(i in from)) {
41
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
42
- ar[i] = from[i];
43
- }
44
- }
45
- return to.concat(ar || Array.prototype.slice.call(from));
46
- };
47
- var __importDefault = (this && this.__importDefault) || function (mod) {
48
- return (mod && mod.__esModule) ? mod : { "default": mod };
49
- };
50
- var oas_1 = __importDefault(require("oas"));
51
- var cache_1 = __importDefault(require("./cache"));
52
- var core_1 = __importDefault(require("./core"));
53
- var packageInfo_1 = require("./packageInfo");
54
- var Sdk = /** @class */ (function () {
55
- function Sdk(uri, opts) {
56
- if (opts === void 0) { opts = {}; }
57
- this.uri = uri;
58
- this.userAgent = "".concat(packageInfo_1.PACKAGE_NAME, " (node)/").concat(packageInfo_1.PACKAGE_VERSION);
59
- this.cacheDir = opts.cacheDir ? opts.cacheDir : false;
60
- }
61
- Sdk.prototype.load = function () {
62
- var cache = new cache_1["default"](this.uri, this.cacheDir);
63
- var userAgent = this.userAgent;
64
- var core = new core_1["default"]();
65
- core.setUserAgent(userAgent);
66
- var isLoaded = false;
67
- var isCached = cache.isCached();
68
- var sdk = {};
69
- /**
70
- * Create dynamic accessors for every operation with a defined operation ID. If an operation
71
- * does not have an operation ID it can be accessed by its `.method('/path')` accessor instead.
72
- *
73
- */
74
- function loadOperations(spec) {
75
- return Object.entries(spec.getPaths())
76
- .map(function (_a) {
77
- var operations = _a[1];
78
- return Object.values(operations);
79
- })
80
- .reduce(function (prev, next) { return prev.concat(next); }, [])
81
- .reduce(function (prev, next) {
82
- var _a;
83
- // `getOperationId()` creates dynamic operation IDs when one isn't available but we need
84
- // to know here if we actually have one present or not. The `camelCase` option here also
85
- // cleans up any `operationId` that we might have into something that can be used as a
86
- // valid JS method.
87
- var originalOperationId = next.getOperationId();
88
- var operationId = next.getOperationId({ camelCase: true });
89
- var op = (_a = {},
90
- _a[operationId] = (function (operation) {
91
- var args = [];
92
- for (var _i = 1; _i < arguments.length; _i++) {
93
- args[_i - 1] = arguments[_i];
94
- }
95
- return core.fetchOperation.apply(core, __spreadArray([operation], args, false));
96
- }).bind(null, next),
97
- _a);
98
- if (operationId !== originalOperationId) {
99
- // If we cleaned up their operation ID into a friendly method accessor (`findPetById`
100
- // versus `find pet by id`) we should still let them use the non-friendly version if
101
- // they want.
102
- //
103
- // This work is to maintain backwards compatibility with `api@4` and does not exist
104
- // within our code generated SDKs -- those only allow the cleaner camelCase
105
- // `operationId` to be used.
106
- op[originalOperationId] = (function (operation) {
107
- var args = [];
108
- for (var _i = 1; _i < arguments.length; _i++) {
109
- args[_i - 1] = arguments[_i];
110
- }
111
- return core.fetchOperation.apply(core, __spreadArray([operation], args, false));
112
- }).bind(null, next);
113
- }
114
- return Object.assign(prev, op);
115
- }, {});
116
- }
117
- function loadFromCache() {
118
- return __awaiter(this, void 0, void 0, function () {
119
- var cachedSpec, spec;
120
- return __generator(this, function (_a) {
121
- switch (_a.label) {
122
- case 0:
123
- if (!isCached) return [3 /*break*/, 2];
124
- return [4 /*yield*/, cache.get()];
125
- case 1:
126
- cachedSpec = _a.sent();
127
- return [3 /*break*/, 4];
128
- case 2: return [4 /*yield*/, cache.load()];
129
- case 3:
130
- cachedSpec = _a.sent();
131
- isCached = true;
132
- _a.label = 4;
133
- case 4:
134
- spec = new oas_1["default"](cachedSpec);
135
- core.setSpec(spec);
136
- sdk = Object.assign(sdk, loadOperations(spec));
137
- isLoaded = true;
138
- return [2 /*return*/];
139
- }
140
- });
141
- });
142
- }
143
- var sdkProxy = {
144
- // @give this a better type than any
145
- get: function (target, method) {
146
- // Since auth returns a self-proxy, we **do not** want it to fall through into the async
147
- // function below as when that'll happen, instead of returning a self-proxy, it'll end up
148
- // returning a Promise. When that happens, chaining `sdk.auth().operationId()` will fail.
149
- if (['auth', 'config'].includes(method)) {
150
- // @todo split this up so we have better types for `auth` and `config`
151
- return function authAndConfigHandler() {
152
- var args = [];
153
- for (var _i = 0; _i < arguments.length; _i++) {
154
- args[_i] = arguments[_i];
155
- }
156
- return target[method].apply(this, args);
157
- };
158
- }
159
- return function accessorHandler() {
160
- var args = [];
161
- for (var _i = 0; _i < arguments.length; _i++) {
162
- args[_i] = arguments[_i];
163
- }
164
- return __awaiter(this, void 0, void 0, function () {
165
- return __generator(this, function (_a) {
166
- switch (_a.label) {
167
- case 0:
168
- if (!!(method in target)) return [3 /*break*/, 2];
169
- // If this method doesn't exist on the proxy, have we loaded the SDK? If we have, then
170
- // this method isn't valid.
171
- if (isLoaded) {
172
- throw new Error("Sorry, `".concat(method, "` does not appear to be a valid operation on this API."));
173
- }
174
- return [4 /*yield*/, loadFromCache()];
175
- case 1:
176
- _a.sent();
177
- // If after loading the SDK and this method still doesn't exist, then it's not real!
178
- if (!(method in sdk)) {
179
- throw new Error("Sorry, `".concat(method, "` does not appear to be a valid operation on this API."));
180
- }
181
- // @todo give sdk a better type
182
- return [2 /*return*/, sdk[method].apply(this, args)];
183
- case 2: return [2 /*return*/, target[method].apply(this, args)];
184
- }
185
- });
186
- });
187
- };
188
- }
189
- };
190
- sdk = {
191
- /**
192
- * If the API you're using requires authentication you can supply the required credentials
193
- * through this method and the library will magically determine how they should be used
194
- * within your API request.
195
- *
196
- * With the exception of OpenID and MutualTLS, it supports all forms of authentication
197
- * supported by the OpenAPI specification.
198
- *
199
- * @example <caption>HTTP Basic auth</caption>
200
- * sdk.auth('username', 'password');
201
- *
202
- * @example <caption>Bearer tokens (HTTP or OAuth 2)</caption>
203
- * sdk.auth('myBearerToken');
204
- *
205
- * @example <caption>API Keys</caption>
206
- * sdk.auth('myApiKey');
207
- *
208
- * @see {@link https://spec.openapis.org/oas/v3.0.3#fixed-fields-22}
209
- * @see {@link https://spec.openapis.org/oas/v3.1.0#fixed-fields-22}
210
- * @param values Your auth credentials for the API. Can specify up to two strings or numbers.
211
- */
212
- auth: function () {
213
- var values = [];
214
- for (var _i = 0; _i < arguments.length; _i++) {
215
- values[_i] = arguments[_i];
216
- }
217
- core.setAuth.apply(core, values);
218
- },
219
- /**
220
- * Optionally configure various options that the SDK allows.
221
- *
222
- * @param config Object of supported SDK options and toggles.
223
- * @param config.timeout Override the default `fetch` request timeout of 30 seconds (30000ms).
224
- */
225
- config: function (config) {
226
- core.setConfig(config);
227
- },
228
- /**
229
- * If the API you're using offers alternate server URLs, and server variables, you can tell
230
- * the SDK which one to use with this method. To use it you can supply either one of the
231
- * server URLs that are contained within the OpenAPI definition (along with any server
232
- * variables), or you can pass it a fully qualified URL to use (that may or may not exist
233
- * within the OpenAPI definition).
234
- *
235
- * @example <caption>Server URL with server variables</caption>
236
- * sdk.server('https://{region}.api.example.com/{basePath}', {
237
- * name: 'eu',
238
- * basePath: 'v14',
239
- * });
240
- *
241
- * @example <caption>Fully qualified server URL</caption>
242
- * sdk.server('https://eu.api.example.com/v14');
243
- *
244
- * @param url Server URL
245
- * @param variables An object of variables to replace into the server URL.
246
- */
247
- server: function (url, variables) {
248
- if (variables === void 0) { variables = {}; }
249
- core.setServer(url, variables);
250
- }
251
- };
252
- return new Proxy(sdk, sdkProxy);
253
- };
254
- return Sdk;
255
- }());
256
- module.exports = function (uri, opts) {
257
- if (opts === void 0) { opts = {}; }
258
- return new Sdk(uri, opts).load();
259
- };
package/src/.sink.d.ts DELETED
@@ -1 +0,0 @@
1
- declare module 'form-data-encoder';
package/src/cache.ts DELETED
@@ -1,193 +0,0 @@
1
- import type { OASDocument } from 'oas/dist/rmoas.types';
2
-
3
- import crypto from 'crypto';
4
- import fs from 'fs';
5
- import os from 'os';
6
- import path from 'path';
7
-
8
- import findCacheDir from 'find-cache-dir';
9
- import 'isomorphic-fetch';
10
- import makeDir from 'make-dir';
11
-
12
- import Fetcher from './fetcher';
13
- import { PACKAGE_NAME } from './packageInfo';
14
-
15
- type CacheStore = Record<
16
- string,
17
- {
18
- hash: string;
19
- original: string | OASDocument;
20
- /**
21
- * @deprecated Deprecated in v4.5.0 in favor of `hash`.
22
- */
23
- path?: string;
24
- title?: string;
25
- version?: string;
26
- }
27
- >;
28
-
29
- export default class Cache {
30
- static dir: string;
31
-
32
- static cacheStore: string;
33
-
34
- static specsCache: string;
35
-
36
- uri: string | OASDocument;
37
-
38
- uriHash: string;
39
-
40
- cached: false | CacheStore;
41
-
42
- fetcher: Fetcher;
43
-
44
- constructor(uri: string | OASDocument, cacheDir: string | false = false) {
45
- Cache.setCacheDir(cacheDir);
46
- Cache.cacheStore = path.join(Cache.dir, 'cache.json');
47
- Cache.specsCache = path.join(Cache.dir, 'specs');
48
-
49
- this.fetcher = new Fetcher(uri);
50
-
51
- this.uri = this.fetcher.uri;
52
- this.uriHash = Cache.getCacheHash(this.uri);
53
-
54
- // This should default to false so we have awareness if we've looked at the cache yet.
55
- this.cached = false;
56
- }
57
-
58
- static getCacheHash(file: string | OASDocument) {
59
- let data: string;
60
- if (typeof file === 'object') {
61
- // Under certain unit testing circumstances, we might be supplying the class with a raw JSON
62
- // object so we'll need to convert it to a string in order to hand it off to the crypto
63
- // module.
64
- data = JSON.stringify(file);
65
- } else {
66
- data = file;
67
- }
68
-
69
- return crypto.createHash('md5').update(data).digest('hex');
70
- }
71
-
72
- static setCacheDir(dir?: string | false) {
73
- if (dir) {
74
- Cache.dir = dir;
75
- return;
76
- } else if (Cache.dir) {
77
- // If we already have a cache dir set and aren't explicitly it to something new then we
78
- // shouldn't overwrite what we've already got.
79
- return;
80
- }
81
-
82
- Cache.dir = findCacheDir({ name: PACKAGE_NAME });
83
- if (typeof Cache.dir === 'undefined') {
84
- // The `find-cache-dir` module returns `undefined` if the `node_modules/` directory isn't
85
- // writable, or there's no `package.json` in the root-most directory. If this happens, we can
86
- // instead adhoc create a cache directory in the users OS temp directory and store our data
87
- // there.
88
- //
89
- // @link https://github.com/avajs/find-cache-dir/issues/29
90
- Cache.dir = makeDir.sync(path.join(os.tmpdir(), PACKAGE_NAME));
91
- }
92
- }
93
-
94
- static async reset() {
95
- if (Cache.cacheStore) {
96
- await fs.promises.rm(Cache.cacheStore).catch(() => {
97
- // no-op
98
- });
99
- }
100
-
101
- if (Cache.specsCache) {
102
- await fs.promises.rm(Cache.specsCache, { recursive: true }).catch(() => {
103
- // no-op
104
- });
105
- }
106
- }
107
-
108
- isCached() {
109
- const cache = this.getCache();
110
- return cache && this.uriHash in cache;
111
- }
112
-
113
- getCache() {
114
- if (typeof this.cached === 'object') {
115
- return this.cached;
116
- }
117
-
118
- this.cached = {};
119
-
120
- if (fs.existsSync(Cache.cacheStore)) {
121
- this.cached = JSON.parse(fs.readFileSync(Cache.cacheStore, 'utf8')) as CacheStore;
122
- }
123
-
124
- return this.cached;
125
- }
126
-
127
- get() {
128
- // If the class was supplied a raw object, just go ahead and bypass the caching system and
129
- // return that.
130
- if (typeof this.uri === 'object') {
131
- return this.uri;
132
- }
133
-
134
- if (!this.isCached()) {
135
- throw new Error(`${this.uri} has not been cached yet and must do so before being retrieved.`);
136
- }
137
-
138
- const cache = this.getCache();
139
-
140
- // Prior to v4.5.0 we were putting a fully resolved path to the API definition in the cache
141
- // store but if you had specified a custom caching directory and would generate the cache on
142
- // your system, that filepath would obviously not be the same in other environments. For this
143
- // reason the `path` was removed from the cache store in favor of storing the `hash` instead.
144
- //
145
- // If we still have `path` in the config cache for backwards compatibility we should use it.
146
- if ('path' in cache[this.uriHash]) {
147
- return JSON.parse(fs.readFileSync(cache[this.uriHash].path, 'utf8'));
148
- }
149
-
150
- return JSON.parse(fs.readFileSync(path.join(Cache.specsCache, `${cache[this.uriHash].hash}.json`), 'utf8'));
151
- }
152
-
153
- async load() {
154
- // If the class was supplied a raw object we should still validate and make sure that it's
155
- // dereferenced in order for everything to function, but we shouldn't worry about saving it
156
- // into the cache directory architecture.
157
- if (typeof this.uri === 'object') {
158
- return Fetcher.validate(this.uri);
159
- }
160
-
161
- return this.fetcher.load().then(async spec => this.save(spec));
162
- }
163
-
164
- save(spec: OASDocument) {
165
- if (!fs.existsSync(Cache.dir)) {
166
- fs.mkdirSync(Cache.dir, { recursive: true });
167
- }
168
-
169
- if (!fs.existsSync(Cache.specsCache)) {
170
- fs.mkdirSync(Cache.specsCache, { recursive: true });
171
- }
172
-
173
- const cache = this.getCache();
174
- if (!(this.uriHash in cache)) {
175
- const saved = JSON.stringify(spec, null, 2);
176
- const fileHash = crypto.createHash('md5').update(saved).digest('hex');
177
-
178
- cache[this.uriHash] = {
179
- hash: fileHash,
180
- original: this.uri,
181
- title: 'title' in spec.info ? spec.info.title : undefined,
182
- version: 'version' in spec.info ? spec.info.version : undefined,
183
- };
184
-
185
- fs.writeFileSync(path.join(Cache.specsCache, `${fileHash}.json`), saved);
186
- fs.writeFileSync(Cache.cacheStore, JSON.stringify(cache, null, 2));
187
-
188
- this.cached = cache;
189
- }
190
-
191
- return spec;
192
- }
193
- }
@@ -1,31 +0,0 @@
1
- class FetchError<Status = number, Data = unknown> extends Error {
2
- /** HTTP Status */
3
- status: Status;
4
-
5
- /** The content of the response. */
6
- data: Data;
7
-
8
- /** The Headers of the response. */
9
- headers: Headers;
10
-
11
- /** The raw `Response` object. */
12
- res: Response;
13
-
14
- constructor(status: Status, data: Data, headers: Headers, res: Response) {
15
- super(res.statusText);
16
-
17
- this.name = 'FetchError';
18
- this.status = status;
19
- this.data = data;
20
- this.headers = headers;
21
- this.res = res;
22
-
23
- // We could fix this by updating our target to ES2015 but because we support exporting to CJS
24
- // we can't.
25
- //
26
- // https://www.dannyguo.com/blog/how-to-fix-instanceof-not-working-for-custom-errors-in-typescript/
27
- Object.setPrototypeOf(this, FetchError.prototype);
28
- }
29
- }
30
-
31
- export default FetchError;
@@ -1,74 +0,0 @@
1
- import type { SchemaWrapper } from 'oas/dist/operation/get-parameters-as-json-schema';
2
- import type { SchemaObject } from 'oas/dist/rmoas.types';
3
-
4
- import traverse from 'json-schema-traverse';
5
-
6
- /**
7
- * Run through a JSON Schema object and compose up an object containing default data for any schema
8
- * property that is required and also has a defined default.
9
- *
10
- * Code partially adapted from the `json-schema-default` package but modified to only return
11
- * defaults of required properties.
12
- *
13
- * @todo This is a good candidate to be moved into a core `oas` library method.
14
- * @see {@link https://github.com/mdornseif/json-schema-default}
15
- */
16
- export default function getJSONSchemaDefaults(jsonSchemas: SchemaWrapper[]) {
17
- return jsonSchemas
18
- .map(({ type: payloadType, schema: jsonSchema }) => {
19
- const defaults: Record<string, unknown> = {};
20
- traverse(
21
- jsonSchema,
22
- (
23
- schema: SchemaObject,
24
- pointer: string,
25
- rootSchema: SchemaObject,
26
- parentPointer: string,
27
- parentKeyword: string,
28
- parentSchema: SchemaObject,
29
- indexProperty: string,
30
- ) => {
31
- if (!pointer.startsWith('/properties/')) {
32
- return;
33
- }
34
-
35
- if (Array.isArray(parentSchema?.required) && parentSchema.required.includes(indexProperty)) {
36
- if (schema.type === 'object' && indexProperty) {
37
- defaults[indexProperty] = {};
38
- }
39
-
40
- let destination = defaults;
41
- if (parentPointer) {
42
- // To map nested objects correct we need to pick apart the parent pointer.
43
- parentPointer
44
- .replace(/\/properties/g, '')
45
- .split('/')
46
- .forEach((subSchema: string) => {
47
- if (subSchema === '') {
48
- return;
49
- }
50
-
51
- destination = (destination?.[subSchema] as Record<string, unknown>) || {};
52
- });
53
- }
54
-
55
- if (schema.default !== undefined) {
56
- if (indexProperty !== undefined) {
57
- destination[indexProperty] = schema.default;
58
- }
59
- }
60
- }
61
- },
62
- );
63
-
64
- if (!Object.keys(defaults).length) {
65
- return {};
66
- }
67
-
68
- return {
69
- // @todo should we filter out empty and undefined objects from here with `remove-undefined-objects`?
70
- [payloadType]: defaults,
71
- };
72
- })
73
- .reduce((prev, next) => Object.assign(prev, next));
74
- }