@nestia/sdk 2.4.3 → 2.4.4
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.
- package/lib/INestiaConfig.d.ts +13 -0
- package/lib/analyses/ControllerAnalyzer.js +12 -1
- package/lib/analyses/ControllerAnalyzer.js.map +1 -1
- package/lib/analyses/PathAnalyzer.d.ts +2 -2
- package/lib/analyses/PathAnalyzer.js +27 -11
- package/lib/analyses/PathAnalyzer.js.map +1 -1
- package/lib/analyses/ReflectAnalyzer.js +11 -2
- package/lib/analyses/ReflectAnalyzer.js.map +1 -1
- package/lib/executable/internal/NestiaConfigLoader.js +5 -1
- package/lib/executable/internal/NestiaConfigLoader.js.map +1 -1
- package/lib/executable/sdk.js +11 -11
- package/lib/generates/SwaggerGenerator.js +16 -22
- package/lib/generates/SwaggerGenerator.js.map +1 -1
- package/lib/generates/internal/SwaggerSchemaGenerator.js +22 -15
- package/lib/generates/internal/SwaggerSchemaGenerator.js.map +1 -1
- package/lib/structures/ISwaggerComponents.d.ts +1 -1
- package/lib/structures/ISwaggerRoute.d.ts +3 -3
- package/package.json +5 -5
- package/src/INestiaConfig.ts +248 -234
- package/src/NestiaSdkApplication.ts +253 -253
- package/src/analyses/AccessorAnalyzer.ts +60 -60
- package/src/analyses/ConfigAnalyzer.ts +147 -147
- package/src/analyses/ControllerAnalyzer.ts +390 -379
- package/src/analyses/ExceptionAnalyzer.ts +115 -115
- package/src/analyses/GenericAnalyzer.ts +51 -51
- package/src/analyses/ImportAnalyzer.ts +138 -138
- package/src/analyses/PathAnalyzer.ts +110 -98
- package/src/analyses/ReflectAnalyzer.ts +11 -6
- package/src/analyses/SecurityAnalyzer.ts +20 -20
- package/src/executable/internal/CommandParser.ts +15 -15
- package/src/executable/internal/NestiaConfigLoader.ts +67 -67
- package/src/executable/internal/NestiaSdkCommand.ts +60 -60
- package/src/executable/sdk.ts +73 -73
- package/src/generates/E2eGenerator.ts +64 -64
- package/src/generates/SdkGenerator.ts +96 -96
- package/src/generates/SwaggerGenerator.ts +376 -372
- package/src/generates/internal/E2eFileProgrammer.ts +123 -123
- package/src/generates/internal/SdkDistributionComposer.ts +91 -91
- package/src/generates/internal/SdkDtoGenerator.ts +424 -424
- package/src/generates/internal/SdkFileProgrammer.ts +106 -106
- package/src/generates/internal/SdkImportWizard.ts +55 -55
- package/src/generates/internal/SdkRouteDirectory.ts +17 -17
- package/src/generates/internal/SdkSimulationProgrammer.ts +133 -133
- package/src/generates/internal/SdkTypeDefiner.ts +119 -119
- package/src/generates/internal/SwaggerSchemaGenerator.ts +18 -2
- package/src/generates/internal/SwaggerSchemaValidator.ts +198 -198
- package/src/index.ts +4 -4
- package/src/module.ts +2 -2
- package/src/structures/IErrorReport.ts +6 -6
- package/src/structures/INestiaProject.ts +13 -13
- package/src/structures/INormalizedInput.ts +20 -20
- package/src/structures/ISwagger.ts +91 -91
- package/src/structures/ISwaggerComponents.ts +29 -29
- package/src/structures/ISwaggerError.ts +8 -8
- package/src/structures/ISwaggerInfo.ts +80 -80
- package/src/structures/ISwaggerLazyProperty.ts +7 -7
- package/src/structures/ISwaggerLazySchema.ts +7 -7
- package/src/structures/ISwaggerRoute.ts +51 -51
- package/src/structures/ISwaggerSecurityScheme.ts +65 -65
- package/src/structures/ITypeTuple.ts +6 -6
- package/src/structures/MethodType.ts +5 -5
- package/src/structures/ParamCategory.ts +1 -1
- package/src/structures/TypeEntry.ts +22 -22
- package/src/utils/ArrayUtil.ts +26 -26
- package/src/utils/FileRetriever.ts +22 -22
- package/src/utils/ImportDictionary.ts +125 -125
- package/src/utils/MapUtil.ts +14 -14
- package/src/utils/PathUtil.ts +10 -10
- package/src/utils/SourceFinder.ts +66 -66
- package/src/utils/StripEnums.ts +5 -5
|
@@ -1,372 +1,376 @@
|
|
|
1
|
-
import fs from "fs";
|
|
2
|
-
import path from "path";
|
|
3
|
-
import { Singleton } from "tstl/thread/Singleton";
|
|
4
|
-
import ts from "typescript";
|
|
5
|
-
import typia, { IJsonApplication, IJsonComponents } from "typia";
|
|
6
|
-
import { MetadataCollection } from "typia/lib/factories/MetadataCollection";
|
|
7
|
-
import { JsonApplicationProgrammer } from "typia/lib/programmers/json/JsonApplicationProgrammer";
|
|
8
|
-
|
|
9
|
-
import { INestiaConfig } from "../INestiaConfig";
|
|
10
|
-
import { IRoute } from "../structures/IRoute";
|
|
11
|
-
import { ISwagger } from "../structures/ISwagger";
|
|
12
|
-
import { ISwaggerError } from "../structures/ISwaggerError";
|
|
13
|
-
import { ISwaggerInfo } from "../structures/ISwaggerInfo";
|
|
14
|
-
import { ISwaggerLazyProperty } from "../structures/ISwaggerLazyProperty";
|
|
15
|
-
import { ISwaggerLazySchema } from "../structures/ISwaggerLazySchema";
|
|
16
|
-
import { ISwaggerRoute } from "../structures/ISwaggerRoute";
|
|
17
|
-
import { ISwaggerSecurityScheme } from "../structures/ISwaggerSecurityScheme";
|
|
18
|
-
import { FileRetriever } from "../utils/FileRetriever";
|
|
19
|
-
import { MapUtil } from "../utils/MapUtil";
|
|
20
|
-
import { SwaggerSchemaGenerator } from "./internal/SwaggerSchemaGenerator";
|
|
21
|
-
|
|
22
|
-
export namespace SwaggerGenerator {
|
|
23
|
-
export interface IProps {
|
|
24
|
-
config: INestiaConfig.ISwaggerConfig;
|
|
25
|
-
checker: ts.TypeChecker;
|
|
26
|
-
collection: MetadataCollection;
|
|
27
|
-
lazySchemas: Array<ISwaggerLazySchema>;
|
|
28
|
-
lazyProperties: Array<ISwaggerLazyProperty>;
|
|
29
|
-
errors: ISwaggerError[];
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export const generate =
|
|
33
|
-
(checker: ts.TypeChecker) =>
|
|
34
|
-
(config: INestiaConfig.ISwaggerConfig) =>
|
|
35
|
-
async (routeList: IRoute[]): Promise<void> => {
|
|
36
|
-
console.log("Generating Swagger Documents");
|
|
37
|
-
|
|
38
|
-
// VALIDATE SECURITY
|
|
39
|
-
validate_security(config)(routeList);
|
|
40
|
-
|
|
41
|
-
// PREPARE ASSETS
|
|
42
|
-
const parsed: path.ParsedPath = path.parse(config.output);
|
|
43
|
-
const directory: string = path.dirname(parsed.dir);
|
|
44
|
-
if (fs.existsSync(directory) === false)
|
|
45
|
-
try {
|
|
46
|
-
await fs.promises.mkdir(directory);
|
|
47
|
-
} catch {}
|
|
48
|
-
if (fs.existsSync(directory) === false)
|
|
49
|
-
throw new Error(
|
|
50
|
-
`Error on NestiaApplication.swagger(): failed to create output directory: ${directory}`,
|
|
51
|
-
);
|
|
52
|
-
|
|
53
|
-
const location: string = !!parsed.ext
|
|
54
|
-
? path.resolve(config.output)
|
|
55
|
-
: path.join(path.resolve(config.output), "swagger.json");
|
|
56
|
-
|
|
57
|
-
const collection: MetadataCollection = new MetadataCollection({
|
|
58
|
-
replace: MetadataCollection.replace,
|
|
59
|
-
});
|
|
60
|
-
|
|
61
|
-
// CONSTRUCT SWAGGER DOCUMENTS
|
|
62
|
-
const errors: ISwaggerError[] = [];
|
|
63
|
-
const lazySchemas: Array<ISwaggerLazySchema> = [];
|
|
64
|
-
const lazyProperties: Array<ISwaggerLazyProperty> = [];
|
|
65
|
-
const swagger: ISwagger = await initialize(config);
|
|
66
|
-
const pathDict: Map<string, Record<string, ISwaggerRoute>> = new Map();
|
|
67
|
-
|
|
68
|
-
for (const route of routeList) {
|
|
69
|
-
if (route.jsDocTags.find((tag) => tag.name === "internal")) continue;
|
|
70
|
-
|
|
71
|
-
const path: Record<string, ISwaggerRoute> = MapUtil.take(
|
|
72
|
-
pathDict,
|
|
73
|
-
get_path(route.path, route.parameters),
|
|
74
|
-
() => ({}),
|
|
75
|
-
);
|
|
76
|
-
path[route.method.toLowerCase()] = generate_route({
|
|
77
|
-
config,
|
|
78
|
-
checker,
|
|
79
|
-
collection,
|
|
80
|
-
lazySchemas,
|
|
81
|
-
lazyProperties,
|
|
82
|
-
errors,
|
|
83
|
-
})(route);
|
|
84
|
-
}
|
|
85
|
-
swagger.paths = {};
|
|
86
|
-
for (const [path, routes] of pathDict) swagger.paths[path] = routes;
|
|
87
|
-
|
|
88
|
-
// FILL JSON-SCHEMAS
|
|
89
|
-
const application: IJsonApplication = JsonApplicationProgrammer.write({
|
|
90
|
-
purpose: "swagger",
|
|
91
|
-
})(lazySchemas.map(({ metadata }) => metadata));
|
|
92
|
-
swagger.components = {
|
|
93
|
-
...(swagger.components ?? {}),
|
|
94
|
-
...(application.components ?? {}),
|
|
95
|
-
};
|
|
96
|
-
lazySchemas.forEach(({ schema }, index) => {
|
|
97
|
-
Object.assign(schema, application.schemas[index]!);
|
|
98
|
-
});
|
|
99
|
-
for (const p of lazyProperties)
|
|
100
|
-
Object.assign(
|
|
101
|
-
p.schema,
|
|
102
|
-
(
|
|
103
|
-
application.components.schemas?.[
|
|
104
|
-
p.object
|
|
105
|
-
] as IJsonComponents.IObject
|
|
106
|
-
)?.properties[p.property],
|
|
107
|
-
);
|
|
108
|
-
|
|
109
|
-
// CONFIGURE SECURITY
|
|
110
|
-
if (config.security) fill_security(config.security, swagger);
|
|
111
|
-
|
|
112
|
-
// REPORT ERRORS
|
|
113
|
-
if (errors.length) {
|
|
114
|
-
for (const e of errors)
|
|
115
|
-
console.error(
|
|
116
|
-
`${path.relative(e.route.location, process.cwd())}:${
|
|
117
|
-
e.route.symbol.class
|
|
118
|
-
}.${e.route.symbol.function}:${
|
|
119
|
-
e.from
|
|
120
|
-
} - error TS(@nestia/sdk): invalid type detected.\n\n` +
|
|
121
|
-
e.messages.map((m) => ` - ${m}`).join("\n"),
|
|
122
|
-
"\n\n",
|
|
123
|
-
);
|
|
124
|
-
throw new TypeError("Invalid type detected");
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
// DO GENERATE
|
|
128
|
-
await fs.promises.writeFile(
|
|
129
|
-
location,
|
|
130
|
-
!config.beautify
|
|
131
|
-
? JSON.stringify(swagger)
|
|
132
|
-
: JSON.stringify(
|
|
133
|
-
swagger,
|
|
134
|
-
null,
|
|
135
|
-
typeof config.beautify === "number" ? config.beautify : 2,
|
|
136
|
-
),
|
|
137
|
-
"utf8",
|
|
138
|
-
);
|
|
139
|
-
};
|
|
140
|
-
|
|
141
|
-
const validate_security =
|
|
142
|
-
(config: INestiaConfig.ISwaggerConfig) =>
|
|
143
|
-
(routeList: IRoute[]): void | never => {
|
|
144
|
-
const securityMap: Map<
|
|
145
|
-
string,
|
|
146
|
-
{ scheme: ISwaggerSecurityScheme; scopes: Set<string> }
|
|
147
|
-
> = new Map();
|
|
148
|
-
for (const [key, value] of Object.entries(config.security ?? {}))
|
|
149
|
-
securityMap.set(key, {
|
|
150
|
-
scheme: emend_security(value),
|
|
151
|
-
scopes:
|
|
152
|
-
value.type === "oauth2"
|
|
153
|
-
? new Set([
|
|
154
|
-
...Object.keys(value.flows.authorizationCode?.scopes ?? {}),
|
|
155
|
-
...Object.keys(value.flows.implicit?.scopes ?? {}),
|
|
156
|
-
...Object.keys(value.flows.password?.scopes ?? {}),
|
|
157
|
-
...Object.keys(value.flows.clientCredentials?.scopes ?? {}),
|
|
158
|
-
])
|
|
159
|
-
: new Set(),
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
const validate =
|
|
163
|
-
(reporter: (str: string) => void) =>
|
|
164
|
-
(key: string, scopes: string[]) => {
|
|
165
|
-
const security = securityMap.get(key);
|
|
166
|
-
if (security === undefined)
|
|
167
|
-
return reporter(`target security scheme "${key}" does not exists.`);
|
|
168
|
-
else if (scopes.length === 0) return;
|
|
169
|
-
else if (security.scheme.type !== "oauth2")
|
|
170
|
-
return reporter(
|
|
171
|
-
`target security scheme "${key}" is not "oauth2" type, but you've configured the scopes.`,
|
|
172
|
-
);
|
|
173
|
-
for (const s of scopes)
|
|
174
|
-
if (security.scopes.has(s) === false)
|
|
175
|
-
reporter(
|
|
176
|
-
`target security scheme "${key}" does not have a specific scope "${s}".`,
|
|
177
|
-
);
|
|
178
|
-
};
|
|
179
|
-
|
|
180
|
-
const violations: string[] = [];
|
|
181
|
-
for (const route of routeList)
|
|
182
|
-
for (const record of route.security)
|
|
183
|
-
for (const [key, scopes] of Object.entries(record))
|
|
184
|
-
validate((str) =>
|
|
185
|
-
violations.push(
|
|
186
|
-
` - ${str} (${route.symbol} at "${route.location}")`,
|
|
187
|
-
),
|
|
188
|
-
)(key, scopes);
|
|
189
|
-
|
|
190
|
-
if (violations.length)
|
|
191
|
-
throw new Error(
|
|
192
|
-
`Error on NestiaApplication.swagger(): invalid security specification. Check your "nestia.config.ts" file's "swagger.security" property, or each controller methods.\n` +
|
|
193
|
-
`\n` +
|
|
194
|
-
`List of violations:\n` +
|
|
195
|
-
violations.join("\n"),
|
|
196
|
-
);
|
|
197
|
-
};
|
|
198
|
-
|
|
199
|
-
/* ---------------------------------------------------------
|
|
200
|
-
INITIALIZERS
|
|
201
|
-
--------------------------------------------------------- */
|
|
202
|
-
const initialize = async (
|
|
203
|
-
config: INestiaConfig.ISwaggerConfig,
|
|
204
|
-
): Promise<ISwagger> => {
|
|
205
|
-
const pack = new Singleton(
|
|
206
|
-
async (): Promise<Partial<ISwaggerInfo> | null> => {
|
|
207
|
-
const location: string | null = await FileRetriever.file(
|
|
208
|
-
"package.json",
|
|
209
|
-
)(process.cwd());
|
|
210
|
-
if (location === null) return null;
|
|
211
|
-
|
|
212
|
-
try {
|
|
213
|
-
const content: string = await fs.promises.readFile(location, "utf8");
|
|
214
|
-
const data = typia.json.assertParse<{
|
|
215
|
-
name?: string;
|
|
216
|
-
version?: string;
|
|
217
|
-
description?: string;
|
|
218
|
-
license?:
|
|
219
|
-
| string
|
|
220
|
-
| {
|
|
221
|
-
type: string;
|
|
222
|
-
/**
|
|
223
|
-
* @format url
|
|
224
|
-
*/
|
|
225
|
-
url: string;
|
|
226
|
-
};
|
|
227
|
-
}>(content);
|
|
228
|
-
return {
|
|
229
|
-
title: data.name,
|
|
230
|
-
version: data.version,
|
|
231
|
-
description: data.description,
|
|
232
|
-
license: data.license
|
|
233
|
-
? typeof data.license === "string"
|
|
234
|
-
? { name: data.license }
|
|
235
|
-
: typeof data.license === "object"
|
|
236
|
-
? {
|
|
237
|
-
name: data.license.type,
|
|
238
|
-
url: data.license.url,
|
|
239
|
-
}
|
|
240
|
-
: undefined
|
|
241
|
-
: undefined,
|
|
242
|
-
};
|
|
243
|
-
} catch {
|
|
244
|
-
return null;
|
|
245
|
-
}
|
|
246
|
-
},
|
|
247
|
-
);
|
|
248
|
-
|
|
249
|
-
return {
|
|
250
|
-
openapi: "3.0.1",
|
|
251
|
-
servers: config.servers ?? [
|
|
252
|
-
{
|
|
253
|
-
url: "https://github.com/samchon/nestia",
|
|
254
|
-
description: "insert your server url",
|
|
255
|
-
},
|
|
256
|
-
],
|
|
257
|
-
info: {
|
|
258
|
-
...(config.info ?? {}),
|
|
259
|
-
version: config.info?.version ?? (await pack.get())?.version ?? "0.1.0",
|
|
260
|
-
title:
|
|
261
|
-
config.info?.title ??
|
|
262
|
-
(await pack.get())?.title ??
|
|
263
|
-
"Swagger Documents",
|
|
264
|
-
description:
|
|
265
|
-
config.info?.description ??
|
|
266
|
-
(await pack.get())?.description ??
|
|
267
|
-
"Generated by nestia - https://github.com/samchon/nestia",
|
|
268
|
-
license: config.info?.license ?? (await pack.get())?.license,
|
|
269
|
-
},
|
|
270
|
-
paths: {},
|
|
271
|
-
components: {},
|
|
272
|
-
};
|
|
273
|
-
};
|
|
274
|
-
|
|
275
|
-
function get_path(path: string, parameters: IRoute.IParameter[]): string {
|
|
276
|
-
const filtered: IRoute.IParameter[] = parameters.filter(
|
|
277
|
-
(param) => param.category === "param" && !!param.field,
|
|
278
|
-
);
|
|
279
|
-
for (const param of filtered)
|
|
280
|
-
path = path.replace(`:${param.field}`, `{${param.field}}`);
|
|
281
|
-
return path;
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
const generate_route =
|
|
285
|
-
(props: IProps) =>
|
|
286
|
-
(route: IRoute): ISwaggerRoute => {
|
|
287
|
-
const body = route.parameters.find((param) => param.category === "body");
|
|
288
|
-
const getJsDocTexts = (name: string) =>
|
|
289
|
-
route.jsDocTags
|
|
290
|
-
.filter(
|
|
291
|
-
(tag) =>
|
|
292
|
-
tag.name === name &&
|
|
293
|
-
tag.text &&
|
|
294
|
-
tag.text.find(
|
|
295
|
-
(elem) => elem.kind === "text" && elem.text.length,
|
|
296
|
-
) !== undefined,
|
|
297
|
-
)
|
|
298
|
-
.map((tag) => tag.text!.find((elem) => elem.kind === "text")!.text);
|
|
299
|
-
|
|
300
|
-
const description: string | undefined = route.description?.length
|
|
301
|
-
? route.description
|
|
302
|
-
: undefined;
|
|
303
|
-
const summary: string | undefined = (() => {
|
|
304
|
-
if (description === undefined) return undefined;
|
|
305
|
-
|
|
306
|
-
const [explicit] = getJsDocTexts("summary");
|
|
307
|
-
if (explicit?.length) return explicit;
|
|
308
|
-
|
|
309
|
-
const index: number = description.indexOf(".");
|
|
310
|
-
if (index <= 0) return undefined;
|
|
311
|
-
|
|
312
|
-
const content: string = description.substring(0, index).trim();
|
|
313
|
-
return content.length ? content : undefined;
|
|
314
|
-
})();
|
|
315
|
-
const deprecated = route.jsDocTags.find(
|
|
316
|
-
(tag) => tag.name === "deprecated",
|
|
317
|
-
);
|
|
318
|
-
|
|
319
|
-
return {
|
|
320
|
-
deprecated: deprecated ? true : undefined,
|
|
321
|
-
tags: [...route.swaggerTags, ...new Set([...getJsDocTexts("tag")])],
|
|
322
|
-
operationId:
|
|
323
|
-
route.operationId ??
|
|
324
|
-
props.config.operationId?.({
|
|
325
|
-
class: route.symbol.class,
|
|
326
|
-
function: route.symbol.function,
|
|
327
|
-
method: route.method as "GET",
|
|
328
|
-
path: route.path,
|
|
329
|
-
}),
|
|
330
|
-
parameters: route.parameters
|
|
331
|
-
.filter((param) => param.category !== "body")
|
|
332
|
-
.map((param) => SwaggerSchemaGenerator.parameter(props)(route)(param))
|
|
333
|
-
.flat(),
|
|
334
|
-
requestBody: body
|
|
335
|
-
? SwaggerSchemaGenerator.body(props)(route)(body)
|
|
336
|
-
: undefined,
|
|
337
|
-
responses: SwaggerSchemaGenerator.response(props)(route),
|
|
338
|
-
summary,
|
|
339
|
-
description,
|
|
340
|
-
security: route.security.length ? route.security : undefined,
|
|
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
|
-
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import { Singleton } from "tstl/thread/Singleton";
|
|
4
|
+
import ts from "typescript";
|
|
5
|
+
import typia, { IJsonApplication, IJsonComponents } from "typia";
|
|
6
|
+
import { MetadataCollection } from "typia/lib/factories/MetadataCollection";
|
|
7
|
+
import { JsonApplicationProgrammer } from "typia/lib/programmers/json/JsonApplicationProgrammer";
|
|
8
|
+
|
|
9
|
+
import { INestiaConfig } from "../INestiaConfig";
|
|
10
|
+
import { IRoute } from "../structures/IRoute";
|
|
11
|
+
import { ISwagger } from "../structures/ISwagger";
|
|
12
|
+
import { ISwaggerError } from "../structures/ISwaggerError";
|
|
13
|
+
import { ISwaggerInfo } from "../structures/ISwaggerInfo";
|
|
14
|
+
import { ISwaggerLazyProperty } from "../structures/ISwaggerLazyProperty";
|
|
15
|
+
import { ISwaggerLazySchema } from "../structures/ISwaggerLazySchema";
|
|
16
|
+
import { ISwaggerRoute } from "../structures/ISwaggerRoute";
|
|
17
|
+
import { ISwaggerSecurityScheme } from "../structures/ISwaggerSecurityScheme";
|
|
18
|
+
import { FileRetriever } from "../utils/FileRetriever";
|
|
19
|
+
import { MapUtil } from "../utils/MapUtil";
|
|
20
|
+
import { SwaggerSchemaGenerator } from "./internal/SwaggerSchemaGenerator";
|
|
21
|
+
|
|
22
|
+
export namespace SwaggerGenerator {
|
|
23
|
+
export interface IProps {
|
|
24
|
+
config: INestiaConfig.ISwaggerConfig;
|
|
25
|
+
checker: ts.TypeChecker;
|
|
26
|
+
collection: MetadataCollection;
|
|
27
|
+
lazySchemas: Array<ISwaggerLazySchema>;
|
|
28
|
+
lazyProperties: Array<ISwaggerLazyProperty>;
|
|
29
|
+
errors: ISwaggerError[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const generate =
|
|
33
|
+
(checker: ts.TypeChecker) =>
|
|
34
|
+
(config: INestiaConfig.ISwaggerConfig) =>
|
|
35
|
+
async (routeList: IRoute[]): Promise<void> => {
|
|
36
|
+
console.log("Generating Swagger Documents");
|
|
37
|
+
|
|
38
|
+
// VALIDATE SECURITY
|
|
39
|
+
validate_security(config)(routeList);
|
|
40
|
+
|
|
41
|
+
// PREPARE ASSETS
|
|
42
|
+
const parsed: path.ParsedPath = path.parse(config.output);
|
|
43
|
+
const directory: string = path.dirname(parsed.dir);
|
|
44
|
+
if (fs.existsSync(directory) === false)
|
|
45
|
+
try {
|
|
46
|
+
await fs.promises.mkdir(directory);
|
|
47
|
+
} catch {}
|
|
48
|
+
if (fs.existsSync(directory) === false)
|
|
49
|
+
throw new Error(
|
|
50
|
+
`Error on NestiaApplication.swagger(): failed to create output directory: ${directory}`,
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
const location: string = !!parsed.ext
|
|
54
|
+
? path.resolve(config.output)
|
|
55
|
+
: path.join(path.resolve(config.output), "swagger.json");
|
|
56
|
+
|
|
57
|
+
const collection: MetadataCollection = new MetadataCollection({
|
|
58
|
+
replace: MetadataCollection.replace,
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
// CONSTRUCT SWAGGER DOCUMENTS
|
|
62
|
+
const errors: ISwaggerError[] = [];
|
|
63
|
+
const lazySchemas: Array<ISwaggerLazySchema> = [];
|
|
64
|
+
const lazyProperties: Array<ISwaggerLazyProperty> = [];
|
|
65
|
+
const swagger: ISwagger = await initialize(config);
|
|
66
|
+
const pathDict: Map<string, Record<string, ISwaggerRoute>> = new Map();
|
|
67
|
+
|
|
68
|
+
for (const route of routeList) {
|
|
69
|
+
if (route.jsDocTags.find((tag) => tag.name === "internal")) continue;
|
|
70
|
+
|
|
71
|
+
const path: Record<string, ISwaggerRoute> = MapUtil.take(
|
|
72
|
+
pathDict,
|
|
73
|
+
get_path(route.path, route.parameters),
|
|
74
|
+
() => ({}),
|
|
75
|
+
);
|
|
76
|
+
path[route.method.toLowerCase()] = generate_route({
|
|
77
|
+
config,
|
|
78
|
+
checker,
|
|
79
|
+
collection,
|
|
80
|
+
lazySchemas,
|
|
81
|
+
lazyProperties,
|
|
82
|
+
errors,
|
|
83
|
+
})(route);
|
|
84
|
+
}
|
|
85
|
+
swagger.paths = {};
|
|
86
|
+
for (const [path, routes] of pathDict) swagger.paths[path] = routes;
|
|
87
|
+
|
|
88
|
+
// FILL JSON-SCHEMAS
|
|
89
|
+
const application: IJsonApplication = JsonApplicationProgrammer.write({
|
|
90
|
+
purpose: "swagger",
|
|
91
|
+
})(lazySchemas.map(({ metadata }) => metadata));
|
|
92
|
+
swagger.components = {
|
|
93
|
+
...(swagger.components ?? {}),
|
|
94
|
+
...(application.components ?? {}),
|
|
95
|
+
};
|
|
96
|
+
lazySchemas.forEach(({ schema }, index) => {
|
|
97
|
+
Object.assign(schema, application.schemas[index]!);
|
|
98
|
+
});
|
|
99
|
+
for (const p of lazyProperties)
|
|
100
|
+
Object.assign(
|
|
101
|
+
p.schema,
|
|
102
|
+
(
|
|
103
|
+
application.components.schemas?.[
|
|
104
|
+
p.object
|
|
105
|
+
] as IJsonComponents.IObject
|
|
106
|
+
)?.properties[p.property],
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
// CONFIGURE SECURITY
|
|
110
|
+
if (config.security) fill_security(config.security, swagger);
|
|
111
|
+
|
|
112
|
+
// REPORT ERRORS
|
|
113
|
+
if (errors.length) {
|
|
114
|
+
for (const e of errors)
|
|
115
|
+
console.error(
|
|
116
|
+
`${path.relative(e.route.location, process.cwd())}:${
|
|
117
|
+
e.route.symbol.class
|
|
118
|
+
}.${e.route.symbol.function}:${
|
|
119
|
+
e.from
|
|
120
|
+
} - error TS(@nestia/sdk): invalid type detected.\n\n` +
|
|
121
|
+
e.messages.map((m) => ` - ${m}`).join("\n"),
|
|
122
|
+
"\n\n",
|
|
123
|
+
);
|
|
124
|
+
throw new TypeError("Invalid type detected");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// DO GENERATE
|
|
128
|
+
await fs.promises.writeFile(
|
|
129
|
+
location,
|
|
130
|
+
!config.beautify
|
|
131
|
+
? JSON.stringify(swagger)
|
|
132
|
+
: JSON.stringify(
|
|
133
|
+
swagger,
|
|
134
|
+
null,
|
|
135
|
+
typeof config.beautify === "number" ? config.beautify : 2,
|
|
136
|
+
),
|
|
137
|
+
"utf8",
|
|
138
|
+
);
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const validate_security =
|
|
142
|
+
(config: INestiaConfig.ISwaggerConfig) =>
|
|
143
|
+
(routeList: IRoute[]): void | never => {
|
|
144
|
+
const securityMap: Map<
|
|
145
|
+
string,
|
|
146
|
+
{ scheme: ISwaggerSecurityScheme; scopes: Set<string> }
|
|
147
|
+
> = new Map();
|
|
148
|
+
for (const [key, value] of Object.entries(config.security ?? {}))
|
|
149
|
+
securityMap.set(key, {
|
|
150
|
+
scheme: emend_security(value),
|
|
151
|
+
scopes:
|
|
152
|
+
value.type === "oauth2"
|
|
153
|
+
? new Set([
|
|
154
|
+
...Object.keys(value.flows.authorizationCode?.scopes ?? {}),
|
|
155
|
+
...Object.keys(value.flows.implicit?.scopes ?? {}),
|
|
156
|
+
...Object.keys(value.flows.password?.scopes ?? {}),
|
|
157
|
+
...Object.keys(value.flows.clientCredentials?.scopes ?? {}),
|
|
158
|
+
])
|
|
159
|
+
: new Set(),
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
const validate =
|
|
163
|
+
(reporter: (str: string) => void) =>
|
|
164
|
+
(key: string, scopes: string[]) => {
|
|
165
|
+
const security = securityMap.get(key);
|
|
166
|
+
if (security === undefined)
|
|
167
|
+
return reporter(`target security scheme "${key}" does not exists.`);
|
|
168
|
+
else if (scopes.length === 0) return;
|
|
169
|
+
else if (security.scheme.type !== "oauth2")
|
|
170
|
+
return reporter(
|
|
171
|
+
`target security scheme "${key}" is not "oauth2" type, but you've configured the scopes.`,
|
|
172
|
+
);
|
|
173
|
+
for (const s of scopes)
|
|
174
|
+
if (security.scopes.has(s) === false)
|
|
175
|
+
reporter(
|
|
176
|
+
`target security scheme "${key}" does not have a specific scope "${s}".`,
|
|
177
|
+
);
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
const violations: string[] = [];
|
|
181
|
+
for (const route of routeList)
|
|
182
|
+
for (const record of route.security)
|
|
183
|
+
for (const [key, scopes] of Object.entries(record))
|
|
184
|
+
validate((str) =>
|
|
185
|
+
violations.push(
|
|
186
|
+
` - ${str} (${route.symbol} at "${route.location}")`,
|
|
187
|
+
),
|
|
188
|
+
)(key, scopes);
|
|
189
|
+
|
|
190
|
+
if (violations.length)
|
|
191
|
+
throw new Error(
|
|
192
|
+
`Error on NestiaApplication.swagger(): invalid security specification. Check your "nestia.config.ts" file's "swagger.security" property, or each controller methods.\n` +
|
|
193
|
+
`\n` +
|
|
194
|
+
`List of violations:\n` +
|
|
195
|
+
violations.join("\n"),
|
|
196
|
+
);
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
/* ---------------------------------------------------------
|
|
200
|
+
INITIALIZERS
|
|
201
|
+
--------------------------------------------------------- */
|
|
202
|
+
const initialize = async (
|
|
203
|
+
config: INestiaConfig.ISwaggerConfig,
|
|
204
|
+
): Promise<ISwagger> => {
|
|
205
|
+
const pack = new Singleton(
|
|
206
|
+
async (): Promise<Partial<ISwaggerInfo> | null> => {
|
|
207
|
+
const location: string | null = await FileRetriever.file(
|
|
208
|
+
"package.json",
|
|
209
|
+
)(process.cwd());
|
|
210
|
+
if (location === null) return null;
|
|
211
|
+
|
|
212
|
+
try {
|
|
213
|
+
const content: string = await fs.promises.readFile(location, "utf8");
|
|
214
|
+
const data = typia.json.assertParse<{
|
|
215
|
+
name?: string;
|
|
216
|
+
version?: string;
|
|
217
|
+
description?: string;
|
|
218
|
+
license?:
|
|
219
|
+
| string
|
|
220
|
+
| {
|
|
221
|
+
type: string;
|
|
222
|
+
/**
|
|
223
|
+
* @format url
|
|
224
|
+
*/
|
|
225
|
+
url: string;
|
|
226
|
+
};
|
|
227
|
+
}>(content);
|
|
228
|
+
return {
|
|
229
|
+
title: data.name,
|
|
230
|
+
version: data.version,
|
|
231
|
+
description: data.description,
|
|
232
|
+
license: data.license
|
|
233
|
+
? typeof data.license === "string"
|
|
234
|
+
? { name: data.license }
|
|
235
|
+
: typeof data.license === "object"
|
|
236
|
+
? {
|
|
237
|
+
name: data.license.type,
|
|
238
|
+
url: data.license.url,
|
|
239
|
+
}
|
|
240
|
+
: undefined
|
|
241
|
+
: undefined,
|
|
242
|
+
};
|
|
243
|
+
} catch {
|
|
244
|
+
return null;
|
|
245
|
+
}
|
|
246
|
+
},
|
|
247
|
+
);
|
|
248
|
+
|
|
249
|
+
return {
|
|
250
|
+
openapi: "3.0.1",
|
|
251
|
+
servers: config.servers ?? [
|
|
252
|
+
{
|
|
253
|
+
url: "https://github.com/samchon/nestia",
|
|
254
|
+
description: "insert your server url",
|
|
255
|
+
},
|
|
256
|
+
],
|
|
257
|
+
info: {
|
|
258
|
+
...(config.info ?? {}),
|
|
259
|
+
version: config.info?.version ?? (await pack.get())?.version ?? "0.1.0",
|
|
260
|
+
title:
|
|
261
|
+
config.info?.title ??
|
|
262
|
+
(await pack.get())?.title ??
|
|
263
|
+
"Swagger Documents",
|
|
264
|
+
description:
|
|
265
|
+
config.info?.description ??
|
|
266
|
+
(await pack.get())?.description ??
|
|
267
|
+
"Generated by nestia - https://github.com/samchon/nestia",
|
|
268
|
+
license: config.info?.license ?? (await pack.get())?.license,
|
|
269
|
+
},
|
|
270
|
+
paths: {},
|
|
271
|
+
components: {},
|
|
272
|
+
};
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
function get_path(path: string, parameters: IRoute.IParameter[]): string {
|
|
276
|
+
const filtered: IRoute.IParameter[] = parameters.filter(
|
|
277
|
+
(param) => param.category === "param" && !!param.field,
|
|
278
|
+
);
|
|
279
|
+
for (const param of filtered)
|
|
280
|
+
path = path.replace(`:${param.field}`, `{${param.field}}`);
|
|
281
|
+
return path;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const generate_route =
|
|
285
|
+
(props: IProps) =>
|
|
286
|
+
(route: IRoute): ISwaggerRoute => {
|
|
287
|
+
const body = route.parameters.find((param) => param.category === "body");
|
|
288
|
+
const getJsDocTexts = (name: string) =>
|
|
289
|
+
route.jsDocTags
|
|
290
|
+
.filter(
|
|
291
|
+
(tag) =>
|
|
292
|
+
tag.name === name &&
|
|
293
|
+
tag.text &&
|
|
294
|
+
tag.text.find(
|
|
295
|
+
(elem) => elem.kind === "text" && elem.text.length,
|
|
296
|
+
) !== undefined,
|
|
297
|
+
)
|
|
298
|
+
.map((tag) => tag.text!.find((elem) => elem.kind === "text")!.text);
|
|
299
|
+
|
|
300
|
+
const description: string | undefined = route.description?.length
|
|
301
|
+
? route.description
|
|
302
|
+
: undefined;
|
|
303
|
+
const summary: string | undefined = (() => {
|
|
304
|
+
if (description === undefined) return undefined;
|
|
305
|
+
|
|
306
|
+
const [explicit] = getJsDocTexts("summary");
|
|
307
|
+
if (explicit?.length) return explicit;
|
|
308
|
+
|
|
309
|
+
const index: number = description.indexOf(".");
|
|
310
|
+
if (index <= 0) return undefined;
|
|
311
|
+
|
|
312
|
+
const content: string = description.substring(0, index).trim();
|
|
313
|
+
return content.length ? content : undefined;
|
|
314
|
+
})();
|
|
315
|
+
const deprecated = route.jsDocTags.find(
|
|
316
|
+
(tag) => tag.name === "deprecated",
|
|
317
|
+
);
|
|
318
|
+
|
|
319
|
+
return {
|
|
320
|
+
deprecated: deprecated ? true : undefined,
|
|
321
|
+
tags: [...route.swaggerTags, ...new Set([...getJsDocTexts("tag")])],
|
|
322
|
+
operationId:
|
|
323
|
+
route.operationId ??
|
|
324
|
+
props.config.operationId?.({
|
|
325
|
+
class: route.symbol.class,
|
|
326
|
+
function: route.symbol.function,
|
|
327
|
+
method: route.method as "GET",
|
|
328
|
+
path: route.path,
|
|
329
|
+
}),
|
|
330
|
+
parameters: route.parameters
|
|
331
|
+
.filter((param) => param.category !== "body")
|
|
332
|
+
.map((param) => SwaggerSchemaGenerator.parameter(props)(route)(param))
|
|
333
|
+
.flat(),
|
|
334
|
+
requestBody: body
|
|
335
|
+
? SwaggerSchemaGenerator.body(props)(route)(body)
|
|
336
|
+
: undefined,
|
|
337
|
+
responses: SwaggerSchemaGenerator.response(props)(route),
|
|
338
|
+
summary,
|
|
339
|
+
description,
|
|
340
|
+
security: route.security.length ? route.security : undefined,
|
|
341
|
+
...(props.config.additional === true
|
|
342
|
+
? {
|
|
343
|
+
"x-nestia-namespace": [
|
|
344
|
+
...route.path
|
|
345
|
+
.split("/")
|
|
346
|
+
.filter((str) => str.length && str[0] !== ":"),
|
|
347
|
+
route.name,
|
|
348
|
+
].join("."),
|
|
349
|
+
"x-nestia-jsDocTags": route.jsDocTags,
|
|
350
|
+
"x-nestia-method": route.method,
|
|
351
|
+
}
|
|
352
|
+
: {}),
|
|
353
|
+
};
|
|
354
|
+
};
|
|
355
|
+
|
|
356
|
+
function fill_security(
|
|
357
|
+
security: Required<INestiaConfig.ISwaggerConfig>["security"],
|
|
358
|
+
swagger: ISwagger,
|
|
359
|
+
): void {
|
|
360
|
+
swagger.components.securitySchemes = {};
|
|
361
|
+
for (const [key, value] of Object.entries(security))
|
|
362
|
+
swagger.components.securitySchemes[key] = emend_security(value);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function emend_security(
|
|
366
|
+
input: ISwaggerSecurityScheme,
|
|
367
|
+
): ISwaggerSecurityScheme {
|
|
368
|
+
if (input.type === "apiKey")
|
|
369
|
+
return {
|
|
370
|
+
...input,
|
|
371
|
+
in: input.in ?? "header",
|
|
372
|
+
name: input.name ?? "Authorization",
|
|
373
|
+
};
|
|
374
|
+
return input;
|
|
375
|
+
}
|
|
376
|
+
}
|