@nestia/core 4.4.0 → 4.4.1-dev.20241216

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 (89) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +87 -87
  3. package/lib/options/INestiaTransformOptions.d.ts +7 -0
  4. package/lib/programmers/TypedBodyProgrammer.js +11 -0
  5. package/lib/programmers/TypedBodyProgrammer.js.map +1 -1
  6. package/lib/programmers/TypedQueryBodyProgrammer.js +36 -0
  7. package/lib/programmers/TypedQueryBodyProgrammer.js.map +1 -1
  8. package/lib/programmers/TypedQueryProgrammer.js +36 -0
  9. package/lib/programmers/TypedQueryProgrammer.js.map +1 -1
  10. package/lib/programmers/TypedQueryRouteProgrammer.js +36 -0
  11. package/lib/programmers/TypedQueryRouteProgrammer.js.map +1 -1
  12. package/lib/programmers/TypedRouteProgrammer.js +18 -0
  13. package/lib/programmers/TypedRouteProgrammer.js.map +1 -1
  14. package/lib/programmers/internal/LlmValidatePredicator.d.ts +5 -0
  15. package/lib/programmers/internal/LlmValidatePredicator.js +18 -0
  16. package/lib/programmers/internal/LlmValidatePredicator.js.map +1 -0
  17. package/package.json +6 -6
  18. package/src/adaptors/WebSocketAdaptor.ts +426 -426
  19. package/src/decorators/DynamicModule.ts +43 -43
  20. package/src/decorators/EncryptedBody.ts +101 -101
  21. package/src/decorators/EncryptedController.ts +38 -38
  22. package/src/decorators/EncryptedModule.ts +100 -100
  23. package/src/decorators/EncryptedRoute.ts +219 -219
  24. package/src/decorators/NoTransformConfigurationError.ts +32 -32
  25. package/src/decorators/PlainBody.ts +79 -79
  26. package/src/decorators/SwaggerCustomizer.ts +115 -115
  27. package/src/decorators/SwaggerExample.ts +100 -100
  28. package/src/decorators/TypedBody.ts +59 -59
  29. package/src/decorators/TypedException.ts +128 -128
  30. package/src/decorators/TypedFormData.ts +195 -195
  31. package/src/decorators/TypedHeaders.ts +64 -64
  32. package/src/decorators/TypedParam.ts +77 -77
  33. package/src/decorators/TypedQuery.ts +245 -245
  34. package/src/decorators/TypedRoute.ts +214 -214
  35. package/src/decorators/WebSocketRoute.ts +242 -242
  36. package/src/decorators/internal/EncryptedConstant.ts +4 -4
  37. package/src/decorators/internal/IWebSocketRouteReflect.ts +23 -23
  38. package/src/decorators/internal/NoTransformConfigureError.ts +2 -2
  39. package/src/decorators/internal/get_path_and_querify.ts +108 -108
  40. package/src/decorators/internal/get_path_and_stringify.ts +122 -122
  41. package/src/decorators/internal/get_text_body.ts +20 -20
  42. package/src/decorators/internal/headers_to_object.ts +13 -13
  43. package/src/decorators/internal/is_request_body_undefined.ts +14 -14
  44. package/src/decorators/internal/load_controller.ts +49 -49
  45. package/src/decorators/internal/route_error.ts +45 -45
  46. package/src/decorators/internal/validate_request_body.ts +74 -74
  47. package/src/decorators/internal/validate_request_form_data.ts +77 -77
  48. package/src/decorators/internal/validate_request_headers.ts +86 -86
  49. package/src/decorators/internal/validate_request_query.ts +74 -74
  50. package/src/index.ts +5 -5
  51. package/src/module.ts +21 -21
  52. package/src/options/INestiaTransformOptions.ts +38 -29
  53. package/src/options/INestiaTransformProject.ts +8 -8
  54. package/src/options/IRequestBodyValidator.ts +20 -20
  55. package/src/options/IRequestFormDataProps.ts +27 -27
  56. package/src/options/IRequestHeadersValidator.ts +22 -22
  57. package/src/options/IRequestQueryValidator.ts +20 -20
  58. package/src/options/IResponseBodyQuerifier.ts +25 -25
  59. package/src/options/IResponseBodyStringifier.ts +30 -30
  60. package/src/programmers/PlainBodyProgrammer.ts +70 -70
  61. package/src/programmers/TypedBodyProgrammer.ts +143 -132
  62. package/src/programmers/TypedFormDataBodyProgrammer.ts +118 -118
  63. package/src/programmers/TypedHeadersProgrammer.ts +63 -63
  64. package/src/programmers/TypedParamProgrammer.ts +33 -33
  65. package/src/programmers/TypedQueryBodyProgrammer.ts +106 -63
  66. package/src/programmers/TypedQueryProgrammer.ts +108 -65
  67. package/src/programmers/TypedQueryRouteProgrammer.ts +99 -56
  68. package/src/programmers/TypedRouteProgrammer.ts +95 -76
  69. package/src/programmers/http/HttpAssertQuerifyProgrammer.ts +72 -72
  70. package/src/programmers/http/HttpIsQuerifyProgrammer.ts +75 -75
  71. package/src/programmers/http/HttpQuerifyProgrammer.ts +108 -108
  72. package/src/programmers/http/HttpValidateQuerifyProgrammer.ts +76 -76
  73. package/src/programmers/internal/CoreMetadataUtil.ts +21 -21
  74. package/src/programmers/internal/LlmValidatePredicator.ts +16 -0
  75. package/src/transform.ts +35 -35
  76. package/src/transformers/FileTransformer.ts +110 -110
  77. package/src/transformers/MethodTransformer.ts +103 -103
  78. package/src/transformers/NodeTransformer.ts +23 -23
  79. package/src/transformers/ParameterDecoratorTransformer.ts +143 -143
  80. package/src/transformers/ParameterTransformer.ts +57 -57
  81. package/src/transformers/TypedRouteTransformer.ts +85 -85
  82. package/src/transformers/WebSocketRouteTransformer.ts +120 -120
  83. package/src/typings/Creator.ts +3 -3
  84. package/src/typings/get-function-location.d.ts +7 -7
  85. package/src/utils/ArrayUtil.ts +7 -7
  86. package/src/utils/ExceptionManager.ts +112 -112
  87. package/src/utils/Singleton.ts +20 -20
  88. package/src/utils/SourceFinder.ts +57 -57
  89. package/src/utils/VersioningStrategy.ts +27 -27
@@ -1,426 +1,426 @@
1
- /// <reference path="../typings/get-function-location.d.ts" />
2
- import { INestApplication, VersioningType } from "@nestjs/common";
3
- import {
4
- HOST_METADATA,
5
- MODULE_PATH,
6
- PATH_METADATA,
7
- SCOPE_OPTIONS_METADATA,
8
- VERSION_METADATA,
9
- } from "@nestjs/common/constants";
10
- import { VERSION_NEUTRAL, VersionValue } from "@nestjs/common/interfaces";
11
- import { NestContainer } from "@nestjs/core";
12
- import { InstanceWrapper } from "@nestjs/core/injector/instance-wrapper";
13
- import { Module } from "@nestjs/core/injector/module";
14
- import getFunctionLocation from "get-function-location";
15
- import { IncomingMessage, Server } from "http";
16
- import path from "path";
17
- import { Path } from "path-parser";
18
- import { Duplex } from "stream";
19
- import { WebSocketAcceptor } from "tgrid";
20
- import typia from "typia";
21
- import WebSocket from "ws";
22
-
23
- import { IWebSocketRouteReflect } from "../decorators/internal/IWebSocketRouteReflect";
24
- import { ArrayUtil } from "../utils/ArrayUtil";
25
- import { VersioningStrategy } from "../utils/VersioningStrategy";
26
-
27
- export class WebSocketAdaptor {
28
- public static async upgrade(
29
- app: INestApplication,
30
- ): Promise<WebSocketAdaptor> {
31
- return new this(app, await visitApplication(app));
32
- }
33
-
34
- public readonly close = async (): Promise<void> =>
35
- new Promise((resolve) => {
36
- this.http.off("close", this.close);
37
- this.http.off("upgrade", this.handleUpgrade);
38
- this.ws.close(() => resolve());
39
- });
40
-
41
- protected constructor(app: INestApplication, operations: IOperator[]) {
42
- this.operators = operations;
43
- this.ws = new WebSocket.Server({ noServer: true });
44
- this.http = app.getHttpServer();
45
- this.http.on("close", this.close);
46
- this.http.on("upgrade", this.handleUpgrade);
47
- }
48
-
49
- private readonly handleUpgrade = (
50
- request: IncomingMessage,
51
- duplex: Duplex,
52
- head: Buffer,
53
- ) => {
54
- this.ws.handleUpgrade(request, duplex, head, (client, request) =>
55
- WebSocketAcceptor.upgrade(
56
- request,
57
- client as any,
58
- async (acceptor): Promise<void> => {
59
- const path: string = (() => {
60
- const index: number = acceptor.path.indexOf("?");
61
- return index === -1 ? acceptor.path : acceptor.path.slice(0, index);
62
- })();
63
- for (const op of this.operators) {
64
- const params: Record<string, string> | null = op.parser.test(path);
65
- if (params !== null)
66
- try {
67
- await op.handler({ params, acceptor });
68
- } catch (error) {
69
- if (
70
- acceptor.state === WebSocketAcceptor.State.OPEN ||
71
- acceptor.state === WebSocketAcceptor.State.ACCEPTING
72
- )
73
- await acceptor.reject(
74
- 1008,
75
- error instanceof Error
76
- ? JSON.stringify({ ...error })
77
- : "unknown error",
78
- );
79
- } finally {
80
- return;
81
- }
82
- }
83
- await acceptor.reject(1002, `WebSocket API not found`);
84
- },
85
- ),
86
- );
87
- };
88
-
89
- private readonly http: Server;
90
- private readonly operators: IOperator[];
91
- private readonly ws: WebSocket.Server;
92
- }
93
-
94
- const visitApplication = async (
95
- app: INestApplication,
96
- ): Promise<IOperator[]> => {
97
- const operators: IOperator[] = [];
98
- const errors: IControllerError[] = [];
99
-
100
- const config: IConfig = {
101
- globalPrefix:
102
- typeof (app as any).config?.globalPrefix === "string"
103
- ? (app as any).config.globalPrefix
104
- : undefined,
105
- versioning: (() => {
106
- const versioning = (app as any).config?.versioningOptions;
107
- return versioning === undefined || versioning.type !== VersioningType.URI
108
- ? undefined
109
- : {
110
- prefix:
111
- versioning.prefix === undefined || versioning.prefix === false
112
- ? "v"
113
- : versioning.prefix,
114
- defaultVersion: versioning.defaultVersion,
115
- };
116
- })(),
117
- };
118
- const container: NestContainer = (app as any).container as NestContainer;
119
- const modules: Module[] = [...container.getModules().values()].filter(
120
- (m) => !!m.controllers?.size,
121
- );
122
- for (const m of modules) {
123
- const modulePrefix: string =
124
- Reflect.getMetadata(
125
- MODULE_PATH + container.getModules().applicationId,
126
- m.metatype,
127
- ) ??
128
- Reflect.getMetadata(MODULE_PATH, m.metatype) ??
129
- "";
130
- for (const controller of m.controllers.values())
131
- await visitController({
132
- config,
133
- errors,
134
- operators,
135
- controller,
136
- modulePrefix,
137
- });
138
- }
139
- if (errors.length)
140
- throw new Error(
141
- [
142
- `WebSocketAdaptor: ${errors.length} error(s) found:`,
143
- ``,
144
- ...errors.map((e) =>
145
- [
146
- ` - controller: ${e.name}`,
147
- ` methods:`,
148
- ...e.methods.map((m) =>
149
- [
150
- ` - name: ${m.name}`,
151
- ` file: ${m.source}:${m.line}:${m.column}`,
152
- ` reasons:`,
153
- ...m.messages.map(
154
- (msg) =>
155
- ` - ${msg
156
- .split("\n")
157
- .map((str, i) => (i == 0 ? str : ` ${str}`))
158
- .join("\n")}`,
159
- ),
160
- ].join("\n"),
161
- ),
162
- ].join("\n"),
163
- ),
164
- ].join("\n"),
165
- );
166
- return operators;
167
- };
168
-
169
- const visitController = async (props: {
170
- config: IConfig;
171
- errors: IControllerError[];
172
- operators: IOperator[];
173
- controller: InstanceWrapper<object>;
174
- modulePrefix: string;
175
- }): Promise<void> => {
176
- if (
177
- ArrayUtil.has(
178
- Reflect.getMetadataKeys(props.controller.metatype),
179
- PATH_METADATA,
180
- HOST_METADATA,
181
- SCOPE_OPTIONS_METADATA,
182
- ) === false
183
- )
184
- return;
185
-
186
- const methodErrors: IMethodError[] = [];
187
- const controller: IController = {
188
- name: props.controller.name,
189
- instance: props.controller.instance,
190
- constructor: props.controller.metatype,
191
- prototype: Object.getPrototypeOf(props.controller.instance),
192
- prefixes: (() => {
193
- const value: string | string[] = Reflect.getMetadata(
194
- PATH_METADATA,
195
- props.controller.metatype,
196
- );
197
- if (typeof value === "string") return [value];
198
- else if (value.length === 0) return [""];
199
- else return value;
200
- })(),
201
- versions: props.config.versioning
202
- ? VersioningStrategy.cast(
203
- Reflect.getMetadata(VERSION_METADATA, props.controller.metatype),
204
- )
205
- : undefined,
206
- modulePrefix: props.modulePrefix,
207
- };
208
- for (const mk of getOwnPropertyNames(controller.prototype).filter(
209
- (key) =>
210
- key !== "constructor" && typeof controller.prototype[key] === "function",
211
- )) {
212
- const errorMessages: string[] = [];
213
- visitMethod({
214
- config: props.config,
215
- operators: props.operators,
216
- controller,
217
- method: {
218
- key: mk,
219
- value: controller.prototype[mk],
220
- },
221
- report: (msg) => errorMessages.push(msg),
222
- });
223
- if (errorMessages.length) {
224
- const file = await getFunctionLocation(controller.prototype[mk]);
225
- methodErrors.push({
226
- name: mk,
227
- messages: errorMessages,
228
- ...file,
229
- source: path.relative(
230
- process.cwd(),
231
- file.source.replace("file:///", ""),
232
- ),
233
- });
234
- }
235
- }
236
-
237
- if (methodErrors.length)
238
- props.errors.push({
239
- name: controller.name,
240
- methods: methodErrors,
241
- });
242
- };
243
-
244
- const visitMethod = (props: {
245
- config: IConfig;
246
- operators: IOperator[];
247
- controller: IController;
248
- method: Entry<Function>;
249
- report: (message: string) => void;
250
- }): void => {
251
- const route: IWebSocketRouteReflect | undefined = Reflect.getMetadata(
252
- "nestia/WebSocketRoute",
253
- props.method.value,
254
- );
255
- if (typia.is<IWebSocketRouteReflect>(route) === false) return;
256
-
257
- const parameters: IWebSocketRouteReflect.IArgument[] = (
258
- (Reflect.getMetadata(
259
- "nestia/WebSocketRoute/Parameters",
260
- props.controller.prototype,
261
- props.method.key,
262
- ) ?? []) as IWebSocketRouteReflect.IArgument[]
263
- ).sort((a, b) => a.index - b.index);
264
- // acceptor must be
265
- if (parameters.some((p) => p.category === "acceptor") === false)
266
- return props.report(
267
- "@WebSocketRoute.Acceptor() decorated parameter must be.",
268
- );
269
- // length of parameters must be fulfilled
270
- if (parameters.length !== props.method.value.length)
271
- return props.report(
272
- [
273
- "Every parameters must be one of below:",
274
- " - @WebSocketRoute.Acceptor()",
275
- " - @WebSocketRoute.Driver()",
276
- " - @WebSocketRoute.Header()",
277
- " - @WebSocketRoute.Param()",
278
- " - @WebSocketRoute.Query()",
279
- ].join("\n"),
280
- );
281
-
282
- const versions: string[] = VersioningStrategy.merge(props.config.versioning)([
283
- ...(props.controller.versions ?? []),
284
- ...VersioningStrategy.cast(
285
- Reflect.getMetadata(VERSION_METADATA, props.method.value),
286
- ),
287
- ]);
288
- for (const v of versions)
289
- for (const cp of wrapPaths(props.controller.prefixes))
290
- for (const mp of wrapPaths(route.paths)) {
291
- const parser: Path = new Path(
292
- "/" +
293
- [
294
- props.config.globalPrefix ?? "",
295
- v,
296
- props.controller.modulePrefix,
297
- cp,
298
- mp,
299
- ]
300
- .filter((str) => !!str.length)
301
- .join("/")
302
- .split("/")
303
- .filter((str) => str.length)
304
- .join("/"),
305
- );
306
- const pathParams: IWebSocketRouteReflect.IParam[] = parameters.filter(
307
- (p) => p.category === "param",
308
- ) as IWebSocketRouteReflect.IParam[];
309
- if (parser.params.length !== pathParams.length) {
310
- props.report(
311
- [
312
- `Path "${parser}" must have same number of parameters with @WebSocketRoute.Param()`,
313
- ` - path: ${JSON.stringify(parser.params)}`,
314
- ` - arguments: ${JSON.stringify(pathParams.map((p) => p.field))}`,
315
- ].join("\n"),
316
- );
317
- continue;
318
- }
319
- const meet: boolean = pathParams
320
- .map((p) => {
321
- const has: boolean = parser.params.includes(p.field);
322
- if (has === false)
323
- props.report(
324
- `Path "${parser}" must have parameter "${p.field}" with @WebSocketRoute.Param()`,
325
- );
326
- return has;
327
- })
328
- .every((b) => b);
329
- if (meet === false) continue;
330
-
331
- props.operators.push({
332
- parser,
333
- handler: async (input: {
334
- params: Record<string, string>;
335
- acceptor: WebSocketAcceptor<any, any, any>;
336
- }): Promise<void> => {
337
- const args: any[] = [];
338
- try {
339
- for (const p of parameters)
340
- if (p.category === "acceptor") args.push(input.acceptor);
341
- else if (p.category === "driver")
342
- args.push(input.acceptor.getDriver());
343
- else if (p.category === "header") {
344
- const error: Error | null = p.validate(input.acceptor.header);
345
- if (error !== null) throw error;
346
- args.push(input.acceptor.header);
347
- } else if (p.category === "param")
348
- args.push(p.assert(input.params[p.field]));
349
- else if (p.category === "query") {
350
- const query: any | Error = p.validate(
351
- new URLSearchParams(
352
- input.acceptor.path.indexOf("?") !== -1
353
- ? input.acceptor.path.split("?")[1]
354
- : "",
355
- ),
356
- );
357
- if (query instanceof Error) throw query;
358
- args.push(query);
359
- }
360
- } catch (exp) {
361
- await input.acceptor.reject(
362
- 1003,
363
- exp instanceof Error
364
- ? JSON.stringify({ ...exp })
365
- : "unknown error",
366
- );
367
- return;
368
- }
369
- await props.method.value.call(props.controller.instance, ...args);
370
- },
371
- });
372
- }
373
- };
374
-
375
- const wrapPaths = (value: string[]) => (value.length === 0 ? [""] : value);
376
- const getOwnPropertyNames = (prototype: any): string[] => {
377
- const result: Set<string> = new Set();
378
- const iterate = (m: any) => {
379
- if (m === null) return;
380
- for (const k of Object.getOwnPropertyNames(m)) result.add(k);
381
- iterate(Object.getPrototypeOf(m));
382
- };
383
- iterate(prototype);
384
- return Array.from(result);
385
- };
386
-
387
- interface Entry<T> {
388
- key: string;
389
- value: T;
390
- }
391
-
392
- interface IController {
393
- name: string;
394
- versions: Array<string | typeof VERSION_NEUTRAL> | undefined;
395
- instance: object;
396
- constructor: Function;
397
- prototype: any;
398
- prefixes: string[];
399
- modulePrefix: string;
400
- }
401
- interface IOperator {
402
- parser: Path;
403
- handler: (props: {
404
- params: Record<string, string>;
405
- acceptor: WebSocketAcceptor<any, any, any>;
406
- }) => Promise<any>;
407
- }
408
- interface IConfig {
409
- globalPrefix?: string;
410
- versioning?: {
411
- prefix: string;
412
- defaultVersion?: VersionValue;
413
- };
414
- }
415
-
416
- interface IControllerError {
417
- name: string;
418
- methods: IMethodError[];
419
- }
420
- interface IMethodError {
421
- name: string;
422
- messages: string[];
423
- source: string;
424
- line: number;
425
- column: number;
426
- }
1
+ /// <reference path="../typings/get-function-location.d.ts" />
2
+ import { INestApplication, VersioningType } from "@nestjs/common";
3
+ import {
4
+ HOST_METADATA,
5
+ MODULE_PATH,
6
+ PATH_METADATA,
7
+ SCOPE_OPTIONS_METADATA,
8
+ VERSION_METADATA,
9
+ } from "@nestjs/common/constants";
10
+ import { VERSION_NEUTRAL, VersionValue } from "@nestjs/common/interfaces";
11
+ import { NestContainer } from "@nestjs/core";
12
+ import { InstanceWrapper } from "@nestjs/core/injector/instance-wrapper";
13
+ import { Module } from "@nestjs/core/injector/module";
14
+ import getFunctionLocation from "get-function-location";
15
+ import { IncomingMessage, Server } from "http";
16
+ import path from "path";
17
+ import { Path } from "path-parser";
18
+ import { Duplex } from "stream";
19
+ import { WebSocketAcceptor } from "tgrid";
20
+ import typia from "typia";
21
+ import WebSocket from "ws";
22
+
23
+ import { IWebSocketRouteReflect } from "../decorators/internal/IWebSocketRouteReflect";
24
+ import { ArrayUtil } from "../utils/ArrayUtil";
25
+ import { VersioningStrategy } from "../utils/VersioningStrategy";
26
+
27
+ export class WebSocketAdaptor {
28
+ public static async upgrade(
29
+ app: INestApplication,
30
+ ): Promise<WebSocketAdaptor> {
31
+ return new this(app, await visitApplication(app));
32
+ }
33
+
34
+ public readonly close = async (): Promise<void> =>
35
+ new Promise((resolve) => {
36
+ this.http.off("close", this.close);
37
+ this.http.off("upgrade", this.handleUpgrade);
38
+ this.ws.close(() => resolve());
39
+ });
40
+
41
+ protected constructor(app: INestApplication, operations: IOperator[]) {
42
+ this.operators = operations;
43
+ this.ws = new WebSocket.Server({ noServer: true });
44
+ this.http = app.getHttpServer();
45
+ this.http.on("close", this.close);
46
+ this.http.on("upgrade", this.handleUpgrade);
47
+ }
48
+
49
+ private readonly handleUpgrade = (
50
+ request: IncomingMessage,
51
+ duplex: Duplex,
52
+ head: Buffer,
53
+ ) => {
54
+ this.ws.handleUpgrade(request, duplex, head, (client, request) =>
55
+ WebSocketAcceptor.upgrade(
56
+ request,
57
+ client as any,
58
+ async (acceptor): Promise<void> => {
59
+ const path: string = (() => {
60
+ const index: number = acceptor.path.indexOf("?");
61
+ return index === -1 ? acceptor.path : acceptor.path.slice(0, index);
62
+ })();
63
+ for (const op of this.operators) {
64
+ const params: Record<string, string> | null = op.parser.test(path);
65
+ if (params !== null)
66
+ try {
67
+ await op.handler({ params, acceptor });
68
+ } catch (error) {
69
+ if (
70
+ acceptor.state === WebSocketAcceptor.State.OPEN ||
71
+ acceptor.state === WebSocketAcceptor.State.ACCEPTING
72
+ )
73
+ await acceptor.reject(
74
+ 1008,
75
+ error instanceof Error
76
+ ? JSON.stringify({ ...error })
77
+ : "unknown error",
78
+ );
79
+ } finally {
80
+ return;
81
+ }
82
+ }
83
+ await acceptor.reject(1002, `WebSocket API not found`);
84
+ },
85
+ ),
86
+ );
87
+ };
88
+
89
+ private readonly http: Server;
90
+ private readonly operators: IOperator[];
91
+ private readonly ws: WebSocket.Server;
92
+ }
93
+
94
+ const visitApplication = async (
95
+ app: INestApplication,
96
+ ): Promise<IOperator[]> => {
97
+ const operators: IOperator[] = [];
98
+ const errors: IControllerError[] = [];
99
+
100
+ const config: IConfig = {
101
+ globalPrefix:
102
+ typeof (app as any).config?.globalPrefix === "string"
103
+ ? (app as any).config.globalPrefix
104
+ : undefined,
105
+ versioning: (() => {
106
+ const versioning = (app as any).config?.versioningOptions;
107
+ return versioning === undefined || versioning.type !== VersioningType.URI
108
+ ? undefined
109
+ : {
110
+ prefix:
111
+ versioning.prefix === undefined || versioning.prefix === false
112
+ ? "v"
113
+ : versioning.prefix,
114
+ defaultVersion: versioning.defaultVersion,
115
+ };
116
+ })(),
117
+ };
118
+ const container: NestContainer = (app as any).container as NestContainer;
119
+ const modules: Module[] = [...container.getModules().values()].filter(
120
+ (m) => !!m.controllers?.size,
121
+ );
122
+ for (const m of modules) {
123
+ const modulePrefix: string =
124
+ Reflect.getMetadata(
125
+ MODULE_PATH + container.getModules().applicationId,
126
+ m.metatype,
127
+ ) ??
128
+ Reflect.getMetadata(MODULE_PATH, m.metatype) ??
129
+ "";
130
+ for (const controller of m.controllers.values())
131
+ await visitController({
132
+ config,
133
+ errors,
134
+ operators,
135
+ controller,
136
+ modulePrefix,
137
+ });
138
+ }
139
+ if (errors.length)
140
+ throw new Error(
141
+ [
142
+ `WebSocketAdaptor: ${errors.length} error(s) found:`,
143
+ ``,
144
+ ...errors.map((e) =>
145
+ [
146
+ ` - controller: ${e.name}`,
147
+ ` methods:`,
148
+ ...e.methods.map((m) =>
149
+ [
150
+ ` - name: ${m.name}`,
151
+ ` file: ${m.source}:${m.line}:${m.column}`,
152
+ ` reasons:`,
153
+ ...m.messages.map(
154
+ (msg) =>
155
+ ` - ${msg
156
+ .split("\n")
157
+ .map((str, i) => (i == 0 ? str : ` ${str}`))
158
+ .join("\n")}`,
159
+ ),
160
+ ].join("\n"),
161
+ ),
162
+ ].join("\n"),
163
+ ),
164
+ ].join("\n"),
165
+ );
166
+ return operators;
167
+ };
168
+
169
+ const visitController = async (props: {
170
+ config: IConfig;
171
+ errors: IControllerError[];
172
+ operators: IOperator[];
173
+ controller: InstanceWrapper<object>;
174
+ modulePrefix: string;
175
+ }): Promise<void> => {
176
+ if (
177
+ ArrayUtil.has(
178
+ Reflect.getMetadataKeys(props.controller.metatype),
179
+ PATH_METADATA,
180
+ HOST_METADATA,
181
+ SCOPE_OPTIONS_METADATA,
182
+ ) === false
183
+ )
184
+ return;
185
+
186
+ const methodErrors: IMethodError[] = [];
187
+ const controller: IController = {
188
+ name: props.controller.name,
189
+ instance: props.controller.instance,
190
+ constructor: props.controller.metatype,
191
+ prototype: Object.getPrototypeOf(props.controller.instance),
192
+ prefixes: (() => {
193
+ const value: string | string[] = Reflect.getMetadata(
194
+ PATH_METADATA,
195
+ props.controller.metatype,
196
+ );
197
+ if (typeof value === "string") return [value];
198
+ else if (value.length === 0) return [""];
199
+ else return value;
200
+ })(),
201
+ versions: props.config.versioning
202
+ ? VersioningStrategy.cast(
203
+ Reflect.getMetadata(VERSION_METADATA, props.controller.metatype),
204
+ )
205
+ : undefined,
206
+ modulePrefix: props.modulePrefix,
207
+ };
208
+ for (const mk of getOwnPropertyNames(controller.prototype).filter(
209
+ (key) =>
210
+ key !== "constructor" && typeof controller.prototype[key] === "function",
211
+ )) {
212
+ const errorMessages: string[] = [];
213
+ visitMethod({
214
+ config: props.config,
215
+ operators: props.operators,
216
+ controller,
217
+ method: {
218
+ key: mk,
219
+ value: controller.prototype[mk],
220
+ },
221
+ report: (msg) => errorMessages.push(msg),
222
+ });
223
+ if (errorMessages.length) {
224
+ const file = await getFunctionLocation(controller.prototype[mk]);
225
+ methodErrors.push({
226
+ name: mk,
227
+ messages: errorMessages,
228
+ ...file,
229
+ source: path.relative(
230
+ process.cwd(),
231
+ file.source.replace("file:///", ""),
232
+ ),
233
+ });
234
+ }
235
+ }
236
+
237
+ if (methodErrors.length)
238
+ props.errors.push({
239
+ name: controller.name,
240
+ methods: methodErrors,
241
+ });
242
+ };
243
+
244
+ const visitMethod = (props: {
245
+ config: IConfig;
246
+ operators: IOperator[];
247
+ controller: IController;
248
+ method: Entry<Function>;
249
+ report: (message: string) => void;
250
+ }): void => {
251
+ const route: IWebSocketRouteReflect | undefined = Reflect.getMetadata(
252
+ "nestia/WebSocketRoute",
253
+ props.method.value,
254
+ );
255
+ if (typia.is<IWebSocketRouteReflect>(route) === false) return;
256
+
257
+ const parameters: IWebSocketRouteReflect.IArgument[] = (
258
+ (Reflect.getMetadata(
259
+ "nestia/WebSocketRoute/Parameters",
260
+ props.controller.prototype,
261
+ props.method.key,
262
+ ) ?? []) as IWebSocketRouteReflect.IArgument[]
263
+ ).sort((a, b) => a.index - b.index);
264
+ // acceptor must be
265
+ if (parameters.some((p) => p.category === "acceptor") === false)
266
+ return props.report(
267
+ "@WebSocketRoute.Acceptor() decorated parameter must be.",
268
+ );
269
+ // length of parameters must be fulfilled
270
+ if (parameters.length !== props.method.value.length)
271
+ return props.report(
272
+ [
273
+ "Every parameters must be one of below:",
274
+ " - @WebSocketRoute.Acceptor()",
275
+ " - @WebSocketRoute.Driver()",
276
+ " - @WebSocketRoute.Header()",
277
+ " - @WebSocketRoute.Param()",
278
+ " - @WebSocketRoute.Query()",
279
+ ].join("\n"),
280
+ );
281
+
282
+ const versions: string[] = VersioningStrategy.merge(props.config.versioning)([
283
+ ...(props.controller.versions ?? []),
284
+ ...VersioningStrategy.cast(
285
+ Reflect.getMetadata(VERSION_METADATA, props.method.value),
286
+ ),
287
+ ]);
288
+ for (const v of versions)
289
+ for (const cp of wrapPaths(props.controller.prefixes))
290
+ for (const mp of wrapPaths(route.paths)) {
291
+ const parser: Path = new Path(
292
+ "/" +
293
+ [
294
+ props.config.globalPrefix ?? "",
295
+ v,
296
+ props.controller.modulePrefix,
297
+ cp,
298
+ mp,
299
+ ]
300
+ .filter((str) => !!str.length)
301
+ .join("/")
302
+ .split("/")
303
+ .filter((str) => str.length)
304
+ .join("/"),
305
+ );
306
+ const pathParams: IWebSocketRouteReflect.IParam[] = parameters.filter(
307
+ (p) => p.category === "param",
308
+ ) as IWebSocketRouteReflect.IParam[];
309
+ if (parser.params.length !== pathParams.length) {
310
+ props.report(
311
+ [
312
+ `Path "${parser}" must have same number of parameters with @WebSocketRoute.Param()`,
313
+ ` - path: ${JSON.stringify(parser.params)}`,
314
+ ` - arguments: ${JSON.stringify(pathParams.map((p) => p.field))}`,
315
+ ].join("\n"),
316
+ );
317
+ continue;
318
+ }
319
+ const meet: boolean = pathParams
320
+ .map((p) => {
321
+ const has: boolean = parser.params.includes(p.field);
322
+ if (has === false)
323
+ props.report(
324
+ `Path "${parser}" must have parameter "${p.field}" with @WebSocketRoute.Param()`,
325
+ );
326
+ return has;
327
+ })
328
+ .every((b) => b);
329
+ if (meet === false) continue;
330
+
331
+ props.operators.push({
332
+ parser,
333
+ handler: async (input: {
334
+ params: Record<string, string>;
335
+ acceptor: WebSocketAcceptor<any, any, any>;
336
+ }): Promise<void> => {
337
+ const args: any[] = [];
338
+ try {
339
+ for (const p of parameters)
340
+ if (p.category === "acceptor") args.push(input.acceptor);
341
+ else if (p.category === "driver")
342
+ args.push(input.acceptor.getDriver());
343
+ else if (p.category === "header") {
344
+ const error: Error | null = p.validate(input.acceptor.header);
345
+ if (error !== null) throw error;
346
+ args.push(input.acceptor.header);
347
+ } else if (p.category === "param")
348
+ args.push(p.assert(input.params[p.field]));
349
+ else if (p.category === "query") {
350
+ const query: any | Error = p.validate(
351
+ new URLSearchParams(
352
+ input.acceptor.path.indexOf("?") !== -1
353
+ ? input.acceptor.path.split("?")[1]
354
+ : "",
355
+ ),
356
+ );
357
+ if (query instanceof Error) throw query;
358
+ args.push(query);
359
+ }
360
+ } catch (exp) {
361
+ await input.acceptor.reject(
362
+ 1003,
363
+ exp instanceof Error
364
+ ? JSON.stringify({ ...exp })
365
+ : "unknown error",
366
+ );
367
+ return;
368
+ }
369
+ await props.method.value.call(props.controller.instance, ...args);
370
+ },
371
+ });
372
+ }
373
+ };
374
+
375
+ const wrapPaths = (value: string[]) => (value.length === 0 ? [""] : value);
376
+ const getOwnPropertyNames = (prototype: any): string[] => {
377
+ const result: Set<string> = new Set();
378
+ const iterate = (m: any) => {
379
+ if (m === null) return;
380
+ for (const k of Object.getOwnPropertyNames(m)) result.add(k);
381
+ iterate(Object.getPrototypeOf(m));
382
+ };
383
+ iterate(prototype);
384
+ return Array.from(result);
385
+ };
386
+
387
+ interface Entry<T> {
388
+ key: string;
389
+ value: T;
390
+ }
391
+
392
+ interface IController {
393
+ name: string;
394
+ versions: Array<string | typeof VERSION_NEUTRAL> | undefined;
395
+ instance: object;
396
+ constructor: Function;
397
+ prototype: any;
398
+ prefixes: string[];
399
+ modulePrefix: string;
400
+ }
401
+ interface IOperator {
402
+ parser: Path;
403
+ handler: (props: {
404
+ params: Record<string, string>;
405
+ acceptor: WebSocketAcceptor<any, any, any>;
406
+ }) => Promise<any>;
407
+ }
408
+ interface IConfig {
409
+ globalPrefix?: string;
410
+ versioning?: {
411
+ prefix: string;
412
+ defaultVersion?: VersionValue;
413
+ };
414
+ }
415
+
416
+ interface IControllerError {
417
+ name: string;
418
+ methods: IMethodError[];
419
+ }
420
+ interface IMethodError {
421
+ name: string;
422
+ messages: string[];
423
+ source: string;
424
+ line: number;
425
+ column: number;
426
+ }