@nestia/sdk 10.0.2 → 11.0.0-dev.20260305

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 (198) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +93 -93
  3. package/assets/bundle/api/HttpError.ts +1 -1
  4. package/assets/bundle/api/IConnection.ts +1 -1
  5. package/assets/bundle/api/Primitive.ts +1 -1
  6. package/assets/bundle/api/Resolved.ts +1 -1
  7. package/assets/bundle/api/index.ts +4 -4
  8. package/assets/bundle/api/module.ts +6 -6
  9. package/assets/bundle/distribute/README.md +37 -37
  10. package/assets/bundle/distribute/package.json +28 -28
  11. package/assets/bundle/distribute/tsconfig.json +109 -109
  12. package/assets/bundle/e2e/index.ts +42 -42
  13. package/assets/config/nestia.config.ts +97 -97
  14. package/lib/INestiaConfig.d.ts +1 -1
  15. package/lib/NestiaSdkApplication.js.map +1 -1
  16. package/lib/NestiaSwaggerComposer.d.ts +2 -1
  17. package/lib/NestiaSwaggerComposer.js +3 -3
  18. package/lib/NestiaSwaggerComposer.js.map +1 -1
  19. package/lib/analyses/AccessorAnalyzer.js +2 -2
  20. package/lib/analyses/AccessorAnalyzer.js.map +1 -1
  21. package/lib/analyses/DtoAnalyzer.js.map +1 -1
  22. package/lib/analyses/ImportAnalyzer.js.map +1 -1
  23. package/lib/analyses/ReflectHttpOperationAnalyzer.js +3 -3
  24. package/lib/analyses/ReflectHttpOperationAnalyzer.js.map +1 -1
  25. package/lib/analyses/ReflectHttpOperationExceptionAnalyzer.js +2 -2
  26. package/lib/analyses/ReflectHttpOperationExceptionAnalyzer.js.map +1 -1
  27. package/lib/analyses/ReflectHttpOperationParameterAnalyzer.js +7 -11
  28. package/lib/analyses/ReflectHttpOperationParameterAnalyzer.js.map +1 -1
  29. package/lib/analyses/ReflectHttpOperationResponseAnalyzer.js +6 -6
  30. package/lib/analyses/ReflectHttpOperationResponseAnalyzer.js.map +1 -1
  31. package/lib/analyses/TypedHttpRouteAnalyzer.d.ts +1 -1
  32. package/lib/analyses/TypedHttpRouteAnalyzer.js +6 -8
  33. package/lib/analyses/TypedHttpRouteAnalyzer.js.map +1 -1
  34. package/lib/executable/internal/NestiaConfigLoader.js +47 -43
  35. package/lib/executable/internal/NestiaConfigLoader.js.map +1 -1
  36. package/lib/executable/internal/NestiaSdkCommand.js.map +1 -1
  37. package/lib/executable/sdk.js +12 -12
  38. package/lib/generates/SwaggerGenerator.d.ts +1 -1
  39. package/lib/generates/SwaggerGenerator.js +6 -6
  40. package/lib/generates/SwaggerGenerator.js.map +1 -1
  41. package/lib/generates/internal/E2eFileProgrammer.js +8 -9
  42. package/lib/generates/internal/E2eFileProgrammer.js.map +1 -1
  43. package/lib/generates/internal/SdkAliasCollection.d.ts +2 -2
  44. package/lib/generates/internal/SdkAliasCollection.js +2 -2
  45. package/lib/generates/internal/SdkAliasCollection.js.map +1 -1
  46. package/lib/generates/internal/SdkDistributionComposer.js +1 -1
  47. package/lib/generates/internal/SdkHttpCloneProgrammer.js.map +1 -1
  48. package/lib/generates/internal/SdkHttpCloneReferencer.js.map +1 -1
  49. package/lib/generates/internal/SdkHttpFunctionProgrammer.js +11 -12
  50. package/lib/generates/internal/SdkHttpFunctionProgrammer.js.map +1 -1
  51. package/lib/generates/internal/SdkHttpNamespaceProgrammer.js +13 -16
  52. package/lib/generates/internal/SdkHttpNamespaceProgrammer.js.map +1 -1
  53. package/lib/generates/internal/SdkHttpRouteProgrammer.js +4 -4
  54. package/lib/generates/internal/SdkHttpRouteProgrammer.js.map +1 -1
  55. package/lib/generates/internal/SdkHttpSimulationProgrammer.js +12 -16
  56. package/lib/generates/internal/SdkHttpSimulationProgrammer.js.map +1 -1
  57. package/lib/generates/internal/SdkImportWizard.js +2 -2
  58. package/lib/generates/internal/SdkImportWizard.js.map +1 -1
  59. package/lib/generates/internal/SdkTypeProgrammer.d.ts +2 -3
  60. package/lib/generates/internal/SdkTypeProgrammer.js +6 -7
  61. package/lib/generates/internal/SdkTypeProgrammer.js.map +1 -1
  62. package/lib/generates/internal/SdkTypeTagProgrammer.d.ts +1 -1
  63. package/lib/generates/internal/SdkTypeTagProgrammer.js +11 -11
  64. package/lib/generates/internal/SdkTypeTagProgrammer.js.map +1 -1
  65. package/lib/generates/internal/SdkWebSocketNamespaceProgrammer.js +6 -8
  66. package/lib/generates/internal/SdkWebSocketNamespaceProgrammer.js.map +1 -1
  67. package/lib/generates/internal/SdkWebSocketRouteProgrammer.js +2 -2
  68. package/lib/generates/internal/SdkWebSocketRouteProgrammer.js.map +1 -1
  69. package/lib/generates/internal/SwaggerOperationComposer.d.ts +3 -3
  70. package/lib/generates/internal/SwaggerOperationComposer.js.map +1 -1
  71. package/lib/generates/internal/SwaggerOperationParameterComposer.d.ts +1 -1
  72. package/lib/generates/internal/SwaggerOperationParameterComposer.js +10 -8
  73. package/lib/generates/internal/SwaggerOperationParameterComposer.js.map +1 -1
  74. package/lib/generates/internal/SwaggerOperationResponseComposer.d.ts +3 -3
  75. package/lib/generates/internal/SwaggerOperationResponseComposer.js.map +1 -1
  76. package/lib/module.d.ts +1 -0
  77. package/lib/module.js +1 -0
  78. package/lib/module.js.map +1 -1
  79. package/lib/structures/IReflectHttpOperationException.d.ts +3 -4
  80. package/lib/structures/IReflectHttpOperationParameter.d.ts +3 -5
  81. package/lib/structures/IReflectHttpOperationSuccess.d.ts +3 -4
  82. package/lib/structures/ITypedApplication.d.ts +1 -1
  83. package/lib/structures/ITypedHttpRouteException.d.ts +2 -2
  84. package/lib/structures/ITypedHttpRouteParameter.d.ts +2 -2
  85. package/lib/structures/ITypedHttpRouteSuccess.d.ts +2 -2
  86. package/lib/transformers/IOperationMetadata.d.ts +2 -4
  87. package/lib/transformers/ISdkOperationTransformerContext.d.ts +1 -1
  88. package/lib/transformers/SdkOperationProgrammer.js +8 -10
  89. package/lib/transformers/SdkOperationProgrammer.js.map +1 -1
  90. package/lib/transformers/SdkOperationTransformer.js +5 -7
  91. package/lib/transformers/SdkOperationTransformer.js.map +1 -1
  92. package/lib/transformers/TextPlainValidator.d.ts +2 -2
  93. package/lib/transformers/TextPlainValidator.js.map +1 -1
  94. package/lib/utils/MetadataUtil.d.ts +2 -2
  95. package/lib/utils/MetadataUtil.js.map +1 -1
  96. package/lib/validators/HttpHeadersValidator.d.ts +2 -3
  97. package/lib/validators/HttpHeadersValidator.js +2 -2
  98. package/lib/validators/HttpHeadersValidator.js.map +1 -1
  99. package/lib/validators/HttpQueryValidator.d.ts +2 -3
  100. package/lib/validators/HttpQueryValidator.js +2 -2
  101. package/lib/validators/HttpQueryValidator.js.map +1 -1
  102. package/package.json +44 -30
  103. package/src/INestiaConfig.ts +267 -267
  104. package/src/NestiaSdkApplication.ts +307 -307
  105. package/src/NestiaSwaggerComposer.ts +140 -138
  106. package/src/analyses/AccessorAnalyzer.ts +67 -67
  107. package/src/analyses/ConfigAnalyzer.ts +155 -155
  108. package/src/analyses/DtoAnalyzer.ts +260 -260
  109. package/src/analyses/ExceptionAnalyzer.ts +154 -154
  110. package/src/analyses/GenericAnalyzer.ts +49 -49
  111. package/src/analyses/ImportAnalyzer.ts +126 -126
  112. package/src/analyses/PathAnalyzer.ts +69 -69
  113. package/src/analyses/ReflectControllerAnalyzer.ts +105 -105
  114. package/src/analyses/ReflectHttpOperationAnalyzer.ts +183 -183
  115. package/src/analyses/ReflectHttpOperationExceptionAnalyzer.ts +72 -71
  116. package/src/analyses/ReflectHttpOperationParameterAnalyzer.ts +350 -348
  117. package/src/analyses/ReflectHttpOperationResponseAnalyzer.ts +126 -127
  118. package/src/analyses/ReflectMetadataAnalyzer.ts +44 -44
  119. package/src/analyses/ReflectWebSocketOperationAnalyzer.ts +172 -172
  120. package/src/analyses/SecurityAnalyzer.ts +25 -25
  121. package/src/analyses/TypedHttpRouteAnalyzer.ts +208 -204
  122. package/src/analyses/TypedWebSocketRouteAnalyzer.ts +33 -33
  123. package/src/decorators/OperationMetadata.ts +15 -15
  124. package/src/executable/internal/CommandParser.ts +15 -15
  125. package/src/executable/internal/NestiaConfigLoader.ts +85 -78
  126. package/src/executable/internal/NestiaSdkCommand.ts +107 -103
  127. package/src/executable/sdk.ts +75 -75
  128. package/src/generates/CloneGenerator.ts +66 -66
  129. package/src/generates/E2eGenerator.ts +32 -32
  130. package/src/generates/SdkGenerator.ts +160 -160
  131. package/src/generates/SwaggerGenerator.ts +285 -284
  132. package/src/generates/internal/E2eFileProgrammer.ts +196 -197
  133. package/src/generates/internal/FilePrinter.ts +64 -64
  134. package/src/generates/internal/ImportDictionary.ts +192 -192
  135. package/src/generates/internal/SdkAliasCollection.ts +260 -261
  136. package/src/generates/internal/SdkDistributionComposer.ts +103 -103
  137. package/src/generates/internal/SdkFileProgrammer.ts +110 -110
  138. package/src/generates/internal/SdkHttpCloneProgrammer.ts +126 -124
  139. package/src/generates/internal/SdkHttpCloneReferencer.ts +77 -77
  140. package/src/generates/internal/SdkHttpFunctionProgrammer.ts +278 -279
  141. package/src/generates/internal/SdkHttpNamespaceProgrammer.ts +502 -500
  142. package/src/generates/internal/SdkHttpParameterProgrammer.ts +178 -178
  143. package/src/generates/internal/SdkHttpRouteProgrammer.ts +109 -108
  144. package/src/generates/internal/SdkHttpSimulationProgrammer.ts +312 -310
  145. package/src/generates/internal/SdkImportWizard.ts +62 -62
  146. package/src/generates/internal/SdkRouteDirectory.ts +18 -18
  147. package/src/generates/internal/SdkTypeProgrammer.ts +388 -385
  148. package/src/generates/internal/SdkTypeTagProgrammer.ts +114 -104
  149. package/src/generates/internal/SdkWebSocketNamespaceProgrammer.ts +379 -381
  150. package/src/generates/internal/SdkWebSocketParameterProgrammer.ts +87 -87
  151. package/src/generates/internal/SdkWebSocketRouteProgrammer.ts +302 -302
  152. package/src/generates/internal/SwaggerDescriptionComposer.ts +64 -64
  153. package/src/generates/internal/SwaggerOperationComposer.ts +119 -119
  154. package/src/generates/internal/SwaggerOperationParameterComposer.ts +161 -162
  155. package/src/generates/internal/SwaggerOperationResponseComposer.ts +110 -110
  156. package/src/index.ts +4 -4
  157. package/src/module.ts +4 -3
  158. package/src/structures/INestiaProject.ts +13 -13
  159. package/src/structures/INestiaSdkInput.ts +20 -20
  160. package/src/structures/IReflectApplication.ts +8 -8
  161. package/src/structures/IReflectController.ts +15 -15
  162. package/src/structures/IReflectHttpOperation.ts +26 -26
  163. package/src/structures/IReflectHttpOperationException.ts +18 -19
  164. package/src/structures/IReflectHttpOperationParameter.ts +79 -77
  165. package/src/structures/IReflectHttpOperationSuccess.ts +21 -22
  166. package/src/structures/IReflectImport.ts +6 -6
  167. package/src/structures/IReflectOperationError.ts +26 -26
  168. package/src/structures/IReflectType.ts +4 -4
  169. package/src/structures/IReflectWebSocketOperation.ts +17 -17
  170. package/src/structures/IReflectWebSocketOperationParameter.ts +36 -36
  171. package/src/structures/ITypedApplication.ts +11 -11
  172. package/src/structures/ITypedHttpRoute.ts +41 -41
  173. package/src/structures/ITypedHttpRouteException.ts +15 -15
  174. package/src/structures/ITypedHttpRouteParameter.ts +41 -41
  175. package/src/structures/ITypedHttpRouteSuccess.ts +22 -22
  176. package/src/structures/ITypedWebSocketRoute.ts +24 -24
  177. package/src/structures/ITypedWebSocketRouteParameter.ts +3 -3
  178. package/src/structures/MethodType.ts +5 -5
  179. package/src/structures/ParamCategory.ts +1 -1
  180. package/src/structures/TypeEntry.ts +22 -22
  181. package/src/transform.ts +9 -9
  182. package/src/transformers/IOperationMetadata.ts +46 -44
  183. package/src/transformers/ISdkOperationTransformerContext.ts +8 -8
  184. package/src/transformers/SdkOperationProgrammer.ts +240 -238
  185. package/src/transformers/SdkOperationTransformer.ts +248 -252
  186. package/src/transformers/TextPlainValidator.ts +17 -17
  187. package/src/typings/get-function-location.d.ts +7 -7
  188. package/src/utils/ArrayUtil.ts +26 -26
  189. package/src/utils/FileRetriever.ts +22 -22
  190. package/src/utils/MapUtil.ts +14 -14
  191. package/src/utils/MetadataUtil.ts +26 -26
  192. package/src/utils/PathUtil.ts +10 -10
  193. package/src/utils/SourceFinder.ts +63 -63
  194. package/src/utils/StringUtil.ts +17 -17
  195. package/src/utils/StripEnums.ts +5 -5
  196. package/src/utils/VersioningStrategy.ts +28 -28
  197. package/src/validators/HttpHeadersValidator.ts +36 -34
  198. package/src/validators/HttpQueryValidator.ts +36 -34
@@ -1,284 +1,285 @@
1
- import { SwaggerCustomizer } from "@nestia/core";
2
- import { OpenApi, OpenApiV3, SwaggerV2 } from "@samchon/openapi";
3
- import fs from "fs";
4
- import path from "path";
5
- import { Singleton } from "tstl";
6
- import typia, { IJsonSchemaCollection } from "typia";
7
- import { JsonSchemasProgrammer } from "typia/lib/programmers/json/JsonSchemasProgrammer";
8
- import { Metadata } from "typia/lib/schemas/metadata/Metadata";
9
-
10
- import { INestiaConfig } from "../INestiaConfig";
11
- import { ITypedApplication } from "../structures/ITypedApplication";
12
- import { ITypedHttpRoute } from "../structures/ITypedHttpRoute";
13
- import { FileRetriever } from "../utils/FileRetriever";
14
- import { SdkHttpParameterProgrammer } from "./internal/SdkHttpParameterProgrammer";
15
- import { SwaggerOperationComposer } from "./internal/SwaggerOperationComposer";
16
-
17
- export namespace SwaggerGenerator {
18
- export const generate = async (app: ITypedApplication): Promise<void> => {
19
- // GET CONFIGURATION
20
- console.log("Generating Swagger Document");
21
- if (app.project.config.swagger === undefined)
22
- throw new Error("Swagger configuration is not defined.");
23
- const config: INestiaConfig.ISwaggerConfig = app.project.config.swagger;
24
-
25
- // TARGET LOCATION
26
- const parsed: path.ParsedPath = path.parse(config.output);
27
- const directory: string = path.dirname(parsed.dir);
28
- if (fs.existsSync(directory) === false)
29
- try {
30
- await fs.promises.mkdir(directory);
31
- } catch {}
32
- if (fs.existsSync(directory) === false)
33
- throw new Error(
34
- `Error on NestiaApplication.swagger(): failed to create output directory: ${directory}`,
35
- );
36
- const location: string = !!parsed.ext
37
- ? path.resolve(config.output)
38
- : path.join(path.resolve(config.output), "swagger.json");
39
-
40
- // COMPOSE SWAGGER DOCUMENT
41
- const document: OpenApi.IDocument = compose({
42
- config,
43
- routes: app.routes.filter((route) => route.protocol === "http"),
44
- document: await initialize(config),
45
- });
46
- const specified:
47
- | OpenApi.IDocument
48
- | SwaggerV2.IDocument
49
- | OpenApiV3.IDocument =
50
- config.openapi === "2.0"
51
- ? OpenApi.downgrade(document, config.openapi as "2.0")
52
- : config.openapi === "3.0"
53
- ? OpenApi.downgrade(document, config.openapi as "3.0")
54
- : document;
55
- await fs.promises.writeFile(
56
- location,
57
- !config.beautify
58
- ? JSON.stringify(specified)
59
- : JSON.stringify(
60
- specified,
61
- null,
62
- typeof config.beautify === "number" ? config.beautify : 2,
63
- ),
64
- "utf8",
65
- );
66
- };
67
-
68
- export const compose = (props: {
69
- config: Omit<INestiaConfig.ISwaggerConfig, "output">;
70
- routes: ITypedHttpRoute[];
71
- document: OpenApi.IDocument;
72
- }): OpenApi.IDocument => {
73
- // GATHER METADATA
74
- const routes: ITypedHttpRoute[] = props.routes.filter((r) =>
75
- r.jsDocTags.every(
76
- (tag) => tag.name !== "internal" && tag.name !== "hidden",
77
- ),
78
- );
79
- const metadatas: Metadata[] = routes
80
- .map((r) => [
81
- r.success.metadata,
82
- ...SdkHttpParameterProgrammer.getAll(r).map((p) => p.metadata),
83
- ...Object.values(r.exceptions).map((e) => e.metadata),
84
- ])
85
- .flat()
86
- .filter((m) => m.size() !== 0);
87
-
88
- // COMPOSE JSON SCHEMAS
89
- const json: IJsonSchemaCollection = JsonSchemasProgrammer.write({
90
- version: "3.1",
91
- metadatas,
92
- });
93
- const dict: WeakMap<Metadata, OpenApi.IJsonSchema> = new WeakMap();
94
- json.schemas.forEach((schema, i) => dict.set(metadatas[i], schema));
95
- const schema = (metadata: Metadata): OpenApi.IJsonSchema | undefined =>
96
- dict.get(metadata);
97
-
98
- // COMPOSE DOCUMENT
99
- const document: OpenApi.IDocument = props.document;
100
- document.components.schemas ??= {};
101
- Object.assign(document.components.schemas, json.components.schemas);
102
- fillPaths({
103
- ...props,
104
- routes,
105
- schema,
106
- document,
107
- });
108
- return document;
109
- };
110
-
111
- export const initialize = async (
112
- config: Omit<INestiaConfig.ISwaggerConfig, "output">,
113
- ): Promise<OpenApi.IDocument> => {
114
- const pack = new Singleton(
115
- async (): Promise<Partial<OpenApi.IDocument.IInfo> | null> => {
116
- const location: string | null = await FileRetriever.file(
117
- "package.json",
118
- )(process.cwd());
119
- if (location === null) return null;
120
-
121
- try {
122
- const content: string = await fs.promises.readFile(location, "utf8");
123
- const data = typia.json.assertParse<{
124
- name?: string;
125
- version?: string;
126
- description?: string;
127
- license?:
128
- | string
129
- | {
130
- type: string;
131
- /** @format uri */
132
- url: string;
133
- };
134
- }>(content);
135
- return {
136
- title: data.name,
137
- version: data.version,
138
- description: data.description,
139
- license: data.license
140
- ? typeof data.license === "string"
141
- ? { name: data.license }
142
- : typeof data.license === "object"
143
- ? {
144
- name: data.license.type,
145
- url: data.license.url,
146
- }
147
- : undefined
148
- : undefined,
149
- };
150
- } catch {
151
- return null;
152
- }
153
- },
154
- );
155
-
156
- return {
157
- openapi: "3.1.0",
158
- servers: config.servers ?? [
159
- {
160
- url: "https://github.com/samchon/nestia",
161
- description: "insert your server url",
162
- },
163
- ],
164
- info: {
165
- ...(config.info ?? {}),
166
- version: config.info?.version ?? (await pack.get())?.version ?? "0.1.0",
167
- title:
168
- config.info?.title ??
169
- (await pack.get())?.title ??
170
- "Swagger Documents",
171
- description:
172
- config.info?.description ??
173
- (await pack.get())?.description ??
174
- "Generated by nestia - https://github.com/samchon/nestia",
175
- license: config.info?.license ?? (await pack.get())?.license,
176
- },
177
- paths: {},
178
- components: {
179
- schemas: {},
180
- securitySchemes: config.security,
181
- },
182
- tags: config.tags ?? [],
183
- "x-samchon-emended-v4": true,
184
- };
185
- };
186
-
187
- const fillPaths = (props: {
188
- config: Omit<INestiaConfig.ISwaggerConfig, "output">;
189
- document: OpenApi.IDocument;
190
- schema: (metadata: Metadata) => OpenApi.IJsonSchema | undefined;
191
- routes: ITypedHttpRoute[];
192
- }): void => {
193
- // SWAGGER CUSTOMIZER
194
- const customizers: Array<() => void> = [];
195
- const neighbor = {
196
- at: new Singleton(() => {
197
- const functor: Map<Function, Endpoint> = new Map();
198
- for (const r of props.routes) {
199
- const method: OpenApi.Method =
200
- r.method.toLowerCase() as OpenApi.Method;
201
- const path: string = getPath(r);
202
- const operation: OpenApi.IOperation | undefined =
203
- props.document.paths?.[path]?.[method];
204
- if (operation === undefined) continue;
205
- functor.set(r.function, {
206
- method,
207
- path,
208
- route: operation,
209
- });
210
- }
211
- return functor;
212
- }),
213
- get: new Singleton(
214
- () =>
215
- (key: Accessor): OpenApi.IOperation | undefined => {
216
- const method: OpenApi.Method =
217
- key.method.toLowerCase() as OpenApi.Method;
218
- const path: string =
219
- "/" +
220
- key.path
221
- .split("/")
222
- .filter((str) => !!str.length)
223
- .map((str) =>
224
- str.startsWith(":") ? `{${str.substring(1)}}` : str,
225
- )
226
- .join("/");
227
- return props.document.paths?.[path]?.[method];
228
- },
229
- ),
230
- };
231
-
232
- // COMPOSE OPERATIONS
233
- for (const r of props.routes) {
234
- const operation: OpenApi.IOperation = SwaggerOperationComposer.compose({
235
- ...props,
236
- route: r,
237
- });
238
- const path: string = getPath(r);
239
- props.document.paths ??= {};
240
- props.document.paths[path] ??= {};
241
- props.document.paths[path][r.method.toLowerCase() as "get"] = operation;
242
-
243
- const closure: Function | Function[] | undefined = Reflect.getMetadata(
244
- "nestia/SwaggerCustomizer",
245
- r.controller.class.prototype,
246
- r.name,
247
- );
248
- if (closure !== undefined) {
249
- const array: Function[] = Array.isArray(closure) ? closure : [closure];
250
- customizers.push(() => {
251
- for (const closure of array)
252
- closure({
253
- swagger: props.document,
254
- method: r.method,
255
- path,
256
- route: operation,
257
- at: (func: Function) => neighbor.at.get().get(func),
258
- get: (accessor: Accessor) => neighbor.get.get()(accessor),
259
- } satisfies SwaggerCustomizer.IProps);
260
- });
261
- }
262
- }
263
-
264
- // DO CUSTOMIZE
265
- for (const fn of customizers) fn();
266
- };
267
-
268
- const getPath = (route: ITypedHttpRoute): string => {
269
- let str: string = route.path;
270
- for (const param of route.pathParameters)
271
- str = str.replace(`:${param.field}`, `{${param.field}}`);
272
- return str;
273
- };
274
- }
275
-
276
- interface Accessor {
277
- method: string;
278
- path: string;
279
- }
280
- interface Endpoint {
281
- method: string;
282
- path: string;
283
- route: OpenApi.IOperation;
284
- }
1
+ import { SwaggerCustomizer } from "@nestia/core";
2
+ import { JsonSchemasProgrammer, MetadataSchema } from "@typia/core";
3
+ import { OpenApi, OpenApiV3, SwaggerV2 } from "@typia/interface";
4
+ import { OpenApiConverter } from "@typia/utils";
5
+ import fs from "fs";
6
+ import path from "path";
7
+ import { Singleton } from "tstl";
8
+ import typia, { IJsonSchemaCollection } from "typia";
9
+
10
+ import { INestiaConfig } from "../INestiaConfig";
11
+ import { ITypedApplication } from "../structures/ITypedApplication";
12
+ import { ITypedHttpRoute } from "../structures/ITypedHttpRoute";
13
+ import { FileRetriever } from "../utils/FileRetriever";
14
+ import { SdkHttpParameterProgrammer } from "./internal/SdkHttpParameterProgrammer";
15
+ import { SwaggerOperationComposer } from "./internal/SwaggerOperationComposer";
16
+
17
+ export namespace SwaggerGenerator {
18
+ export const generate = async (app: ITypedApplication): Promise<void> => {
19
+ // GET CONFIGURATION
20
+ console.log("Generating Swagger Document");
21
+ if (app.project.config.swagger === undefined)
22
+ throw new Error("Swagger configuration is not defined.");
23
+ const config: INestiaConfig.ISwaggerConfig = app.project.config.swagger;
24
+
25
+ // TARGET LOCATION
26
+ const parsed: path.ParsedPath = path.parse(config.output);
27
+ const directory: string = path.dirname(parsed.dir);
28
+ if (fs.existsSync(directory) === false)
29
+ try {
30
+ await fs.promises.mkdir(directory);
31
+ } catch {}
32
+ if (fs.existsSync(directory) === false)
33
+ throw new Error(
34
+ `Error on NestiaApplication.swagger(): failed to create output directory: ${directory}`,
35
+ );
36
+ const location: string = !!parsed.ext
37
+ ? path.resolve(config.output)
38
+ : path.join(path.resolve(config.output), "swagger.json");
39
+
40
+ // COMPOSE SWAGGER DOCUMENT
41
+ const document: OpenApi.IDocument = compose({
42
+ config,
43
+ routes: app.routes.filter((route) => route.protocol === "http"),
44
+ document: await initialize(config),
45
+ });
46
+ const specified:
47
+ | OpenApi.IDocument
48
+ | SwaggerV2.IDocument
49
+ | OpenApiV3.IDocument =
50
+ config.openapi === "2.0"
51
+ ? OpenApiConverter.downgradeDocument(document, config.openapi)
52
+ : config.openapi === "3.0"
53
+ ? OpenApiConverter.downgradeDocument(document, config.openapi)
54
+ : document;
55
+ await fs.promises.writeFile(
56
+ location,
57
+ !config.beautify
58
+ ? JSON.stringify(specified)
59
+ : JSON.stringify(
60
+ specified,
61
+ null,
62
+ typeof config.beautify === "number" ? config.beautify : 2,
63
+ ),
64
+ "utf8",
65
+ );
66
+ };
67
+
68
+ export const compose = (props: {
69
+ config: Omit<INestiaConfig.ISwaggerConfig, "output">;
70
+ routes: ITypedHttpRoute[];
71
+ document: OpenApi.IDocument;
72
+ }): OpenApi.IDocument => {
73
+ // GATHER METADATA
74
+ const routes: ITypedHttpRoute[] = props.routes.filter((r) =>
75
+ r.jsDocTags.every(
76
+ (tag) => tag.name !== "internal" && tag.name !== "hidden",
77
+ ),
78
+ );
79
+ const metadatas: MetadataSchema[] = routes
80
+ .map((r) => [
81
+ r.success.metadata,
82
+ ...SdkHttpParameterProgrammer.getAll(r).map((p) => p.metadata),
83
+ ...Object.values(r.exceptions).map((e) => e.metadata),
84
+ ])
85
+ .flat()
86
+ .filter((m) => m.size() !== 0);
87
+
88
+ // COMPOSE JSON SCHEMAS
89
+ const json: IJsonSchemaCollection = JsonSchemasProgrammer.write({
90
+ version: "3.1",
91
+ metadatas,
92
+ });
93
+ const dict: WeakMap<MetadataSchema, OpenApi.IJsonSchema> = new WeakMap();
94
+ json.schemas.forEach((schema, i) => dict.set(metadatas[i]!, schema));
95
+ const schema = (
96
+ metadata: MetadataSchema,
97
+ ): OpenApi.IJsonSchema | undefined => dict.get(metadata);
98
+
99
+ // COMPOSE DOCUMENT
100
+ const document: OpenApi.IDocument = props.document;
101
+ document.components.schemas ??= {};
102
+ Object.assign(document.components.schemas, json.components.schemas);
103
+ fillPaths({
104
+ ...props,
105
+ routes,
106
+ schema,
107
+ document,
108
+ });
109
+ return document;
110
+ };
111
+
112
+ export const initialize = async (
113
+ config: Omit<INestiaConfig.ISwaggerConfig, "output">,
114
+ ): Promise<OpenApi.IDocument> => {
115
+ const pack = new Singleton(
116
+ async (): Promise<Partial<OpenApi.IDocument.IInfo> | null> => {
117
+ const location: string | null = await FileRetriever.file(
118
+ "package.json",
119
+ )(process.cwd());
120
+ if (location === null) return null;
121
+
122
+ try {
123
+ const content: string = await fs.promises.readFile(location, "utf8");
124
+ const data = typia.json.assertParse<{
125
+ name?: string;
126
+ version?: string;
127
+ description?: string;
128
+ license?:
129
+ | string
130
+ | {
131
+ type: string;
132
+ /** @format uri */
133
+ url: string;
134
+ };
135
+ }>(content);
136
+ return {
137
+ title: data.name,
138
+ version: data.version,
139
+ description: data.description,
140
+ license: data.license
141
+ ? typeof data.license === "string"
142
+ ? { name: data.license }
143
+ : typeof data.license === "object"
144
+ ? {
145
+ name: data.license.type,
146
+ url: data.license.url,
147
+ }
148
+ : undefined
149
+ : undefined,
150
+ };
151
+ } catch {
152
+ return null;
153
+ }
154
+ },
155
+ );
156
+
157
+ return {
158
+ openapi: "3.1.0",
159
+ servers: config.servers ?? [
160
+ {
161
+ url: "https://github.com/samchon/nestia",
162
+ description: "insert your server url",
163
+ },
164
+ ],
165
+ info: {
166
+ ...(config.info ?? {}),
167
+ version: config.info?.version ?? (await pack.get())?.version ?? "0.1.0",
168
+ title:
169
+ config.info?.title ??
170
+ (await pack.get())?.title ??
171
+ "Swagger Documents",
172
+ description:
173
+ config.info?.description ??
174
+ (await pack.get())?.description ??
175
+ "Generated by nestia - https://github.com/samchon/nestia",
176
+ license: config.info?.license ?? (await pack.get())?.license,
177
+ },
178
+ paths: {},
179
+ components: {
180
+ schemas: {},
181
+ securitySchemes: config.security,
182
+ },
183
+ tags: config.tags ?? [],
184
+ "x-samchon-emended-v4": true,
185
+ };
186
+ };
187
+
188
+ const fillPaths = (props: {
189
+ config: Omit<INestiaConfig.ISwaggerConfig, "output">;
190
+ document: OpenApi.IDocument;
191
+ schema: (metadata: MetadataSchema) => OpenApi.IJsonSchema | undefined;
192
+ routes: ITypedHttpRoute[];
193
+ }): void => {
194
+ // SWAGGER CUSTOMIZER
195
+ const customizers: Array<() => void> = [];
196
+ const neighbor = {
197
+ at: new Singleton(() => {
198
+ const functor: Map<Function, Endpoint> = new Map();
199
+ for (const r of props.routes) {
200
+ const method: OpenApi.Method =
201
+ r.method.toLowerCase() as OpenApi.Method;
202
+ const path: string = getPath(r);
203
+ const operation: OpenApi.IOperation | undefined =
204
+ props.document.paths?.[path]?.[method];
205
+ if (operation === undefined) continue;
206
+ functor.set(r.function, {
207
+ method,
208
+ path,
209
+ route: operation,
210
+ });
211
+ }
212
+ return functor;
213
+ }),
214
+ get: new Singleton(
215
+ () =>
216
+ (key: Accessor): OpenApi.IOperation | undefined => {
217
+ const method: OpenApi.Method =
218
+ key.method.toLowerCase() as OpenApi.Method;
219
+ const path: string =
220
+ "/" +
221
+ key.path
222
+ .split("/")
223
+ .filter((str) => !!str.length)
224
+ .map((str) =>
225
+ str.startsWith(":") ? `{${str.substring(1)}}` : str,
226
+ )
227
+ .join("/");
228
+ return props.document.paths?.[path]?.[method];
229
+ },
230
+ ),
231
+ };
232
+
233
+ // COMPOSE OPERATIONS
234
+ for (const r of props.routes) {
235
+ const operation: OpenApi.IOperation = SwaggerOperationComposer.compose({
236
+ ...props,
237
+ route: r,
238
+ });
239
+ const path: string = getPath(r);
240
+ props.document.paths ??= {};
241
+ props.document.paths[path] ??= {};
242
+ props.document.paths[path][r.method.toLowerCase() as "get"] = operation;
243
+
244
+ const closure: Function | Function[] | undefined = Reflect.getMetadata(
245
+ "nestia/SwaggerCustomizer",
246
+ r.controller.class.prototype,
247
+ r.name,
248
+ );
249
+ if (closure !== undefined) {
250
+ const array: Function[] = Array.isArray(closure) ? closure : [closure];
251
+ customizers.push(() => {
252
+ for (const closure of array)
253
+ closure({
254
+ swagger: props.document,
255
+ method: r.method,
256
+ path,
257
+ route: operation,
258
+ at: (func: Function) => neighbor.at.get().get(func),
259
+ get: (accessor: Accessor) => neighbor.get.get()(accessor),
260
+ } satisfies SwaggerCustomizer.IProps);
261
+ });
262
+ }
263
+ }
264
+
265
+ // DO CUSTOMIZE
266
+ for (const fn of customizers) fn();
267
+ };
268
+
269
+ const getPath = (route: ITypedHttpRoute): string => {
270
+ let str: string = route.path;
271
+ for (const param of route.pathParameters)
272
+ str = str.replace(`:${param.field}`, `{${param.field}}`);
273
+ return str;
274
+ };
275
+ }
276
+
277
+ interface Accessor {
278
+ method: string;
279
+ path: string;
280
+ }
281
+ interface Endpoint {
282
+ method: string;
283
+ path: string;
284
+ route: OpenApi.IOperation;
285
+ }