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/cache.js DELETED
@@ -1,198 +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 __importDefault = (this && this.__importDefault) || function (mod) {
39
- return (mod && mod.__esModule) ? mod : { "default": mod };
40
- };
41
- exports.__esModule = true;
42
- var crypto_1 = __importDefault(require("crypto"));
43
- var fs_1 = __importDefault(require("fs"));
44
- var os_1 = __importDefault(require("os"));
45
- var path_1 = __importDefault(require("path"));
46
- var find_cache_dir_1 = __importDefault(require("find-cache-dir"));
47
- require("isomorphic-fetch");
48
- var make_dir_1 = __importDefault(require("make-dir"));
49
- var fetcher_1 = __importDefault(require("./fetcher"));
50
- var packageInfo_1 = require("./packageInfo");
51
- var Cache = /** @class */ (function () {
52
- function Cache(uri, cacheDir) {
53
- if (cacheDir === void 0) { cacheDir = false; }
54
- Cache.setCacheDir(cacheDir);
55
- Cache.cacheStore = path_1["default"].join(Cache.dir, 'cache.json');
56
- Cache.specsCache = path_1["default"].join(Cache.dir, 'specs');
57
- this.fetcher = new fetcher_1["default"](uri);
58
- this.uri = this.fetcher.uri;
59
- this.uriHash = Cache.getCacheHash(this.uri);
60
- // This should default to false so we have awareness if we've looked at the cache yet.
61
- this.cached = false;
62
- }
63
- Cache.getCacheHash = function (file) {
64
- var data;
65
- if (typeof file === 'object') {
66
- // Under certain unit testing circumstances, we might be supplying the class with a raw JSON
67
- // object so we'll need to convert it to a string in order to hand it off to the crypto
68
- // module.
69
- data = JSON.stringify(file);
70
- }
71
- else {
72
- data = file;
73
- }
74
- return crypto_1["default"].createHash('md5').update(data).digest('hex');
75
- };
76
- Cache.setCacheDir = function (dir) {
77
- if (dir) {
78
- Cache.dir = dir;
79
- return;
80
- }
81
- else if (Cache.dir) {
82
- // If we already have a cache dir set and aren't explicitly it to something new then we
83
- // shouldn't overwrite what we've already got.
84
- return;
85
- }
86
- Cache.dir = (0, find_cache_dir_1["default"])({ name: packageInfo_1.PACKAGE_NAME });
87
- if (typeof Cache.dir === 'undefined') {
88
- // The `find-cache-dir` module returns `undefined` if the `node_modules/` directory isn't
89
- // writable, or there's no `package.json` in the root-most directory. If this happens, we can
90
- // instead adhoc create a cache directory in the users OS temp directory and store our data
91
- // there.
92
- //
93
- // @link https://github.com/avajs/find-cache-dir/issues/29
94
- Cache.dir = make_dir_1["default"].sync(path_1["default"].join(os_1["default"].tmpdir(), packageInfo_1.PACKAGE_NAME));
95
- }
96
- };
97
- Cache.reset = function () {
98
- return __awaiter(this, void 0, void 0, function () {
99
- return __generator(this, function (_a) {
100
- switch (_a.label) {
101
- case 0:
102
- if (!Cache.cacheStore) return [3 /*break*/, 2];
103
- return [4 /*yield*/, fs_1["default"].promises.rm(Cache.cacheStore)["catch"](function () {
104
- // no-op
105
- })];
106
- case 1:
107
- _a.sent();
108
- _a.label = 2;
109
- case 2:
110
- if (!Cache.specsCache) return [3 /*break*/, 4];
111
- return [4 /*yield*/, fs_1["default"].promises.rm(Cache.specsCache, { recursive: true })["catch"](function () {
112
- // no-op
113
- })];
114
- case 3:
115
- _a.sent();
116
- _a.label = 4;
117
- case 4: return [2 /*return*/];
118
- }
119
- });
120
- });
121
- };
122
- Cache.prototype.isCached = function () {
123
- var cache = this.getCache();
124
- return cache && this.uriHash in cache;
125
- };
126
- Cache.prototype.getCache = function () {
127
- if (typeof this.cached === 'object') {
128
- return this.cached;
129
- }
130
- this.cached = {};
131
- if (fs_1["default"].existsSync(Cache.cacheStore)) {
132
- this.cached = JSON.parse(fs_1["default"].readFileSync(Cache.cacheStore, 'utf8'));
133
- }
134
- return this.cached;
135
- };
136
- Cache.prototype.get = function () {
137
- // If the class was supplied a raw object, just go ahead and bypass the caching system and
138
- // return that.
139
- if (typeof this.uri === 'object') {
140
- return this.uri;
141
- }
142
- if (!this.isCached()) {
143
- throw new Error("".concat(this.uri, " has not been cached yet and must do so before being retrieved."));
144
- }
145
- var cache = this.getCache();
146
- // Prior to v4.5.0 we were putting a fully resolved path to the API definition in the cache
147
- // store but if you had specified a custom caching directory and would generate the cache on
148
- // your system, that filepath would obviously not be the same in other environments. For this
149
- // reason the `path` was removed from the cache store in favor of storing the `hash` instead.
150
- //
151
- // If we still have `path` in the config cache for backwards compatibility we should use it.
152
- if ('path' in cache[this.uriHash]) {
153
- return JSON.parse(fs_1["default"].readFileSync(cache[this.uriHash].path, 'utf8'));
154
- }
155
- return JSON.parse(fs_1["default"].readFileSync(path_1["default"].join(Cache.specsCache, "".concat(cache[this.uriHash].hash, ".json")), 'utf8'));
156
- };
157
- Cache.prototype.load = function () {
158
- return __awaiter(this, void 0, void 0, function () {
159
- var _this = this;
160
- return __generator(this, function (_a) {
161
- // If the class was supplied a raw object we should still validate and make sure that it's
162
- // dereferenced in order for everything to function, but we shouldn't worry about saving it
163
- // into the cache directory architecture.
164
- if (typeof this.uri === 'object') {
165
- return [2 /*return*/, fetcher_1["default"].validate(this.uri)];
166
- }
167
- return [2 /*return*/, this.fetcher.load().then(function (spec) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
168
- return [2 /*return*/, this.save(spec)];
169
- }); }); })];
170
- });
171
- });
172
- };
173
- Cache.prototype.save = function (spec) {
174
- if (!fs_1["default"].existsSync(Cache.dir)) {
175
- fs_1["default"].mkdirSync(Cache.dir, { recursive: true });
176
- }
177
- if (!fs_1["default"].existsSync(Cache.specsCache)) {
178
- fs_1["default"].mkdirSync(Cache.specsCache, { recursive: true });
179
- }
180
- var cache = this.getCache();
181
- if (!(this.uriHash in cache)) {
182
- var saved = JSON.stringify(spec, null, 2);
183
- var fileHash = crypto_1["default"].createHash('md5').update(saved).digest('hex');
184
- cache[this.uriHash] = {
185
- hash: fileHash,
186
- original: this.uri,
187
- title: 'title' in spec.info ? spec.info.title : undefined,
188
- version: 'version' in spec.info ? spec.info.version : undefined
189
- };
190
- fs_1["default"].writeFileSync(path_1["default"].join(Cache.specsCache, "".concat(fileHash, ".json")), saved);
191
- fs_1["default"].writeFileSync(Cache.cacheStore, JSON.stringify(cache, null, 2));
192
- this.cached = cache;
193
- }
194
- return spec;
195
- };
196
- return Cache;
197
- }());
198
- exports["default"] = Cache;
@@ -1,20 +0,0 @@
1
- /**
2
- * @see {@link https://www.30secondsofcode.org/js/s/word-wrap}
3
- */
4
- export declare function wordWrap(str: string, max?: number): string;
5
- /**
6
- * Safely escape some string characters that may break a docblock.
7
- *
8
- */
9
- export declare function docblockEscape(str: string): string;
10
- /**
11
- * Convert a string that might contain spaces or special characters to one that can safely be used
12
- * as a TypeScript interface or enum name.
13
- *
14
- * This function has been adapted and slighty modified from `json-schema-to-typescript`.
15
- *
16
- * @license MIT
17
- * @see {@link https://github.com/bcherny/json-schema-to-typescript}
18
- */
19
- export declare function toSafeString(str: string): string;
20
- export declare function generateTypeName(...parts: string[]): string;
@@ -1,12 +0,0 @@
1
- declare class FetchError<Status = number, Data = unknown> extends Error {
2
- /** HTTP Status */
3
- status: Status;
4
- /** The content of the response. */
5
- data: Data;
6
- /** The Headers of the response. */
7
- headers: Headers;
8
- /** The raw `Response` object. */
9
- res: Response;
10
- constructor(status: Status, data: Data, headers: Headers, res: Response);
11
- }
12
- export default FetchError;
@@ -1,36 +0,0 @@
1
- "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
- exports.__esModule = true;
18
- var FetchError = /** @class */ (function (_super) {
19
- __extends(FetchError, _super);
20
- function FetchError(status, data, headers, res) {
21
- var _this = _super.call(this, res.statusText) || this;
22
- _this.name = 'FetchError';
23
- _this.status = status;
24
- _this.data = data;
25
- _this.headers = headers;
26
- _this.res = res;
27
- // We could fix this by updating our target to ES2015 but because we support exporting to CJS
28
- // we can't.
29
- //
30
- // https://www.dannyguo.com/blog/how-to-fix-instanceof-not-working-for-custom-errors-in-typescript/
31
- Object.setPrototypeOf(_this, FetchError.prototype);
32
- return _this;
33
- }
34
- return FetchError;
35
- }(Error));
36
- exports["default"] = FetchError;
@@ -1,14 +0,0 @@
1
- import type { SchemaWrapper } from 'oas/dist/operation/get-parameters-as-json-schema';
2
- /**
3
- * Run through a JSON Schema object and compose up an object containing default data for any schema
4
- * property that is required and also has a defined default.
5
- *
6
- * Code partially adapted from the `json-schema-default` package but modified to only return
7
- * defaults of required properties.
8
- *
9
- * @todo This is a good candidate to be moved into a core `oas` library method.
10
- * @see {@link https://github.com/mdornseif/json-schema-default}
11
- */
12
- export default function getJSONSchemaDefaults(jsonSchemas: SchemaWrapper[]): {
13
- [x: string]: Record<string, unknown>;
14
- };
@@ -1,61 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- exports.__esModule = true;
6
- var json_schema_traverse_1 = __importDefault(require("json-schema-traverse"));
7
- /**
8
- * Run through a JSON Schema object and compose up an object containing default data for any schema
9
- * property that is required and also has a defined default.
10
- *
11
- * Code partially adapted from the `json-schema-default` package but modified to only return
12
- * defaults of required properties.
13
- *
14
- * @todo This is a good candidate to be moved into a core `oas` library method.
15
- * @see {@link https://github.com/mdornseif/json-schema-default}
16
- */
17
- function getJSONSchemaDefaults(jsonSchemas) {
18
- return jsonSchemas
19
- .map(function (_a) {
20
- var _b;
21
- var payloadType = _a.type, jsonSchema = _a.schema;
22
- var defaults = {};
23
- (0, json_schema_traverse_1["default"])(jsonSchema, function (schema, pointer, rootSchema, parentPointer, parentKeyword, parentSchema, indexProperty) {
24
- if (!pointer.startsWith('/properties/')) {
25
- return;
26
- }
27
- if (Array.isArray(parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.required) && parentSchema.required.includes(indexProperty)) {
28
- if (schema.type === 'object' && indexProperty) {
29
- defaults[indexProperty] = {};
30
- }
31
- var destination_1 = defaults;
32
- if (parentPointer) {
33
- // To map nested objects correct we need to pick apart the parent pointer.
34
- parentPointer
35
- .replace(/\/properties/g, '')
36
- .split('/')
37
- .forEach(function (subSchema) {
38
- if (subSchema === '') {
39
- return;
40
- }
41
- destination_1 = (destination_1 === null || destination_1 === void 0 ? void 0 : destination_1[subSchema]) || {};
42
- });
43
- }
44
- if (schema["default"] !== undefined) {
45
- if (indexProperty !== undefined) {
46
- destination_1[indexProperty] = schema["default"];
47
- }
48
- }
49
- }
50
- });
51
- if (!Object.keys(defaults).length) {
52
- return {};
53
- }
54
- return _b = {},
55
- // @todo should we filter out empty and undefined objects from here with `remove-undefined-objects`?
56
- _b[payloadType] = defaults,
57
- _b;
58
- })
59
- .reduce(function (prev, next) { return Object.assign(prev, next); });
60
- }
61
- exports["default"] = getJSONSchemaDefaults;
@@ -1,40 +0,0 @@
1
- import type Oas from 'oas';
2
- import type { Operation } from 'oas';
3
- import type { HttpMethods } from 'oas/dist/rmoas.types';
4
- import 'isomorphic-fetch';
5
- import getJSONSchemaDefaults from './getJSONSchemaDefaults';
6
- import parseResponse from './parseResponse';
7
- import prepareAuth from './prepareAuth';
8
- import prepareParams from './prepareParams';
9
- import prepareServer from './prepareServer';
10
- export interface ConfigOptions {
11
- /**
12
- * Override the default `fetch` request timeout of 30 seconds. This number should be represented
13
- * in milliseconds.
14
- */
15
- timeout?: number;
16
- }
17
- export interface FetchResponse<status, data> {
18
- data: data;
19
- headers: Headers;
20
- res: Response;
21
- status: status;
22
- }
23
- type Enumerate<N extends number, Acc extends number[] = []> = Acc['length'] extends N ? Acc[number] : Enumerate<N, [...Acc, Acc['length']]>;
24
- export type HTTPMethodRange<F extends number, T extends number> = Exclude<Enumerate<T>, Enumerate<F>>;
25
- export { getJSONSchemaDefaults, parseResponse, prepareAuth, prepareParams, prepareServer };
26
- export default class APICore {
27
- spec: Oas;
28
- private auth;
29
- private server;
30
- private config;
31
- private userAgent;
32
- constructor(spec?: Oas, userAgent?: string);
33
- setSpec(spec: Oas): void;
34
- setConfig(config: ConfigOptions): this;
35
- setUserAgent(userAgent: string): this;
36
- setAuth(...values: string[] | number[]): this;
37
- setServer(url: string, variables?: Record<string, string | number>): this;
38
- fetch(path: string, method: HttpMethods, body?: unknown, metadata?: Record<string, unknown>): Promise<any>;
39
- fetchOperation(operation: Operation, body?: unknown, metadata?: Record<string, unknown>): Promise<any>;
40
- }
@@ -1,168 +0,0 @@
1
- "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- 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;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
48
- };
49
- var __importDefault = (this && this.__importDefault) || function (mod) {
50
- return (mod && mod.__esModule) ? mod : { "default": mod };
51
- };
52
- exports.__esModule = true;
53
- exports.prepareServer = exports.prepareParams = exports.prepareAuth = exports.parseResponse = exports.getJSONSchemaDefaults = void 0;
54
- var oas_to_har_1 = __importDefault(require("@readme/oas-to-har"));
55
- var fetch_har_1 = __importDefault(require("fetch-har"));
56
- var form_data_encoder_1 = require("form-data-encoder");
57
- require("isomorphic-fetch");
58
- // `AbortController` was shipped in Node 15 so when Node 14 is EOL'd we can drop this dependency.
59
- var node_abort_controller_1 = require("node-abort-controller");
60
- var fetchError_1 = __importDefault(require("./errors/fetchError"));
61
- var getJSONSchemaDefaults_1 = __importDefault(require("./getJSONSchemaDefaults"));
62
- exports.getJSONSchemaDefaults = getJSONSchemaDefaults_1["default"];
63
- var parseResponse_1 = __importDefault(require("./parseResponse"));
64
- exports.parseResponse = parseResponse_1["default"];
65
- var prepareAuth_1 = __importDefault(require("./prepareAuth"));
66
- exports.prepareAuth = prepareAuth_1["default"];
67
- var prepareParams_1 = __importDefault(require("./prepareParams"));
68
- exports.prepareParams = prepareParams_1["default"];
69
- var prepareServer_1 = __importDefault(require("./prepareServer"));
70
- exports.prepareServer = prepareServer_1["default"];
71
- var APICore = /** @class */ (function () {
72
- function APICore(spec, userAgent) {
73
- this.auth = [];
74
- this.server = false;
75
- this.config = {};
76
- this.spec = spec;
77
- this.userAgent = userAgent;
78
- }
79
- APICore.prototype.setSpec = function (spec) {
80
- this.spec = spec;
81
- };
82
- APICore.prototype.setConfig = function (config) {
83
- this.config = config;
84
- return this;
85
- };
86
- APICore.prototype.setUserAgent = function (userAgent) {
87
- this.userAgent = userAgent;
88
- return this;
89
- };
90
- APICore.prototype.setAuth = function () {
91
- var values = [];
92
- for (var _i = 0; _i < arguments.length; _i++) {
93
- values[_i] = arguments[_i];
94
- }
95
- this.auth = values;
96
- return this;
97
- };
98
- APICore.prototype.setServer = function (url, variables) {
99
- if (variables === void 0) { variables = {}; }
100
- this.server = { url: url, variables: variables };
101
- return this;
102
- };
103
- APICore.prototype.fetch = function (path, method, body, metadata) {
104
- return __awaiter(this, void 0, void 0, function () {
105
- var operation;
106
- return __generator(this, function (_a) {
107
- operation = this.spec.operation(path, method);
108
- return [2 /*return*/, this.fetchOperation(operation, body, metadata)];
109
- });
110
- });
111
- };
112
- APICore.prototype.fetchOperation = function (operation, body, metadata) {
113
- return __awaiter(this, void 0, void 0, function () {
114
- var _this = this;
115
- return __generator(this, function (_a) {
116
- return [2 /*return*/, (0, prepareParams_1["default"])(operation, body, metadata).then(function (params) {
117
- var data = __assign({}, params);
118
- // If `sdk.server()` has been issued data then we need to do some extra work to figure out
119
- // how to use that supplied server, and also handle any server variables that were sent
120
- // alongside it.
121
- if (_this.server) {
122
- var preparedServer = (0, prepareServer_1["default"])(_this.spec, _this.server.url, _this.server.variables);
123
- if (preparedServer) {
124
- data.server = preparedServer;
125
- }
126
- }
127
- // @ts-expect-error `this.auth` typing is off. FIXME
128
- var har = (0, oas_to_har_1["default"])(_this.spec, operation, data, (0, prepareAuth_1["default"])(_this.auth, operation));
129
- var timeoutSignal;
130
- var init = {};
131
- if (_this.config.timeout) {
132
- var controller_1 = new node_abort_controller_1.AbortController();
133
- timeoutSignal = setTimeout(function () { return controller_1.abort(); }, _this.config.timeout);
134
- // @todo Typing on `AbortController` coming out of `node-abort-controler` isn't right so when
135
- // we eventually drop that dependency we can remove the `as any` here.
136
- init.signal = controller_1.signal;
137
- }
138
- return (0, fetch_har_1["default"])(har, {
139
- files: data.files || {},
140
- init: init,
141
- multipartEncoder: form_data_encoder_1.FormDataEncoder,
142
- userAgent: _this.userAgent
143
- })
144
- .then(function (res) { return __awaiter(_this, void 0, void 0, function () {
145
- var parsed;
146
- return __generator(this, function (_a) {
147
- switch (_a.label) {
148
- case 0: return [4 /*yield*/, (0, parseResponse_1["default"])(res)];
149
- case 1:
150
- parsed = _a.sent();
151
- if (res.status >= 400 && res.status <= 599) {
152
- throw new fetchError_1["default"](parsed.status, parsed.data, parsed.headers, parsed.res);
153
- }
154
- return [2 /*return*/, parsed];
155
- }
156
- });
157
- }); })["finally"](function () {
158
- if (_this.config.timeout) {
159
- clearTimeout(timeoutSignal);
160
- }
161
- });
162
- })];
163
- });
164
- });
165
- };
166
- return APICore;
167
- }());
168
- exports["default"] = APICore;
@@ -1,6 +0,0 @@
1
- export default function getResponseBody(response: Response): Promise<{
2
- data: string;
3
- status: number;
4
- headers: Headers;
5
- res: Response;
6
- }>;
@@ -1,71 +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
- exports.__esModule = true;
39
- var oas_1 = require("oas");
40
- var matchesMimeType = oas_1.utils.matchesMimeType;
41
- function getResponseBody(response) {
42
- return __awaiter(this, void 0, void 0, function () {
43
- var contentType, isJSON, responseBody, data;
44
- return __generator(this, function (_a) {
45
- switch (_a.label) {
46
- case 0:
47
- contentType = response.headers.get('Content-Type');
48
- isJSON = contentType && (matchesMimeType.json(contentType) || matchesMimeType.wildcard(contentType));
49
- return [4 /*yield*/, response.text()];
50
- case 1:
51
- responseBody = _a.sent();
52
- data = responseBody;
53
- if (isJSON) {
54
- try {
55
- data = JSON.parse(responseBody);
56
- }
57
- catch (e) {
58
- // If our JSON parsing failed then we can just return plaintext instead.
59
- }
60
- }
61
- return [2 /*return*/, {
62
- data: data,
63
- status: response.status,
64
- headers: response.headers,
65
- res: response
66
- }];
67
- }
68
- });
69
- });
70
- }
71
- exports["default"] = getResponseBody;
@@ -1,5 +0,0 @@
1
- import type { Operation } from 'oas';
2
- export default function prepareAuth(authKey: (number | string)[], operation: Operation): Record<string, string | number | {
3
- pass: string | number;
4
- user: string | number;
5
- }>;