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