@noxfly/noxus 1.1.1 → 1.1.2
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/dist/noxus.d.mts +344 -30
- package/dist/noxus.d.ts +344 -30
- package/dist/noxus.js +5 -1208
- package/dist/noxus.mjs +5 -1130
- package/dist/noxus.mjs.map +1 -1
- package/package.json +1 -1
- package/src/DI/app-injector.ts +38 -10
- package/src/DI/injector-explorer.ts +9 -7
- package/src/app.ts +40 -7
- package/src/bootstrap.ts +6 -1
- package/src/decorators/controller.decorator.ts +18 -3
- package/src/decorators/guards.decorator.ts +25 -5
- package/src/decorators/injectable.decorator.ts +16 -3
- package/src/decorators/method.decorator.ts +65 -11
- package/src/decorators/middleware.decorator.ts +34 -4
- package/src/decorators/module.decorator.ts +17 -11
- package/src/request.ts +14 -0
- package/src/router.ts +76 -19
- package/src/utils/logger.ts +109 -31
- package/src/utils/radix-tree.ts +71 -4
- package/src/utils/types.ts +8 -3
- package/tsup.config.ts +2 -2
package/dist/noxus.mjs
CHANGED
|
@@ -3,1136 +3,11 @@
|
|
|
3
3
|
* @license MIT
|
|
4
4
|
* @author NoxFly
|
|
5
5
|
*/
|
|
6
|
-
var
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
// src/DI/app-injector.ts
|
|
12
|
-
import "reflect-metadata";
|
|
13
|
-
|
|
14
|
-
// src/exceptions.ts
|
|
15
|
-
var _ResponseException = class _ResponseException extends Error {
|
|
16
|
-
constructor(statusOrMessage, message) {
|
|
17
|
-
let statusCode;
|
|
18
|
-
if (typeof statusOrMessage === "number") {
|
|
19
|
-
statusCode = statusOrMessage;
|
|
20
|
-
} else if (typeof statusOrMessage === "string") {
|
|
21
|
-
message = statusOrMessage;
|
|
22
|
-
}
|
|
23
|
-
super(message ?? "");
|
|
24
|
-
__publicField(this, "status", 0);
|
|
25
|
-
if (statusCode !== void 0) {
|
|
26
|
-
this.status = statusCode;
|
|
27
|
-
}
|
|
28
|
-
this.name = this.constructor.name.replace(/([A-Z])/g, " $1");
|
|
29
|
-
}
|
|
30
|
-
};
|
|
31
|
-
__name(_ResponseException, "ResponseException");
|
|
32
|
-
var ResponseException = _ResponseException;
|
|
33
|
-
var _BadRequestException = class _BadRequestException extends ResponseException {
|
|
34
|
-
constructor() {
|
|
35
|
-
super(...arguments);
|
|
36
|
-
__publicField(this, "status", 400);
|
|
37
|
-
}
|
|
38
|
-
};
|
|
39
|
-
__name(_BadRequestException, "BadRequestException");
|
|
40
|
-
var BadRequestException = _BadRequestException;
|
|
41
|
-
var _UnauthorizedException = class _UnauthorizedException extends ResponseException {
|
|
42
|
-
constructor() {
|
|
43
|
-
super(...arguments);
|
|
44
|
-
__publicField(this, "status", 401);
|
|
45
|
-
}
|
|
46
|
-
};
|
|
47
|
-
__name(_UnauthorizedException, "UnauthorizedException");
|
|
48
|
-
var UnauthorizedException = _UnauthorizedException;
|
|
49
|
-
var _PaymentRequiredException = class _PaymentRequiredException extends ResponseException {
|
|
50
|
-
constructor() {
|
|
51
|
-
super(...arguments);
|
|
52
|
-
__publicField(this, "status", 402);
|
|
53
|
-
}
|
|
54
|
-
};
|
|
55
|
-
__name(_PaymentRequiredException, "PaymentRequiredException");
|
|
56
|
-
var PaymentRequiredException = _PaymentRequiredException;
|
|
57
|
-
var _ForbiddenException = class _ForbiddenException extends ResponseException {
|
|
58
|
-
constructor() {
|
|
59
|
-
super(...arguments);
|
|
60
|
-
__publicField(this, "status", 403);
|
|
61
|
-
}
|
|
62
|
-
};
|
|
63
|
-
__name(_ForbiddenException, "ForbiddenException");
|
|
64
|
-
var ForbiddenException = _ForbiddenException;
|
|
65
|
-
var _NotFoundException = class _NotFoundException extends ResponseException {
|
|
66
|
-
constructor() {
|
|
67
|
-
super(...arguments);
|
|
68
|
-
__publicField(this, "status", 404);
|
|
69
|
-
}
|
|
70
|
-
};
|
|
71
|
-
__name(_NotFoundException, "NotFoundException");
|
|
72
|
-
var NotFoundException = _NotFoundException;
|
|
73
|
-
var _MethodNotAllowedException = class _MethodNotAllowedException extends ResponseException {
|
|
74
|
-
constructor() {
|
|
75
|
-
super(...arguments);
|
|
76
|
-
__publicField(this, "status", 405);
|
|
77
|
-
}
|
|
78
|
-
};
|
|
79
|
-
__name(_MethodNotAllowedException, "MethodNotAllowedException");
|
|
80
|
-
var MethodNotAllowedException = _MethodNotAllowedException;
|
|
81
|
-
var _NotAcceptableException = class _NotAcceptableException extends ResponseException {
|
|
82
|
-
constructor() {
|
|
83
|
-
super(...arguments);
|
|
84
|
-
__publicField(this, "status", 406);
|
|
85
|
-
}
|
|
86
|
-
};
|
|
87
|
-
__name(_NotAcceptableException, "NotAcceptableException");
|
|
88
|
-
var NotAcceptableException = _NotAcceptableException;
|
|
89
|
-
var _RequestTimeoutException = class _RequestTimeoutException extends ResponseException {
|
|
90
|
-
constructor() {
|
|
91
|
-
super(...arguments);
|
|
92
|
-
__publicField(this, "status", 408);
|
|
93
|
-
}
|
|
94
|
-
};
|
|
95
|
-
__name(_RequestTimeoutException, "RequestTimeoutException");
|
|
96
|
-
var RequestTimeoutException = _RequestTimeoutException;
|
|
97
|
-
var _ConflictException = class _ConflictException extends ResponseException {
|
|
98
|
-
constructor() {
|
|
99
|
-
super(...arguments);
|
|
100
|
-
__publicField(this, "status", 409);
|
|
101
|
-
}
|
|
102
|
-
};
|
|
103
|
-
__name(_ConflictException, "ConflictException");
|
|
104
|
-
var ConflictException = _ConflictException;
|
|
105
|
-
var _UpgradeRequiredException = class _UpgradeRequiredException extends ResponseException {
|
|
106
|
-
constructor() {
|
|
107
|
-
super(...arguments);
|
|
108
|
-
__publicField(this, "status", 426);
|
|
109
|
-
}
|
|
110
|
-
};
|
|
111
|
-
__name(_UpgradeRequiredException, "UpgradeRequiredException");
|
|
112
|
-
var UpgradeRequiredException = _UpgradeRequiredException;
|
|
113
|
-
var _TooManyRequestsException = class _TooManyRequestsException extends ResponseException {
|
|
114
|
-
constructor() {
|
|
115
|
-
super(...arguments);
|
|
116
|
-
__publicField(this, "status", 429);
|
|
117
|
-
}
|
|
118
|
-
};
|
|
119
|
-
__name(_TooManyRequestsException, "TooManyRequestsException");
|
|
120
|
-
var TooManyRequestsException = _TooManyRequestsException;
|
|
121
|
-
var _InternalServerException = class _InternalServerException extends ResponseException {
|
|
122
|
-
constructor() {
|
|
123
|
-
super(...arguments);
|
|
124
|
-
__publicField(this, "status", 500);
|
|
125
|
-
}
|
|
126
|
-
};
|
|
127
|
-
__name(_InternalServerException, "InternalServerException");
|
|
128
|
-
var InternalServerException = _InternalServerException;
|
|
129
|
-
var _NotImplementedException = class _NotImplementedException extends ResponseException {
|
|
130
|
-
constructor() {
|
|
131
|
-
super(...arguments);
|
|
132
|
-
__publicField(this, "status", 501);
|
|
133
|
-
}
|
|
134
|
-
};
|
|
135
|
-
__name(_NotImplementedException, "NotImplementedException");
|
|
136
|
-
var NotImplementedException = _NotImplementedException;
|
|
137
|
-
var _BadGatewayException = class _BadGatewayException extends ResponseException {
|
|
138
|
-
constructor() {
|
|
139
|
-
super(...arguments);
|
|
140
|
-
__publicField(this, "status", 502);
|
|
141
|
-
}
|
|
142
|
-
};
|
|
143
|
-
__name(_BadGatewayException, "BadGatewayException");
|
|
144
|
-
var BadGatewayException = _BadGatewayException;
|
|
145
|
-
var _ServiceUnavailableException = class _ServiceUnavailableException extends ResponseException {
|
|
146
|
-
constructor() {
|
|
147
|
-
super(...arguments);
|
|
148
|
-
__publicField(this, "status", 503);
|
|
149
|
-
}
|
|
150
|
-
};
|
|
151
|
-
__name(_ServiceUnavailableException, "ServiceUnavailableException");
|
|
152
|
-
var ServiceUnavailableException = _ServiceUnavailableException;
|
|
153
|
-
var _GatewayTimeoutException = class _GatewayTimeoutException extends ResponseException {
|
|
154
|
-
constructor() {
|
|
155
|
-
super(...arguments);
|
|
156
|
-
__publicField(this, "status", 504);
|
|
157
|
-
}
|
|
158
|
-
};
|
|
159
|
-
__name(_GatewayTimeoutException, "GatewayTimeoutException");
|
|
160
|
-
var GatewayTimeoutException = _GatewayTimeoutException;
|
|
161
|
-
var _HttpVersionNotSupportedException = class _HttpVersionNotSupportedException extends ResponseException {
|
|
162
|
-
constructor() {
|
|
163
|
-
super(...arguments);
|
|
164
|
-
__publicField(this, "status", 505);
|
|
165
|
-
}
|
|
166
|
-
};
|
|
167
|
-
__name(_HttpVersionNotSupportedException, "HttpVersionNotSupportedException");
|
|
168
|
-
var HttpVersionNotSupportedException = _HttpVersionNotSupportedException;
|
|
169
|
-
var _VariantAlsoNegotiatesException = class _VariantAlsoNegotiatesException extends ResponseException {
|
|
170
|
-
constructor() {
|
|
171
|
-
super(...arguments);
|
|
172
|
-
__publicField(this, "status", 506);
|
|
173
|
-
}
|
|
174
|
-
};
|
|
175
|
-
__name(_VariantAlsoNegotiatesException, "VariantAlsoNegotiatesException");
|
|
176
|
-
var VariantAlsoNegotiatesException = _VariantAlsoNegotiatesException;
|
|
177
|
-
var _InsufficientStorageException = class _InsufficientStorageException extends ResponseException {
|
|
178
|
-
constructor() {
|
|
179
|
-
super(...arguments);
|
|
180
|
-
__publicField(this, "status", 507);
|
|
181
|
-
}
|
|
182
|
-
};
|
|
183
|
-
__name(_InsufficientStorageException, "InsufficientStorageException");
|
|
184
|
-
var InsufficientStorageException = _InsufficientStorageException;
|
|
185
|
-
var _LoopDetectedException = class _LoopDetectedException extends ResponseException {
|
|
186
|
-
constructor() {
|
|
187
|
-
super(...arguments);
|
|
188
|
-
__publicField(this, "status", 508);
|
|
189
|
-
}
|
|
190
|
-
};
|
|
191
|
-
__name(_LoopDetectedException, "LoopDetectedException");
|
|
192
|
-
var LoopDetectedException = _LoopDetectedException;
|
|
193
|
-
var _NotExtendedException = class _NotExtendedException extends ResponseException {
|
|
194
|
-
constructor() {
|
|
195
|
-
super(...arguments);
|
|
196
|
-
__publicField(this, "status", 510);
|
|
197
|
-
}
|
|
198
|
-
};
|
|
199
|
-
__name(_NotExtendedException, "NotExtendedException");
|
|
200
|
-
var NotExtendedException = _NotExtendedException;
|
|
201
|
-
var _NetworkAuthenticationRequiredException = class _NetworkAuthenticationRequiredException extends ResponseException {
|
|
202
|
-
constructor() {
|
|
203
|
-
super(...arguments);
|
|
204
|
-
__publicField(this, "status", 511);
|
|
205
|
-
}
|
|
206
|
-
};
|
|
207
|
-
__name(_NetworkAuthenticationRequiredException, "NetworkAuthenticationRequiredException");
|
|
208
|
-
var NetworkAuthenticationRequiredException = _NetworkAuthenticationRequiredException;
|
|
209
|
-
var _NetworkConnectTimeoutException = class _NetworkConnectTimeoutException extends ResponseException {
|
|
210
|
-
constructor() {
|
|
211
|
-
super(...arguments);
|
|
212
|
-
__publicField(this, "status", 599);
|
|
213
|
-
}
|
|
214
|
-
};
|
|
215
|
-
__name(_NetworkConnectTimeoutException, "NetworkConnectTimeoutException");
|
|
216
|
-
var NetworkConnectTimeoutException = _NetworkConnectTimeoutException;
|
|
217
|
-
|
|
218
|
-
// src/DI/app-injector.ts
|
|
219
|
-
var _AppInjector = class _AppInjector {
|
|
220
|
-
constructor(name = null) {
|
|
221
|
-
__publicField(this, "name");
|
|
222
|
-
__publicField(this, "bindings", /* @__PURE__ */ new Map());
|
|
223
|
-
__publicField(this, "singletons", /* @__PURE__ */ new Map());
|
|
224
|
-
__publicField(this, "scoped", /* @__PURE__ */ new Map());
|
|
225
|
-
this.name = name;
|
|
226
|
-
}
|
|
227
|
-
/**
|
|
228
|
-
* Utilisé généralement pour créer un scope d'injection de dépendances
|
|
229
|
-
* au niveau "scope" (donc durée de vie d'une requête)
|
|
230
|
-
*/
|
|
231
|
-
createScope() {
|
|
232
|
-
const scope = new _AppInjector();
|
|
233
|
-
scope.bindings = this.bindings;
|
|
234
|
-
scope.singletons = this.singletons;
|
|
235
|
-
return scope;
|
|
236
|
-
}
|
|
237
|
-
/**
|
|
238
|
-
* Appelé lorsqu'on souhaite résoudre une dépendance,
|
|
239
|
-
* c'est-à-dire récupérer l'instance d'une classe donnée.
|
|
240
|
-
*/
|
|
241
|
-
resolve(target) {
|
|
242
|
-
const binding = this.bindings.get(target);
|
|
243
|
-
if (!binding) throw new InternalServerException(`Failed to resolve a dependency injection : No binding for type ${target.name}.
|
|
244
|
-
Did you forget to use @Injectable() decorator ?`);
|
|
245
|
-
switch (binding.lifetime) {
|
|
246
|
-
case "transient":
|
|
247
|
-
return this.instantiate(binding.implementation);
|
|
248
|
-
case "scope": {
|
|
249
|
-
if (this.scoped.has(target)) {
|
|
250
|
-
return this.scoped.get(target);
|
|
251
|
-
}
|
|
252
|
-
const instance = this.instantiate(binding.implementation);
|
|
253
|
-
this.scoped.set(target, instance);
|
|
254
|
-
return instance;
|
|
255
|
-
}
|
|
256
|
-
case "singleton": {
|
|
257
|
-
if (binding.instance === void 0 && this.name === "root") {
|
|
258
|
-
binding.instance = this.instantiate(binding.implementation);
|
|
259
|
-
this.singletons.set(target, binding.instance);
|
|
260
|
-
}
|
|
261
|
-
return binding.instance;
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
/**
|
|
266
|
-
*
|
|
267
|
-
*/
|
|
268
|
-
instantiate(target) {
|
|
269
|
-
const paramTypes = Reflect.getMetadata("design:paramtypes", target) || [];
|
|
270
|
-
const params = paramTypes.map((p) => this.resolve(p));
|
|
271
|
-
return new target(...params);
|
|
272
|
-
}
|
|
273
|
-
};
|
|
274
|
-
__name(_AppInjector, "AppInjector");
|
|
275
|
-
var AppInjector = _AppInjector;
|
|
276
|
-
var RootInjector = new AppInjector("root");
|
|
277
|
-
function inject(t) {
|
|
278
|
-
return RootInjector.resolve(t);
|
|
279
|
-
}
|
|
280
|
-
__name(inject, "inject");
|
|
281
|
-
|
|
282
|
-
// src/router.ts
|
|
283
|
-
import "reflect-metadata";
|
|
284
|
-
|
|
285
|
-
// src/utils/logger.ts
|
|
286
|
-
function getPrettyTimestamp() {
|
|
287
|
-
const now = /* @__PURE__ */ new Date();
|
|
288
|
-
return `${now.getDate().toString().padStart(2, "0")}/${(now.getMonth() + 1).toString().padStart(2, "0")}/${now.getFullYear()} ${now.getHours().toString().padStart(2, "0")}:${now.getMinutes().toString().padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;
|
|
289
|
-
}
|
|
290
|
-
__name(getPrettyTimestamp, "getPrettyTimestamp");
|
|
291
|
-
function getLogPrefix(callee, messageType, color) {
|
|
292
|
-
const timestamp = getPrettyTimestamp();
|
|
293
|
-
const spaces = " ".repeat(10 - messageType.length);
|
|
294
|
-
return `${color}[APP] ${process.pid} - ${Logger.colors.initial}${timestamp}${spaces}${color}${messageType.toUpperCase()}${Logger.colors.initial} ${Logger.colors.yellow}[${callee}]${Logger.colors.initial}`;
|
|
295
|
-
}
|
|
296
|
-
__name(getLogPrefix, "getLogPrefix");
|
|
297
|
-
function formatObject(prefix, arg) {
|
|
298
|
-
const json = JSON.stringify(arg, null, 2);
|
|
299
|
-
const prefixedJson = json.split("\n").map((line, idx) => idx === 0 ? `${Logger.colors.darkGrey}${line}` : `${prefix} ${Logger.colors.grey}${line}`).join("\n") + Logger.colors.initial;
|
|
300
|
-
return prefixedJson;
|
|
301
|
-
}
|
|
302
|
-
__name(formatObject, "formatObject");
|
|
303
|
-
function formattedArgs(prefix, args, color) {
|
|
304
|
-
return args.map((arg) => {
|
|
305
|
-
if (typeof arg === "string") {
|
|
306
|
-
return `${color}${arg}${Logger.colors.initial}`;
|
|
307
|
-
} else if (typeof arg === "object") {
|
|
308
|
-
return formatObject(prefix, arg);
|
|
309
|
-
}
|
|
310
|
-
return arg;
|
|
311
|
-
});
|
|
312
|
-
}
|
|
313
|
-
__name(formattedArgs, "formattedArgs");
|
|
314
|
-
function getCallee() {
|
|
315
|
-
const stack = new Error().stack?.split("\n") ?? [];
|
|
316
|
-
const caller = stack[3]?.trim().match(/at (.+?)(?:\..+)? .+$/)?.[1]?.replace("Object", "") || "App";
|
|
317
|
-
return caller;
|
|
318
|
-
}
|
|
319
|
-
__name(getCallee, "getCallee");
|
|
320
|
-
var logLevelRank = {
|
|
321
|
-
debug: 0,
|
|
322
|
-
log: 1,
|
|
323
|
-
info: 2,
|
|
324
|
-
warn: 3,
|
|
325
|
-
error: 4
|
|
326
|
-
};
|
|
327
|
-
function canLog(level) {
|
|
328
|
-
return logLevelRank[level] >= logLevelRank[logLevel];
|
|
329
|
-
}
|
|
330
|
-
__name(canLog, "canLog");
|
|
331
|
-
var logLevel = "log";
|
|
332
|
-
(function(Logger2) {
|
|
333
|
-
function setLogLevel(level) {
|
|
334
|
-
logLevel = level;
|
|
335
|
-
}
|
|
336
|
-
__name(setLogLevel, "setLogLevel");
|
|
337
|
-
Logger2.setLogLevel = setLogLevel;
|
|
338
|
-
Logger2.colors = {
|
|
339
|
-
black: "\x1B[0;30m",
|
|
340
|
-
grey: "\x1B[0;37m",
|
|
341
|
-
red: "\x1B[0;31m",
|
|
342
|
-
green: "\x1B[0;32m",
|
|
343
|
-
brown: "\x1B[0;33m",
|
|
344
|
-
blue: "\x1B[0;34m",
|
|
345
|
-
purple: "\x1B[0;35m",
|
|
346
|
-
darkGrey: "\x1B[1;30m",
|
|
347
|
-
lightRed: "\x1B[1;31m",
|
|
348
|
-
lightGreen: "\x1B[1;32m",
|
|
349
|
-
yellow: "\x1B[1;33m",
|
|
350
|
-
lightBlue: "\x1B[1;34m",
|
|
351
|
-
magenta: "\x1B[1;35m",
|
|
352
|
-
cyan: "\x1B[1;36m",
|
|
353
|
-
white: "\x1B[1;37m",
|
|
354
|
-
initial: "\x1B[0m"
|
|
355
|
-
};
|
|
356
|
-
function log(...args) {
|
|
357
|
-
if (!canLog("log")) return;
|
|
358
|
-
const callee = getCallee();
|
|
359
|
-
const prefix = getLogPrefix(callee, "log", Logger2.colors.green);
|
|
360
|
-
console.log(prefix, ...formattedArgs(prefix, args, Logger2.colors.green));
|
|
361
|
-
}
|
|
362
|
-
__name(log, "log");
|
|
363
|
-
Logger2.log = log;
|
|
364
|
-
function info(...args) {
|
|
365
|
-
if (!canLog("info")) return;
|
|
366
|
-
const callee = getCallee();
|
|
367
|
-
const prefix = getLogPrefix(callee, "info", Logger2.colors.blue);
|
|
368
|
-
console.info(prefix, ...formattedArgs(prefix, args, Logger2.colors.blue));
|
|
369
|
-
}
|
|
370
|
-
__name(info, "info");
|
|
371
|
-
Logger2.info = info;
|
|
372
|
-
function warn(...args) {
|
|
373
|
-
if (!canLog("warn")) return;
|
|
374
|
-
const callee = getCallee();
|
|
375
|
-
const prefix = getLogPrefix(callee, "warn", Logger2.colors.brown);
|
|
376
|
-
console.warn(prefix, ...formattedArgs(prefix, args, Logger2.colors.brown));
|
|
377
|
-
}
|
|
378
|
-
__name(warn, "warn");
|
|
379
|
-
Logger2.warn = warn;
|
|
380
|
-
function error(...args) {
|
|
381
|
-
if (!canLog("error")) return;
|
|
382
|
-
const callee = getCallee();
|
|
383
|
-
const prefix = getLogPrefix(callee, "error", Logger2.colors.red);
|
|
384
|
-
console.error(prefix, ...formattedArgs(prefix, args, Logger2.colors.red));
|
|
385
|
-
}
|
|
386
|
-
__name(error, "error");
|
|
387
|
-
Logger2.error = error;
|
|
388
|
-
function debug(...args) {
|
|
389
|
-
if (!canLog("debug")) return;
|
|
390
|
-
const callee = getCallee();
|
|
391
|
-
const prefix = getLogPrefix(callee, "debug", Logger2.colors.purple);
|
|
392
|
-
console.debug(prefix, ...formattedArgs(prefix, args, Logger2.colors.purple));
|
|
393
|
-
}
|
|
394
|
-
__name(debug, "debug");
|
|
395
|
-
Logger2.debug = debug;
|
|
396
|
-
})(Logger || (Logger = {}));
|
|
397
|
-
var Logger;
|
|
398
|
-
|
|
399
|
-
// src/decorators/guards.decorator.ts
|
|
400
|
-
var authorizations = /* @__PURE__ */ new Map();
|
|
401
|
-
function Authorize(...guardClasses) {
|
|
402
|
-
return (target, propertyKey) => {
|
|
403
|
-
let key;
|
|
404
|
-
if (propertyKey) {
|
|
405
|
-
const ctrlName = target.constructor.name;
|
|
406
|
-
const actionName = propertyKey;
|
|
407
|
-
key = `${ctrlName}.${actionName}`;
|
|
408
|
-
} else {
|
|
409
|
-
const ctrlName = target.name;
|
|
410
|
-
key = `${ctrlName}`;
|
|
411
|
-
}
|
|
412
|
-
if (authorizations.has(key)) {
|
|
413
|
-
throw new Error(`Guard(s) already registered for ${key}`);
|
|
414
|
-
}
|
|
415
|
-
Logger.debug(`Registering guard(s) for ${key}: ${guardClasses.map((c) => c.name).join(", ")}`);
|
|
416
|
-
authorizations.set(key, guardClasses);
|
|
417
|
-
};
|
|
418
|
-
}
|
|
419
|
-
__name(Authorize, "Authorize");
|
|
420
|
-
function getGuardForController(controllerName) {
|
|
421
|
-
const key = `${controllerName}`;
|
|
422
|
-
return authorizations.get(key) ?? [];
|
|
423
|
-
}
|
|
424
|
-
__name(getGuardForController, "getGuardForController");
|
|
425
|
-
function getGuardForControllerAction(controllerName, actionName) {
|
|
426
|
-
const key = `${controllerName}.${actionName}`;
|
|
427
|
-
return authorizations.get(key) ?? [];
|
|
428
|
-
}
|
|
429
|
-
__name(getGuardForControllerAction, "getGuardForControllerAction");
|
|
430
|
-
|
|
431
|
-
// src/decorators/method.decorator.ts
|
|
432
|
-
function createRouteDecorator(verb) {
|
|
433
|
-
return (path) => {
|
|
434
|
-
return (target, propertyKey) => {
|
|
435
|
-
const existingRoutes = Reflect.getMetadata(ROUTE_METADATA_KEY, target.constructor) || [];
|
|
436
|
-
const metadata = {
|
|
437
|
-
method: verb,
|
|
438
|
-
path: path.trim().replace(/^\/|\/$/g, ""),
|
|
439
|
-
handler: propertyKey,
|
|
440
|
-
guards: getGuardForControllerAction(target.constructor.__controllerName, propertyKey)
|
|
441
|
-
};
|
|
442
|
-
existingRoutes.push(metadata);
|
|
443
|
-
Reflect.defineMetadata(ROUTE_METADATA_KEY, existingRoutes, target.constructor);
|
|
444
|
-
};
|
|
445
|
-
};
|
|
446
|
-
}
|
|
447
|
-
__name(createRouteDecorator, "createRouteDecorator");
|
|
448
|
-
var Get = createRouteDecorator("GET");
|
|
449
|
-
var Post = createRouteDecorator("POST");
|
|
450
|
-
var Put = createRouteDecorator("PUT");
|
|
451
|
-
var Patch = createRouteDecorator("PATCH");
|
|
452
|
-
var Delete = createRouteDecorator("DELETE");
|
|
453
|
-
var ROUTE_METADATA_KEY = Symbol("ROUTE_METADATA_KEY");
|
|
454
|
-
function getRouteMetadata(target) {
|
|
455
|
-
return Reflect.getMetadata(ROUTE_METADATA_KEY, target) || [];
|
|
456
|
-
}
|
|
457
|
-
__name(getRouteMetadata, "getRouteMetadata");
|
|
458
|
-
|
|
459
|
-
// src/decorators/module.decorator.ts
|
|
460
|
-
function Module(metadata) {
|
|
461
|
-
return (target) => {
|
|
462
|
-
const checkModule = /* @__PURE__ */ __name((arr, arrName) => {
|
|
463
|
-
if (!arr) return;
|
|
464
|
-
for (const clazz of arr) {
|
|
465
|
-
if (!Reflect.getMetadata(MODULE_METADATA_KEY, clazz)) {
|
|
466
|
-
throw new Error(`Class ${clazz.name} in ${arrName} must be decorated with @Module`);
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
}, "checkModule");
|
|
470
|
-
const checkInjectable = /* @__PURE__ */ __name((arr) => {
|
|
471
|
-
if (!arr) return;
|
|
472
|
-
for (const clazz of arr) {
|
|
473
|
-
if (!Reflect.getMetadata(INJECTABLE_METADATA_KEY, clazz)) {
|
|
474
|
-
throw new Error(`Class ${clazz.name} in providers must be decorated with @Injectable`);
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
}, "checkInjectable");
|
|
478
|
-
const checkController = /* @__PURE__ */ __name((arr) => {
|
|
479
|
-
if (!arr) return;
|
|
480
|
-
for (const clazz of arr) {
|
|
481
|
-
if (!Reflect.getMetadata(CONTROLLER_METADATA_KEY, clazz)) {
|
|
482
|
-
throw new Error(`Class ${clazz.name} in controllers must be decorated with @Controller`);
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
}, "checkController");
|
|
486
|
-
checkModule(metadata.imports, "imports");
|
|
487
|
-
checkModule(metadata.exports, "exports");
|
|
488
|
-
checkInjectable(metadata.providers);
|
|
489
|
-
checkController(metadata.controllers);
|
|
490
|
-
Reflect.defineMetadata(MODULE_METADATA_KEY, metadata, target);
|
|
491
|
-
Injectable("singleton")(target);
|
|
492
|
-
};
|
|
493
|
-
}
|
|
494
|
-
__name(Module, "Module");
|
|
495
|
-
var MODULE_METADATA_KEY = Symbol("MODULE_METADATA_KEY");
|
|
496
|
-
function getModuleMetadata(target) {
|
|
497
|
-
return Reflect.getMetadata(MODULE_METADATA_KEY, target);
|
|
498
|
-
}
|
|
499
|
-
__name(getModuleMetadata, "getModuleMetadata");
|
|
500
|
-
|
|
501
|
-
// src/DI/injector-explorer.ts
|
|
502
|
-
var _InjectorExplorer = class _InjectorExplorer {
|
|
503
|
-
/**
|
|
504
|
-
* Enregistre la classe comme étant injectable.
|
|
505
|
-
* Lorsqu'une classe sera instanciée, si elle a des dépendances, et que celles-ci
|
|
506
|
-
* figurent dans la liste grâce à cette méthode, elles seront injectées dans le
|
|
507
|
-
* constructeur de la classe.
|
|
508
|
-
*/
|
|
509
|
-
static register(target, lifetime) {
|
|
510
|
-
Logger.debug(`Registering ${target.name} as ${lifetime}`);
|
|
511
|
-
if (RootInjector.bindings.has(target)) return RootInjector;
|
|
512
|
-
RootInjector.bindings.set(target, {
|
|
513
|
-
implementation: target,
|
|
514
|
-
lifetime
|
|
515
|
-
});
|
|
516
|
-
if (lifetime === "singleton") {
|
|
517
|
-
RootInjector.resolve(target);
|
|
518
|
-
}
|
|
519
|
-
if (getModuleMetadata(target)) {
|
|
520
|
-
Logger.log(`${target.name} dependencies initialized`);
|
|
521
|
-
return RootInjector;
|
|
522
|
-
}
|
|
523
|
-
const controllerMeta = getControllerMetadata(target);
|
|
524
|
-
if (controllerMeta) {
|
|
525
|
-
const router = RootInjector.resolve(Router);
|
|
526
|
-
router?.registerController(target);
|
|
527
|
-
return RootInjector;
|
|
528
|
-
}
|
|
529
|
-
const routeMeta = getRouteMetadata(target);
|
|
530
|
-
if (routeMeta) {
|
|
531
|
-
return RootInjector;
|
|
532
|
-
}
|
|
533
|
-
if (getInjectableMetadata(target)) {
|
|
534
|
-
Logger.log(`Registered ${target.name} as ${lifetime}`);
|
|
535
|
-
return RootInjector;
|
|
536
|
-
}
|
|
537
|
-
return RootInjector;
|
|
538
|
-
}
|
|
539
|
-
};
|
|
540
|
-
__name(_InjectorExplorer, "InjectorExplorer");
|
|
541
|
-
var InjectorExplorer = _InjectorExplorer;
|
|
542
|
-
|
|
543
|
-
// src/decorators/injectable.decorator.ts
|
|
544
|
-
function Injectable(lifetime = "scope") {
|
|
545
|
-
return (target) => {
|
|
546
|
-
if (typeof target !== "function" || !target.prototype) {
|
|
547
|
-
throw new Error(`@Injectable can only be used on classes, not on ${typeof target}`);
|
|
548
|
-
}
|
|
549
|
-
Reflect.defineMetadata(INJECTABLE_METADATA_KEY, lifetime, target);
|
|
550
|
-
InjectorExplorer.register(target, lifetime);
|
|
551
|
-
};
|
|
552
|
-
}
|
|
553
|
-
__name(Injectable, "Injectable");
|
|
554
|
-
var INJECTABLE_METADATA_KEY = Symbol("INJECTABLE_METADATA_KEY");
|
|
555
|
-
function getInjectableMetadata(target) {
|
|
556
|
-
return Reflect.getMetadata(INJECTABLE_METADATA_KEY, target);
|
|
557
|
-
}
|
|
558
|
-
__name(getInjectableMetadata, "getInjectableMetadata");
|
|
559
|
-
|
|
560
|
-
// src/decorators/controller.decorator.ts
|
|
561
|
-
function Controller(path) {
|
|
562
|
-
return (target) => {
|
|
563
|
-
const data = {
|
|
564
|
-
path,
|
|
565
|
-
guards: getGuardForController(target.name)
|
|
566
|
-
};
|
|
567
|
-
Reflect.defineMetadata(CONTROLLER_METADATA_KEY, data, target);
|
|
568
|
-
Injectable("scope")(target);
|
|
569
|
-
};
|
|
570
|
-
}
|
|
571
|
-
__name(Controller, "Controller");
|
|
572
|
-
var CONTROLLER_METADATA_KEY = Symbol("CONTROLLER_METADATA_KEY");
|
|
573
|
-
function getControllerMetadata(target) {
|
|
574
|
-
return Reflect.getMetadata(CONTROLLER_METADATA_KEY, target);
|
|
575
|
-
}
|
|
576
|
-
__name(getControllerMetadata, "getControllerMetadata");
|
|
577
|
-
|
|
578
|
-
// src/decorators/middleware.decorator.ts
|
|
579
|
-
var middlewares = /* @__PURE__ */ new Map();
|
|
580
|
-
function UseMiddlewares(mdlw) {
|
|
581
|
-
return (target, propertyKey) => {
|
|
582
|
-
let key;
|
|
583
|
-
if (propertyKey) {
|
|
584
|
-
const ctrlName = target.constructor.name;
|
|
585
|
-
const actionName = propertyKey;
|
|
586
|
-
key = `${ctrlName}.${actionName}`;
|
|
587
|
-
} else {
|
|
588
|
-
const ctrlName = target.name;
|
|
589
|
-
key = `${ctrlName}`;
|
|
590
|
-
}
|
|
591
|
-
if (middlewares.has(key)) {
|
|
592
|
-
throw new Error(`Middlewares(s) already registered for ${key}`);
|
|
593
|
-
}
|
|
594
|
-
Logger.debug(`Registering middleware(s) for ${key}: ${mdlw.map((c) => c.name).join(", ")}`);
|
|
595
|
-
middlewares.set(key, mdlw);
|
|
596
|
-
};
|
|
597
|
-
}
|
|
598
|
-
__name(UseMiddlewares, "UseMiddlewares");
|
|
599
|
-
function getMiddlewaresForController(controllerName) {
|
|
600
|
-
const key = `${controllerName}`;
|
|
601
|
-
return middlewares.get(key) ?? [];
|
|
602
|
-
}
|
|
603
|
-
__name(getMiddlewaresForController, "getMiddlewaresForController");
|
|
604
|
-
function getMiddlewaresForControllerAction(controllerName, actionName) {
|
|
605
|
-
const key = `${controllerName}.${actionName}`;
|
|
606
|
-
return middlewares.get(key) ?? [];
|
|
607
|
-
}
|
|
608
|
-
__name(getMiddlewaresForControllerAction, "getMiddlewaresForControllerAction");
|
|
609
|
-
|
|
610
|
-
// src/utils/radix-tree.ts
|
|
611
|
-
var _a;
|
|
612
|
-
var RadixNode = (_a = class {
|
|
613
|
-
constructor(segment) {
|
|
614
|
-
__publicField(this, "segment");
|
|
615
|
-
__publicField(this, "children", []);
|
|
616
|
-
__publicField(this, "value");
|
|
617
|
-
__publicField(this, "isParam");
|
|
618
|
-
__publicField(this, "paramName");
|
|
619
|
-
this.segment = segment;
|
|
620
|
-
this.isParam = segment.startsWith(":");
|
|
621
|
-
if (this.isParam) {
|
|
622
|
-
this.paramName = segment.slice(1);
|
|
623
|
-
}
|
|
624
|
-
}
|
|
625
|
-
matchChild(segment) {
|
|
626
|
-
for (const child of this.children) {
|
|
627
|
-
if (child.isParam || segment.startsWith(child.segment)) return child;
|
|
628
|
-
}
|
|
629
|
-
return void 0;
|
|
630
|
-
}
|
|
631
|
-
findExactChild(segment) {
|
|
632
|
-
return this.children.find((c) => c.segment === segment);
|
|
633
|
-
}
|
|
634
|
-
addChild(node) {
|
|
635
|
-
this.children.push(node);
|
|
636
|
-
}
|
|
637
|
-
}, __name(_a, "RadixNode"), _a);
|
|
638
|
-
var _RadixTree = class _RadixTree {
|
|
639
|
-
constructor() {
|
|
640
|
-
__publicField(this, "root", new RadixNode(""));
|
|
641
|
-
}
|
|
642
|
-
insert(path, value) {
|
|
643
|
-
const segments = this.normalize(path);
|
|
644
|
-
this.insertRecursive(this.root, segments, value);
|
|
645
|
-
}
|
|
646
|
-
insertRecursive(node, segments, value) {
|
|
647
|
-
if (segments.length === 0) {
|
|
648
|
-
node.value = value;
|
|
649
|
-
return;
|
|
650
|
-
}
|
|
651
|
-
const segment = segments[0] ?? "";
|
|
652
|
-
let child = node.children.find((c) => c.isParam === segment.startsWith(":") && (c.isParam || c.segment === segment));
|
|
653
|
-
if (!child) {
|
|
654
|
-
child = new RadixNode(segment);
|
|
655
|
-
node.addChild(child);
|
|
656
|
-
}
|
|
657
|
-
this.insertRecursive(child, segments.slice(1), value);
|
|
658
|
-
}
|
|
659
|
-
search(path) {
|
|
660
|
-
const segments = this.normalize(path);
|
|
661
|
-
return this.searchRecursive(this.root, segments, {});
|
|
662
|
-
}
|
|
663
|
-
searchRecursive(node, segments, params) {
|
|
664
|
-
if (segments.length === 0) {
|
|
665
|
-
if (node.value !== void 0) {
|
|
666
|
-
return {
|
|
667
|
-
node,
|
|
668
|
-
params
|
|
669
|
-
};
|
|
670
|
-
}
|
|
671
|
-
return void 0;
|
|
672
|
-
}
|
|
673
|
-
const [segment, ...rest] = segments;
|
|
674
|
-
for (const child of node.children) {
|
|
675
|
-
if (child.isParam) {
|
|
676
|
-
const paramName = child.paramName;
|
|
677
|
-
const childParams = {
|
|
678
|
-
...params,
|
|
679
|
-
[paramName]: segment ?? ""
|
|
680
|
-
};
|
|
681
|
-
if (rest.length === 0) {
|
|
682
|
-
return {
|
|
683
|
-
node: child,
|
|
684
|
-
params: childParams
|
|
685
|
-
};
|
|
686
|
-
}
|
|
687
|
-
const result = this.searchRecursive(child, rest, childParams);
|
|
688
|
-
if (result) return result;
|
|
689
|
-
} else if (segment === child.segment) {
|
|
690
|
-
if (rest.length === 0) {
|
|
691
|
-
return {
|
|
692
|
-
node: child,
|
|
693
|
-
params
|
|
694
|
-
};
|
|
695
|
-
}
|
|
696
|
-
const result = this.searchRecursive(child, rest, params);
|
|
697
|
-
if (result) return result;
|
|
698
|
-
}
|
|
699
|
-
}
|
|
700
|
-
return void 0;
|
|
701
|
-
}
|
|
702
|
-
normalize(path) {
|
|
703
|
-
const segments = path.replace(/^\/+|\/+$/g, "").split("/").filter(Boolean);
|
|
704
|
-
return [
|
|
705
|
-
"",
|
|
706
|
-
...segments
|
|
707
|
-
];
|
|
708
|
-
}
|
|
709
|
-
};
|
|
710
|
-
__name(_RadixTree, "RadixTree");
|
|
711
|
-
var RadixTree = _RadixTree;
|
|
712
|
-
|
|
713
|
-
// src/router.ts
|
|
714
|
-
function _ts_decorate(decorators, target, key, desc) {
|
|
715
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
716
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
717
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
718
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
719
|
-
}
|
|
720
|
-
__name(_ts_decorate, "_ts_decorate");
|
|
721
|
-
var _Router = class _Router {
|
|
722
|
-
constructor() {
|
|
723
|
-
__publicField(this, "routes", new RadixTree());
|
|
724
|
-
__publicField(this, "rootMiddlewares", []);
|
|
725
|
-
}
|
|
726
|
-
/**
|
|
727
|
-
*
|
|
728
|
-
*/
|
|
729
|
-
registerController(controllerClass) {
|
|
730
|
-
const controllerMeta = getControllerMetadata(controllerClass);
|
|
731
|
-
const controllerGuards = getGuardForController(controllerClass.name);
|
|
732
|
-
const controllerMiddlewares = getMiddlewaresForController(controllerClass.name);
|
|
733
|
-
if (!controllerMeta) throw new Error(`Missing @Controller decorator on ${controllerClass.name}`);
|
|
734
|
-
const routeMetadata = getRouteMetadata(controllerClass);
|
|
735
|
-
for (const def of routeMetadata) {
|
|
736
|
-
const fullPath = `${controllerMeta.path}/${def.path}`.replace(/\/+/g, "/");
|
|
737
|
-
const routeGuards = getGuardForControllerAction(controllerClass.name, def.handler);
|
|
738
|
-
const routeMiddlewares = getMiddlewaresForControllerAction(controllerClass.name, def.handler);
|
|
739
|
-
const guards = /* @__PURE__ */ new Set([
|
|
740
|
-
...controllerGuards,
|
|
741
|
-
...routeGuards
|
|
742
|
-
]);
|
|
743
|
-
const middlewares2 = /* @__PURE__ */ new Set([
|
|
744
|
-
...controllerMiddlewares,
|
|
745
|
-
...routeMiddlewares
|
|
746
|
-
]);
|
|
747
|
-
const routeDef = {
|
|
748
|
-
method: def.method,
|
|
749
|
-
path: fullPath,
|
|
750
|
-
controller: controllerClass,
|
|
751
|
-
handler: def.handler,
|
|
752
|
-
guards: [
|
|
753
|
-
...guards
|
|
754
|
-
],
|
|
755
|
-
middlewares: [
|
|
756
|
-
...middlewares2
|
|
757
|
-
]
|
|
758
|
-
};
|
|
759
|
-
this.routes.insert(fullPath + "/" + def.method, routeDef);
|
|
760
|
-
const hasActionGuards = routeDef.guards.length > 0;
|
|
761
|
-
const actionGuardsInfo = hasActionGuards ? "<" + routeDef.guards.map((g) => g.name).join("|") + ">" : "";
|
|
762
|
-
Logger.log(`Mapped {${routeDef.method} /${fullPath}}${actionGuardsInfo} route`);
|
|
763
|
-
}
|
|
764
|
-
const hasCtrlGuards = controllerMeta.guards.length > 0;
|
|
765
|
-
const controllerGuardsInfo = hasCtrlGuards ? "<" + controllerMeta.guards.map((g) => g.name).join("|") + ">" : "";
|
|
766
|
-
Logger.log(`Mapped ${controllerClass.name}${controllerGuardsInfo} controller's routes`);
|
|
767
|
-
return this;
|
|
768
|
-
}
|
|
769
|
-
/**
|
|
770
|
-
*
|
|
771
|
-
*/
|
|
772
|
-
defineRootMiddleware(middleware) {
|
|
773
|
-
Logger.debug(`Registering root middleware: ${middleware.name}`);
|
|
774
|
-
this.rootMiddlewares.push(middleware);
|
|
775
|
-
return this;
|
|
776
|
-
}
|
|
777
|
-
/**
|
|
778
|
-
*
|
|
779
|
-
*/
|
|
780
|
-
async handle(request) {
|
|
781
|
-
Logger.log(`> Received request: {${request.method} /${request.path}}`);
|
|
782
|
-
const t0 = performance.now();
|
|
783
|
-
const response = {
|
|
784
|
-
requestId: request.id,
|
|
785
|
-
status: 200,
|
|
786
|
-
body: null,
|
|
787
|
-
error: void 0
|
|
788
|
-
};
|
|
789
|
-
try {
|
|
790
|
-
const routeDef = this.findRoute(request);
|
|
791
|
-
await this.resolveController(request, response, routeDef);
|
|
792
|
-
if (response.status > 400) {
|
|
793
|
-
throw new ResponseException(response.status, response.error);
|
|
794
|
-
}
|
|
795
|
-
} catch (error) {
|
|
796
|
-
if (error instanceof ResponseException) {
|
|
797
|
-
response.status = error.status;
|
|
798
|
-
response.error = error.message;
|
|
799
|
-
} else if (error instanceof Error) {
|
|
800
|
-
response.status = 500;
|
|
801
|
-
response.error = error.message || "Internal Server Error";
|
|
802
|
-
} else {
|
|
803
|
-
response.status = 500;
|
|
804
|
-
response.error = "Unknown error occurred";
|
|
805
|
-
}
|
|
806
|
-
} finally {
|
|
807
|
-
const t1 = performance.now();
|
|
808
|
-
const message = `< ${response.status} ${request.method} /${request.path} ${Logger.colors.yellow}${Math.round(t1 - t0)}ms${Logger.colors.initial}`;
|
|
809
|
-
if (response.status < 400) Logger.log(message);
|
|
810
|
-
else if (response.status < 500) Logger.warn(message);
|
|
811
|
-
else Logger.error(message);
|
|
812
|
-
if (response.error !== void 0) {
|
|
813
|
-
Logger.error(response.error);
|
|
814
|
-
}
|
|
815
|
-
return response;
|
|
816
|
-
}
|
|
817
|
-
}
|
|
818
|
-
/**
|
|
819
|
-
*
|
|
820
|
-
*/
|
|
821
|
-
findRoute(request) {
|
|
822
|
-
const matchedRoutes = this.routes.search(request.path);
|
|
823
|
-
if (matchedRoutes?.node === void 0 || matchedRoutes.node.children.length === 0) {
|
|
824
|
-
throw new NotFoundException(`No route matches ${request.method} ${request.path}`);
|
|
825
|
-
}
|
|
826
|
-
const routeDef = matchedRoutes.node.findExactChild(request.method);
|
|
827
|
-
if (routeDef?.value === void 0) {
|
|
828
|
-
throw new MethodNotAllowedException(`Method Not Allowed for ${request.method} ${request.path}`);
|
|
829
|
-
}
|
|
830
|
-
return routeDef.value;
|
|
831
|
-
}
|
|
832
|
-
/**
|
|
833
|
-
*
|
|
834
|
-
*/
|
|
835
|
-
async resolveController(request, response, routeDef) {
|
|
836
|
-
const controllerInstance = request.context.resolve(routeDef.controller);
|
|
837
|
-
Object.assign(request.params, this.extractParams(request.path, routeDef.path));
|
|
838
|
-
await this.runRequestPipeline(request, response, routeDef, controllerInstance);
|
|
839
|
-
}
|
|
840
|
-
/**
|
|
841
|
-
*
|
|
842
|
-
*/
|
|
843
|
-
async runRequestPipeline(request, response, routeDef, controllerInstance) {
|
|
844
|
-
const middlewares2 = [
|
|
845
|
-
.../* @__PURE__ */ new Set([
|
|
846
|
-
...this.rootMiddlewares,
|
|
847
|
-
...routeDef.middlewares
|
|
848
|
-
])
|
|
849
|
-
];
|
|
850
|
-
const middlewareMaxIndex = middlewares2.length - 1;
|
|
851
|
-
const guardsMaxIndex = middlewareMaxIndex + routeDef.guards.length;
|
|
852
|
-
let index = -1;
|
|
853
|
-
const dispatch = /* @__PURE__ */ __name(async (i) => {
|
|
854
|
-
if (i <= index) throw new Error("next() called multiple times");
|
|
855
|
-
index = i;
|
|
856
|
-
if (i <= middlewareMaxIndex) {
|
|
857
|
-
const nextFn = dispatch.bind(null, i + 1);
|
|
858
|
-
await this.runMiddleware(request, response, nextFn, middlewares2[i]);
|
|
859
|
-
if (response.status >= 400) {
|
|
860
|
-
throw new ResponseException(response.status, response.error);
|
|
861
|
-
}
|
|
862
|
-
return;
|
|
863
|
-
}
|
|
864
|
-
if (i <= guardsMaxIndex) {
|
|
865
|
-
const guardIndex = i - middlewares2.length;
|
|
866
|
-
const guardType = routeDef.guards[guardIndex];
|
|
867
|
-
await this.runGuard(request, guardType);
|
|
868
|
-
dispatch(i + 1);
|
|
869
|
-
return;
|
|
870
|
-
}
|
|
871
|
-
const action = controllerInstance[routeDef.handler];
|
|
872
|
-
response.body = await action.call(controllerInstance, request, response);
|
|
873
|
-
}, "dispatch");
|
|
874
|
-
await dispatch(0);
|
|
875
|
-
}
|
|
876
|
-
/**
|
|
877
|
-
*
|
|
878
|
-
*/
|
|
879
|
-
async runMiddleware(request, response, next, middlewareType) {
|
|
880
|
-
const middleware = request.context.resolve(middlewareType);
|
|
881
|
-
await middleware.invoke(request, response, next);
|
|
882
|
-
}
|
|
883
|
-
/**
|
|
884
|
-
*
|
|
885
|
-
*/
|
|
886
|
-
async runGuard(request, guardType) {
|
|
887
|
-
const guard = request.context.resolve(guardType);
|
|
888
|
-
const allowed = await guard.canActivate(request);
|
|
889
|
-
if (!allowed) throw new UnauthorizedException(`Unauthorized for ${request.method} ${request.path}`);
|
|
890
|
-
}
|
|
891
|
-
/**
|
|
892
|
-
*
|
|
893
|
-
*/
|
|
894
|
-
extractParams(actual, template) {
|
|
895
|
-
const aParts = actual.split("/");
|
|
896
|
-
const tParts = template.split("/");
|
|
897
|
-
const params = {};
|
|
898
|
-
tParts.forEach((part, i) => {
|
|
899
|
-
if (part.startsWith(":")) {
|
|
900
|
-
params[part.slice(1)] = aParts[i] ?? "";
|
|
901
|
-
}
|
|
902
|
-
});
|
|
903
|
-
return params;
|
|
904
|
-
}
|
|
905
|
-
};
|
|
906
|
-
__name(_Router, "Router");
|
|
907
|
-
var Router = _Router;
|
|
908
|
-
Router = _ts_decorate([
|
|
909
|
-
Injectable("singleton")
|
|
910
|
-
], Router);
|
|
911
|
-
|
|
912
|
-
// src/app.ts
|
|
913
|
-
import { app, BrowserWindow, ipcMain, MessageChannelMain } from "electron/main";
|
|
914
|
-
|
|
915
|
-
// src/request.ts
|
|
916
|
-
import "reflect-metadata";
|
|
917
|
-
var _Request = class _Request {
|
|
918
|
-
constructor(event, id, method, path, body) {
|
|
919
|
-
__publicField(this, "event");
|
|
920
|
-
__publicField(this, "id");
|
|
921
|
-
__publicField(this, "method");
|
|
922
|
-
__publicField(this, "path");
|
|
923
|
-
__publicField(this, "body");
|
|
924
|
-
__publicField(this, "context", RootInjector.createScope());
|
|
925
|
-
__publicField(this, "params", {});
|
|
926
|
-
this.event = event;
|
|
927
|
-
this.id = id;
|
|
928
|
-
this.method = method;
|
|
929
|
-
this.path = path;
|
|
930
|
-
this.body = body;
|
|
931
|
-
this.path = path.replace(/^\/|\/$/g, "");
|
|
932
|
-
}
|
|
933
|
-
};
|
|
934
|
-
__name(_Request, "Request");
|
|
935
|
-
var Request = _Request;
|
|
936
|
-
|
|
937
|
-
// src/app.ts
|
|
938
|
-
function _ts_decorate2(decorators, target, key, desc) {
|
|
939
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
940
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
941
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
942
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
943
|
-
}
|
|
944
|
-
__name(_ts_decorate2, "_ts_decorate");
|
|
945
|
-
function _ts_metadata(k, v) {
|
|
946
|
-
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
947
|
-
}
|
|
948
|
-
__name(_ts_metadata, "_ts_metadata");
|
|
949
|
-
var _NoxApp = class _NoxApp {
|
|
950
|
-
constructor(router) {
|
|
951
|
-
__publicField(this, "router");
|
|
952
|
-
__publicField(this, "messagePorts", /* @__PURE__ */ new Map());
|
|
953
|
-
__publicField(this, "app");
|
|
954
|
-
this.router = router;
|
|
955
|
-
}
|
|
956
|
-
/**
|
|
957
|
-
*
|
|
958
|
-
*/
|
|
959
|
-
async init() {
|
|
960
|
-
ipcMain.on("gimme-my-port", this.giveTheRendererAPort.bind(this));
|
|
961
|
-
app.once("activate", this.onAppActivated.bind(this));
|
|
962
|
-
app.once("window-all-closed", this.onAllWindowsClosed.bind(this));
|
|
963
|
-
console.log("");
|
|
964
|
-
return this;
|
|
965
|
-
}
|
|
966
|
-
/**
|
|
967
|
-
*
|
|
968
|
-
*/
|
|
969
|
-
giveTheRendererAPort(event) {
|
|
970
|
-
const senderId = event.sender.id;
|
|
971
|
-
if (this.messagePorts.has(senderId)) {
|
|
972
|
-
this.shutdownChannel(senderId);
|
|
973
|
-
}
|
|
974
|
-
const channel = new MessageChannelMain();
|
|
975
|
-
this.messagePorts.set(senderId, channel);
|
|
976
|
-
channel.port1.on("message", this.onRendererMessage.bind(this));
|
|
977
|
-
channel.port1.start();
|
|
978
|
-
event.sender.postMessage("port", {
|
|
979
|
-
senderId
|
|
980
|
-
}, [
|
|
981
|
-
channel.port2
|
|
982
|
-
]);
|
|
983
|
-
}
|
|
984
|
-
/**
|
|
985
|
-
* Electron specific message handling.
|
|
986
|
-
* Replaces HTTP calls by using Electron's IPC mechanism.
|
|
987
|
-
*/
|
|
988
|
-
async onRendererMessage(event) {
|
|
989
|
-
const { senderId, requestId, path, method, body } = event.data;
|
|
990
|
-
const channel = this.messagePorts.get(senderId);
|
|
991
|
-
if (!channel) {
|
|
992
|
-
Logger.error(`No message channel found for sender ID: ${senderId}`);
|
|
993
|
-
return;
|
|
994
|
-
}
|
|
995
|
-
try {
|
|
996
|
-
const request = new Request(event, requestId, method, path, body);
|
|
997
|
-
const response = await this.router.handle(request);
|
|
998
|
-
channel.port1.postMessage(response);
|
|
999
|
-
} catch (err) {
|
|
1000
|
-
const response = {
|
|
1001
|
-
requestId,
|
|
1002
|
-
status: 500,
|
|
1003
|
-
body: null,
|
|
1004
|
-
error: err.message || "Internal Server Error"
|
|
1005
|
-
};
|
|
1006
|
-
channel.port1.postMessage(response);
|
|
1007
|
-
}
|
|
1008
|
-
}
|
|
1009
|
-
/**
|
|
1010
|
-
* MacOS specific behavior.
|
|
1011
|
-
*/
|
|
1012
|
-
onAppActivated() {
|
|
1013
|
-
if (process.platform === "darwin" && BrowserWindow.getAllWindows().length === 0) {
|
|
1014
|
-
this.app?.onActivated();
|
|
1015
|
-
}
|
|
1016
|
-
}
|
|
1017
|
-
shutdownChannel(channelSenderId, remove = true) {
|
|
1018
|
-
const channel = this.messagePorts.get(channelSenderId);
|
|
1019
|
-
if (!channel) {
|
|
1020
|
-
Logger.warn(`No message channel found for sender ID: ${channelSenderId}`);
|
|
1021
|
-
return;
|
|
1022
|
-
}
|
|
1023
|
-
channel.port1.off("message", this.onRendererMessage.bind(this));
|
|
1024
|
-
channel.port1.close();
|
|
1025
|
-
channel.port2.close();
|
|
1026
|
-
this.messagePorts.delete(channelSenderId);
|
|
1027
|
-
}
|
|
1028
|
-
/**
|
|
1029
|
-
*
|
|
1030
|
-
*/
|
|
1031
|
-
async onAllWindowsClosed() {
|
|
1032
|
-
this.messagePorts.forEach((channel, senderId) => {
|
|
1033
|
-
this.shutdownChannel(senderId, false);
|
|
1034
|
-
});
|
|
1035
|
-
this.messagePorts.clear();
|
|
1036
|
-
this.app?.dispose();
|
|
1037
|
-
if (process.platform !== "darwin") {
|
|
1038
|
-
app.quit();
|
|
1039
|
-
}
|
|
1040
|
-
}
|
|
1041
|
-
// ---
|
|
1042
|
-
configure(app3) {
|
|
1043
|
-
this.app = inject(app3);
|
|
1044
|
-
return this;
|
|
1045
|
-
}
|
|
1046
|
-
use(middleware) {
|
|
1047
|
-
this.router.defineRootMiddleware(middleware);
|
|
1048
|
-
return this;
|
|
1049
|
-
}
|
|
1050
|
-
/**
|
|
1051
|
-
* Should be called after the bootstrapApplication function is called.
|
|
1052
|
-
*/
|
|
1053
|
-
start() {
|
|
1054
|
-
this.app?.onReady();
|
|
1055
|
-
return this;
|
|
1056
|
-
}
|
|
1057
|
-
};
|
|
1058
|
-
__name(_NoxApp, "NoxApp");
|
|
1059
|
-
var NoxApp = _NoxApp;
|
|
1060
|
-
NoxApp = _ts_decorate2([
|
|
1061
|
-
Injectable("singleton"),
|
|
1062
|
-
_ts_metadata("design:type", Function),
|
|
1063
|
-
_ts_metadata("design:paramtypes", [
|
|
1064
|
-
typeof Router === "undefined" ? Object : Router
|
|
1065
|
-
])
|
|
1066
|
-
], NoxApp);
|
|
1067
|
-
|
|
1068
|
-
// src/bootstrap.ts
|
|
1069
|
-
import { app as app2 } from "electron/main";
|
|
1070
|
-
async function bootstrapApplication(rootModule) {
|
|
1071
|
-
if (!getModuleMetadata(rootModule)) {
|
|
1072
|
-
throw new Error(`Root module must be decorated with @Module`);
|
|
1073
|
-
}
|
|
1074
|
-
await app2.whenReady();
|
|
1075
|
-
const noxApp = inject(NoxApp);
|
|
1076
|
-
await noxApp.init();
|
|
1077
|
-
return noxApp;
|
|
1078
|
-
}
|
|
1079
|
-
__name(bootstrapApplication, "bootstrapApplication");
|
|
1080
|
-
export {
|
|
1081
|
-
AppInjector,
|
|
1082
|
-
Authorize,
|
|
1083
|
-
BadGatewayException,
|
|
1084
|
-
BadRequestException,
|
|
1085
|
-
CONTROLLER_METADATA_KEY,
|
|
1086
|
-
ConflictException,
|
|
1087
|
-
Controller,
|
|
1088
|
-
Delete,
|
|
1089
|
-
ForbiddenException,
|
|
1090
|
-
GatewayTimeoutException,
|
|
1091
|
-
Get,
|
|
1092
|
-
HttpVersionNotSupportedException,
|
|
1093
|
-
INJECTABLE_METADATA_KEY,
|
|
1094
|
-
Injectable,
|
|
1095
|
-
InsufficientStorageException,
|
|
1096
|
-
InternalServerException,
|
|
1097
|
-
Logger,
|
|
1098
|
-
LoopDetectedException,
|
|
1099
|
-
MODULE_METADATA_KEY,
|
|
1100
|
-
MethodNotAllowedException,
|
|
1101
|
-
Module,
|
|
1102
|
-
NetworkAuthenticationRequiredException,
|
|
1103
|
-
NetworkConnectTimeoutException,
|
|
1104
|
-
NotAcceptableException,
|
|
1105
|
-
NotExtendedException,
|
|
1106
|
-
NotFoundException,
|
|
1107
|
-
NotImplementedException,
|
|
1108
|
-
NoxApp,
|
|
1109
|
-
Patch,
|
|
1110
|
-
PaymentRequiredException,
|
|
1111
|
-
Post,
|
|
1112
|
-
Put,
|
|
1113
|
-
ROUTE_METADATA_KEY,
|
|
1114
|
-
Request,
|
|
1115
|
-
RequestTimeoutException,
|
|
1116
|
-
ResponseException,
|
|
1117
|
-
RootInjector,
|
|
1118
|
-
Router,
|
|
1119
|
-
ServiceUnavailableException,
|
|
1120
|
-
TooManyRequestsException,
|
|
1121
|
-
UnauthorizedException,
|
|
1122
|
-
UpgradeRequiredException,
|
|
1123
|
-
UseMiddlewares,
|
|
1124
|
-
VariantAlsoNegotiatesException,
|
|
1125
|
-
bootstrapApplication,
|
|
1126
|
-
getControllerMetadata,
|
|
1127
|
-
getGuardForController,
|
|
1128
|
-
getGuardForControllerAction,
|
|
1129
|
-
getInjectableMetadata,
|
|
1130
|
-
getMiddlewaresForController,
|
|
1131
|
-
getMiddlewaresForControllerAction,
|
|
1132
|
-
getModuleMetadata,
|
|
1133
|
-
getRouteMetadata,
|
|
1134
|
-
inject
|
|
1135
|
-
};
|
|
6
|
+
var Pt=Object.defineProperty;var ee=(o,t,e)=>t in o?Pt(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var n=(o,t)=>Pt(o,"name",{value:t,configurable:!0});var i=(o,t,e)=>ee(o,typeof t!="symbol"?t+"":t,e);import"reflect-metadata";var Z=class Z extends Error{constructor(e,r){let s;typeof e=="number"?s=e:typeof e=="string"&&(r=e);super(r??"");i(this,"status",0);s!==void 0&&(this.status=s),this.name=this.constructor.name.replace(/([A-Z])/g," $1")}};n(Z,"ResponseException");var f=Z,H=class H extends f{constructor(){super(...arguments);i(this,"status",400)}};n(H,"BadRequestException");var jt=H,Q=class Q extends f{constructor(){super(...arguments);i(this,"status",401)}};n(Q,"UnauthorizedException");var j=Q,X=class X extends f{constructor(){super(...arguments);i(this,"status",402)}};n(X,"PaymentRequiredException");var Ct=X,V=class V extends f{constructor(){super(...arguments);i(this,"status",403)}};n(V,"ForbiddenException");var Tt=V,_=class _ extends f{constructor(){super(...arguments);i(this,"status",404)}};n(_,"NotFoundException");var C=_,q=class q extends f{constructor(){super(...arguments);i(this,"status",405)}};n(q,"MethodNotAllowedException");var T=q,tt=class tt extends f{constructor(){super(...arguments);i(this,"status",406)}};n(tt,"NotAcceptableException");var It=tt,et=class et extends f{constructor(){super(...arguments);i(this,"status",408)}};n(et,"RequestTimeoutException");var Ot=et,rt=class rt extends f{constructor(){super(...arguments);i(this,"status",409)}};n(rt,"ConflictException");var Dt=rt,ot=class ot extends f{constructor(){super(...arguments);i(this,"status",426)}};n(ot,"UpgradeRequiredException");var Gt=ot,nt=class nt extends f{constructor(){super(...arguments);i(this,"status",429)}};n(nt,"TooManyRequestsException");var St=nt,st=class st extends f{constructor(){super(...arguments);i(this,"status",500)}};n(st,"InternalServerException");var I=st,at=class at extends f{constructor(){super(...arguments);i(this,"status",501)}};n(at,"NotImplementedException");var Nt=at,it=class it extends f{constructor(){super(...arguments);i(this,"status",502)}};n(it,"BadGatewayException");var zt=it,lt=class lt extends f{constructor(){super(...arguments);i(this,"status",503)}};n(lt,"ServiceUnavailableException");var Ft=lt,ct=class ct extends f{constructor(){super(...arguments);i(this,"status",504)}};n(ct,"GatewayTimeoutException");var Yt=ct,dt=class dt extends f{constructor(){super(...arguments);i(this,"status",505)}};n(dt,"HttpVersionNotSupportedException");var Et=dt,ut=class ut extends f{constructor(){super(...arguments);i(this,"status",506)}};n(ut,"VariantAlsoNegotiatesException");var Lt=ut,ft=class ft extends f{constructor(){super(...arguments);i(this,"status",507)}};n(ft,"InsufficientStorageException");var Wt=ft,mt=class mt extends f{constructor(){super(...arguments);i(this,"status",508)}};n(mt,"LoopDetectedException");var Kt=mt,ht=class ht extends f{constructor(){super(...arguments);i(this,"status",510)}};n(ht,"NotExtendedException");var kt=ht,pt=class pt extends f{constructor(){super(...arguments);i(this,"status",511)}};n(pt,"NetworkAuthenticationRequiredException");var Jt=pt,gt=class gt extends f{constructor(){super(...arguments);i(this,"status",599)}};n(gt,"NetworkConnectTimeoutException");var Ut=gt;var O=class O{constructor(t=null){i(this,"name");i(this,"bindings",new Map);i(this,"singletons",new Map);i(this,"scoped",new Map);this.name=t}createScope(){let t=new O;return t.bindings=this.bindings,t.singletons=this.singletons,t}resolve(t){let e=this.bindings.get(t);if(!e)throw new I(`Failed to resolve a dependency injection : No binding for type ${t.name}.
|
|
7
|
+
Did you forget to use @Injectable() decorator ?`);switch(e.lifetime){case"transient":return this.instantiate(e.implementation);case"scope":{if(this.scoped.has(t))return this.scoped.get(t);let r=this.instantiate(e.implementation);return this.scoped.set(t,r),r}case"singleton":return e.instance===void 0&&this.name==="root"&&(e.instance=this.instantiate(e.implementation),this.singletons.set(t,e.instance)),e.instance}}instantiate(t){let r=(Reflect.getMetadata("design:paramtypes",t)||[]).map(s=>this.resolve(s));return new t(...r)}};n(O,"AppInjector");var wt=O;function D(o){return h.resolve(o)}n(D,"inject");var h=new wt("root");import"reflect-metadata";function re(){let o=new Date;return`${o.getDate().toString().padStart(2,"0")}/${(o.getMonth()+1).toString().padStart(2,"0")}/${o.getFullYear()} ${o.getHours().toString().padStart(2,"0")}:${o.getMinutes().toString().padStart(2,"0")}:${o.getSeconds().toString().padStart(2,"0")}`}n(re,"getPrettyTimestamp");function b(o,t,e){let r=re(),s=" ".repeat(10-t.length);return`${e}[APP] ${process.pid} - ${d.colors.initial}${r}${s}${e}${t.toUpperCase()}${d.colors.initial} ${d.colors.yellow}[${o}]${d.colors.initial}`}n(b,"getLogPrefix");function oe(o,t){return JSON.stringify(t,null,2).split(`
|
|
8
|
+
`).map((s,a)=>a===0?`${d.colors.darkGrey}${s}`:`${o} ${d.colors.grey}${s}`).join(`
|
|
9
|
+
`)+d.colors.initial}n(oe,"formatObject");function R(o,t,e){return t.map(r=>typeof r=="string"?`${e}${r}${d.colors.initial}`:typeof r=="object"?oe(o,r):r)}n(R,"formattedArgs");function A(){return(new Error().stack?.split(`
|
|
10
|
+
`)??[])[3]?.trim().match(/at (.+?)(?:\..+)? .+$/)?.[1]?.replace("Object","")||"App"}n(A,"getCallee");function y(o){return Bt[o]>=Bt[Zt]}n(y,"canLog");var Zt="log",Bt={debug:0,log:1,info:2,warn:3,error:4};(function(o){function t(c){Zt=c}n(t,"setLogLevel"),o.setLogLevel=t;function e(...c){if(!y("log"))return;let m=A(),u=b(m,"log",o.colors.green);console.log(u,...R(u,c,o.colors.green))}n(e,"log"),o.log=e;function r(...c){if(!y("info"))return;let m=A(),u=b(m,"info",o.colors.blue);console.info(u,...R(u,c,o.colors.blue))}n(r,"info"),o.info=r;function s(...c){if(!y("warn"))return;let m=A(),u=b(m,"warn",o.colors.brown);console.warn(u,...R(u,c,o.colors.brown))}n(s,"warn"),o.warn=s;function a(...c){if(!y("error"))return;let m=A(),u=b(m,"error",o.colors.red);console.error(u,...R(u,c,o.colors.red))}n(a,"error"),o.error=a;function l(...c){if(!y("debug"))return;let m=A(),u=b(m,"debug",o.colors.purple);console.debug(u,...R(u,c,o.colors.purple))}n(l,"debug"),o.debug=l,o.colors={black:"\x1B[0;30m",grey:"\x1B[0;37m",red:"\x1B[0;31m",green:"\x1B[0;32m",brown:"\x1B[0;33m",blue:"\x1B[0;34m",purple:"\x1B[0;35m",darkGrey:"\x1B[1;30m",lightRed:"\x1B[1;31m",lightGreen:"\x1B[1;32m",yellow:"\x1B[1;33m",lightBlue:"\x1B[1;34m",magenta:"\x1B[1;35m",cyan:"\x1B[1;36m",white:"\x1B[1;37m",initial:"\x1B[0m"}})(d||(d={}));var d;function be(...o){return(t,e)=>{let r;if(e?r=`${t.constructor.name}.${e}`:r=`${t.name}`,G.has(r))throw new Error(`Guard(s) already registered for ${r}`);d.debug(`Registering guard(s) for ${r}: ${o.map(s=>s.name).join(", ")}`),G.set(r,o)}}n(be,"Authorize");function S(o){let t=`${o}`;return G.get(t)??[]}n(S,"getGuardForController");function N(o,t){let e=`${o}.${t}`;return G.get(e)??[]}n(N,"getGuardForControllerAction");var G=new Map;function v(o){return t=>(e,r)=>{let s=Reflect.getMetadata(xt,e.constructor)||[],a={method:o,path:t.trim().replace(/^\/|\/$/g,""),handler:r,guards:N(e.constructor.__controllerName,r)};s.push(a),Reflect.defineMetadata(xt,s,e.constructor)}}n(v,"createRouteDecorator");function z(o){return Reflect.getMetadata(xt,o)||[]}n(z,"getRouteMetadata");var ve=v("GET"),Pe=v("POST"),je=v("PUT"),Ce=v("PATCH"),Te=v("DELETE"),xt=Symbol("ROUTE_METADATA_KEY");function Se(o){return t=>{let e=n((a,l)=>{if(a){for(let c of a)if(!Reflect.getMetadata($t,c))throw new Error(`Class ${c.name} in ${l} must be decorated with @Module`)}},"checkModule"),r=n(a=>{if(a){for(let l of a)if(!Reflect.getMetadata(Y,l))throw new Error(`Class ${l.name} in providers must be decorated with @Injectable`)}},"checkInjectable"),s=n(a=>{if(a){for(let l of a)if(!Reflect.getMetadata(E,l))throw new Error(`Class ${l.name} in controllers must be decorated with @Controller`)}},"checkController");e(o.imports,"imports"),e(o.exports,"exports"),r(o.providers),s(o.controllers),Reflect.defineMetadata($t,o,t),w("singleton")(t)}}n(Se,"Module");function F(o){return Reflect.getMetadata($t,o)}n(F,"getModuleMetadata");var $t=Symbol("MODULE_METADATA_KEY");var Mt=class Mt{static register(t,e){return d.debug(`Registering ${t.name} as ${e}`),h.bindings.has(t)?h:(h.bindings.set(t,{implementation:t,lifetime:e}),e==="singleton"&&h.resolve(t),F(t)?(d.log(`${t.name} dependencies initialized`),h):W(t)?(h.resolve(g)?.registerController(t),h):z(t)?h:Ht(t)?(d.log(`Registered ${t.name} as ${e}`),h):h)}};n(Mt,"InjectorExplorer");var L=Mt;function w(o="scope"){return t=>{if(typeof t!="function"||!t.prototype)throw new Error(`@Injectable can only be used on classes, not on ${typeof t}`);Reflect.defineMetadata(Y,o,t),L.register(t,o)}}n(w,"Injectable");function Ht(o){return Reflect.getMetadata(Y,o)}n(Ht,"getInjectableMetadata");var Y=Symbol("INJECTABLE_METADATA_KEY");function Ve(o){return t=>{let e={path:o,guards:S(t.name)};Reflect.defineMetadata(E,e,t),w("scope")(t)}}n(Ve,"Controller");function W(o){return Reflect.getMetadata(E,o)}n(W,"getControllerMetadata");var E=Symbol("CONTROLLER_METADATA_KEY");function er(o){return(t,e)=>{let r;if(e?r=`${t.constructor.name}.${e}`:r=`${t.name}`,K.has(r))throw new Error(`Middlewares(s) already registered for ${r}`);d.debug(`Registering middleware(s) for ${r}: ${o.map(s=>s.name).join(", ")}`),K.set(r,o)}}n(er,"UseMiddlewares");function Qt(o){let t=`${o}`;return K.get(t)??[]}n(Qt,"getMiddlewaresForController");function Xt(o,t){let e=`${o}.${t}`;return K.get(e)??[]}n(Xt,"getMiddlewaresForControllerAction");var K=new Map;var x,Vt=(x=class{constructor(t){i(this,"segment");i(this,"children",[]);i(this,"value");i(this,"isParam");i(this,"paramName");this.segment=t,this.isParam=t.startsWith(":"),this.isParam&&(this.paramName=t.slice(1))}matchChild(t){for(let e of this.children)if(e.isParam||t.startsWith(e.segment))return e}findExactChild(t){return this.children.find(e=>e.segment===t)}addChild(t){this.children.push(t)}},n(x,"RadixNode"),x),bt=class bt{constructor(){i(this,"root",new Vt(""))}insert(t,e){let r=this.normalize(t);this.insertRecursive(this.root,r,e)}insertRecursive(t,e,r){if(e.length===0){t.value=r;return}let s=e[0]??"",a=t.children.find(l=>l.isParam===s.startsWith(":")&&(l.isParam||l.segment===s));a||(a=new Vt(s),t.addChild(a)),this.insertRecursive(a,e.slice(1),r)}search(t){let e=this.normalize(t);return this.searchRecursive(this.root,e,{})}searchRecursive(t,e,r){if(e.length===0)return t.value!==void 0?{node:t,params:r}:void 0;let[s,...a]=e;for(let l of t.children)if(l.isParam){let c=l.paramName,m={...r,[c]:s??""};if(a.length===0)return{node:l,params:m};let u=this.searchRecursive(l,a,m);if(u)return u}else if(s===l.segment){if(a.length===0)return{node:l,params:r};let c=this.searchRecursive(l,a,r);if(c)return c}}normalize(t){return["",...t.replace(/^\/+|\/+$/g,"").split("/").filter(Boolean)]}};n(bt,"RadixTree");var k=bt;function ne(o,t,e,r){var s=arguments.length,a=s<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(o,t,e,r);else for(var c=o.length-1;c>=0;c--)(l=o[c])&&(a=(s<3?l(a):s>3?l(t,e,a):l(t,e))||a);return s>3&&a&&Object.defineProperty(t,e,a),a}n(ne,"_ts_decorate");var Rt=class Rt{constructor(){i(this,"routes",new k);i(this,"rootMiddlewares",[])}registerController(t){let e=W(t),r=S(t.name),s=Qt(t.name);if(!e)throw new Error(`Missing @Controller decorator on ${t.name}`);let a=z(t);for(let m of a){let u=`${e.path}/${m.path}`.replace(/\/+/g,"/"),p=N(t.name,m.handler),U=Xt(t.name,m.handler),M=new Set([...r,...p]),B=new Set([...s,...U]),P={method:m.method,path:u,controller:t,handler:m.handler,guards:[...M],middlewares:[...B]};this.routes.insert(u+"/"+m.method,P);let qt=P.guards.length>0?"<"+P.guards.map(te=>te.name).join("|")+">":"";d.log(`Mapped {${P.method} /${u}}${qt} route`)}let c=e.guards.length>0?"<"+e.guards.map(m=>m.name).join("|")+">":"";return d.log(`Mapped ${t.name}${c} controller's routes`),this}defineRootMiddleware(t){return d.debug(`Registering root middleware: ${t.name}`),this.rootMiddlewares.push(t),this}async handle(t){d.log(`> Received request: {${t.method} /${t.path}}`);let e=performance.now(),r={requestId:t.id,status:200,body:null,error:void 0};try{let s=this.findRoute(t);if(await this.resolveController(t,r,s),r.status>400)throw new f(r.status,r.error)}catch(s){s instanceof f?(r.status=s.status,r.error=s.message):s instanceof Error?(r.status=500,r.error=s.message||"Internal Server Error"):(r.status=500,r.error="Unknown error occurred")}finally{let s=performance.now(),a=`< ${r.status} ${t.method} /${t.path} ${d.colors.yellow}${Math.round(s-e)}ms${d.colors.initial}`;return r.status<400?d.log(a):r.status<500?d.warn(a):d.error(a),r.error!==void 0&&d.error(r.error),r}}findRoute(t){let e=this.routes.search(t.path);if(e?.node===void 0||e.node.children.length===0)throw new C(`No route matches ${t.method} ${t.path}`);let r=e.node.findExactChild(t.method);if(r?.value===void 0)throw new T(`Method Not Allowed for ${t.method} ${t.path}`);return r.value}async resolveController(t,e,r){let s=t.context.resolve(r.controller);Object.assign(t.params,this.extractParams(t.path,r.path)),await this.runRequestPipeline(t,e,r,s)}async runRequestPipeline(t,e,r,s){let a=[...new Set([...this.rootMiddlewares,...r.middlewares])],l=a.length-1,c=l+r.guards.length,m=-1,u=n(async p=>{if(p<=m)throw new Error("next() called multiple times");if(m=p,p<=l){let M=u.bind(null,p+1);if(await this.runMiddleware(t,e,M,a[p]),e.status>=400)throw new f(e.status,e.error);return}if(p<=c){let M=p-a.length,B=r.guards[M];await this.runGuard(t,B),u(p+1);return}let U=s[r.handler];e.body=await U.call(s,t,e)},"dispatch");await u(0)}async runMiddleware(t,e,r,s){await t.context.resolve(s).invoke(t,e,r)}async runGuard(t,e){if(!await t.context.resolve(e).canActivate(t))throw new j(`Unauthorized for ${t.method} ${t.path}`)}extractParams(t,e){let r=t.split("/"),s=e.split("/"),a={};return s.forEach((l,c)=>{l.startsWith(":")&&(a[l.slice(1)]=r[c]??"")}),a}};n(Rt,"Router");var g=Rt;g=ne([w("singleton")],g);import{app as yt,BrowserWindow as ae,ipcMain as ie,MessageChannelMain as le}from"electron/main";import"reflect-metadata";var At=class At{constructor(t,e,r,s,a){i(this,"event");i(this,"id");i(this,"method");i(this,"path");i(this,"body");i(this,"context",h.createScope());i(this,"params",{});this.event=t,this.id=e,this.method=r,this.path=s,this.body=a,this.path=s.replace(/^\/|\/$/g,"")}};n(At,"Request");var J=At;function se(o,t,e,r){var s=arguments.length,a=s<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(o,t,e,r);else for(var c=o.length-1;c>=0;c--)(l=o[c])&&(a=(s<3?l(a):s>3?l(t,e,a):l(t,e))||a);return s>3&&a&&Object.defineProperty(t,e,a),a}n(se,"_ts_decorate");function _t(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)}n(_t,"_ts_metadata");var vt=class vt{constructor(t){i(this,"router");i(this,"messagePorts",new Map);i(this,"app");this.router=t}async init(){return ie.on("gimme-my-port",this.giveTheRendererAPort.bind(this)),yt.once("activate",this.onAppActivated.bind(this)),yt.once("window-all-closed",this.onAllWindowsClosed.bind(this)),console.log(""),this}giveTheRendererAPort(t){let e=t.sender.id;this.messagePorts.has(e)&&this.shutdownChannel(e);let r=new le;this.messagePorts.set(e,r),r.port1.on("message",this.onRendererMessage.bind(this)),r.port1.start(),t.sender.postMessage("port",{senderId:e},[r.port2])}async onRendererMessage(t){let{senderId:e,requestId:r,path:s,method:a,body:l}=t.data,c=this.messagePorts.get(e);if(!c){d.error(`No message channel found for sender ID: ${e}`);return}try{let m=new J(t,r,a,s,l),u=await this.router.handle(m);c.port1.postMessage(u)}catch(m){let u={requestId:r,status:500,body:null,error:m.message||"Internal Server Error"};c.port1.postMessage(u)}}onAppActivated(){process.platform==="darwin"&&ae.getAllWindows().length===0&&this.app?.onActivated()}shutdownChannel(t){let e=this.messagePorts.get(t);if(!e){d.warn(`No message channel found for sender ID: ${t}`);return}e.port1.off("message",this.onRendererMessage.bind(this)),e.port1.close(),e.port2.close(),this.messagePorts.delete(t)}async onAllWindowsClosed(){this.messagePorts.forEach((t,e)=>{this.shutdownChannel(e)}),this.messagePorts.clear(),this.app?.dispose(),process.platform!=="darwin"&&yt.quit()}configure(t){return this.app=D(t),this}use(t){return this.router.defineRootMiddleware(t),this}start(){return this.app?.onReady(),this}};n(vt,"NoxApp");var $=vt;$=se([w("singleton"),_t("design:type",Function),_t("design:paramtypes",[typeof g>"u"?Object:g])],$);import{app as ce}from"electron/main";async function Gr(o){if(!F(o))throw new Error("Root module must be decorated with @Module");await ce.whenReady();let t=D($);return await t.init(),t}n(Gr,"bootstrapApplication");export{wt as AppInjector,be as Authorize,zt as BadGatewayException,jt as BadRequestException,E as CONTROLLER_METADATA_KEY,Dt as ConflictException,Ve as Controller,Te as Delete,Tt as ForbiddenException,Yt as GatewayTimeoutException,ve as Get,Et as HttpVersionNotSupportedException,Y as INJECTABLE_METADATA_KEY,w as Injectable,Wt as InsufficientStorageException,I as InternalServerException,d as Logger,Kt as LoopDetectedException,$t as MODULE_METADATA_KEY,T as MethodNotAllowedException,Se as Module,Jt as NetworkAuthenticationRequiredException,Ut as NetworkConnectTimeoutException,It as NotAcceptableException,kt as NotExtendedException,C as NotFoundException,Nt as NotImplementedException,$ as NoxApp,Ce as Patch,Ct as PaymentRequiredException,Pe as Post,je as Put,xt as ROUTE_METADATA_KEY,J as Request,Ot as RequestTimeoutException,f as ResponseException,h as RootInjector,g as Router,Ft as ServiceUnavailableException,St as TooManyRequestsException,j as UnauthorizedException,Gt as UpgradeRequiredException,er as UseMiddlewares,Lt as VariantAlsoNegotiatesException,Gr as bootstrapApplication,W as getControllerMetadata,S as getGuardForController,N as getGuardForControllerAction,Ht as getInjectableMetadata,Qt as getMiddlewaresForController,Xt as getMiddlewaresForControllerAction,F as getModuleMetadata,z as getRouteMetadata,D as inject};
|
|
1136
11
|
/**
|
|
1137
12
|
* @copyright 2025 NoxFly
|
|
1138
13
|
* @license MIT
|