api 4.5.1 → 5.0.0-beta.2

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 (70) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +32 -162
  3. package/bin/api +2 -0
  4. package/dist/bin.d.ts +1 -0
  5. package/dist/bin.js +91 -0
  6. package/dist/cache.d.ts +30 -0
  7. package/dist/cache.js +217 -0
  8. package/dist/cli/codegen/index.d.ts +4 -0
  9. package/dist/cli/codegen/index.js +23 -0
  10. package/dist/cli/codegen/language.d.ts +27 -0
  11. package/dist/cli/codegen/language.js +19 -0
  12. package/dist/cli/codegen/languages/typescript.d.ts +99 -0
  13. package/dist/cli/codegen/languages/typescript.js +769 -0
  14. package/dist/cli/commands/index.d.ts +4 -0
  15. package/dist/cli/commands/index.js +9 -0
  16. package/dist/cli/commands/install.d.ts +3 -0
  17. package/dist/cli/commands/install.js +230 -0
  18. package/dist/cli/lib/prompt.d.ts +9 -0
  19. package/dist/cli/lib/prompt.js +81 -0
  20. package/dist/cli/logger.d.ts +1 -0
  21. package/dist/cli/logger.js +16 -0
  22. package/dist/cli/storage.d.ts +105 -0
  23. package/dist/cli/storage.js +264 -0
  24. package/dist/core/getJSONSchemaDefaults.d.ts +15 -0
  25. package/dist/core/getJSONSchemaDefaults.js +62 -0
  26. package/dist/core/index.d.ts +32 -0
  27. package/dist/core/index.js +143 -0
  28. package/dist/core/parseResponse.d.ts +1 -0
  29. package/dist/core/parseResponse.js +65 -0
  30. package/dist/core/prepareAuth.d.ts +5 -0
  31. package/dist/core/prepareAuth.js +55 -0
  32. package/dist/core/prepareParams.d.ts +24 -0
  33. package/dist/core/prepareParams.js +351 -0
  34. package/dist/core/prepareServer.d.ts +13 -0
  35. package/dist/core/prepareServer.js +50 -0
  36. package/dist/fetcher.d.ts +54 -0
  37. package/dist/fetcher.js +165 -0
  38. package/dist/index.d.ts +6 -0
  39. package/dist/index.js +276 -0
  40. package/dist/packageInfo.d.ts +2 -0
  41. package/dist/packageInfo.js +6 -0
  42. package/package.json +67 -28
  43. package/src/.sink.d.ts +1 -0
  44. package/src/bin.ts +20 -0
  45. package/src/cache.ts +212 -0
  46. package/src/cli/codegen/index.ts +31 -0
  47. package/src/cli/codegen/language.ts +47 -0
  48. package/src/cli/codegen/languages/typescript.ts +807 -0
  49. package/src/cli/commands/index.ts +5 -0
  50. package/src/cli/commands/install.ts +196 -0
  51. package/src/cli/lib/prompt.ts +29 -0
  52. package/src/cli/logger.ts +10 -0
  53. package/src/cli/storage.ts +297 -0
  54. package/src/core/getJSONSchemaDefaults.ts +74 -0
  55. package/src/core/index.ts +108 -0
  56. package/src/{lib/parseResponse.js → core/parseResponse.ts} +5 -7
  57. package/src/core/prepareAuth.ts +85 -0
  58. package/src/core/prepareParams.ts +338 -0
  59. package/src/{lib/prepareServer.js → core/prepareServer.ts} +13 -12
  60. package/src/fetcher.ts +141 -0
  61. package/src/index.ts +212 -0
  62. package/src/packageInfo.ts +3 -0
  63. package/src/typings.d.ts +3 -0
  64. package/tsconfig.json +24 -0
  65. package/src/cache.js +0 -225
  66. package/src/index.js +0 -177
  67. package/src/lib/getSchema.js +0 -34
  68. package/src/lib/index.js +0 -11
  69. package/src/lib/prepareAuth.js +0 -69
  70. package/src/lib/prepareParams.js +0 -198
@@ -0,0 +1,264 @@
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 (_) 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 ssri_1 = __importDefault(require("ssri"));
43
+ var fs_1 = __importDefault(require("fs"));
44
+ var path_1 = __importDefault(require("path"));
45
+ var make_dir_1 = __importDefault(require("make-dir"));
46
+ var packageInfo_1 = require("../packageInfo");
47
+ var fetcher_1 = __importDefault(require("../fetcher"));
48
+ var Storage = /** @class */ (function () {
49
+ function Storage(source, identifier) {
50
+ Storage.setStorageDir();
51
+ this.fetcher = new fetcher_1["default"](source);
52
+ this.source = source;
53
+ this.identifier = identifier;
54
+ // This should default to false so we have awareness if we've looked at the lockfile yet.
55
+ Storage.lockfile = false;
56
+ }
57
+ Storage.getLockfilePath = function () {
58
+ return path_1["default"].join(Storage.dir, 'api.json');
59
+ };
60
+ Storage.getAPIsDir = function () {
61
+ return path_1["default"].join(Storage.dir, 'apis');
62
+ };
63
+ Storage.setStorageDir = function (dir) {
64
+ if (dir) {
65
+ Storage.dir = dir;
66
+ return;
67
+ }
68
+ else if (Storage.dir) {
69
+ // If we already have a storage dir set and aren't explicitly it to something new then we
70
+ // shouldn't overwrite what we've already got.
71
+ return;
72
+ }
73
+ Storage.dir = make_dir_1["default"].sync(path_1["default"].join(process.cwd(), '.api'));
74
+ make_dir_1["default"].sync(Storage.getAPIsDir());
75
+ };
76
+ /**
77
+ * Reset the state of the entire storage system.
78
+ *
79
+ * This will completely destroy the contents of the `.api/` directory!
80
+ */
81
+ Storage.reset = function () {
82
+ return __awaiter(this, void 0, void 0, function () {
83
+ return __generator(this, function (_a) {
84
+ switch (_a.label) {
85
+ case 0:
86
+ if (!Storage.getLockfilePath()) return [3 /*break*/, 2];
87
+ return [4 /*yield*/, fs_1["default"].promises.writeFile(Storage.getLockfilePath(), JSON.stringify(Storage.getDefaultLockfile(), null, 2))];
88
+ case 1:
89
+ _a.sent();
90
+ _a.label = 2;
91
+ case 2:
92
+ if (!Storage.getAPIsDir()) return [3 /*break*/, 5];
93
+ return [4 /*yield*/, fs_1["default"].promises.rm(Storage.getAPIsDir(), { recursive: true })];
94
+ case 3:
95
+ _a.sent();
96
+ return [4 /*yield*/, fs_1["default"].promises.mkdir(Storage.getAPIsDir(), { recursive: true })];
97
+ case 4:
98
+ _a.sent();
99
+ _a.label = 5;
100
+ case 5: return [2 /*return*/];
101
+ }
102
+ });
103
+ });
104
+ };
105
+ Storage.getDefaultLockfile = function () {
106
+ return {
107
+ version: '1.0',
108
+ apis: []
109
+ };
110
+ };
111
+ Storage.generateIntegrityHash = function (definition) {
112
+ return ssri_1["default"]
113
+ .fromData(JSON.stringify(definition), {
114
+ algorithms: ['sha512']
115
+ })
116
+ .toString();
117
+ };
118
+ Storage.getLockfile = function () {
119
+ if (typeof Storage.lockfile === 'object') {
120
+ return Storage.lockfile;
121
+ }
122
+ if (fs_1["default"].existsSync(Storage.getLockfilePath())) {
123
+ var file = fs_1["default"].readFileSync(Storage.getLockfilePath(), 'utf8');
124
+ Storage.lockfile = JSON.parse(file);
125
+ }
126
+ else {
127
+ Storage.lockfile = Storage.getDefaultLockfile();
128
+ }
129
+ return Storage.lockfile;
130
+ };
131
+ Storage.isInLockFile = function (search) {
132
+ // Because this method may run before we initialize a new storage object we should make sure
133
+ // that we have a storage directory present.
134
+ Storage.setStorageDir();
135
+ if (!search.identifier && !search.source) {
136
+ throw new TypeError('An `identifier` or `source` must be supplied to this method to search in the lockfile.');
137
+ }
138
+ var lockfile = Storage.getLockfile();
139
+ if (typeof lockfile !== 'object' || lockfile === null || !lockfile.apis) {
140
+ return false;
141
+ }
142
+ var res = lockfile.apis.find(function (a) {
143
+ if (search.identifier) {
144
+ return a.identifier === search.identifier;
145
+ }
146
+ return a.source === search.source;
147
+ });
148
+ return res === undefined ? false : res;
149
+ };
150
+ Storage.prototype.setIdentifier = function (identifier) {
151
+ this.identifier = identifier;
152
+ };
153
+ /**
154
+ * Determine if the current spec + identifier we're working with is already in the lockfile.
155
+ */
156
+ Storage.prototype.isInLockfile = function () {
157
+ return Boolean(this.getFromLockfile());
158
+ };
159
+ /**
160
+ * Retrieve the lockfile record for the current spec + identifier if it exists in the lockfile.
161
+ */
162
+ Storage.prototype.getFromLockfile = function () {
163
+ var _this = this;
164
+ var lockfile = Storage.getLockfile();
165
+ return lockfile.apis.find(function (a) { return a.identifier === _this.identifier; });
166
+ };
167
+ Storage.prototype.getIdentifierStorageDir = function () {
168
+ if (!this.isInLockfile()) {
169
+ throw new Error("".concat(this.source, " has not been saved to storage yet and must do so before being retrieved."));
170
+ }
171
+ return path_1["default"].join(Storage.getAPIsDir(), this.identifier);
172
+ };
173
+ Storage.prototype.getAPIDefinition = function () {
174
+ var file = fs_1["default"].readFileSync(path_1["default"].join(this.getIdentifierStorageDir(), 'openapi.json'), 'utf8');
175
+ return JSON.parse(file);
176
+ };
177
+ Storage.prototype.saveSourceFiles = function (files) {
178
+ var _this = this;
179
+ if (!this.isInLockfile()) {
180
+ throw new Error("".concat(this.source, " has not been saved to storage yet and must do so before being retrieved."));
181
+ }
182
+ return new Promise(function (resolve) {
183
+ var savedSource = [];
184
+ Object.entries(files).forEach(function (_a) {
185
+ var fileName = _a[0], contents = _a[1];
186
+ var sourceFilePath = path_1["default"].join(_this.getIdentifierStorageDir(), fileName);
187
+ fs_1["default"].writeFileSync(sourceFilePath, contents);
188
+ savedSource.push(sourceFilePath);
189
+ });
190
+ resolve(savedSource);
191
+ });
192
+ };
193
+ Storage.prototype.load = function () {
194
+ return __awaiter(this, void 0, void 0, function () {
195
+ var _this = this;
196
+ return __generator(this, function (_a) {
197
+ return [2 /*return*/, this.fetcher.load().then(function (spec) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
198
+ return [2 /*return*/, this.save(spec)];
199
+ }); }); })];
200
+ });
201
+ });
202
+ };
203
+ /**
204
+ * @example <caption>Storage directory structure</caption>
205
+ * .api/
206
+ * ├── api.json // The `package-lock.json` equivalent that records everything that's
207
+ * | // installed, when it was installed, what the original source was,
208
+ * | // and what version of `api` was used.
209
+ * └── apis/
210
+ * ├── readme/
211
+ * | ├── node_modules/
212
+ * │ ├── index.js // We may offer the option to export a raw TS file for folks who want
213
+ * | | // that, but for now it'll be a compiled JS file.
214
+ * │ ├── index.d.ts // All types for their SDK, ready to use in an IDE.
215
+ * │ |── openapi.json
216
+ * │ └── package.json
217
+ * └── petstore/
218
+ * ├── node_modules/
219
+ * ├── index.js
220
+ * ├── index.d.ts
221
+ * ├── openapi.json
222
+ * └── package.json
223
+ *
224
+ * @param spec
225
+ */
226
+ Storage.prototype.save = function (spec) {
227
+ if (!this.identifier) {
228
+ throw new TypeError('An identifier must be set before saving the API definition into storage.');
229
+ }
230
+ // Create our main `.api/` directory.
231
+ if (!fs_1["default"].existsSync(Storage.dir)) {
232
+ fs_1["default"].mkdirSync(Storage.dir, { recursive: true });
233
+ }
234
+ // Create the `.api/apis/` diretory where we'll be storing API definitions.
235
+ if (!fs_1["default"].existsSync(Storage.getAPIsDir())) {
236
+ fs_1["default"].mkdirSync(Storage.getAPIsDir(), { recursive: true });
237
+ }
238
+ if (!this.isInLockfile()) {
239
+ // This API doesn't exist within our storage system yet so we need to record it in the
240
+ // lockfile.
241
+ var identifierStorageDir = path_1["default"].join(Storage.getAPIsDir(), this.identifier);
242
+ var saved = JSON.stringify(spec, null, 2);
243
+ // Create the `.api/apis/<identifier>` directory where we'll be storing this API definition
244
+ // and eventually its codegen'd SDK.
245
+ if (!fs_1["default"].existsSync(identifierStorageDir)) {
246
+ fs_1["default"].mkdirSync(identifierStorageDir, { recursive: true });
247
+ }
248
+ Storage.lockfile.apis.push({
249
+ identifier: this.identifier,
250
+ source: this.source,
251
+ integrity: Storage.generateIntegrityHash(spec),
252
+ installerVersion: packageInfo_1.PACKAGE_VERSION
253
+ });
254
+ fs_1["default"].writeFileSync(path_1["default"].join(identifierStorageDir, 'openapi.json'), saved);
255
+ fs_1["default"].writeFileSync(Storage.getLockfilePath(), JSON.stringify(Storage.lockfile, null, 2));
256
+ }
257
+ else {
258
+ // Is this the same spec that we already have? Should we update it? // @todo
259
+ }
260
+ return spec;
261
+ };
262
+ return Storage;
263
+ }());
264
+ exports["default"] = Storage;
@@ -0,0 +1,15 @@
1
+ import type { SchemaWrapper } from 'oas/@types/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
+ * @param jsonSchemas
12
+ */
13
+ export default function getJSONSchemaDefaults(jsonSchemas: SchemaWrapper[]): {
14
+ [x: string]: Record<string, unknown>;
15
+ };
@@ -0,0 +1,62 @@
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
+ * @param jsonSchemas
17
+ */
18
+ function getJSONSchemaDefaults(jsonSchemas) {
19
+ return jsonSchemas
20
+ .map(function (_a) {
21
+ var _b;
22
+ var payloadType = _a.type, jsonSchema = _a.schema;
23
+ var defaults = {};
24
+ (0, json_schema_traverse_1["default"])(jsonSchema, function (schema, pointer, rootSchema, parentPointer, parentKeyword, parentSchema, indexProperty) {
25
+ if (!pointer.startsWith('/properties/')) {
26
+ return;
27
+ }
28
+ if (Array.isArray(parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.required) && parentSchema.required.includes(indexProperty)) {
29
+ if (schema.type === 'object' && indexProperty) {
30
+ defaults[indexProperty] = {};
31
+ }
32
+ var destination_1 = defaults;
33
+ if (parentPointer) {
34
+ // To map nested objects correct we need to pick apart the parent pointer.
35
+ parentPointer
36
+ .replace(/\/properties/g, '')
37
+ .split('/')
38
+ .forEach(function (subSchema) {
39
+ if (subSchema === '') {
40
+ return;
41
+ }
42
+ destination_1 = (destination_1 === null || destination_1 === void 0 ? void 0 : destination_1[subSchema]) || {};
43
+ });
44
+ }
45
+ if (schema["default"] !== undefined) {
46
+ if (indexProperty !== undefined) {
47
+ destination_1[indexProperty] = schema["default"];
48
+ }
49
+ }
50
+ }
51
+ });
52
+ if (!Object.keys(defaults).length) {
53
+ return {};
54
+ }
55
+ return _b = {},
56
+ // @todo should we filter out empty and undefined objects from here with `remove-undefined-objects`?
57
+ _b[payloadType] = defaults,
58
+ _b;
59
+ })
60
+ .reduce(function (prev, next) { return Object.assign(prev, next); });
61
+ }
62
+ exports["default"] = getJSONSchemaDefaults;
@@ -0,0 +1,32 @@
1
+ import type Oas from 'oas';
2
+ import type { Operation } from 'oas';
3
+ import type { HttpMethods } from 'oas/@types/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
+ * By default we parse the response based on the `Content-Type` header of the request. You can
13
+ * disable this functionality by negating this option.
14
+ */
15
+ parseResponse: boolean;
16
+ }
17
+ export { getJSONSchemaDefaults, parseResponse, prepareAuth, prepareParams, prepareServer };
18
+ export default class APICore {
19
+ spec: Oas;
20
+ private auth;
21
+ private server;
22
+ private config;
23
+ private userAgent;
24
+ constructor(spec?: Oas, userAgent?: string);
25
+ setSpec(spec: Oas): void;
26
+ setConfig(config: ConfigOptions): this;
27
+ setUserAgent(userAgent: string): this;
28
+ setAuth(...values: string[] | number[]): this;
29
+ setServer(url: string, variables?: Record<string, string | number>): this;
30
+ fetch(path: string, method: HttpMethods, body?: unknown, metadata?: Record<string, unknown>): Promise<any>;
31
+ fetchOperation(operation: Operation, body?: unknown, metadata?: Record<string, unknown>): Promise<any>;
32
+ }
@@ -0,0 +1,143 @@
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 (_) 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
+ require("isomorphic-fetch");
55
+ var fetch_har_1 = __importDefault(require("fetch-har"));
56
+ var oas_to_har_1 = __importDefault(require("@readme/oas-to-har"));
57
+ var form_data_encoder_1 = require("form-data-encoder");
58
+ var getJSONSchemaDefaults_1 = __importDefault(require("./getJSONSchemaDefaults"));
59
+ exports.getJSONSchemaDefaults = getJSONSchemaDefaults_1["default"];
60
+ var parseResponse_1 = __importDefault(require("./parseResponse"));
61
+ exports.parseResponse = parseResponse_1["default"];
62
+ var prepareAuth_1 = __importDefault(require("./prepareAuth"));
63
+ exports.prepareAuth = prepareAuth_1["default"];
64
+ var prepareParams_1 = __importDefault(require("./prepareParams"));
65
+ exports.prepareParams = prepareParams_1["default"];
66
+ var prepareServer_1 = __importDefault(require("./prepareServer"));
67
+ exports.prepareServer = prepareServer_1["default"];
68
+ var APICore = /** @class */ (function () {
69
+ function APICore(spec, userAgent) {
70
+ this.auth = [];
71
+ this.server = false;
72
+ this.config = { parseResponse: true };
73
+ this.spec = spec;
74
+ this.userAgent = userAgent;
75
+ }
76
+ APICore.prototype.setSpec = function (spec) {
77
+ this.spec = spec;
78
+ };
79
+ APICore.prototype.setConfig = function (config) {
80
+ this.config = config;
81
+ return this;
82
+ };
83
+ APICore.prototype.setUserAgent = function (userAgent) {
84
+ this.userAgent = userAgent;
85
+ return this;
86
+ };
87
+ APICore.prototype.setAuth = function () {
88
+ var values = [];
89
+ for (var _i = 0; _i < arguments.length; _i++) {
90
+ values[_i] = arguments[_i];
91
+ }
92
+ this.auth = values;
93
+ return this;
94
+ };
95
+ APICore.prototype.setServer = function (url, variables) {
96
+ if (variables === void 0) { variables = {}; }
97
+ this.server = { url: url, variables: variables };
98
+ return this;
99
+ };
100
+ APICore.prototype.fetch = function (path, method, body, metadata) {
101
+ return __awaiter(this, void 0, void 0, function () {
102
+ var operation;
103
+ return __generator(this, function (_a) {
104
+ operation = this.spec.operation(path, method);
105
+ return [2 /*return*/, this.fetchOperation(operation, body, metadata)];
106
+ });
107
+ });
108
+ };
109
+ APICore.prototype.fetchOperation = function (operation, body, metadata) {
110
+ return __awaiter(this, void 0, void 0, function () {
111
+ var _this = this;
112
+ return __generator(this, function (_a) {
113
+ return [2 /*return*/, (0, prepareParams_1["default"])(operation, body, metadata).then(function (params) {
114
+ var data = __assign({}, params);
115
+ // If `sdk.server()` has been issued data then we need to do some extra work to figure out
116
+ // how to use that supplied server, and also handle any server variables that were sent
117
+ // alongside it.
118
+ if (_this.server) {
119
+ var preparedServer = (0, prepareServer_1["default"])(_this.spec, _this.server.url, _this.server.variables);
120
+ if (preparedServer) {
121
+ data.server = preparedServer;
122
+ }
123
+ }
124
+ var har = (0, oas_to_har_1["default"])(_this.spec, operation, data, (0, prepareAuth_1["default"])(_this.auth, operation));
125
+ return (0, fetch_har_1["default"])(har, {
126
+ userAgent: _this.userAgent,
127
+ files: data.files || {},
128
+ multipartEncoder: form_data_encoder_1.FormDataEncoder
129
+ }).then(function (res) {
130
+ if (res.status >= 400 && res.status <= 599) {
131
+ throw res;
132
+ }
133
+ if (_this.config.parseResponse === false)
134
+ return res;
135
+ return (0, parseResponse_1["default"])(res);
136
+ });
137
+ })];
138
+ });
139
+ });
140
+ };
141
+ return APICore;
142
+ }());
143
+ exports["default"] = APICore;
@@ -0,0 +1 @@
1
+ export default function getResponseBody(response: Response): Promise<any>;
@@ -0,0 +1,65 @@
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 (_) 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;
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
+ if (isJSON) {
53
+ try {
54
+ return [2 /*return*/, JSON.parse(responseBody)];
55
+ }
56
+ catch (e) {
57
+ // If our JSON parsing failed then we can just return plaintext instead.
58
+ }
59
+ }
60
+ return [2 /*return*/, responseBody];
61
+ }
62
+ });
63
+ });
64
+ }
65
+ exports["default"] = getResponseBody;
@@ -0,0 +1,5 @@
1
+ import type { Operation } from 'oas';
2
+ export default function prepareAuth(authKey: (number | string)[], operation: Operation): Record<string, string | number | {
3
+ user: string | number;
4
+ pass: string | number;
5
+ }>;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ exports.__esModule = true;
3
+ function prepareAuth(authKey, operation) {
4
+ if (authKey.length === 0) {
5
+ return {};
6
+ }
7
+ var preparedAuth = {};
8
+ var security = operation.prepareSecurity();
9
+ var securitySchemes = Object.keys(security);
10
+ if (securitySchemes.length === 0) {
11
+ // If there's no auth configured on this operation, don't prepare anything (even if it was
12
+ // supplied by the user).
13
+ return {};
14
+ }
15
+ var securityType = securitySchemes[0];
16
+ var schemes = security[securityType];
17
+ if (schemes.length > 1) {
18
+ throw new Error("Sorry, this API currently requires multiple forms of authentication which we don't yet support.");
19
+ }
20
+ var scheme = schemes[0];
21
+ switch (scheme.type) {
22
+ case 'http':
23
+ if (scheme.scheme === 'basic') {
24
+ preparedAuth[scheme._key] = {
25
+ user: authKey[0],
26
+ pass: authKey.length === 2 ? authKey[1] : ''
27
+ };
28
+ }
29
+ else if (scheme.scheme === 'bearer') {
30
+ if (authKey.length > 1) {
31
+ throw new Error('Multiple auth tokens were supplied for the auth on this endpoint, but only a single token is needed.');
32
+ }
33
+ preparedAuth[scheme._key] = authKey[0];
34
+ }
35
+ break;
36
+ case 'oauth2':
37
+ if (authKey.length > 1) {
38
+ throw new Error('Multiple auth tokens were supplied for the auth on this endpoint, but only a single token is needed.');
39
+ }
40
+ preparedAuth[scheme._key] = authKey[0];
41
+ break;
42
+ case 'apiKey':
43
+ if (authKey.length > 1) {
44
+ throw new Error('Multiple auth keys were supplied for the auth on this endpoint, but only a single key is needed.');
45
+ }
46
+ if (scheme["in"] === 'query' || scheme["in"] === 'header' || scheme["in"] === 'cookie') {
47
+ preparedAuth[scheme._key] = authKey[0];
48
+ }
49
+ break;
50
+ default:
51
+ throw new Error("Sorry, this API currently supports a scheme, ".concat(scheme.type, ", that we don't yet support."));
52
+ }
53
+ return preparedAuth;
54
+ }
55
+ exports["default"] = prepareAuth;