-
Notifications
You must be signed in to change notification settings - Fork 760
/
Copy pathindex.js
executable file
·419 lines (353 loc) · 12.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import cookie from 'cookie';
import { isPlainObject } from 'is-plain-object';
import { escapeRegExp } from 'ramda-adjunct';
import { ApiDOMStructuredError } from '@swagger-api/apidom-error';
import { url } from '@swagger-api/apidom-reference/configuration/empty';
import { DEFAULT_BASE_URL, DEFAULT_OPENAPI_3_SERVER } from '../constants.js';
import stockHttp from '../http/index.js';
import { serializeRequest } from '../http/serializers/request/index.js';
import SWAGGER2_PARAMETER_BUILDERS from './swagger2/parameter-builders.js';
import * as OAS3_PARAMETER_BUILDERS from './oas3/parameter-builders.js';
import oas3BuildRequest from './oas3/build-request.js';
import swagger2BuildRequest from './swagger2/build-request.js';
import { getOperationRaw, idFromPathMethodLegacy } from '../helpers/index.js';
import { isOpenAPI3 } from '../helpers/openapi-predicates.js';
const arrayOrEmpty = (ar) => (Array.isArray(ar) ? ar : []);
/**
* `parseURIReference` function simulates the behavior of `node:url` parse function.
* New WHATWG URL API is not capable of parsing relative references natively,
* but can be adapter by utilizing the `base` parameter.
*/
const parseURIReference = (uriReference) => {
try {
return new URL(uriReference);
} catch {
const parsedURL = new URL(uriReference, DEFAULT_BASE_URL);
const pathname = String(uriReference).startsWith('/')
? parsedURL.pathname
: parsedURL.pathname.substring(1);
return {
hash: parsedURL.hash,
host: '',
hostname: '',
href: '',
origin: '',
password: '',
pathname,
port: '',
protocol: '',
search: parsedURL.search,
searchParams: parsedURL.searchParams,
};
}
};
class OperationNotFoundError extends ApiDOMStructuredError {}
const findParametersWithName = (name, parameters) => parameters.filter((p) => p.name === name);
// removes parameters that have duplicate 'in' and 'name' properties
const deduplicateParameters = (parameters) => {
const paramsMap = {};
parameters.forEach((p) => {
if (!paramsMap[p.in]) {
paramsMap[p.in] = {};
}
paramsMap[p.in][p.name] = p;
});
const dedupedParameters = [];
Object.keys(paramsMap).forEach((i) => {
Object.keys(paramsMap[i]).forEach((p) => {
dedupedParameters.push(paramsMap[i][p]);
});
});
return dedupedParameters;
};
// For stubbing in tests
export const self = {
buildRequest,
};
// Execute request, with the given operationId and parameters
// pathName/method or operationId is optional
export function execute({
http: userHttp,
fetch, // This is legacy
spec,
operationId,
pathName,
method,
parameters,
securities,
...extras
}) {
// Provide default fetch implementation
const http = userHttp || fetch || stockHttp; // Default to _our_ http
if (pathName && method && !operationId) {
operationId = idFromPathMethodLegacy(pathName, method);
}
const request = self.buildRequest({
spec,
operationId,
parameters,
securities,
http,
...extras,
});
if (request.body && (isPlainObject(request.body) || Array.isArray(request.body))) {
request.body = JSON.stringify(request.body);
}
// Build request and execute it
return http(request);
}
// Build a request, which can be handled by the `http.js` implementation.
export function buildRequest(options) {
const {
spec,
operationId,
responseContentType,
scheme,
requestInterceptor,
responseInterceptor,
contextUrl,
userFetch,
server,
serverVariables,
http,
signal,
} = options;
let { parameters, parameterBuilders } = options;
const specIsOAS3 = isOpenAPI3(spec);
if (!parameterBuilders) {
// user did not provide custom parameter builders
if (specIsOAS3) {
parameterBuilders = OAS3_PARAMETER_BUILDERS;
} else {
parameterBuilders = SWAGGER2_PARAMETER_BUILDERS;
}
}
// Set credentials with 'http.withCredentials' value
const credentials = http && http.withCredentials ? 'include' : 'same-origin';
// Base Template
let req = {
url: '',
credentials,
headers: {},
cookies: {},
};
if (signal) {
req.signal = signal;
}
if (requestInterceptor) {
req.requestInterceptor = requestInterceptor;
}
if (responseInterceptor) {
req.responseInterceptor = responseInterceptor;
}
if (userFetch) {
req.userFetch = userFetch;
}
const operationRaw = getOperationRaw(spec, operationId);
if (!operationRaw) {
throw new OperationNotFoundError(`Operation ${operationId} not found`);
}
const { operation = {}, method, pathName } = operationRaw;
const baseURL = baseUrl({
spec,
scheme,
contextUrl,
server,
serverVariables,
pathName,
method,
});
req.url += baseURL;
// Mostly for testing
if (!operationId) {
// Not removing req.cookies causes testing issues and would
// change our interface, so we're always sure to remove it.
// See the same statement lower down in this function for
// more context.
delete req.cookies;
return req;
}
req.url += pathName; // Have not yet replaced the path parameters
req.method = `${method}`.toUpperCase();
parameters = parameters || {};
const path = spec.paths[pathName] || {};
if (responseContentType) {
req.headers.accept = responseContentType;
}
const combinedParameters = deduplicateParameters(
[]
.concat(arrayOrEmpty(operation.parameters)) // operation parameters
.concat(arrayOrEmpty(path.parameters))
); // path parameters
// REVIEW: OAS3: have any key names or parameter shapes changed?
// Any new features that need to be plugged in here?
// Add values to request
combinedParameters.forEach((parameter) => {
const builder = parameterBuilders[parameter.in];
let value;
if (parameter.in === 'body' && parameter.schema && parameter.schema.properties) {
value = parameters;
}
value = parameter && parameter.name && parameters[parameter.name];
if (typeof value === 'undefined') {
// check for `name-in` formatted key
value = parameter && parameter.name && parameters[`${parameter.in}.${parameter.name}`];
} else if (findParametersWithName(parameter.name, combinedParameters).length > 1) {
// value came from `parameters[parameter.name]`
// check to see if this is an ambiguous parameter
// eslint-disable-next-line no-console
console.warn(
`Parameter '${parameter.name}' is ambiguous because the defined spec has more than one parameter with the name: '${parameter.name}' and the passed-in parameter values did not define an 'in' value.`
);
}
if (value === null) {
return;
}
if (typeof parameter.default !== 'undefined' && typeof value === 'undefined') {
value = parameter.default;
}
if (typeof value === 'undefined' && parameter.required && !parameter.allowEmptyValue) {
throw new Error(`Required parameter ${parameter.name} is not provided`);
}
if (
specIsOAS3 &&
parameter.schema &&
parameter.schema.type === 'object' &&
typeof value === 'string'
) {
try {
value = JSON.parse(value);
} catch (e) {
throw new Error('Could not parse object parameter value string as JSON');
}
}
if (builder) {
builder({
req,
parameter,
value,
operation,
spec,
baseURL,
});
}
});
// Do version-specific tasks, then return those results.
const versionSpecificOptions = { ...options, operation };
if (specIsOAS3) {
req = oas3BuildRequest(versionSpecificOptions, req);
} else {
// If not OAS3, then treat as Swagger2.
req = swagger2BuildRequest(versionSpecificOptions, req);
}
// If the cookie convenience object exists in our request,
// serialize its content and then delete the cookie object.
if (req.cookies && Object.keys(req.cookies).length) {
const cookieString = Object.keys(req.cookies).reduce((prev, cookieName) => {
const cookieValue = req.cookies[cookieName];
const prefix = prev ? '&' : '';
const stringified = cookie.serialize(cookieName, cookieValue);
return prev + prefix + stringified;
}, '');
req.headers.Cookie = cookieString;
}
if (req.cookies) {
// even if no cookies were defined, we need to remove
// the cookies key from our request, or many legacy
// tests will break.
delete req.cookies;
}
// Will add the query object into the URL, if it exists
// ... will also create a FormData instance, if multipart/form-data (eg: a file)
return serializeRequest(req);
}
const stripNonAlpha = (str) => (str ? str.replace(/\W/g, '') : null);
// be careful when modifying this! it is a publicly-exposed method.
export function baseUrl(obj) {
const specIsOAS3 = isOpenAPI3(obj.spec);
return specIsOAS3 ? oas3BaseUrl(obj) : swagger2BaseUrl(obj);
}
const isNonEmptyServerList = (value) => Array.isArray(value) && value.length > 0;
function oas3BaseUrl({ spec, pathName, method, server, contextUrl, serverVariables = {} }) {
let servers = [];
let selectedServerUrl = '';
let selectedServerObj;
// compute the servers (this will be taken care of by ApiDOM refrator plugins in future
const operationLevelServers = spec?.paths?.[pathName]?.[(method || '').toLowerCase()]?.servers;
const pathItemLevelServers = spec?.paths?.[pathName]?.servers;
const rootLevelServers = spec?.servers;
servers = isNonEmptyServerList(operationLevelServers) // eslint-disable-line no-nested-ternary
? operationLevelServers
: isNonEmptyServerList(pathItemLevelServers) // eslint-disable-line no-nested-ternary
? pathItemLevelServers
: isNonEmptyServerList(rootLevelServers)
? rootLevelServers
: [DEFAULT_OPENAPI_3_SERVER];
// pick the first server that matches the server url
if (server) {
selectedServerObj = servers.find((srv) => srv.url === server);
if (selectedServerObj) selectedServerUrl = server;
}
// default to the first server if we don't have one by now
if (!selectedServerUrl) {
[selectedServerObj] = servers;
selectedServerUrl = selectedServerObj.url;
}
if (selectedServerUrl.includes('{')) {
// do variable substitution
const varNames = extractServerVariableNames(selectedServerUrl);
varNames.forEach((variable) => {
if (selectedServerObj.variables && selectedServerObj.variables[variable]) {
// variable is defined in server
const variableDefinition = selectedServerObj.variables[variable];
const variableValue = serverVariables[variable] || variableDefinition.default;
const re = new RegExp(`{${escapeRegExp(variable)}}`, 'g');
selectedServerUrl = selectedServerUrl.replace(re, variableValue);
}
});
}
return buildOas3UrlWithContext(selectedServerUrl, contextUrl);
}
function buildOas3UrlWithContext(ourUrl = '', contextUrl = '') {
// relative server url should be resolved against contextUrl
const parsedUrl =
ourUrl && contextUrl
? parseURIReference(url.resolve(contextUrl, ourUrl))
: parseURIReference(ourUrl);
const parsedContextUrl = parseURIReference(contextUrl);
const computedScheme =
stripNonAlpha(parsedUrl.protocol) || stripNonAlpha(parsedContextUrl.protocol);
const computedHost = parsedUrl.host || parsedContextUrl.host;
const computedPath = parsedUrl.pathname;
let res;
if (computedScheme && computedHost) {
res = `${computedScheme}://${computedHost + computedPath}`;
// if last character is '/', trim it off
} else {
res = computedPath;
}
return res[res.length - 1] === '/' ? res.slice(0, -1) : res;
}
function extractServerVariableNames(serverURL) {
const match = serverURL.matchAll(/\{([^{}]+)}|([^{}]+)/g);
return Array.from(match, ([, variable]) => variable).filter(Boolean);
}
// Compose the baseUrl ( scheme + host + basePath )
function swagger2BaseUrl({ spec, scheme, contextUrl = '' }) {
const parsedContextUrl = parseURIReference(contextUrl);
const firstSchemeInSpec = Array.isArray(spec.schemes) ? spec.schemes[0] : null;
const computedScheme =
scheme || firstSchemeInSpec || stripNonAlpha(parsedContextUrl.protocol) || 'http';
const computedHost = spec.host || parsedContextUrl.host || '';
const computedPath = spec.basePath || '';
let res;
if (computedScheme && computedHost) {
// we have what we need for an absolute URL
res = `${computedScheme}://${computedHost + computedPath}`;
} else {
// if not, a relative URL will have to do
res = computedPath;
}
// If last character is '/', trim it off
return res[res.length - 1] === '/' ? res.slice(0, -1) : res;
}