@readme/api-core 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.
@@ -0,0 +1,440 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ var node_fs_1 = __importDefault(require("node:fs"));
43
+ var node_path_1 = __importDefault(require("node:path"));
44
+ var node_stream_1 = __importDefault(require("node:stream"));
45
+ var caseless_1 = __importDefault(require("caseless"));
46
+ var parser_1 = __importDefault(require("datauri/parser"));
47
+ var sync_1 = __importDefault(require("datauri/sync"));
48
+ var get_stream_1 = __importDefault(require("get-stream"));
49
+ var lodash_merge_1 = __importDefault(require("lodash.merge"));
50
+ var remove_undefined_objects_1 = __importDefault(require("remove-undefined-objects"));
51
+ var getJSONSchemaDefaults_1 = __importDefault(require("./getJSONSchemaDefaults"));
52
+ // These headers are normally only defined by the OpenAPI definition but we allow the user to
53
+ // manually supply them in their `metadata` parameter if they wish.
54
+ var specialHeaders = ['accept', 'authorization'];
55
+ /**
56
+ * Extract all available parameters from an operations Parameter Object into a digestable array
57
+ * that we can use to apply to the request.
58
+ *
59
+ * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameterObject}
60
+ * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterObject}
61
+ */
62
+ function digestParameters(parameters) {
63
+ return parameters.reduce(function (prev, param) {
64
+ var _a;
65
+ if ('$ref' in param || 'allOf' in param || 'anyOf' in param || 'oneOf' in param) {
66
+ throw new Error("The OpenAPI document for this operation wasn't dereferenced before processing.");
67
+ }
68
+ else if (param.name in prev) {
69
+ throw new Error("The operation you are using has the same parameter, ".concat(param.name, ", spread across multiple entry points. We unfortunately can't handle this right now."));
70
+ }
71
+ return Object.assign(prev, (_a = {}, _a[param.name] = param, _a));
72
+ }, {});
73
+ }
74
+ // https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_isempty
75
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
76
+ function isEmpty(obj) {
77
+ return [Object, Array].includes((obj || {}).constructor) && !Object.entries(obj || {}).length;
78
+ }
79
+ function isObject(thing) {
80
+ if (thing instanceof node_stream_1.default.Readable) {
81
+ return false;
82
+ }
83
+ return typeof thing === 'object' && thing !== null && !Array.isArray(thing);
84
+ }
85
+ function isPrimitive(obj) {
86
+ return obj === null || typeof obj === 'number' || typeof obj === 'string';
87
+ }
88
+ function merge(src, target) {
89
+ if (Array.isArray(target)) {
90
+ // @todo we need to add support for merging array defaults with array body/metadata arguments
91
+ return target;
92
+ }
93
+ else if (!isObject(target)) {
94
+ return target;
95
+ }
96
+ return (0, lodash_merge_1.default)(src, target);
97
+ }
98
+ /**
99
+ * Ingest a file path or readable stream into a common object that we can later use to process it
100
+ * into a parameters object for making an API request.
101
+ *
102
+ */
103
+ function processFile(paramName, file) {
104
+ var _this = this;
105
+ if (typeof file === 'string') {
106
+ // In order to support relative pathed files, we need to attempt to resolve them.
107
+ var resolvedFile_1 = node_path_1.default.resolve(file);
108
+ return new Promise(function (resolve, reject) {
109
+ node_fs_1.default.stat(resolvedFile_1, function (err) { return __awaiter(_this, void 0, void 0, function () {
110
+ var fileMetadata, payloadFilename;
111
+ var _a;
112
+ return __generator(this, function (_b) {
113
+ switch (_b.label) {
114
+ case 0:
115
+ if (err) {
116
+ if (err.code === 'ENOENT') {
117
+ // It's less than ideal for us to handle files that don't exist like this but because
118
+ // `file` is a string it might actually be the full text contents of the file and not
119
+ // actually a path.
120
+ //
121
+ // We also can't really regex to see if `file` *looks*` like a path because one should be
122
+ // able to pass in a relative `owlbert.png` (instead of `./owlbert.png`) and though that
123
+ // doesn't *look* like a path, it is one that should still work.
124
+ return [2 /*return*/, resolve(undefined)];
125
+ }
126
+ return [2 /*return*/, reject(err)];
127
+ }
128
+ return [4 /*yield*/, (0, sync_1.default)(resolvedFile_1)];
129
+ case 1:
130
+ fileMetadata = _b.sent();
131
+ payloadFilename = encodeURIComponent(node_path_1.default.basename(resolvedFile_1));
132
+ return [2 /*return*/, resolve({
133
+ paramName: paramName,
134
+ base64: (_a = fileMetadata === null || fileMetadata === void 0 ? void 0 : fileMetadata.content) === null || _a === void 0 ? void 0 : _a.replace(';base64', ";name=".concat(payloadFilename, ";base64")),
135
+ filename: payloadFilename,
136
+ buffer: fileMetadata.buffer,
137
+ })];
138
+ }
139
+ });
140
+ }); });
141
+ });
142
+ }
143
+ else if (file instanceof node_stream_1.default.Readable) {
144
+ return get_stream_1.default.buffer(file).then(function (buffer) {
145
+ var filePath = file.path;
146
+ var parser = new parser_1.default();
147
+ var base64 = parser.format(filePath, buffer).content;
148
+ var payloadFilename = encodeURIComponent(node_path_1.default.basename(filePath));
149
+ return {
150
+ paramName: paramName,
151
+ base64: base64 === null || base64 === void 0 ? void 0 : base64.replace(';base64', ";name=".concat(payloadFilename, ";base64")),
152
+ filename: payloadFilename,
153
+ buffer: buffer,
154
+ };
155
+ });
156
+ }
157
+ return Promise.reject(new TypeError(paramName
158
+ ? "The data supplied for the `".concat(paramName, "` request body parameter is not a file handler that we support.")
159
+ : 'The data supplied for the request body payload is not a file handler that we support.'));
160
+ }
161
+ /**
162
+ * With potentially supplied body and/or metadata we need to run through them against a given API
163
+ * operation to see what's what and prepare any available parameters to be used in an API request
164
+ * with `@readme/oas-to-har`.
165
+ *
166
+ */
167
+ function prepareParams(operation, body, metadata) {
168
+ var _a, _b, _c, _d;
169
+ return __awaiter(this, void 0, void 0, function () {
170
+ var metadataIntersected, digestedParameters, jsonSchema, throwNoParamsError, bodyParams_1, jsonSchemaDefaults, params, headerParams_1, intersection, payloadJsonSchema, conversions_1;
171
+ return __generator(this, function (_e) {
172
+ switch (_e.label) {
173
+ case 0:
174
+ metadataIntersected = false;
175
+ digestedParameters = digestParameters(operation.getParameters());
176
+ jsonSchema = operation.getParametersAsJSONSchema();
177
+ /**
178
+ * It might be common for somebody to run `sdk.findPetsByStatus({ status: 'available' }, {})`, in
179
+ * which case we want to filter out the second (metadata) parameter and treat the first parameter
180
+ * as the metadata instead. If we don't do this, their supplied `status` metadata will be treated
181
+ * as a body parameter, and because there's no `status` body parameter, and no supplied metadata
182
+ * (because it's an empty object), the request won't send a payload.
183
+ *
184
+ * @see {@link https://github.com/readmeio/api/issues/449}
185
+ */
186
+ // eslint-disable-next-line no-param-reassign
187
+ metadata = (0, remove_undefined_objects_1.default)(metadata);
188
+ if (!jsonSchema && (body !== undefined || metadata !== undefined)) {
189
+ throwNoParamsError = true;
190
+ // If this operation doesn't have any parameters for us to transform to JSON Schema but they've
191
+ // sent us either an `Accept` or `Authorization` header (or both) we should let them do that.
192
+ // We should, however, only do this check for the `body` parameter as if they've sent this
193
+ // request both `body` and `metadata` we can reject it outright as the operation won't have any
194
+ // body data.
195
+ if (body !== undefined) {
196
+ if (typeof body === 'object' && body !== null && !Array.isArray(body)) {
197
+ if (Object.keys(body).length <= 2) {
198
+ bodyParams_1 = (0, caseless_1.default)(body);
199
+ if (specialHeaders.some(function (header) { return bodyParams_1.has(header); })) {
200
+ throwNoParamsError = false;
201
+ }
202
+ }
203
+ }
204
+ }
205
+ if (throwNoParamsError) {
206
+ throw new Error("You supplied metadata and/or body data for this operation but it doesn't have any documented parameters or request payloads. If you think this is an error please contact support for the API you're using.");
207
+ }
208
+ }
209
+ jsonSchemaDefaults = jsonSchema ? (0, getJSONSchemaDefaults_1.default)(jsonSchema) : {};
210
+ params = jsonSchemaDefaults;
211
+ // If a body argument was supplied we need to do a bit of work to see if it's actually a body
212
+ // argument or metadata because the library lets you supply either a body, metadata, or body with
213
+ // metadata.
214
+ if (typeof body !== 'undefined') {
215
+ if (Array.isArray(body) || isPrimitive(body)) {
216
+ // If the body param is an array or a primitive then we know it's absolutely a body because
217
+ // metadata can only ever be undefined or an object.
218
+ params.body = merge(params.body, body);
219
+ }
220
+ else if (typeof metadata === 'undefined') {
221
+ headerParams_1 = (0, caseless_1.default)({});
222
+ Object.entries(digestedParameters).forEach(function (_a) {
223
+ var paramName = _a[0], param = _a[1];
224
+ // Headers are sent case-insensitive so we need to make sure that we're properly
225
+ // matching them when detecting what our incoming payload looks like.
226
+ if (param.in === 'header') {
227
+ headerParams_1.set(paramName, '');
228
+ }
229
+ });
230
+ // `Accept` and `Authorization` headers can't be defined as normal parameters but we should
231
+ // always allow the user to supply them if they wish.
232
+ specialHeaders.forEach(function (header) {
233
+ if (!headerParams_1.has(header)) {
234
+ headerParams_1.set(header, '');
235
+ }
236
+ });
237
+ intersection = Object.keys(body).filter(function (value) {
238
+ if (Object.keys(digestedParameters).includes(value)) {
239
+ return true;
240
+ }
241
+ else if (headerParams_1.has(value)) {
242
+ return true;
243
+ }
244
+ return false;
245
+ }).length;
246
+ // If more than 25% of the body intersects with the parameters that we've got on hand, then
247
+ // we should treat it as a metadata object and organize into parameters.
248
+ if (intersection && intersection / Object.keys(body).length > 0.25) {
249
+ /* eslint-disable no-param-reassign */
250
+ metadataIntersected = true;
251
+ metadata = merge(params.body, body);
252
+ body = undefined;
253
+ /* eslint-enable no-param-reassign */
254
+ }
255
+ else {
256
+ // For all other cases, we should just treat the supplied body as a body.
257
+ params.body = merge(params.body, body);
258
+ }
259
+ }
260
+ else {
261
+ // Body and metadata were both supplied.
262
+ params.body = merge(params.body, body);
263
+ }
264
+ }
265
+ if (!!operation.hasRequestBody()) return [3 /*break*/, 1];
266
+ // If this operation doesn't have any documented request body then we shouldn't be sending
267
+ // anything.
268
+ delete params.body;
269
+ return [3 /*break*/, 3];
270
+ case 1:
271
+ if (!('body' in params))
272
+ params.body = {};
273
+ payloadJsonSchema = jsonSchema.find(function (js) { return js.type === 'body'; });
274
+ if (!payloadJsonSchema) return [3 /*break*/, 3];
275
+ if (!params.files)
276
+ params.files = {};
277
+ conversions_1 = [];
278
+ // @todo add support for `type: array`, `oneOf` and `anyOf`
279
+ if ((_a = payloadJsonSchema.schema) === null || _a === void 0 ? void 0 : _a.properties) {
280
+ Object.entries((_b = payloadJsonSchema.schema) === null || _b === void 0 ? void 0 : _b.properties)
281
+ .filter(function (_a) {
282
+ var schema = _a[1];
283
+ return (schema === null || schema === void 0 ? void 0 : schema.format) === 'binary';
284
+ })
285
+ .filter(function (_a) {
286
+ var prop = _a[0];
287
+ return Object.keys(params.body).includes(prop);
288
+ })
289
+ .forEach(function (_a) {
290
+ var prop = _a[0];
291
+ conversions_1.push(processFile(prop, params.body[prop]));
292
+ });
293
+ }
294
+ else if (((_c = payloadJsonSchema.schema) === null || _c === void 0 ? void 0 : _c.type) === 'string') {
295
+ if (((_d = payloadJsonSchema.schema) === null || _d === void 0 ? void 0 : _d.format) === 'binary') {
296
+ conversions_1.push(processFile(undefined, params.body));
297
+ }
298
+ }
299
+ return [4 /*yield*/, Promise.all(conversions_1)
300
+ .then(function (fileMetadata) { return fileMetadata.filter(Boolean); })
301
+ .then(function (fm) {
302
+ fm.forEach(function (fileMetadata) {
303
+ if (!fileMetadata) {
304
+ // If we don't have any metadata here it's because the file we have is likely
305
+ // the full string content of the file so since we don't have any filenames to
306
+ // work with we shouldn't do any additional handling to the `body` or `files`
307
+ // parameters.
308
+ return;
309
+ }
310
+ if (fileMetadata.paramName) {
311
+ params.body[fileMetadata.paramName] = fileMetadata.base64;
312
+ }
313
+ else {
314
+ params.body = fileMetadata.base64;
315
+ }
316
+ if (fileMetadata.buffer && (params === null || params === void 0 ? void 0 : params.files)) {
317
+ params.files[fileMetadata.filename] = fileMetadata.buffer;
318
+ }
319
+ });
320
+ })];
321
+ case 2:
322
+ _e.sent();
323
+ _e.label = 3;
324
+ case 3:
325
+ // Form data should be placed within `formData` instead of `body` for it to properly get picked
326
+ // up by `fetch-har`.
327
+ if (operation.isFormUrlEncoded()) {
328
+ params.formData = merge(params.formData, params.body);
329
+ delete params.body;
330
+ }
331
+ // Only spend time trying to organize metadata into parameters if we were able to digest
332
+ // parameters out of the operation schema. If we couldn't digest anything, but metadata was
333
+ // supplied then we wouldn't know how to send it in the request!
334
+ if (typeof metadata !== 'undefined') {
335
+ if (!('cookie' in params))
336
+ params.cookie = {};
337
+ if (!('header' in params))
338
+ params.header = {};
339
+ if (!('path' in params))
340
+ params.path = {};
341
+ if (!('query' in params))
342
+ params.query = {};
343
+ Object.entries(digestedParameters).forEach(function (_a) {
344
+ var paramName = _a[0], param = _a[1];
345
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
346
+ var value;
347
+ var metadataHeaderParam;
348
+ if (typeof metadata === 'object' && !isEmpty(metadata)) {
349
+ if (paramName in metadata) {
350
+ value = metadata[paramName];
351
+ metadataHeaderParam = paramName;
352
+ }
353
+ else if (param.in === 'header') {
354
+ // Headers are sent case-insensitive so we need to make sure that we're properly
355
+ // matching them when detecting what our incoming payload looks like.
356
+ metadataHeaderParam = Object.keys(metadata).find(function (k) { return k.toLowerCase() === paramName.toLowerCase(); }) || '';
357
+ value = metadata[metadataHeaderParam];
358
+ }
359
+ }
360
+ if (value === undefined) {
361
+ return;
362
+ }
363
+ /* eslint-disable no-param-reassign */
364
+ switch (param.in) {
365
+ case 'path':
366
+ params.path[paramName] = value;
367
+ if (metadata === null || metadata === void 0 ? void 0 : metadata[paramName])
368
+ delete metadata[paramName];
369
+ break;
370
+ case 'query':
371
+ params.query[paramName] = value;
372
+ if (metadata === null || metadata === void 0 ? void 0 : metadata[paramName])
373
+ delete metadata[paramName];
374
+ break;
375
+ case 'header':
376
+ params.header[paramName.toLowerCase()] = value;
377
+ if (metadataHeaderParam && (metadata === null || metadata === void 0 ? void 0 : metadata[metadataHeaderParam]))
378
+ delete metadata[metadataHeaderParam];
379
+ break;
380
+ case 'cookie':
381
+ params.cookie[paramName] = value;
382
+ if (metadata === null || metadata === void 0 ? void 0 : metadata[paramName])
383
+ delete metadata[paramName];
384
+ break;
385
+ default: // no-op
386
+ }
387
+ /* eslint-enable no-param-reassign */
388
+ // Because a user might have sent just a metadata object, we want to make sure that we filter
389
+ // out anything that they sent that is a parameter from also being sent as part of a form
390
+ // data payload for `x-www-form-urlencoded` requests.
391
+ if (metadataIntersected && operation.isFormUrlEncoded()) {
392
+ if (paramName in params.formData) {
393
+ delete params.formData[paramName];
394
+ }
395
+ }
396
+ });
397
+ // If there's any leftover metadata that hasn't been moved into form data for this request we
398
+ // need to move it or else it'll get tossed.
399
+ if (!isEmpty(metadata)) {
400
+ if (typeof metadata === 'object') {
401
+ // If the user supplied an `accept` or `authorization` header themselves we should allow it
402
+ // through. Normally these headers are automatically handled by `@readme/oas-to-har` but in
403
+ // the event that maybe the user wants to return XML for an API that normally returns JSON
404
+ // or specify a custom auth header (maybe we can't handle their auth case right) this is the
405
+ // only way with this library that they can do that.
406
+ specialHeaders.forEach(function (headerName) {
407
+ var headerParam = Object.keys(metadata || {}).find(function (m) { return m.toLowerCase() === headerName; });
408
+ if (headerParam) {
409
+ // this if-statement below is a typeguard
410
+ if (typeof metadata === 'object') {
411
+ // this if-statement below is a typeguard
412
+ if (typeof params.header === 'object') {
413
+ params.header[headerName] = metadata[headerParam];
414
+ }
415
+ // eslint-disable-next-line no-param-reassign
416
+ delete metadata[headerParam];
417
+ }
418
+ }
419
+ });
420
+ }
421
+ if (operation.isFormUrlEncoded()) {
422
+ params.formData = merge(params.formData, metadata);
423
+ }
424
+ else {
425
+ // Any other remaining unused metadata will be unused because we don't know where to place
426
+ // it in the request.
427
+ }
428
+ }
429
+ }
430
+ ['body', 'cookie', 'files', 'formData', 'header', 'path', 'query'].forEach(function (type) {
431
+ if (type in params && isEmpty(params[type])) {
432
+ delete params[type];
433
+ }
434
+ });
435
+ return [2 /*return*/, params];
436
+ }
437
+ });
438
+ });
439
+ }
440
+ exports.default = prepareParams;
@@ -0,0 +1,10 @@
1
+ import type Oas from 'oas';
2
+ /**
3
+ * With an SDK server config and an instance of OAS we should extract and prepare the server and
4
+ * any server variables to be supplied to `@readme/oas-to-har`.
5
+ *
6
+ */
7
+ export default function prepareServer(spec: Oas, url: string, variables?: Record<string, string | number>): false | {
8
+ selected: number;
9
+ variables: Record<string, string | number>;
10
+ };
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ function stripTrailingSlash(url) {
4
+ if (url[url.length - 1] === '/') {
5
+ return url.slice(0, -1);
6
+ }
7
+ return url;
8
+ }
9
+ /**
10
+ * With an SDK server config and an instance of OAS we should extract and prepare the server and
11
+ * any server variables to be supplied to `@readme/oas-to-har`.
12
+ *
13
+ */
14
+ function prepareServer(spec, url, variables) {
15
+ if (variables === void 0) { variables = {}; }
16
+ var serverIdx;
17
+ var sanitizedUrl = stripTrailingSlash(url);
18
+ (spec.api.servers || []).forEach(function (server, i) {
19
+ if (server.url === sanitizedUrl) {
20
+ serverIdx = i;
21
+ }
22
+ });
23
+ // If we were able to find the passed in server in the OAS servers, we should use that! If we
24
+ // couldn't and server variables were passed in we should try our best to handle that, otherwise
25
+ // we should ignore the passed in server and use whever the default from the OAS is.
26
+ if (serverIdx) {
27
+ return {
28
+ selected: serverIdx,
29
+ variables: variables,
30
+ };
31
+ }
32
+ else if (Object.keys(variables).length) {
33
+ // @todo we should run `oas.replaceUrl(url)` and pass that unto `@readme/oas-to-har`
34
+ }
35
+ else {
36
+ var server = spec.splitVariables(url);
37
+ if (server) {
38
+ return {
39
+ selected: server.selected,
40
+ variables: server.variables,
41
+ };
42
+ }
43
+ // @todo we should pass `url` directly into `@readme/oas-to-har` as the base URL
44
+ }
45
+ return false;
46
+ }
47
+ exports.default = prepareServer;
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@readme/api-core",
3
+ "version": "7.0.0-alpha.1",
4
+ "description": "The magic behind `api` 🧙",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "lint:types": "tsc --noEmit",
10
+ "prebuild": "rm -rf dist/",
11
+ "prepack": "npm run build",
12
+ "test": "vitest run --coverage"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/readmeio/api.git",
17
+ "directory": "packages/core"
18
+ },
19
+ "homepage": "https://api.readme.dev",
20
+ "bugs": {
21
+ "url": "https://github.com/readmeio/api/issues"
22
+ },
23
+ "author": "Jon Ursenbach <jon@readme.io>",
24
+ "license": "MIT",
25
+ "engines": {
26
+ "node": ">=18"
27
+ },
28
+ "dependencies": {
29
+ "@readme/oas-to-har": "^20.1.1",
30
+ "caseless": "^0.12.0",
31
+ "datauri": "^4.1.0",
32
+ "fetch-har": "^10.0.0",
33
+ "get-stream": "^6.0.1",
34
+ "json-schema-traverse": "^1.0.0",
35
+ "lodash.merge": "^4.6.2",
36
+ "oas": "^20.10.3",
37
+ "remove-undefined-objects": "^3.0.0"
38
+ },
39
+ "devDependencies": {
40
+ "@api/test-utils": "file:../test-utils",
41
+ "@readme/oas-examples": "^5.12.0",
42
+ "@types/caseless": "^0.12.3",
43
+ "@types/lodash.merge": "^4.6.7",
44
+ "@vitest/coverage-v8": "^0.34.4",
45
+ "fetch-mock": "^9.11.0",
46
+ "typescript": "^5.2.2",
47
+ "vitest": "^0.34.4"
48
+ },
49
+ "prettier": "@readme/eslint-config/prettier"
50
+ }
@@ -0,0 +1,31 @@
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;