api 4.4.0 → 5.0.0-beta.0

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 +18 -5
  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 +762 -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 +53 -0
  37. package/dist/fetcher.js +149 -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 +65 -25
  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 +798 -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 +126 -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 -209
  66. package/src/index.js +0 -175
  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,108 @@
1
+ import type Oas from 'oas';
2
+ import type { Operation } from 'oas';
3
+ import type { HttpMethods } from 'oas/@types/rmoas.types';
4
+
5
+ import 'isomorphic-fetch';
6
+ import fetchHar from 'fetch-har';
7
+ import oasToHar from '@readme/oas-to-har';
8
+ import { FormDataEncoder } from 'form-data-encoder';
9
+
10
+ import getJSONSchemaDefaults from './getJSONSchemaDefaults';
11
+ import parseResponse from './parseResponse';
12
+ import prepareAuth from './prepareAuth';
13
+ import prepareParams from './prepareParams';
14
+ import prepareServer from './prepareServer';
15
+
16
+ export interface ConfigOptions {
17
+ /**
18
+ * By default we parse the response based on the `Content-Type` header of the request. You can
19
+ * disable this functionality by negating this option.
20
+ */
21
+ parseResponse: boolean;
22
+ }
23
+
24
+ export { getJSONSchemaDefaults, parseResponse, prepareAuth, prepareParams, prepareServer };
25
+
26
+ export default class APICore {
27
+ spec: Oas;
28
+
29
+ private auth: (number | string)[] = [];
30
+
31
+ private server:
32
+ | false
33
+ | {
34
+ url?: string;
35
+ variables?: Record<string, string | number>;
36
+ } = false;
37
+
38
+ private config: ConfigOptions = { parseResponse: true };
39
+
40
+ private userAgent: string;
41
+
42
+ constructor(spec?: Oas, userAgent?: string) {
43
+ this.spec = spec;
44
+ this.userAgent = userAgent;
45
+ }
46
+
47
+ setSpec(spec: Oas) {
48
+ this.spec = spec;
49
+ }
50
+
51
+ setConfig(config: ConfigOptions) {
52
+ this.config = config;
53
+ return this;
54
+ }
55
+
56
+ setUserAgent(userAgent: string) {
57
+ this.userAgent = userAgent;
58
+ return this;
59
+ }
60
+
61
+ setAuth(...values: string[] | number[]) {
62
+ this.auth = values;
63
+ return this;
64
+ }
65
+
66
+ setServer(url: string, variables: Record<string, string | number> = {}) {
67
+ this.server = { url, variables };
68
+ return this;
69
+ }
70
+
71
+ async fetch(path: string, method: HttpMethods, body?: unknown, metadata?: Record<string, unknown>) {
72
+ const operation = this.spec.operation(path, method);
73
+
74
+ return this.fetchOperation(operation, body, metadata);
75
+ }
76
+
77
+ async fetchOperation(operation: Operation, body?: unknown, metadata?: Record<string, unknown>) {
78
+ return prepareParams(operation, body, metadata).then(params => {
79
+ const data = { ...params };
80
+
81
+ // If `sdk.server()` has been issued data then we need to do some extra work to figure out
82
+ // how to use that supplied server, and also handle any server variables that were sent
83
+ // alongside it.
84
+ if (this.server) {
85
+ const preparedServer = prepareServer(this.spec, this.server.url, this.server.variables);
86
+ if (preparedServer) {
87
+ data.server = preparedServer;
88
+ }
89
+ }
90
+
91
+ const har = oasToHar(this.spec, operation, data, prepareAuth(this.auth, operation));
92
+
93
+ return fetchHar(har, {
94
+ userAgent: this.userAgent,
95
+ files: data.files || {},
96
+ multipartEncoder: FormDataEncoder,
97
+ }).then((res: Response) => {
98
+ if (res.status >= 400 && res.status <= 599) {
99
+ throw res;
100
+ }
101
+
102
+ if (this.config.parseResponse === false) return res;
103
+
104
+ return parseResponse(res);
105
+ });
106
+ });
107
+ }
108
+ }
@@ -1,10 +1,8 @@
1
- // Nabbed from here:
2
- // https://github.com/readmeio/api-explorer/blob/77b90ebed4673f168354cdcd730e34b7ee016360/packages/api-explorer/src/lib/parse-response.js#L13-L30
3
- const {
4
- utils: { matchesMimeType },
5
- } = require('oas');
1
+ import { utils } from 'oas';
6
2
 
7
- module.exports = async function getResponseBody(response) {
3
+ const { matchesMimeType } = utils;
4
+
5
+ export default async function getResponseBody(response: Response) {
8
6
  const contentType = response.headers.get('Content-Type');
9
7
  const isJSON = contentType && (matchesMimeType.json(contentType) || matchesMimeType.wildcard(contentType));
10
8
 
@@ -19,4 +17,4 @@ module.exports = async function getResponseBody(response) {
19
17
  }
20
18
 
21
19
  return responseBody;
22
- };
20
+ }
@@ -0,0 +1,85 @@
1
+ /* eslint-disable no-underscore-dangle */
2
+ import type { Operation } from 'oas';
3
+
4
+ type SecurityType = 'Basic' | 'Bearer' | 'Query' | 'Header' | 'Cookie' | 'OAuth2' | 'http' | 'apiKey';
5
+
6
+ export default function prepareAuth(authKey: (number | string)[], operation: Operation) {
7
+ if (authKey.length === 0) {
8
+ return {};
9
+ }
10
+
11
+ const preparedAuth: Record<
12
+ string,
13
+ | string
14
+ | number
15
+ | {
16
+ user: string | number;
17
+ pass: string | number;
18
+ }
19
+ > = {};
20
+
21
+ const security = operation.prepareSecurity();
22
+
23
+ const securitySchemes = Object.keys(security);
24
+ if (securitySchemes.length === 0) {
25
+ // If there's no auth configured on this operation, don't prepare anything (even if it was
26
+ // supplied by the user).
27
+ return {};
28
+ }
29
+
30
+ const securityType = securitySchemes[0] as SecurityType;
31
+
32
+ const schemes = security[securityType];
33
+
34
+ if (schemes.length > 1) {
35
+ throw new Error("Sorry, this API currently requires multiple forms of authentication which we don't yet support.");
36
+ }
37
+
38
+ const scheme = schemes[0];
39
+
40
+ switch (scheme.type) {
41
+ case 'http':
42
+ if (scheme.scheme === 'basic') {
43
+ preparedAuth[scheme._key] = {
44
+ user: authKey[0],
45
+ pass: authKey.length === 2 ? authKey[1] : '',
46
+ };
47
+ } else if (scheme.scheme === 'bearer') {
48
+ if (authKey.length > 1) {
49
+ throw new Error(
50
+ 'Multiple auth tokens were supplied for the auth on this endpoint, but only a single token is needed.'
51
+ );
52
+ }
53
+
54
+ preparedAuth[scheme._key] = authKey[0];
55
+ }
56
+ break;
57
+
58
+ case 'oauth2':
59
+ if (authKey.length > 1) {
60
+ throw new Error(
61
+ 'Multiple auth tokens were supplied for the auth on this endpoint, but only a single token is needed.'
62
+ );
63
+ }
64
+
65
+ preparedAuth[scheme._key] = authKey[0];
66
+ break;
67
+
68
+ case 'apiKey':
69
+ if (authKey.length > 1) {
70
+ throw new Error(
71
+ 'Multiple auth keys were supplied for the auth on this endpoint, but only a single key is needed.'
72
+ );
73
+ }
74
+
75
+ if (scheme.in === 'query' || scheme.in === 'header' || scheme.in === 'cookie') {
76
+ preparedAuth[scheme._key] = authKey[0];
77
+ }
78
+ break;
79
+
80
+ default:
81
+ throw new Error(`Sorry, this API currently supports a scheme, ${scheme.type}, that we don't yet support.`);
82
+ }
83
+
84
+ return preparedAuth;
85
+ }
@@ -0,0 +1,338 @@
1
+ import type { Operation } from 'oas';
2
+ import type { ParameterObject, SchemaObject } from 'oas/@types/rmoas.types';
3
+ import type { ReadStream } from 'fs';
4
+
5
+ import lodashMerge from 'lodash.merge';
6
+ import fs from 'fs/promises';
7
+ import path from 'path';
8
+ import stream from 'stream';
9
+ import getStream from 'get-stream';
10
+ import datauri from 'datauri/sync';
11
+ import DatauriParser from 'datauri/parser';
12
+ import getJSONSchemaDefaults from './getJSONSchemaDefaults';
13
+
14
+ /**
15
+ * Extract all available parameters from an operations Parameter Object into a digestable array
16
+ * that we can use to apply to the request.
17
+ *
18
+ * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameterObject}
19
+ * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterObject}
20
+ * @param parameters
21
+ */
22
+ function digestParameters(parameters: ParameterObject[]): Record<string, ParameterObject> {
23
+ return parameters.reduce((prev, param) => {
24
+ if ('$ref' in param || 'allOf' in param || 'anyOf' in param || 'oneOf' in param) {
25
+ throw new Error(`The OpenAPI document for this operation wasn't dereferenced before processing.`);
26
+ } else if (param.name in prev) {
27
+ throw new Error(
28
+ `The operation you are using has the same parameter, ${param.name}, spread across multiple entry points. We unfortunately can't handle this right now.`
29
+ );
30
+ }
31
+
32
+ return Object.assign(prev, { [param.name]: param });
33
+ }, {});
34
+ }
35
+
36
+ // https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_isempty
37
+ function isEmpty(obj: any) {
38
+ return [Object, Array].includes((obj || {}).constructor) && !Object.entries(obj || {}).length;
39
+ }
40
+
41
+ function isObject(thing: any) {
42
+ if (thing instanceof stream.Readable) {
43
+ return false;
44
+ }
45
+
46
+ return typeof thing === 'object' && thing !== null && !Array.isArray(thing);
47
+ }
48
+
49
+ function isPrimitive(obj: any) {
50
+ return typeof obj === null || typeof obj === 'number' || typeof obj === 'string';
51
+ }
52
+
53
+ function merge(src: any, target: any) {
54
+ if (Array.isArray(target)) {
55
+ // @todo we need to add support for merging array defaults with array body/metadata arguments
56
+ return target;
57
+ } else if (!isObject(target)) {
58
+ return target;
59
+ }
60
+
61
+ return lodashMerge(src, target);
62
+ }
63
+
64
+ /**
65
+ * Ingest a file path or readable stream into a common object that we can later use to process it
66
+ * into a parameters object for making an API request.
67
+ *
68
+ * @param paramName
69
+ * @param file
70
+ */
71
+ function processFile(
72
+ paramName: string,
73
+ file: string | ReadStream
74
+ ): Promise<{ paramName: string; base64: string; filename: string; buffer: Buffer }> {
75
+ if (typeof file === 'string') {
76
+ // In order to support relative pathed files, we need to attempt to resolve them.
77
+ const resolvedFile = path.resolve(file);
78
+
79
+ return fs
80
+ .stat(resolvedFile)
81
+ .then(() => datauri(resolvedFile))
82
+ .then(fileMetadata => {
83
+ const payloadFilename = encodeURIComponent(path.basename(resolvedFile));
84
+
85
+ return {
86
+ paramName,
87
+ base64: fileMetadata.content.replace(';base64', `;name=${payloadFilename};base64`),
88
+ filename: payloadFilename,
89
+ buffer: fileMetadata.buffer,
90
+ };
91
+ })
92
+ .catch(err => {
93
+ if (err.code === 'ENOENT') {
94
+ // It's less than ideal for us to handle files that don't exist like this but because
95
+ // `file` is a string it might actually be the full text contents of the file and not
96
+ // actually a path.
97
+ //
98
+ // We also can't really regex to see if `file` *looks*` like a path because one should be
99
+ // able to pass in a relative `owlbert.png` (instead of `./owlbert.png`) and though that
100
+ // doesn't *look* like a path, it is one that should still work.
101
+ return undefined;
102
+ }
103
+
104
+ throw err;
105
+ });
106
+ } else if (file instanceof stream.Readable) {
107
+ return getStream.buffer(file).then(buffer => {
108
+ const filePath = file.path as string;
109
+ const parser = new DatauriParser();
110
+ const base64 = parser.format(filePath, buffer).content;
111
+ const payloadFilename = encodeURIComponent(path.basename(filePath));
112
+
113
+ return {
114
+ paramName,
115
+ base64: base64.replace(';base64', `;name=${payloadFilename};base64`),
116
+ filename: payloadFilename,
117
+ buffer,
118
+ };
119
+ });
120
+ }
121
+
122
+ return Promise.reject(
123
+ new TypeError(
124
+ paramName
125
+ ? `The data supplied for the \`${paramName}\` request body parameter is not a file handler that we support.`
126
+ : `The data supplied for the request body payload is not a file handler that we support.`
127
+ )
128
+ );
129
+ }
130
+
131
+ /**
132
+ * With potentially supplied body and/or metadata we need to run through them against a given API
133
+ * operation to see what's what and prepare any available parameters to be used in an API request
134
+ * with `@readme/oas-to-har`.
135
+ *
136
+ * @param operation
137
+ * @param body
138
+ * @param metadata
139
+ */
140
+ export default async function prepareParams(operation: Operation, body?: unknown, metadata?: Record<string, unknown>) {
141
+ let metadataIntersected = false;
142
+ const digestedParameters = digestParameters(operation.getParameters());
143
+ const hasDigestedParams = !!Object.keys(digestedParameters).length;
144
+ const jsonSchema = operation.getParametersAsJsonSchema();
145
+
146
+ if (!jsonSchema && (body !== undefined || metadata !== undefined)) {
147
+ throw new Error(
148
+ "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."
149
+ );
150
+ }
151
+
152
+ const jsonSchemaDefaults = jsonSchema ? getJSONSchemaDefaults(jsonSchema) : {};
153
+
154
+ const params: {
155
+ body?: any;
156
+ cookie?: Record<string, string | number | boolean>;
157
+ files?: Record<string, Buffer>;
158
+ formData?: any;
159
+ header?: Record<string, string | number | boolean>;
160
+ path?: Record<string, string | number | boolean>;
161
+ query?: Record<string, string | number | boolean>;
162
+ server?: {
163
+ selected: number;
164
+ variables: Record<string, string | number>;
165
+ };
166
+ } = jsonSchemaDefaults;
167
+
168
+ // If a body argument was supplied we need to do a bit of work to see if it's actually a body
169
+ // argument or metadata because the library lets you supply either a body, metadata, or body with
170
+ // metadata.
171
+ if (typeof body !== 'undefined') {
172
+ if (Array.isArray(body) || isPrimitive(body)) {
173
+ // If the body param is an array or a primitive then we know it's absolutely a body because
174
+ // metadata can only ever be undefined or an object.
175
+ params.body = merge(params.body, body);
176
+ } else if (typeof metadata === 'undefined') {
177
+ // No metadata was explicitly provided so we need to analyze the body to determine if it's a
178
+ // body or should be actually be treated as metadata.
179
+ if (!hasDigestedParams) {
180
+ // If no parameters were able to be digested it's because this operation has none so then
181
+ // we just have to assume that what the user supplied was for a body and not metadata. This
182
+ // might lead to unwanted false positives if the API definition isn't accurate but short of
183
+ // throwing an error (one that the user would have no control over resolving anyways) there
184
+ // isn't anything we can do about it.
185
+ params.body = merge(params.body, body);
186
+ } else {
187
+ const intersection = Object.keys(body).filter(value => Object.keys(digestedParameters).includes(value)).length;
188
+ if (intersection && intersection / Object.keys(body).length > 0.25) {
189
+ /* eslint-disable no-param-reassign */
190
+ // If more than 25% of the body intersects with the parameters that we've got on hand,
191
+ // then we should treat it as a metadata object and organize into parameters.
192
+ metadataIntersected = true;
193
+ metadata = merge(params.body, body) as Record<string, unknown>;
194
+ body = undefined;
195
+ /* eslint-enable no-param-reassign */
196
+ } else {
197
+ // For all other cases, we should just treat the supplied body as a body.
198
+ params.body = merge(params.body, body);
199
+ }
200
+ }
201
+ } else {
202
+ // Body and metadata were both supplied.
203
+ params.body = merge(params.body, body);
204
+ }
205
+ }
206
+
207
+ if (!operation.hasRequestBody()) {
208
+ // If this operation doesn't have any documented request body then we shouldn't be sending
209
+ // anything.
210
+ delete params.body;
211
+ } else {
212
+ if (!('body' in params)) params.body = {};
213
+
214
+ // We need to retrieve the request body for this operation to search for any `binary` format
215
+ // data that the user wants to send so we know what we need to prepare for the final API
216
+ // request.
217
+ const payloadJsonSchema = jsonSchema.find(js => js.type === 'body');
218
+ if (payloadJsonSchema) {
219
+ if (!params.files) params.files = {};
220
+
221
+ const conversions = [];
222
+
223
+ // @todo add support for `type: array`, `oneOf` and `anyOf`
224
+ if (payloadJsonSchema.schema?.properties) {
225
+ Object.entries(payloadJsonSchema.schema?.properties)
226
+ .filter(([, schema]: [string, SchemaObject]) => schema?.format === 'binary')
227
+ .filter(([prop]) => Object.keys(params.body).includes(prop))
228
+ .forEach(([prop]) => {
229
+ conversions.push(processFile(prop, params.body[prop]));
230
+ });
231
+ } else if (payloadJsonSchema.schema?.type === 'string') {
232
+ if (payloadJsonSchema.schema?.format === 'binary') {
233
+ conversions.push(processFile(undefined, params.body));
234
+ }
235
+ }
236
+
237
+ await Promise.all(conversions)
238
+ .then(fileMetadata => fileMetadata.filter(Boolean))
239
+ .then(fm => {
240
+ fm.forEach(fileMetadata => {
241
+ if (!fileMetadata) {
242
+ // If we don't have any metadata here it's because the file we have is likely
243
+ // the full string content of the file so since we don't have any filenames to
244
+ // work with we shouldn't do any additional handling to the `body` or `files`
245
+ // parameters.
246
+ return;
247
+ }
248
+
249
+ if (fileMetadata.paramName) {
250
+ params.body[fileMetadata.paramName] = fileMetadata.base64;
251
+ } else {
252
+ params.body = fileMetadata.base64;
253
+ }
254
+
255
+ params.files[fileMetadata.filename] = fileMetadata.buffer;
256
+ });
257
+ });
258
+ }
259
+ }
260
+
261
+ // Form data should be placed within `formData` instead of `body` for it to properly get picked
262
+ // up by `fetch-har`.
263
+ if (operation.isFormUrlEncoded()) {
264
+ params.formData = merge(params.formData, params.body);
265
+ delete params.body;
266
+ }
267
+
268
+ // Only spend time trying to organize metadata into parameters if we were able to digest
269
+ // parameters out of the operation schema. If we couldn't digest anything, but metadata was
270
+ // supplied then we wouldn't know how to send it in the request!
271
+ if (hasDigestedParams) {
272
+ if (!('cookie' in params)) params.cookie = {};
273
+ if (!('header' in params)) params.header = {};
274
+ if (!('path' in params)) params.path = {};
275
+ if (!('query' in params)) params.query = {};
276
+
277
+ Object.entries(digestedParameters).forEach(([paramName, param]) => {
278
+ let value: any;
279
+ if (typeof metadata === 'object' && !isEmpty(metadata) && paramName in metadata) {
280
+ value = metadata[paramName];
281
+ }
282
+
283
+ if (value === undefined) {
284
+ return;
285
+ }
286
+
287
+ /* eslint-disable no-param-reassign */
288
+ switch (param.in) {
289
+ case 'path':
290
+ params.path[paramName] = value;
291
+ delete metadata[paramName];
292
+ break;
293
+ case 'query':
294
+ params.query[paramName] = value;
295
+ delete metadata[paramName];
296
+ break;
297
+ case 'header':
298
+ params.header[paramName] = value;
299
+ delete metadata[paramName];
300
+ break;
301
+ case 'cookie':
302
+ params.cookie[paramName] = value;
303
+ delete metadata[paramName];
304
+ break;
305
+ default: // no-op
306
+ }
307
+ /* eslint-enable no-param-reassign */
308
+
309
+ // Because a user might have sent just a metadata object, we want to make sure that we filter
310
+ // out anything that they sent that is a parameter from also being sent as part of a form
311
+ // data payload for `x-www-form-urlencoded` requests.
312
+ if (metadataIntersected && operation.isFormUrlEncoded()) {
313
+ if (paramName in params.formData) {
314
+ delete params.formData[paramName];
315
+ }
316
+ }
317
+ });
318
+
319
+ // If there's any leftover metadata that hasn't been moved into form data for this request we
320
+ // need to move it or else it'll get tossed.
321
+ if (!isEmpty(metadata)) {
322
+ if (operation.isFormUrlEncoded()) {
323
+ params.formData = merge(params.formData, metadata);
324
+ } else {
325
+ // Any other remaining unused metadata will be unused because we don't know where to place
326
+ // it in the request.
327
+ }
328
+ }
329
+ }
330
+
331
+ ['body', 'cookie', 'files', 'formData', 'header', 'path', 'query'].forEach((type: keyof typeof params) => {
332
+ if (type in params && isEmpty(params[type])) {
333
+ delete params[type];
334
+ }
335
+ });
336
+
337
+ return params;
338
+ }
@@ -1,4 +1,6 @@
1
- function stripTrailingSlash(url) {
1
+ import type Oas from 'oas';
2
+
3
+ function stripTrailingSlash(url: string) {
2
4
  if (url[url.length - 1] === '/') {
3
5
  return url.slice(0, -1);
4
6
  }
@@ -7,15 +9,14 @@ function stripTrailingSlash(url) {
7
9
  }
8
10
 
9
11
  /**
10
- * With an SDK server config and an instance of OAS we should extract and prepare the server and any server variables
11
- * to be supplied to `@readme/oas-to-har`.
12
+ * With an SDK server config and an instance of OAS we should extract and prepare the server and
13
+ * any server variables to be supplied to `@readme/oas-to-har`.
12
14
  *
13
- * @param {Oas} spec
14
- * @param {String} url
15
- * @param {Object} variables
16
- * @returns {Object|Boolean}
15
+ * @param spec
16
+ * @param url
17
+ * @param variables
17
18
  */
18
- module.exports = (spec, url, variables = {}) => {
19
+ export default function prepareServer(spec: Oas, url: string, variables: Record<string, string | number> = {}) {
19
20
  let serverIdx;
20
21
  const sanitizedUrl = stripTrailingSlash(url);
21
22
  (spec.api.servers || []).forEach((server, i) => {
@@ -24,9 +25,9 @@ module.exports = (spec, url, variables = {}) => {
24
25
  }
25
26
  });
26
27
 
27
- // If we were able to find the passed in server in the OAS servers, we should use that! If we couldn't
28
- // and server variables were passed in we should try our best to handle that, otherwise we should ignore
29
- // the passed in server and use whever the default from the OAS is.
28
+ // If we were able to find the passed in server in the OAS servers, we should use that! If we
29
+ // couldn't and server variables were passed in we should try our best to handle that, otherwise
30
+ // we should ignore the passed in server and use whever the default from the OAS is.
30
31
  if (serverIdx) {
31
32
  return {
32
33
  selected: serverIdx,
@@ -47,4 +48,4 @@ module.exports = (spec, url, variables = {}) => {
47
48
  }
48
49
 
49
50
  return false;
50
- };
51
+ }