-
Notifications
You must be signed in to change notification settings - Fork 238
/
index.ts
644 lines (594 loc) · 21.9 KB
/
index.ts
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
import fsRoutes from 'fs-routes';
import OpenAPIDefaultSetter from 'openapi-default-setter';
import OpenAPIRequestCoercer from 'openapi-request-coercer';
import OpenAPIRequestValidator from 'openapi-request-validator';
import OpenAPIResponseValidator from 'openapi-response-validator';
import OpenAPISchemaValidator from 'openapi-schema-validator';
import OpenAPISecurityHandler from 'openapi-security-handler';
import { OpenAPI, OpenAPIV2, OpenAPIV3 } from 'openapi-types';
import { Logger } from 'ts-log';
import BasePath from './src/BasePath';
import {
ConsoleDebugAdapterLogger,
IOpenAPIFramework,
OpenAPIFrameworkAPIContext,
OpenAPIFrameworkArgs,
OpenAPIFrameworkConstructorArgs,
OpenAPIFrameworkOperationContext,
OpenAPIFrameworkPathContext,
OpenAPIFrameworkPathObject,
OpenAPIFrameworkVisitor,
} from './src/types';
import {
addOperationTagToApiDoc,
allowsCoercionFeature,
allowsDefaultsFeature,
allowsFeatures,
allowsResponseValidationFeature,
allowsValidationFeature,
assertRegExpAndSecurity,
byDefault,
byDirectory,
byMethods,
byRoute,
byString,
copy,
getAdditionalFeatures,
getBasePathsFromServers,
getMethodDoc,
getSecurityDefinitionByPath,
handleFilePath,
handleYaml,
injectDependencies,
METHOD_ALIASES,
resolveParameterRefs,
resolveRequestBodyRefs,
resolveResponseRefs,
sortApiDocTags,
sortOperationDocTags,
toAbsolutePath,
withNoDuplicates,
} from './src/util';
export { OpenAPIRequestValidatorError } from 'openapi-request-validator';
export { OpenAPIResponseValidatorError } from 'openapi-response-validator';
export { SecurityHandlers } from 'openapi-security-handler';
export {
BasePath,
OpenAPIFrameworkArgs,
OpenAPIFrameworkConstructorArgs,
OpenAPIFrameworkPathContext,
OpenAPIFrameworkPathObject,
OpenAPIFrameworkAPIContext,
OpenAPIFrameworkOperationContext,
};
export default class OpenAPIFramework implements IOpenAPIFramework {
public readonly apiDoc;
public readonly basePaths: BasePath[];
public readonly featureType;
public readonly loggingPrefix;
public readonly name;
private customFormats;
private customKeywords;
private dependencies;
private enableObjectCoercion;
private errorTransformer;
private externalSchemas;
private features;
private originalApiDoc;
private operations;
private paths;
private pathsIgnore;
private pathSecurity;
private routesGlob;
private routesIndexFileRegExp;
private securityHandlers;
private validateApiDoc;
private validator;
private logger: Logger;
constructor(protected args = {} as OpenAPIFrameworkConstructorArgs) {
this.name = args.name;
this.featureType = args.featureType;
this.loggingPrefix = args.name ? `${this.name}: ` : '';
this.logger = args.logger ? args.logger : new ConsoleDebugAdapterLogger();
// monkey patch for node v6:
if (!this.logger.debug) {
this.logger.debug = this.logger.info;
}
[
{ name: 'apiDoc', required: true },
{ name: 'errorTransformer', type: 'function' },
{ name: 'externalSchemas', type: 'object' },
{ name: 'featureType', required: true },
{ name: 'name', required: true },
{ name: 'pathSecurity', class: Array, className: 'Array' },
{ name: 'securityHandlers', type: 'object' },
].forEach((arg) => {
if (arg.required && !(arg.name in args)) {
throw new Error(`${this.loggingPrefix}args.${arg.name} is required`);
}
if (arg.type && arg.name in args && typeof args[arg.name] !== arg.type) {
throw new Error(
`${this.loggingPrefix}args.${arg.name} must be a ${arg.type} when given`
);
}
if (
arg.class &&
arg.name in args &&
!(args[arg.name] instanceof arg.class)
) {
throw new Error(
`${this.loggingPrefix}args.${arg.name} must be an instance of ${arg.className} when given`
);
}
});
if (!args.paths && !args.operations) {
throw new Error(
`${this.loggingPrefix}args.paths and args.operations must not both be empty`
);
}
this.enableObjectCoercion = !!args.enableObjectCoercion;
this.originalApiDoc = handleYaml(handleFilePath(args.apiDoc));
this.apiDoc = copy(this.originalApiDoc);
this.basePaths = this.apiDoc.openapi
? getBasePathsFromServers(this.apiDoc.servers)
: [
new BasePath({
url: (this.apiDoc.basePath || '').replace(/\/$/, ''),
}),
];
this.validateApiDoc =
'validateApiDoc' in args ? !!args.validateApiDoc : true;
this.validator = new OpenAPISchemaValidator({
version:
(this.apiDoc as OpenAPIV3.Document).openapi ||
(this.apiDoc as OpenAPIV2.Document).swagger,
extensions: this.apiDoc[`x-${this.name}-schema-extension`],
});
this.customFormats = args.customFormats;
this.customKeywords = args.customKeywords;
this.dependencies = args.dependencies;
this.errorTransformer = args.errorTransformer;
this.externalSchemas = args.externalSchemas;
this.features = args.features;
this.operations = args.operations;
this.paths = args.paths;
this.pathsIgnore = args.pathsIgnore;
this.pathSecurity = Array.isArray(args.pathSecurity)
? args.pathSecurity
: [];
this.routesGlob = args.routesGlob;
this.routesIndexFileRegExp = args.routesIndexFileRegExp;
this.securityHandlers = args.securityHandlers;
this.pathSecurity.forEach(assertRegExpAndSecurity.bind(null, this));
if (this.validateApiDoc) {
const apiDocValidation = this.validator.validate(this.apiDoc);
if (apiDocValidation.errors.length) {
this.logger.error(
`${this.loggingPrefix}Validating schema before populating paths`
);
this.logger.error(
`${this.loggingPrefix}validation errors`,
JSON.stringify(apiDocValidation.errors, null, ' ')
);
throw new Error(
`${this.loggingPrefix}args.apiDoc was invalid. See the output.`
);
}
}
}
public async initialize(visitor: OpenAPIFrameworkVisitor) {
const securitySchemes = (this.apiDoc as OpenAPIV3.Document).openapi
? (this.apiDoc.components || {}).securitySchemes
: this.apiDoc.securityDefinitions;
const apiSecurityMiddleware =
this.securityHandlers && this.apiDoc.security && securitySchemes
? new OpenAPISecurityHandler({
securityDefinitions: securitySchemes,
securityHandlers: this.securityHandlers,
operationSecurity: this.apiDoc.security,
loggingKey: `${this.name}-security`,
})
: null;
let paths = [];
let routes: { path: string; module: any }[] = [];
const routesCheckMap = {};
if (this.paths) {
paths = [].concat(this.paths);
this.logger.debug(`${this.loggingPrefix}paths=`, paths);
for (let pathItem of paths) {
if (byString(pathItem)) {
pathItem = toAbsolutePath(pathItem);
if (!byDirectory(pathItem)) {
throw new Error(
`${this.loggingPrefix}args.paths contained a value that was not a path to a directory`
);
}
routes = routes.concat(
await Promise.all(
fsRoutes(pathItem, {
glob: this.routesGlob,
indexFileRegExp: this.routesIndexFileRegExp,
})
.filter((fsRoutesItem) => {
return this.pathsIgnore
? !this.pathsIgnore.test(fsRoutesItem.route)
: true;
})
.map(async (fsRoutesItem) => {
routesCheckMap[fsRoutesItem.route] = true;
// There are two cases to distinguish:
// - file is a CommonJS script, and `module.export` appears
// as `default` property
// - file is a ECMAScript module, and `export default` appears
// at top-level
const imported = await import(`file://${fsRoutesItem.path}`);
return {
path: fsRoutesItem.route,
module: imported.default ?? imported,
};
})
)
);
} else {
if (!pathItem.path || !pathItem.module) {
throw new Error(
`${this.loggingPrefix}args.paths must consist of strings or valid route specifications`
);
}
routes.push(pathItem);
}
}
routes = routes.sort(byRoute);
}
if (this.operations) {
const apiDocPaths = this.apiDoc.paths;
Object.keys(apiDocPaths).forEach((apiDocPathUrl) => {
const pathDoc = apiDocPaths[apiDocPathUrl];
const route = {
path: apiDocPathUrl,
module: Object.keys(pathDoc)
.filter(byMethods)
.reduce((acc, method) => {
const methodDoc = pathDoc[METHOD_ALIASES[method]];
const operationId = methodDoc.operationId;
if (operationId && operationId in this.operations) {
const operation = this.operations[operationId];
acc[METHOD_ALIASES[method]] = (() => {
/**
* We have two options:
*
* 1. the middleware gets bound + dependency injected, this may be breaking.
* 2. we pick the last middleware as the operation handler. This means we cannot support
* _after_ middlewares (though not a common express pattern)
*/
const innerFunction: any = Array.isArray(operation)
? operation.map((middleware) =>
middleware.bind({ dependencies: this.dependencies })
)
: operation.bind({ dependencies: this.dependencies });
innerFunction.apiDoc = methodDoc;
return innerFunction;
})();
} else if (operationId === undefined) {
this.logger.warn(
`${this.loggingPrefix}path ${apiDocPathUrl}, operation ${method} is missing an operationId`
);
} else {
this.logger.warn(
`${this.loggingPrefix}Operation ${operationId} not found in the operations parameter`
);
}
return acc;
}, {}),
};
if (routesCheckMap[route.path]) {
this.logger.warn(
`${this.loggingPrefix}Overriding path ${route.path} with handlers from operations`
);
const routeIndex = routes.findIndex((r) => r.path === route.path);
routes[routeIndex] = {
...routes[routeIndex],
...route,
module: {
...((routes[routeIndex] || {}).module || {}),
...(route.module || {}),
},
};
} else {
routes.push(route);
}
});
}
this.logger.debug(`${this.loggingPrefix}routes=`, routes);
// Check for duplicate routes
const dups = routes.filter((v, i, o) => {
if (i > 0 && v.path === o[i - 1].path) {
return v.path;
}
});
if (dups.length > 0) {
throw new Error(
`${this.loggingPrefix}args.paths produced duplicate urls for "${dups[0].path}"`
);
}
const getApiDoc = () => {
return copy(this.apiDoc);
};
routes.forEach((routeItem) => {
const route = routeItem.path;
this.logger.debug(`${this.loggingPrefix}setting up`, route);
const pathModule = injectDependencies(
routeItem.module.default || routeItem.module,
this.dependencies
);
// express path params start with :paramName
// openapi path params use {paramName}
const openapiPath = route;
// Do not make modifications to this.
const originalPathItem = this.originalApiDoc.paths[openapiPath] || {};
const pathDoc = this.apiDoc.paths[openapiPath] || {};
const pathParameters = pathDoc.parameters || [];
// push all parameters defined in the path module to the path parameter list
if (Array.isArray(pathModule.parameters)) {
[].push.apply(pathParameters, pathModule.parameters);
}
pathDoc.parameters = pathParameters;
this.apiDoc.paths[openapiPath] = pathDoc;
const methodsProcessed = {};
new Set(
Object.keys(pathModule).concat(Object.keys(pathDoc)).filter(byMethods)
).forEach((methodAlias) => {
const methodName = METHOD_ALIASES[methodAlias];
if (methodName in methodsProcessed) {
this.logger.warn(
`${this.loggingPrefix}${openapiPath}.${methodAlias} has already been defined as ${openapiPath}.${methodsProcessed[methodName]}. Ignoring the 2nd definition...`
);
return;
}
methodsProcessed[methodName] = methodAlias;
// operationHandler may be an array or a function.
const operationHandler =
pathModule[methodAlias] ||
routeItem.module[(pathDoc?.[methodAlias] || {}).operationId];
const operationDoc =
handleYaml(getMethodDoc(operationHandler)) || pathDoc[methodName];
// consumes is defined as property of each operation or entire document
// in Swagger 2.0. For OpenAPI 3.0 consumes mime types are defined as the
// key value(s) for each operation requestBody.content object.
const consumes =
operationDoc && Array.isArray(operationDoc.consumes)
? operationDoc.consumes
: operationDoc &&
operationDoc.requestBody &&
(operationDoc.requestBody.content ||
operationDoc.requestBody.$ref)
? Object.keys(
resolveRequestBodyRefs(
this,
operationDoc.requestBody,
this.apiDoc
).content
)
: Array.isArray(this.apiDoc.consumes)
? this.apiDoc.consumes
: [];
const operationContext: OpenAPIFrameworkOperationContext = {
additionalFeatures: getAdditionalFeatures(
this,
this.logger,
this.originalApiDoc,
originalPathItem,
pathModule,
operationDoc
),
allowsFeatures: allowsFeatures(
this,
this.apiDoc,
pathModule,
pathDoc,
operationDoc
),
apiDoc: this.apiDoc,
basePaths: this.basePaths,
consumes,
features: {},
methodName,
methodParameters: [],
operationDoc,
operationHandler,
path: openapiPath,
};
if (operationDoc) {
pathDoc[methodName] = operationDoc;
if (operationDoc.tags) {
sortOperationDocTags(operationDoc);
operationDoc.tags.forEach(
addOperationTagToApiDoc.bind(null, this.apiDoc)
);
}
if (operationContext.allowsFeatures) {
// add features
if (
operationDoc.responses &&
allowsResponseValidationFeature(
this,
this.apiDoc,
pathModule,
pathDoc,
operationDoc
)
) {
const ResponseValidatorClass =
this.features?.responseValidator || OpenAPIResponseValidator;
// add response validation feature
// it's invalid for a method doc to not have responses, but the post
// validation will pick it up, so this is almost always going to be added.
const responseValidator = new ResponseValidatorClass({
loggingKey: `${this.name}-response-validation`,
components: this.apiDoc.components,
definitions: this.apiDoc.definitions,
externalSchemas: this.externalSchemas,
errorTransformer: this.errorTransformer,
responses: resolveResponseRefs(
this,
operationDoc.responses,
this.apiDoc,
route
),
customFormats: this.customFormats,
});
operationContext.features.responseValidator = responseValidator;
}
const methodParameters = withNoDuplicates(
resolveParameterRefs(
this,
Array.isArray(operationDoc.parameters)
? pathParameters.concat(operationDoc.parameters)
: pathParameters,
this.apiDoc
)
);
operationContext.methodParameters = methodParameters;
const requestBody = resolveRequestBodyRefs(
this,
operationDoc.requestBody,
this.apiDoc
) as OpenAPIV3.RequestBodyObject;
if (methodParameters.length || operationDoc.requestBody) {
// defaults, coercion, and parameter validation middleware
if (
allowsValidationFeature(
this,
this.apiDoc,
pathModule,
pathDoc,
operationDoc
)
) {
const RequestValidatorClass =
this.features?.requestValidator || OpenAPIRequestValidator;
const requestValidator = new RequestValidatorClass({
errorTransformer: this.errorTransformer,
logger: this.logger,
parameters: methodParameters,
schemas: this.apiDoc.definitions, // v2
componentSchemas: this.apiDoc.components // v3
? this.apiDoc.components.schemas
: undefined,
externalSchemas: this.externalSchemas,
customFormats: this.customFormats,
customKeywords: this.customKeywords,
requestBody,
});
operationContext.features.requestValidator = requestValidator;
this.logger.debug(
`${this.loggingPrefix}request validator on for`,
methodName,
openapiPath
);
}
if (
allowsCoercionFeature(
this,
this.apiDoc,
pathModule,
pathDoc,
operationDoc
)
) {
const CoercerClass =
this.features?.coercer || OpenAPIRequestCoercer;
const coercer = new CoercerClass({
extensionBase: `x-${this.name}-coercion`,
loggingKey: `${this.name}-coercion`,
parameters: methodParameters,
requestBody,
enableObjectCoercion: this.enableObjectCoercion,
});
operationContext.features.coercer = coercer;
}
// no point in default feature if we don't have any parameters with defaults.
if (
methodParameters.filter(byDefault).length &&
allowsDefaultsFeature(
this,
this.apiDoc,
pathModule,
pathDoc,
operationDoc
)
) {
const DefaultSetterClass =
this.features?.defaultSetter || OpenAPIDefaultSetter;
const defaultSetter = new DefaultSetterClass({
parameters: methodParameters,
});
operationContext.features.defaultSetter = defaultSetter;
}
}
let securityFeature;
let securityDefinition;
if (this.securityHandlers && securitySchemes) {
if (operationDoc.security) {
securityDefinition = operationDoc.security;
} else if (this.pathSecurity.length) {
securityDefinition = getSecurityDefinitionByPath(
openapiPath,
this.pathSecurity
);
}
}
if (securityDefinition) {
pathDoc[methodName].security = securityDefinition;
const SecurityHandlerClass =
this.features?.securityHandler || OpenAPISecurityHandler;
securityFeature = new SecurityHandlerClass({
securityDefinitions: securitySchemes,
securityHandlers: this.securityHandlers,
operationSecurity: securityDefinition,
loggingKey: `${this.name}-security`,
});
} else if (apiSecurityMiddleware) {
securityFeature = apiSecurityMiddleware;
}
if (securityFeature) {
operationContext.features.securityHandler = securityFeature;
}
}
}
if (visitor.visitOperation) {
visitor.visitOperation(operationContext);
}
});
if (visitor.visitPath) {
visitor.visitPath({
basePaths: this.basePaths,
getApiDoc,
getPathDoc: () => copy(pathDoc),
});
}
});
sortApiDocTags(this.apiDoc);
if (this.validateApiDoc) {
const apiDocValidation = this.validator.validate(this.apiDoc);
if (apiDocValidation.errors.length) {
this.logger.error(
`${this.loggingPrefix}Validating schema after populating paths`
);
this.logger.error(
`${this.loggingPrefix}validation errors`,
JSON.stringify(apiDocValidation.errors, null, ' ')
);
throw new Error(
`${this.loggingPrefix}args.apiDoc was invalid after populating paths. See the output.`
);
}
}
if (visitor.visitApi) {
visitor.visitApi({
basePaths: this.basePaths,
getApiDoc,
});
}
}
}