@noxfly/noxus 2.4.0 → 3.0.0-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +403 -341
  2. package/dist/app-injector-Bz3Upc0y.d.mts +125 -0
  3. package/dist/app-injector-Bz3Upc0y.d.ts +125 -0
  4. package/dist/child.d.mts +48 -22
  5. package/dist/child.d.ts +48 -22
  6. package/dist/child.js +1114 -1239
  7. package/dist/child.mjs +1090 -1193
  8. package/dist/main.d.mts +304 -261
  9. package/dist/main.d.ts +304 -261
  10. package/dist/main.js +1473 -1873
  11. package/dist/main.mjs +1423 -1791
  12. package/dist/renderer.d.mts +113 -2
  13. package/dist/renderer.d.ts +113 -2
  14. package/dist/renderer.js +144 -132
  15. package/dist/renderer.mjs +143 -132
  16. package/dist/request-BlTtiHbi.d.ts +112 -0
  17. package/dist/request-qJ9EiDZc.d.mts +112 -0
  18. package/package.json +7 -7
  19. package/src/DI/app-injector.ts +95 -106
  20. package/src/DI/injector-explorer.ts +100 -81
  21. package/src/DI/token.ts +53 -0
  22. package/src/app.ts +141 -131
  23. package/src/bootstrap.ts +79 -40
  24. package/src/decorators/controller.decorator.ts +38 -27
  25. package/src/decorators/guards.decorator.ts +5 -64
  26. package/src/decorators/injectable.decorator.ts +68 -15
  27. package/src/decorators/method.decorator.ts +40 -81
  28. package/src/decorators/middleware.decorator.ts +5 -72
  29. package/src/index.ts +3 -0
  30. package/src/main.ts +4 -11
  31. package/src/non-electron-process.ts +0 -1
  32. package/src/preload-bridge.ts +1 -1
  33. package/src/renderer-client.ts +2 -2
  34. package/src/renderer-events.ts +1 -1
  35. package/src/request.ts +3 -3
  36. package/src/router.ts +221 -369
  37. package/src/routes.ts +78 -0
  38. package/src/socket.ts +4 -4
  39. package/src/window/window-manager.ts +255 -0
  40. package/tsconfig.json +5 -10
  41. package/tsup.config.ts +2 -2
  42. package/dist/app-injector-B3MvgV3k.d.mts +0 -95
  43. package/dist/app-injector-B3MvgV3k.d.ts +0 -95
  44. package/dist/index-BxWQVi6C.d.ts +0 -253
  45. package/dist/index-DQBQQfMw.d.mts +0 -253
  46. package/src/decorators/inject.decorator.ts +0 -24
  47. package/src/decorators/injectable.metadata.ts +0 -15
  48. package/src/decorators/module.decorator.ts +0 -75
package/dist/main.js CHANGED
@@ -10,8 +10,10 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
10
  var __getOwnPropNames = Object.getOwnPropertyNames;
11
11
  var __getProtoOf = Object.getPrototypeOf;
12
12
  var __hasOwnProp = Object.prototype.hasOwnProperty;
13
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
13
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
14
+ var __esm = (fn, res) => function __init() {
15
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
16
+ };
15
17
  var __export = (target, all) => {
16
18
  for (var name in all)
17
19
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -33,536 +35,169 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
33
35
  mod
34
36
  ));
35
37
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
37
-
38
- // src/main.ts
39
- var main_exports = {};
40
- __export(main_exports, {
41
- AppInjector: () => AppInjector,
42
- Authorize: () => Authorize,
43
- BadGatewayException: () => BadGatewayException,
44
- BadRequestException: () => BadRequestException,
45
- CONTROLLER_METADATA_KEY: () => CONTROLLER_METADATA_KEY,
46
- ConflictException: () => ConflictException,
47
- Controller: () => Controller,
48
- Delete: () => Delete,
49
- ForbiddenException: () => ForbiddenException,
50
- ForwardReference: () => ForwardReference,
51
- GatewayTimeoutException: () => GatewayTimeoutException,
52
- Get: () => Get,
53
- HttpVersionNotSupportedException: () => HttpVersionNotSupportedException,
54
- INJECTABLE_METADATA_KEY: () => INJECTABLE_METADATA_KEY,
55
- INJECT_METADATA_KEY: () => INJECT_METADATA_KEY,
56
- Inject: () => Inject,
57
- Injectable: () => Injectable,
58
- InsufficientStorageException: () => InsufficientStorageException,
59
- InternalServerException: () => InternalServerException,
60
- Logger: () => Logger,
61
- LoopDetectedException: () => LoopDetectedException,
62
- MODULE_METADATA_KEY: () => MODULE_METADATA_KEY,
63
- MethodNotAllowedException: () => MethodNotAllowedException,
64
- Module: () => Module,
65
- NetworkAuthenticationRequiredException: () => NetworkAuthenticationRequiredException,
66
- NetworkConnectTimeoutException: () => NetworkConnectTimeoutException,
67
- NotAcceptableException: () => NotAcceptableException,
68
- NotExtendedException: () => NotExtendedException,
69
- NotFoundException: () => NotFoundException,
70
- NotImplementedException: () => NotImplementedException,
71
- NoxApp: () => NoxApp,
72
- NoxRendererClient: () => NoxRendererClient,
73
- NoxSocket: () => NoxSocket,
74
- Patch: () => Patch,
75
- PaymentRequiredException: () => PaymentRequiredException,
76
- Post: () => Post,
77
- Put: () => Put,
78
- RENDERER_EVENT_TYPE: () => RENDERER_EVENT_TYPE,
79
- ROUTE_METADATA_KEY: () => ROUTE_METADATA_KEY,
80
- RendererEventRegistry: () => RendererEventRegistry,
81
- Request: () => Request,
82
- RequestTimeoutException: () => RequestTimeoutException,
83
- ResponseException: () => ResponseException,
84
- RootInjector: () => RootInjector,
85
- Router: () => Router,
86
- ServiceUnavailableException: () => ServiceUnavailableException,
87
- TooManyRequestsException: () => TooManyRequestsException,
88
- UnauthorizedException: () => UnauthorizedException,
89
- UpgradeRequiredException: () => UpgradeRequiredException,
90
- UseMiddlewares: () => UseMiddlewares,
91
- VariantAlsoNegotiatesException: () => VariantAlsoNegotiatesException,
92
- bootstrapApplication: () => bootstrapApplication,
93
- createRendererEventMessage: () => createRendererEventMessage,
94
- exposeNoxusBridge: () => exposeNoxusBridge,
95
- forwardRef: () => forwardRef,
96
- getControllerMetadata: () => getControllerMetadata,
97
- getGuardForController: () => getGuardForController,
98
- getGuardForControllerAction: () => getGuardForControllerAction,
99
- getInjectableMetadata: () => getInjectableMetadata,
100
- getMiddlewaresForController: () => getMiddlewaresForController,
101
- getMiddlewaresForControllerAction: () => getMiddlewaresForControllerAction,
102
- getModuleMetadata: () => getModuleMetadata,
103
- getRouteMetadata: () => getRouteMetadata,
104
- hasInjectableMetadata: () => hasInjectableMetadata,
105
- inject: () => inject,
106
- isRendererEventMessage: () => isRendererEventMessage
107
- });
108
- module.exports = __toCommonJS(main_exports);
109
-
110
- // src/DI/app-injector.ts
111
- var import_reflect_metadata2 = require("reflect-metadata");
112
-
113
- // src/decorators/inject.decorator.ts
114
- var import_reflect_metadata = require("reflect-metadata");
115
- var INJECT_METADATA_KEY = "custom:inject";
116
- function Inject(token) {
117
- return (target, propertyKey, parameterIndex) => {
118
- const existingParameters = Reflect.getOwnMetadata(INJECT_METADATA_KEY, target) || [];
119
- existingParameters[parameterIndex] = token;
120
- Reflect.defineMetadata(INJECT_METADATA_KEY, existingParameters, target);
121
- };
122
- }
123
- __name(Inject, "Inject");
124
-
125
- // src/exceptions.ts
126
- var _ResponseException = class _ResponseException extends Error {
127
- constructor(statusOrMessage, message) {
128
- let statusCode;
129
- if (typeof statusOrMessage === "number") {
130
- statusCode = statusOrMessage;
131
- } else if (typeof statusOrMessage === "string") {
132
- message = statusOrMessage;
133
- }
134
- super(message ?? "");
135
- __publicField(this, "status", 0);
136
- if (statusCode !== void 0) {
137
- this.status = statusCode;
138
- }
139
- this.name = this.constructor.name.replace(/([A-Z])/g, " $1");
140
- }
141
- };
142
- __name(_ResponseException, "ResponseException");
143
- var ResponseException = _ResponseException;
144
- var _BadRequestException = class _BadRequestException extends ResponseException {
145
- constructor() {
146
- super(...arguments);
147
- __publicField(this, "status", 400);
148
- }
149
- };
150
- __name(_BadRequestException, "BadRequestException");
151
- var BadRequestException = _BadRequestException;
152
- var _UnauthorizedException = class _UnauthorizedException extends ResponseException {
153
- constructor() {
154
- super(...arguments);
155
- __publicField(this, "status", 401);
156
- }
157
- };
158
- __name(_UnauthorizedException, "UnauthorizedException");
159
- var UnauthorizedException = _UnauthorizedException;
160
- var _PaymentRequiredException = class _PaymentRequiredException extends ResponseException {
161
- constructor() {
162
- super(...arguments);
163
- __publicField(this, "status", 402);
164
- }
165
- };
166
- __name(_PaymentRequiredException, "PaymentRequiredException");
167
- var PaymentRequiredException = _PaymentRequiredException;
168
- var _ForbiddenException = class _ForbiddenException extends ResponseException {
169
- constructor() {
170
- super(...arguments);
171
- __publicField(this, "status", 403);
172
- }
173
- };
174
- __name(_ForbiddenException, "ForbiddenException");
175
- var ForbiddenException = _ForbiddenException;
176
- var _NotFoundException = class _NotFoundException extends ResponseException {
177
- constructor() {
178
- super(...arguments);
179
- __publicField(this, "status", 404);
180
- }
181
- };
182
- __name(_NotFoundException, "NotFoundException");
183
- var NotFoundException = _NotFoundException;
184
- var _MethodNotAllowedException = class _MethodNotAllowedException extends ResponseException {
185
- constructor() {
186
- super(...arguments);
187
- __publicField(this, "status", 405);
188
- }
189
- };
190
- __name(_MethodNotAllowedException, "MethodNotAllowedException");
191
- var MethodNotAllowedException = _MethodNotAllowedException;
192
- var _NotAcceptableException = class _NotAcceptableException extends ResponseException {
193
- constructor() {
194
- super(...arguments);
195
- __publicField(this, "status", 406);
196
- }
197
- };
198
- __name(_NotAcceptableException, "NotAcceptableException");
199
- var NotAcceptableException = _NotAcceptableException;
200
- var _RequestTimeoutException = class _RequestTimeoutException extends ResponseException {
201
- constructor() {
202
- super(...arguments);
203
- __publicField(this, "status", 408);
204
- }
205
- };
206
- __name(_RequestTimeoutException, "RequestTimeoutException");
207
- var RequestTimeoutException = _RequestTimeoutException;
208
- var _ConflictException = class _ConflictException extends ResponseException {
209
- constructor() {
210
- super(...arguments);
211
- __publicField(this, "status", 409);
212
- }
213
- };
214
- __name(_ConflictException, "ConflictException");
215
- var ConflictException = _ConflictException;
216
- var _UpgradeRequiredException = class _UpgradeRequiredException extends ResponseException {
217
- constructor() {
218
- super(...arguments);
219
- __publicField(this, "status", 426);
220
- }
221
- };
222
- __name(_UpgradeRequiredException, "UpgradeRequiredException");
223
- var UpgradeRequiredException = _UpgradeRequiredException;
224
- var _TooManyRequestsException = class _TooManyRequestsException extends ResponseException {
225
- constructor() {
226
- super(...arguments);
227
- __publicField(this, "status", 429);
228
- }
229
- };
230
- __name(_TooManyRequestsException, "TooManyRequestsException");
231
- var TooManyRequestsException = _TooManyRequestsException;
232
- var _InternalServerException = class _InternalServerException extends ResponseException {
233
- constructor() {
234
- super(...arguments);
235
- __publicField(this, "status", 500);
236
- }
237
- };
238
- __name(_InternalServerException, "InternalServerException");
239
- var InternalServerException = _InternalServerException;
240
- var _NotImplementedException = class _NotImplementedException extends ResponseException {
241
- constructor() {
242
- super(...arguments);
243
- __publicField(this, "status", 501);
244
- }
245
- };
246
- __name(_NotImplementedException, "NotImplementedException");
247
- var NotImplementedException = _NotImplementedException;
248
- var _BadGatewayException = class _BadGatewayException extends ResponseException {
249
- constructor() {
250
- super(...arguments);
251
- __publicField(this, "status", 502);
252
- }
253
- };
254
- __name(_BadGatewayException, "BadGatewayException");
255
- var BadGatewayException = _BadGatewayException;
256
- var _ServiceUnavailableException = class _ServiceUnavailableException extends ResponseException {
257
- constructor() {
258
- super(...arguments);
259
- __publicField(this, "status", 503);
260
- }
261
- };
262
- __name(_ServiceUnavailableException, "ServiceUnavailableException");
263
- var ServiceUnavailableException = _ServiceUnavailableException;
264
- var _GatewayTimeoutException = class _GatewayTimeoutException extends ResponseException {
265
- constructor() {
266
- super(...arguments);
267
- __publicField(this, "status", 504);
268
- }
269
- };
270
- __name(_GatewayTimeoutException, "GatewayTimeoutException");
271
- var GatewayTimeoutException = _GatewayTimeoutException;
272
- var _HttpVersionNotSupportedException = class _HttpVersionNotSupportedException extends ResponseException {
273
- constructor() {
274
- super(...arguments);
275
- __publicField(this, "status", 505);
276
- }
277
- };
278
- __name(_HttpVersionNotSupportedException, "HttpVersionNotSupportedException");
279
- var HttpVersionNotSupportedException = _HttpVersionNotSupportedException;
280
- var _VariantAlsoNegotiatesException = class _VariantAlsoNegotiatesException extends ResponseException {
281
- constructor() {
282
- super(...arguments);
283
- __publicField(this, "status", 506);
284
- }
285
- };
286
- __name(_VariantAlsoNegotiatesException, "VariantAlsoNegotiatesException");
287
- var VariantAlsoNegotiatesException = _VariantAlsoNegotiatesException;
288
- var _InsufficientStorageException = class _InsufficientStorageException extends ResponseException {
289
- constructor() {
290
- super(...arguments);
291
- __publicField(this, "status", 507);
292
- }
293
- };
294
- __name(_InsufficientStorageException, "InsufficientStorageException");
295
- var InsufficientStorageException = _InsufficientStorageException;
296
- var _LoopDetectedException = class _LoopDetectedException extends ResponseException {
297
- constructor() {
298
- super(...arguments);
299
- __publicField(this, "status", 508);
300
- }
301
- };
302
- __name(_LoopDetectedException, "LoopDetectedException");
303
- var LoopDetectedException = _LoopDetectedException;
304
- var _NotExtendedException = class _NotExtendedException extends ResponseException {
305
- constructor() {
306
- super(...arguments);
307
- __publicField(this, "status", 510);
308
- }
309
- };
310
- __name(_NotExtendedException, "NotExtendedException");
311
- var NotExtendedException = _NotExtendedException;
312
- var _NetworkAuthenticationRequiredException = class _NetworkAuthenticationRequiredException extends ResponseException {
313
- constructor() {
314
- super(...arguments);
315
- __publicField(this, "status", 511);
316
- }
317
- };
318
- __name(_NetworkAuthenticationRequiredException, "NetworkAuthenticationRequiredException");
319
- var NetworkAuthenticationRequiredException = _NetworkAuthenticationRequiredException;
320
- var _NetworkConnectTimeoutException = class _NetworkConnectTimeoutException extends ResponseException {
321
- constructor() {
322
- super(...arguments);
323
- __publicField(this, "status", 599);
324
- }
38
+ var __decorateClass = (decorators, target, key, kind) => {
39
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
40
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
41
+ if (decorator = decorators[i])
42
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
43
+ if (kind && result) __defProp(target, key, result);
44
+ return result;
325
45
  };
326
- __name(_NetworkConnectTimeoutException, "NetworkConnectTimeoutException");
327
- var NetworkConnectTimeoutException = _NetworkConnectTimeoutException;
328
46
 
329
47
  // src/utils/forward-ref.ts
330
- var _ForwardReference = class _ForwardReference {
331
- constructor(forwardRefFn) {
332
- __publicField(this, "forwardRefFn");
333
- this.forwardRefFn = forwardRefFn;
334
- }
335
- };
336
- __name(_ForwardReference, "ForwardReference");
337
- var ForwardReference = _ForwardReference;
338
48
  function forwardRef(fn) {
339
49
  return new ForwardReference(fn);
340
50
  }
341
- __name(forwardRef, "forwardRef");
342
-
343
- // src/DI/app-injector.ts
344
- var _AppInjector = class _AppInjector {
345
- constructor(name = null) {
346
- __publicField(this, "name");
347
- __publicField(this, "bindings", /* @__PURE__ */ new Map());
348
- __publicField(this, "singletons", /* @__PURE__ */ new Map());
349
- __publicField(this, "scoped", /* @__PURE__ */ new Map());
350
- this.name = name;
351
- }
352
- /**
353
- * Typically used to create a dependency injection scope
354
- * at the "scope" level (i.e., per-request lifetime).
355
- *
356
- * SHOULD NOT BE USED by anything else than the framework itself.
357
- */
358
- createScope() {
359
- const scope = new _AppInjector();
360
- scope.bindings = this.bindings;
361
- scope.singletons = this.singletons;
362
- return scope;
363
- }
364
- /**
365
- * Called when resolving a dependency,
366
- * i.e., retrieving the instance of a given class.
367
- */
368
- resolve(target) {
369
- if (target instanceof ForwardReference) {
370
- return new Proxy({}, {
371
- get: /* @__PURE__ */ __name((obj, prop, receiver) => {
372
- const realType = target.forwardRefFn();
373
- const instance = this.resolve(realType);
374
- const value = Reflect.get(instance, prop, receiver);
375
- return typeof value === "function" ? value.bind(instance) : value;
376
- }, "get"),
377
- set: /* @__PURE__ */ __name((obj, prop, value, receiver) => {
378
- const realType = target.forwardRefFn();
379
- const instance = this.resolve(realType);
380
- return Reflect.set(instance, prop, value, receiver);
381
- }, "set"),
382
- getPrototypeOf: /* @__PURE__ */ __name(() => {
383
- const realType = target.forwardRefFn();
384
- return realType.prototype;
385
- }, "getPrototypeOf")
386
- });
387
- }
388
- const binding = this.bindings.get(target);
389
- if (!binding) {
390
- if (target === void 0) {
391
- throw new InternalServerException("Failed to resolve a dependency injection : Undefined target type.\nThis might be caused by a circular dependency.");
392
- }
393
- const name = target.name || "unknown";
394
- throw new InternalServerException(`Failed to resolve a dependency injection : No binding for type ${name}.
395
- Did you forget to use @Injectable() decorator ?`);
396
- }
397
- switch (binding.lifetime) {
398
- case "transient":
399
- return this.instantiate(binding.implementation);
400
- case "scope": {
401
- if (this.scoped.has(target)) {
402
- return this.scoped.get(target);
403
- }
404
- const instance = this.instantiate(binding.implementation);
405
- this.scoped.set(target, instance);
406
- return instance;
407
- }
408
- case "singleton": {
409
- if (binding.instance === void 0 && this.name === "root") {
410
- binding.instance = this.instantiate(binding.implementation);
411
- this.singletons.set(target, binding.instance);
412
- }
413
- return binding.instance;
51
+ var _ForwardReference, ForwardReference;
52
+ var init_forward_ref = __esm({
53
+ "src/utils/forward-ref.ts"() {
54
+ "use strict";
55
+ _ForwardReference = class _ForwardReference {
56
+ constructor(forwardRefFn) {
57
+ this.forwardRefFn = forwardRefFn;
414
58
  }
415
- }
416
- }
417
- /**
418
- * Instantiates a class, resolving its dependencies.
419
- */
420
- instantiate(target) {
421
- const paramTypes = Reflect.getMetadata("design:paramtypes", target) || [];
422
- const injectParams = Reflect.getMetadata(INJECT_METADATA_KEY, target) || [];
423
- const params = paramTypes.map((paramType, index) => {
424
- const overrideToken = injectParams[index];
425
- const actualToken = overrideToken !== void 0 ? overrideToken : paramType;
426
- return this.resolve(actualToken);
427
- });
428
- return new target(...params);
59
+ };
60
+ __name(_ForwardReference, "ForwardReference");
61
+ ForwardReference = _ForwardReference;
62
+ __name(forwardRef, "forwardRef");
429
63
  }
430
- };
431
- __name(_AppInjector, "AppInjector");
432
- var AppInjector = _AppInjector;
433
- function inject(t) {
434
- return RootInjector.resolve(t);
435
- }
436
- __name(inject, "inject");
437
- var RootInjector = new AppInjector("root");
438
-
439
- // src/router.ts
440
- var import_reflect_metadata4 = require("reflect-metadata");
441
-
442
- // src/decorators/guards.decorator.ts
443
- function Authorize(...guardClasses) {
444
- return (target, propertyKey) => {
445
- let key;
446
- if (propertyKey) {
447
- const ctrlName = target.constructor.name;
448
- const actionName = propertyKey;
449
- key = `${ctrlName}.${actionName}`;
450
- } else {
451
- const ctrlName = target.name;
452
- key = `${ctrlName}`;
453
- }
454
- if (authorizations.has(key)) {
455
- throw new Error(`Guard(s) already registered for ${key}`);
456
- }
457
- authorizations.set(key, guardClasses);
458
- };
459
- }
460
- __name(Authorize, "Authorize");
461
- function getGuardForController(controllerName) {
462
- const key = `${controllerName}`;
463
- return authorizations.get(key) ?? [];
464
- }
465
- __name(getGuardForController, "getGuardForController");
466
- function getGuardForControllerAction(controllerName, actionName) {
467
- const key = `${controllerName}.${actionName}`;
468
- return authorizations.get(key) ?? [];
469
- }
470
- __name(getGuardForControllerAction, "getGuardForControllerAction");
471
- var authorizations = /* @__PURE__ */ new Map();
64
+ });
472
65
 
473
- // src/decorators/injectable.metadata.ts
474
- var INJECTABLE_METADATA_KEY = Symbol("INJECTABLE_METADATA_KEY");
475
- function defineInjectableMetadata(target, lifetime) {
476
- Reflect.defineMetadata(INJECTABLE_METADATA_KEY, lifetime, target);
66
+ // src/DI/token.ts
67
+ function token(target) {
68
+ return new Token(target);
477
69
  }
478
- __name(defineInjectableMetadata, "defineInjectableMetadata");
479
- function getInjectableMetadata(target) {
480
- return Reflect.getMetadata(INJECTABLE_METADATA_KEY, target);
481
- }
482
- __name(getInjectableMetadata, "getInjectableMetadata");
483
- function hasInjectableMetadata(target) {
484
- return Reflect.hasMetadata(INJECTABLE_METADATA_KEY, target);
485
- }
486
- __name(hasInjectableMetadata, "hasInjectableMetadata");
487
-
488
- // src/decorators/method.decorator.ts
489
- function createRouteDecorator(verb) {
490
- return (path2) => {
491
- return (target, propertyKey) => {
492
- const existingRoutes = Reflect.getMetadata(ROUTE_METADATA_KEY, target.constructor) || [];
493
- const metadata = {
494
- method: verb,
495
- path: path2.trim().replace(/^\/|\/$/g, ""),
496
- handler: propertyKey,
497
- guards: getGuardForControllerAction(target.constructor.__controllerName, propertyKey)
498
- };
499
- existingRoutes.push(metadata);
500
- Reflect.defineMetadata(ROUTE_METADATA_KEY, existingRoutes, target.constructor);
70
+ var _Token, Token;
71
+ var init_token = __esm({
72
+ "src/DI/token.ts"() {
73
+ "use strict";
74
+ _Token = class _Token {
75
+ constructor(target) {
76
+ this.target = target;
77
+ this.description = typeof target === "string" ? target : target.name;
78
+ }
79
+ toString() {
80
+ return `Token(${this.description})`;
81
+ }
501
82
  };
502
- };
83
+ __name(_Token, "Token");
84
+ Token = _Token;
85
+ __name(token, "token");
86
+ }
87
+ });
88
+
89
+ // src/DI/app-injector.ts
90
+ function keyOf(k) {
91
+ return k;
503
92
  }
504
- __name(createRouteDecorator, "createRouteDecorator");
505
- function getRouteMetadata(target) {
506
- return Reflect.getMetadata(ROUTE_METADATA_KEY, target) || [];
93
+ function inject(t) {
94
+ return RootInjector.resolve(t);
507
95
  }
508
- __name(getRouteMetadata, "getRouteMetadata");
509
- var Get = createRouteDecorator("GET");
510
- var Post = createRouteDecorator("POST");
511
- var Put = createRouteDecorator("PUT");
512
- var Patch = createRouteDecorator("PATCH");
513
- var Delete = createRouteDecorator("DELETE");
514
- var ROUTE_METADATA_KEY = Symbol("ROUTE_METADATA_KEY");
515
-
516
- // src/decorators/module.decorator.ts
517
- function Module(metadata) {
518
- return (target) => {
519
- const checkModule = /* @__PURE__ */ __name((arr, arrName) => {
520
- if (!arr) return;
521
- for (const clazz of arr) {
522
- if (!Reflect.getMetadata(MODULE_METADATA_KEY, clazz)) {
523
- throw new Error(`Class ${clazz.name} in ${arrName} must be decorated with @Module`);
524
- }
96
+ var _AppInjector, AppInjector, RootInjector;
97
+ var init_app_injector = __esm({
98
+ "src/DI/app-injector.ts"() {
99
+ "use strict";
100
+ init_forward_ref();
101
+ init_token();
102
+ __name(keyOf, "keyOf");
103
+ _AppInjector = class _AppInjector {
104
+ constructor(name = null) {
105
+ this.name = name;
106
+ this.bindings = /* @__PURE__ */ new Map();
107
+ this.singletons = /* @__PURE__ */ new Map();
108
+ this.scoped = /* @__PURE__ */ new Map();
525
109
  }
526
- }, "checkModule");
527
- const checkInjectable = /* @__PURE__ */ __name((arr) => {
528
- if (!arr) return;
529
- for (const clazz of arr) {
530
- if (!Reflect.getMetadata(INJECTABLE_METADATA_KEY, clazz)) {
531
- throw new Error(`Class ${clazz.name} in providers must be decorated with @Injectable`);
110
+ /**
111
+ * Creates a child scope for per-request lifetime resolution.
112
+ */
113
+ createScope() {
114
+ const scope = new _AppInjector();
115
+ scope.bindings = this.bindings;
116
+ scope.singletons = this.singletons;
117
+ return scope;
118
+ }
119
+ /**
120
+ * Registers a binding explicitly.
121
+ */
122
+ register(key, implementation, lifetime, deps = []) {
123
+ const k = keyOf(key);
124
+ if (!this.bindings.has(k)) {
125
+ this.bindings.set(k, { lifetime, implementation, deps });
532
126
  }
533
127
  }
534
- }, "checkInjectable");
535
- const checkController = /* @__PURE__ */ __name((arr) => {
536
- if (!arr) return;
537
- for (const clazz of arr) {
538
- if (!Reflect.getMetadata(CONTROLLER_METADATA_KEY, clazz)) {
539
- throw new Error(`Class ${clazz.name} in controllers must be decorated with @Controller`);
128
+ /**
129
+ * Resolves a dependency by token or class reference.
130
+ */
131
+ resolve(target) {
132
+ if (target instanceof ForwardReference) {
133
+ return this._resolveForwardRef(target);
134
+ }
135
+ const k = keyOf(target);
136
+ const binding = this.bindings.get(k);
137
+ if (!binding) {
138
+ const name = target instanceof Token ? target.description : target.name ?? "unknown";
139
+ throw new Error(
140
+ `[Noxus DI] No binding found for "${name}".
141
+ Did you forget to declare it in @Injectable({ deps }) or in bootstrapApplication({ singletons })?`
142
+ );
143
+ }
144
+ switch (binding.lifetime) {
145
+ case "transient":
146
+ return this._instantiate(binding);
147
+ case "scope": {
148
+ if (this.scoped.has(k)) return this.scoped.get(k);
149
+ const inst = this._instantiate(binding);
150
+ this.scoped.set(k, inst);
151
+ return inst;
152
+ }
153
+ case "singleton": {
154
+ if (this.singletons.has(k)) return this.singletons.get(k);
155
+ const inst = this._instantiate(binding);
156
+ this.singletons.set(k, inst);
157
+ if (binding.instance === void 0) {
158
+ binding.instance = inst;
159
+ }
160
+ return inst;
161
+ }
540
162
  }
541
163
  }
542
- }, "checkController");
543
- checkModule(metadata.imports, "imports");
544
- checkModule(metadata.exports, "exports");
545
- checkInjectable(metadata.providers);
546
- checkController(metadata.controllers);
547
- Reflect.defineMetadata(MODULE_METADATA_KEY, metadata, target);
548
- Injectable("singleton")(target);
549
- };
550
- }
551
- __name(Module, "Module");
552
- function getModuleMetadata(target) {
553
- return Reflect.getMetadata(MODULE_METADATA_KEY, target);
554
- }
555
- __name(getModuleMetadata, "getModuleMetadata");
556
- var MODULE_METADATA_KEY = Symbol("MODULE_METADATA_KEY");
164
+ // -------------------------------------------------------------------------
165
+ _resolveForwardRef(ref) {
166
+ return new Proxy({}, {
167
+ get: /* @__PURE__ */ __name((_obj, prop, receiver) => {
168
+ const realType = ref.forwardRefFn();
169
+ const instance = this.resolve(realType);
170
+ const value = Reflect.get(instance, prop, receiver);
171
+ return typeof value === "function" ? value.bind(instance) : value;
172
+ }, "get"),
173
+ set: /* @__PURE__ */ __name((_obj, prop, value, receiver) => {
174
+ const realType = ref.forwardRefFn();
175
+ const instance = this.resolve(realType);
176
+ return Reflect.set(instance, prop, value, receiver);
177
+ }, "set"),
178
+ getPrototypeOf: /* @__PURE__ */ __name(() => {
179
+ const realType = ref.forwardRefFn();
180
+ return realType.prototype;
181
+ }, "getPrototypeOf")
182
+ });
183
+ }
184
+ _instantiate(binding) {
185
+ const resolvedDeps = binding.deps.map((dep) => this.resolve(dep));
186
+ return new binding.implementation(...resolvedDeps);
187
+ }
188
+ };
189
+ __name(_AppInjector, "AppInjector");
190
+ AppInjector = _AppInjector;
191
+ RootInjector = new AppInjector("root");
192
+ __name(inject, "inject");
193
+ }
194
+ });
557
195
 
558
196
  // src/utils/logger.ts
559
- var fs = __toESM(require("fs"));
560
- var path = __toESM(require("path"));
561
197
  function getPrettyTimestamp() {
562
198
  const now = /* @__PURE__ */ new Date();
563
199
  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")}`;
564
200
  }
565
- __name(getPrettyTimestamp, "getPrettyTimestamp");
566
201
  function getLogPrefix(callee, messageType, color) {
567
202
  const timestamp = getPrettyTimestamp();
568
203
  const spaces = " ".repeat(10 - messageType.length);
@@ -575,7 +210,6 @@ function getLogPrefix(callee, messageType, color) {
575
210
  }
576
211
  return `${color}[APP] ${process.pid} - ${colReset}${timestamp}${spaces}${color}${messageType.toUpperCase()}${colReset} ${colCallee}[${callee}]${colReset}`;
577
212
  }
578
- __name(getLogPrefix, "getLogPrefix");
579
213
  function formatObject(prefix, arg, enableColor = true) {
580
214
  const json = JSON.stringify(arg, null, 2);
581
215
  let colStart = "";
@@ -589,7 +223,6 @@ function formatObject(prefix, arg, enableColor = true) {
589
223
  const prefixedJson = json.split("\n").map((line, idx) => idx === 0 ? `${colStart}${line}` : `${prefix} ${colLine}${line}`).join("\n") + colReset;
590
224
  return prefixedJson;
591
225
  }
592
- __name(formatObject, "formatObject");
593
226
  function formattedArgs(prefix, args, color) {
594
227
  let colReset = Logger.colors.initial;
595
228
  if (color === void 0) {
@@ -605,17 +238,14 @@ function formattedArgs(prefix, args, color) {
605
238
  return arg;
606
239
  });
607
240
  }
608
- __name(formattedArgs, "formattedArgs");
609
241
  function getCallee() {
610
242
  const stack = new Error().stack?.split("\n") ?? [];
611
243
  const caller = stack[3]?.trim().match(/at (.+?)(?:\..+)? .+$/)?.[1]?.replace("Object", "").replace(/^_/, "") || "App";
612
244
  return caller;
613
245
  }
614
- __name(getCallee, "getCallee");
615
246
  function canLog(level) {
616
247
  return logLevels.has(level);
617
248
  }
618
- __name(canLog, "canLog");
619
249
  function processLogQueue(filepath) {
620
250
  const state = fileStates.get(filepath);
621
251
  if (!state || state.isWriting || state.queue.length === 0) {
@@ -625,17 +255,13 @@ function processLogQueue(filepath) {
625
255
  const messagesToWrite = state.queue.join("\n") + "\n";
626
256
  state.queue = [];
627
257
  const dir = path.dirname(filepath);
628
- fs.mkdir(dir, {
629
- recursive: true
630
- }, (err) => {
258
+ fs.mkdir(dir, { recursive: true }, (err) => {
631
259
  if (err) {
632
260
  console.error(`[Logger] Failed to create directory ${dir}`, err);
633
261
  state.isWriting = false;
634
262
  return;
635
263
  }
636
- fs.appendFile(filepath, messagesToWrite, {
637
- encoding: "utf-8"
638
- }, (err2) => {
264
+ fs.appendFile(filepath, messagesToWrite, { encoding: "utf-8" }, (err2) => {
639
265
  state.isWriting = false;
640
266
  if (err2) {
641
267
  console.error(`[Logger] Failed to write log to ${filepath}`, err2);
@@ -646,19 +272,14 @@ function processLogQueue(filepath) {
646
272
  });
647
273
  });
648
274
  }
649
- __name(processLogQueue, "processLogQueue");
650
275
  function enqueue(filepath, message) {
651
276
  if (!fileStates.has(filepath)) {
652
- fileStates.set(filepath, {
653
- queue: [],
654
- isWriting: false
655
- });
277
+ fileStates.set(filepath, { queue: [], isWriting: false });
656
278
  }
657
279
  const state = fileStates.get(filepath);
658
280
  state.queue.push(message);
659
281
  processLogQueue(filepath);
660
282
  }
661
- __name(enqueue, "enqueue");
662
283
  function output(level, args) {
663
284
  if (!canLog(level)) {
664
285
  return;
@@ -679,323 +300,550 @@ function output(level, args) {
679
300
  }
680
301
  }
681
302
  }
682
- __name(output, "output");
683
- (function(Logger2) {
684
- function setLogLevel(level) {
685
- logLevels.clear();
686
- if (Array.isArray(level)) {
687
- for (const lvl of level) {
688
- logLevels.add(lvl);
689
- }
690
- } else {
691
- const targetRank = logLevelRank[level];
692
- for (const [lvl, rank] of Object.entries(logLevelRank)) {
693
- if (rank >= targetRank) {
694
- logLevels.add(lvl);
303
+ var fs, path, Logger, fileSettings, fileStates, logLevels, logLevelRank, logLevelColors, logLevelChannel;
304
+ var init_logger = __esm({
305
+ "src/utils/logger.ts"() {
306
+ "use strict";
307
+ fs = __toESM(require("fs"));
308
+ path = __toESM(require("path"));
309
+ __name(getPrettyTimestamp, "getPrettyTimestamp");
310
+ __name(getLogPrefix, "getLogPrefix");
311
+ __name(formatObject, "formatObject");
312
+ __name(formattedArgs, "formattedArgs");
313
+ __name(getCallee, "getCallee");
314
+ __name(canLog, "canLog");
315
+ __name(processLogQueue, "processLogQueue");
316
+ __name(enqueue, "enqueue");
317
+ __name(output, "output");
318
+ ((Logger2) => {
319
+ function setLogLevel(level) {
320
+ logLevels.clear();
321
+ if (Array.isArray(level)) {
322
+ for (const lvl of level) {
323
+ logLevels.add(lvl);
324
+ }
325
+ } else {
326
+ const targetRank = logLevelRank[level];
327
+ for (const [lvl, rank] of Object.entries(logLevelRank)) {
328
+ if (rank >= targetRank) {
329
+ logLevels.add(lvl);
330
+ }
331
+ }
695
332
  }
696
333
  }
697
- }
698
- }
699
- __name(setLogLevel, "setLogLevel");
700
- Logger2.setLogLevel = setLogLevel;
701
- function log(...args) {
702
- output("log", args);
703
- }
704
- __name(log, "log");
705
- Logger2.log = log;
706
- function info(...args) {
707
- output("info", args);
708
- }
709
- __name(info, "info");
710
- Logger2.info = info;
711
- function warn(...args) {
712
- output("warn", args);
713
- }
714
- __name(warn, "warn");
715
- Logger2.warn = warn;
716
- function error(...args) {
717
- output("error", args);
718
- }
719
- __name(error, "error");
720
- Logger2.error = error;
721
- function errorStack(...args) {
722
- output("error", args);
723
- }
724
- __name(errorStack, "errorStack");
725
- Logger2.errorStack = errorStack;
726
- function debug(...args) {
727
- output("debug", args);
728
- }
729
- __name(debug, "debug");
730
- Logger2.debug = debug;
731
- function comment(...args) {
732
- output("comment", args);
733
- }
734
- __name(comment, "comment");
735
- Logger2.comment = comment;
736
- function critical(...args) {
737
- output("critical", args);
738
- }
739
- __name(critical, "critical");
740
- Logger2.critical = critical;
741
- function enableFileLogging(filepath, levels = [
742
- "debug",
743
- "comment",
744
- "log",
745
- "info",
746
- "warn",
747
- "error",
748
- "critical"
749
- ]) {
750
- for (const level of levels) {
751
- fileSettings.set(level, {
752
- filepath
753
- });
754
- }
755
- }
756
- __name(enableFileLogging, "enableFileLogging");
757
- Logger2.enableFileLogging = enableFileLogging;
758
- function disableFileLogging(levels = [
759
- "debug",
760
- "comment",
761
- "log",
762
- "info",
763
- "warn",
764
- "error",
765
- "critical"
766
- ]) {
767
- for (const level of levels) {
768
- fileSettings.delete(level);
769
- }
334
+ Logger2.setLogLevel = setLogLevel;
335
+ __name(setLogLevel, "setLogLevel");
336
+ function log(...args) {
337
+ output("log", args);
338
+ }
339
+ Logger2.log = log;
340
+ __name(log, "log");
341
+ function info(...args) {
342
+ output("info", args);
343
+ }
344
+ Logger2.info = info;
345
+ __name(info, "info");
346
+ function warn(...args) {
347
+ output("warn", args);
348
+ }
349
+ Logger2.warn = warn;
350
+ __name(warn, "warn");
351
+ function error(...args) {
352
+ output("error", args);
353
+ }
354
+ Logger2.error = error;
355
+ __name(error, "error");
356
+ function errorStack(...args) {
357
+ output("error", args);
358
+ }
359
+ Logger2.errorStack = errorStack;
360
+ __name(errorStack, "errorStack");
361
+ function debug(...args) {
362
+ output("debug", args);
363
+ }
364
+ Logger2.debug = debug;
365
+ __name(debug, "debug");
366
+ function comment(...args) {
367
+ output("comment", args);
368
+ }
369
+ Logger2.comment = comment;
370
+ __name(comment, "comment");
371
+ function critical(...args) {
372
+ output("critical", args);
373
+ }
374
+ Logger2.critical = critical;
375
+ __name(critical, "critical");
376
+ function enableFileLogging(filepath, levels = ["debug", "comment", "log", "info", "warn", "error", "critical"]) {
377
+ for (const level of levels) {
378
+ fileSettings.set(level, { filepath });
379
+ }
380
+ }
381
+ Logger2.enableFileLogging = enableFileLogging;
382
+ __name(enableFileLogging, "enableFileLogging");
383
+ function disableFileLogging(levels = ["debug", "comment", "log", "info", "warn", "error", "critical"]) {
384
+ for (const level of levels) {
385
+ fileSettings.delete(level);
386
+ }
387
+ }
388
+ Logger2.disableFileLogging = disableFileLogging;
389
+ __name(disableFileLogging, "disableFileLogging");
390
+ Logger2.colors = {
391
+ black: "\x1B[0;30m",
392
+ grey: "\x1B[0;37m",
393
+ red: "\x1B[0;31m",
394
+ green: "\x1B[0;32m",
395
+ brown: "\x1B[0;33m",
396
+ blue: "\x1B[0;34m",
397
+ purple: "\x1B[0;35m",
398
+ darkGrey: "\x1B[1;30m",
399
+ lightRed: "\x1B[1;31m",
400
+ lightGreen: "\x1B[1;32m",
401
+ yellow: "\x1B[1;33m",
402
+ lightBlue: "\x1B[1;34m",
403
+ magenta: "\x1B[1;35m",
404
+ cyan: "\x1B[1;36m",
405
+ white: "\x1B[1;37m",
406
+ initial: "\x1B[0m"
407
+ };
408
+ })(Logger || (Logger = {}));
409
+ fileSettings = /* @__PURE__ */ new Map();
410
+ fileStates = /* @__PURE__ */ new Map();
411
+ logLevels = /* @__PURE__ */ new Set();
412
+ logLevelRank = {
413
+ debug: 0,
414
+ comment: 1,
415
+ log: 2,
416
+ info: 3,
417
+ warn: 4,
418
+ error: 5,
419
+ critical: 6
420
+ };
421
+ logLevelColors = {
422
+ debug: Logger.colors.purple,
423
+ comment: Logger.colors.grey,
424
+ log: Logger.colors.green,
425
+ info: Logger.colors.blue,
426
+ warn: Logger.colors.brown,
427
+ error: Logger.colors.red,
428
+ critical: Logger.colors.lightRed
429
+ };
430
+ logLevelChannel = {
431
+ debug: console.debug,
432
+ comment: console.debug,
433
+ log: console.log,
434
+ info: console.info,
435
+ warn: console.warn,
436
+ error: console.error,
437
+ critical: console.error
438
+ };
439
+ Logger.setLogLevel("debug");
770
440
  }
771
- __name(disableFileLogging, "disableFileLogging");
772
- Logger2.disableFileLogging = disableFileLogging;
773
- Logger2.colors = {
774
- black: "\x1B[0;30m",
775
- grey: "\x1B[0;37m",
776
- red: "\x1B[0;31m",
777
- green: "\x1B[0;32m",
778
- brown: "\x1B[0;33m",
779
- blue: "\x1B[0;34m",
780
- purple: "\x1B[0;35m",
781
- darkGrey: "\x1B[1;30m",
782
- lightRed: "\x1B[1;31m",
783
- lightGreen: "\x1B[1;32m",
784
- yellow: "\x1B[1;33m",
785
- lightBlue: "\x1B[1;34m",
786
- magenta: "\x1B[1;35m",
787
- cyan: "\x1B[1;36m",
788
- white: "\x1B[1;37m",
789
- initial: "\x1B[0m"
790
- };
791
- })(Logger || (Logger = {}));
792
- var fileSettings = /* @__PURE__ */ new Map();
793
- var fileStates = /* @__PURE__ */ new Map();
794
- var logLevels = /* @__PURE__ */ new Set();
795
- var logLevelRank = {
796
- debug: 0,
797
- comment: 1,
798
- log: 2,
799
- info: 3,
800
- warn: 4,
801
- error: 5,
802
- critical: 6
803
- };
804
- var logLevelColors = {
805
- debug: Logger.colors.purple,
806
- comment: Logger.colors.grey,
807
- log: Logger.colors.green,
808
- info: Logger.colors.blue,
809
- warn: Logger.colors.brown,
810
- error: Logger.colors.red,
811
- critical: Logger.colors.lightRed
812
- };
813
- var logLevelChannel = {
814
- debug: console.debug,
815
- comment: console.debug,
816
- log: console.log,
817
- info: console.info,
818
- warn: console.warn,
819
- error: console.error,
820
- critical: console.error
821
- };
822
- Logger.setLogLevel("debug");
823
- var Logger;
441
+ });
824
442
 
825
443
  // src/DI/injector-explorer.ts
826
- var _InjectorExplorer = class _InjectorExplorer {
827
- /**
828
- * Enqueues a class for deferred registration.
829
- * Called by the @Injectable decorator at import time.
830
- *
831
- * If {@link processPending} has already been called (i.e. after bootstrap),
832
- * the class is registered immediately so that late dynamic imports
833
- * (e.g. middlewares loaded after bootstrap) work correctly.
834
- */
835
- static enqueue(target, lifetime) {
836
- if (_InjectorExplorer.processed) {
837
- _InjectorExplorer.registerImmediate(target, lifetime);
838
- return;
839
- }
840
- _InjectorExplorer.pending.push({
841
- target,
842
- lifetime
843
- });
844
- }
845
- /**
846
- * Processes all pending registrations in two phases:
847
- * 1. Register all bindings (no instantiation) so every dependency is known.
848
- * 2. Resolve singletons, register controllers and log module readiness.
849
- *
850
- * This two-phase approach makes the system resilient to import ordering:
851
- * all bindings exist before any singleton is instantiated.
852
- */
853
- static processPending() {
854
- const queue = _InjectorExplorer.pending;
855
- for (const { target, lifetime } of queue) {
856
- if (!RootInjector.bindings.has(target)) {
857
- RootInjector.bindings.set(target, {
858
- implementation: target,
859
- lifetime
860
- });
444
+ var _InjectorExplorer, InjectorExplorer;
445
+ var init_injector_explorer = __esm({
446
+ "src/DI/injector-explorer.ts"() {
447
+ "use strict";
448
+ init_app_injector();
449
+ init_logger();
450
+ _InjectorExplorer = class _InjectorExplorer {
451
+ // -------------------------------------------------------------------------
452
+ // Public API
453
+ // -------------------------------------------------------------------------
454
+ static enqueue(reg) {
455
+ if (_InjectorExplorer.processed && !_InjectorExplorer.accumulating) {
456
+ _InjectorExplorer._registerImmediate(reg);
457
+ return;
458
+ }
459
+ _InjectorExplorer.pending.push(reg);
861
460
  }
862
- }
863
- for (const { target, lifetime } of queue) {
864
- _InjectorExplorer.processRegistration(target, lifetime);
865
- }
866
- queue.length = 0;
867
- _InjectorExplorer.processed = true;
461
+ /**
462
+ * Two-phase flush of all pending registrations collected at startup.
463
+ * Called by bootstrapApplication after app.whenReady().
464
+ */
465
+ static processPending(singletonOverrides) {
466
+ const queue = [..._InjectorExplorer.pending];
467
+ _InjectorExplorer.pending.length = 0;
468
+ _InjectorExplorer._phaseOne(queue);
469
+ _InjectorExplorer._phaseTwo(queue, singletonOverrides);
470
+ _InjectorExplorer.processed = true;
471
+ }
472
+ /** Enters accumulation mode for lazy-loaded batches. */
473
+ static beginAccumulate() {
474
+ _InjectorExplorer.accumulating = true;
475
+ }
476
+ /**
477
+ * Exits accumulation mode and flushes queued registrations
478
+ * with the same two-phase guarantee as processPending.
479
+ */
480
+ static flushAccumulated(routeGuards = [], routeMiddlewares = [], pathPrefix = "") {
481
+ _InjectorExplorer.accumulating = false;
482
+ const queue = [..._InjectorExplorer.pending];
483
+ _InjectorExplorer.pending.length = 0;
484
+ _InjectorExplorer._phaseOne(queue);
485
+ for (const reg of queue) {
486
+ if (reg.isController) reg.pathPrefix = pathPrefix;
487
+ }
488
+ _InjectorExplorer._phaseTwo(queue, void 0, routeGuards, routeMiddlewares);
489
+ }
490
+ // -------------------------------------------------------------------------
491
+ // Private helpers
492
+ // -------------------------------------------------------------------------
493
+ /** Phase 1: register all bindings without instantiating anything. */
494
+ static _phaseOne(queue) {
495
+ for (const reg of queue) {
496
+ RootInjector.register(reg.key, reg.implementation, reg.lifetime, reg.deps);
497
+ }
498
+ }
499
+ /** Phase 2: resolve singletons and register controllers in the router. */
500
+ static _phaseTwo(queue, overrides, routeGuards = [], routeMiddlewares = []) {
501
+ for (const reg of queue) {
502
+ if (overrides?.has(reg.key)) {
503
+ const override = overrides.get(reg.key);
504
+ RootInjector.singletons.set(reg.key, override);
505
+ Logger.log(`Registered ${reg.implementation.name} as singleton (overridden)`);
506
+ continue;
507
+ }
508
+ if (reg.lifetime === "singleton") {
509
+ RootInjector.resolve(reg.key);
510
+ }
511
+ if (reg.isController) {
512
+ const { Router: Router2 } = (init_router(), __toCommonJS(router_exports));
513
+ const router = RootInjector.resolve(Router2);
514
+ router.registerController(reg.implementation, reg.pathPrefix ?? "", routeGuards, routeMiddlewares);
515
+ } else if (reg.lifetime !== "singleton") {
516
+ Logger.log(`Registered ${reg.implementation.name} as ${reg.lifetime}`);
517
+ }
518
+ }
519
+ }
520
+ static _registerImmediate(reg) {
521
+ RootInjector.register(reg.key, reg.implementation, reg.lifetime, reg.deps);
522
+ if (reg.lifetime === "singleton") {
523
+ RootInjector.resolve(reg.key);
524
+ }
525
+ if (reg.isController) {
526
+ const { Router: Router2 } = (init_router(), __toCommonJS(router_exports));
527
+ const router = RootInjector.resolve(Router2);
528
+ router.registerController(reg.implementation);
529
+ }
530
+ }
531
+ };
532
+ __name(_InjectorExplorer, "InjectorExplorer");
533
+ _InjectorExplorer.pending = [];
534
+ _InjectorExplorer.processed = false;
535
+ _InjectorExplorer.accumulating = false;
536
+ InjectorExplorer = _InjectorExplorer;
868
537
  }
869
- /**
870
- * Registers a single class immediately (post-bootstrap path).
871
- * Used for classes discovered via late dynamic imports.
872
- */
873
- static registerImmediate(target, lifetime) {
874
- if (RootInjector.bindings.has(target)) {
875
- return;
876
- }
877
- RootInjector.bindings.set(target, {
538
+ });
539
+
540
+ // src/decorators/controller.decorator.ts
541
+ function Controller(options = {}) {
542
+ return (target) => {
543
+ const meta = {
544
+ deps: options.deps ?? []
545
+ };
546
+ controllerMetaMap.set(target, meta);
547
+ InjectorExplorer.enqueue({
548
+ key: target,
878
549
  implementation: target,
879
- lifetime
550
+ lifetime: "scope",
551
+ deps: options.deps ?? [],
552
+ isController: true
880
553
  });
881
- _InjectorExplorer.processRegistration(target, lifetime);
882
- }
883
- /**
884
- * Performs phase-2 work for a single registration: resolve singletons,
885
- * register controllers, and log module readiness.
886
- */
887
- static processRegistration(target, lifetime) {
888
- if (lifetime === "singleton") {
889
- RootInjector.resolve(target);
890
- }
891
- if (getModuleMetadata(target)) {
892
- Logger.log(`${target.name} dependencies initialized`);
893
- return;
894
- }
895
- const controllerMeta = getControllerMetadata(target);
896
- if (controllerMeta) {
897
- const router = RootInjector.resolve(Router);
898
- router?.registerController(target);
899
- return;
900
- }
901
- if (getRouteMetadata(target).length > 0) {
902
- return;
903
- }
904
- if (getInjectableMetadata(target)) {
905
- Logger.log(`Registered ${target.name} as ${lifetime}`);
906
- }
554
+ };
555
+ }
556
+ function getControllerMetadata(target) {
557
+ return controllerMetaMap.get(target);
558
+ }
559
+ var controllerMetaMap;
560
+ var init_controller_decorator = __esm({
561
+ "src/decorators/controller.decorator.ts"() {
562
+ "use strict";
563
+ init_injector_explorer();
564
+ controllerMetaMap = /* @__PURE__ */ new WeakMap();
565
+ __name(Controller, "Controller");
566
+ __name(getControllerMetadata, "getControllerMetadata");
907
567
  }
908
- };
909
- __name(_InjectorExplorer, "InjectorExplorer");
910
- __publicField(_InjectorExplorer, "pending", []);
911
- __publicField(_InjectorExplorer, "processed", false);
912
- var InjectorExplorer = _InjectorExplorer;
568
+ });
913
569
 
914
570
  // src/decorators/injectable.decorator.ts
915
- function Injectable(lifetime = "scope") {
571
+ function Injectable(options = {}) {
572
+ const { lifetime = "scope", deps = [] } = options;
916
573
  return (target) => {
917
574
  if (typeof target !== "function" || !target.prototype) {
918
- throw new Error(`@Injectable can only be used on classes, not on ${typeof target}`);
919
- }
920
- defineInjectableMetadata(target, lifetime);
921
- InjectorExplorer.enqueue(target, lifetime);
575
+ throw new Error(`@Injectable can only be applied to classes, not ${typeof target}`);
576
+ }
577
+ const key = target;
578
+ InjectorExplorer.enqueue({
579
+ key,
580
+ implementation: key,
581
+ lifetime,
582
+ deps,
583
+ isController: false
584
+ });
922
585
  };
923
586
  }
924
- __name(Injectable, "Injectable");
587
+ var init_injectable_decorator = __esm({
588
+ "src/decorators/injectable.decorator.ts"() {
589
+ "use strict";
590
+ init_injector_explorer();
591
+ init_token();
592
+ __name(Injectable, "Injectable");
593
+ }
594
+ });
925
595
 
926
- // src/decorators/controller.decorator.ts
927
- function Controller(path2) {
928
- return (target) => {
929
- const data = {
930
- path: path2,
931
- guards: getGuardForController(target.name)
596
+ // src/decorators/method.decorator.ts
597
+ function isAtomicHttpMethod(m) {
598
+ return typeof m === "string" && ATOMIC_METHODS.has(m);
599
+ }
600
+ function createRouteDecorator(verb) {
601
+ return (path2, options = {}) => {
602
+ return (target, propertyKey) => {
603
+ const ctor = target.constructor;
604
+ const existing = routeMetaMap.get(ctor) ?? [];
605
+ existing.push({
606
+ method: verb,
607
+ path: (path2 ?? "").trim().replace(/^\/|\/$/g, ""),
608
+ handler: propertyKey,
609
+ guards: options.guards ?? [],
610
+ middlewares: options.middlewares ?? []
611
+ });
612
+ routeMetaMap.set(ctor, existing);
932
613
  };
933
- Reflect.defineMetadata(CONTROLLER_METADATA_KEY, data, target);
934
- Injectable("scope")(target);
935
614
  };
936
615
  }
937
- __name(Controller, "Controller");
938
- function getControllerMetadata(target) {
939
- return Reflect.getMetadata(CONTROLLER_METADATA_KEY, target);
616
+ function getRouteMetadata(target) {
617
+ return routeMetaMap.get(target) ?? [];
940
618
  }
941
- __name(getControllerMetadata, "getControllerMetadata");
942
- var CONTROLLER_METADATA_KEY = Symbol("CONTROLLER_METADATA_KEY");
619
+ var ATOMIC_METHODS, routeMetaMap, Get, Post, Put, Patch, Delete;
620
+ var init_method_decorator = __esm({
621
+ "src/decorators/method.decorator.ts"() {
622
+ "use strict";
623
+ ATOMIC_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
624
+ __name(isAtomicHttpMethod, "isAtomicHttpMethod");
625
+ routeMetaMap = /* @__PURE__ */ new WeakMap();
626
+ __name(createRouteDecorator, "createRouteDecorator");
627
+ __name(getRouteMetadata, "getRouteMetadata");
628
+ Get = createRouteDecorator("GET");
629
+ Post = createRouteDecorator("POST");
630
+ Put = createRouteDecorator("PUT");
631
+ Patch = createRouteDecorator("PATCH");
632
+ Delete = createRouteDecorator("DELETE");
633
+ }
634
+ });
943
635
 
944
- // src/decorators/middleware.decorator.ts
945
- function UseMiddlewares(mdlw) {
946
- return (target, propertyKey) => {
947
- let key;
948
- if (propertyKey) {
949
- const ctrlName = target.constructor.name;
950
- const actionName = propertyKey;
951
- key = `${ctrlName}.${actionName}`;
952
- } else {
953
- const ctrlName = target.name;
954
- key = `${ctrlName}`;
955
- }
956
- if (middlewares.has(key)) {
957
- throw new Error(`Middlewares(s) already registered for ${key}`);
958
- }
959
- middlewares.set(key, mdlw);
960
- };
961
- }
962
- __name(UseMiddlewares, "UseMiddlewares");
963
- function getMiddlewaresForController(controllerName) {
964
- const key = `${controllerName}`;
965
- return middlewares.get(key) ?? [];
966
- }
967
- __name(getMiddlewaresForController, "getMiddlewaresForController");
968
- function getMiddlewaresForControllerAction(controllerName, actionName) {
969
- const key = `${controllerName}.${actionName}`;
970
- return middlewares.get(key) ?? [];
971
- }
972
- __name(getMiddlewaresForControllerAction, "getMiddlewaresForControllerAction");
973
- var middlewares = /* @__PURE__ */ new Map();
636
+ // src/exceptions.ts
637
+ var _ResponseException, ResponseException, _BadRequestException, BadRequestException, _UnauthorizedException, UnauthorizedException, _PaymentRequiredException, PaymentRequiredException, _ForbiddenException, ForbiddenException, _NotFoundException, NotFoundException, _MethodNotAllowedException, MethodNotAllowedException, _NotAcceptableException, NotAcceptableException, _RequestTimeoutException, RequestTimeoutException, _ConflictException, ConflictException, _UpgradeRequiredException, UpgradeRequiredException, _TooManyRequestsException, TooManyRequestsException, _InternalServerException, InternalServerException, _NotImplementedException, NotImplementedException, _BadGatewayException, BadGatewayException, _ServiceUnavailableException, ServiceUnavailableException, _GatewayTimeoutException, GatewayTimeoutException, _HttpVersionNotSupportedException, HttpVersionNotSupportedException, _VariantAlsoNegotiatesException, VariantAlsoNegotiatesException, _InsufficientStorageException, InsufficientStorageException, _LoopDetectedException, LoopDetectedException, _NotExtendedException, NotExtendedException, _NetworkAuthenticationRequiredException, NetworkAuthenticationRequiredException, _NetworkConnectTimeoutException, NetworkConnectTimeoutException;
638
+ var init_exceptions = __esm({
639
+ "src/exceptions.ts"() {
640
+ "use strict";
641
+ _ResponseException = class _ResponseException extends Error {
642
+ constructor(statusOrMessage, message) {
643
+ let statusCode;
644
+ if (typeof statusOrMessage === "number") {
645
+ statusCode = statusOrMessage;
646
+ } else if (typeof statusOrMessage === "string") {
647
+ message = statusOrMessage;
648
+ }
649
+ super(message ?? "");
650
+ this.status = 0;
651
+ if (statusCode !== void 0) {
652
+ this.status = statusCode;
653
+ }
654
+ this.name = this.constructor.name.replace(/([A-Z])/g, " $1");
655
+ }
656
+ };
657
+ __name(_ResponseException, "ResponseException");
658
+ ResponseException = _ResponseException;
659
+ _BadRequestException = class _BadRequestException extends ResponseException {
660
+ constructor() {
661
+ super(...arguments);
662
+ this.status = 400;
663
+ }
664
+ };
665
+ __name(_BadRequestException, "BadRequestException");
666
+ BadRequestException = _BadRequestException;
667
+ _UnauthorizedException = class _UnauthorizedException extends ResponseException {
668
+ constructor() {
669
+ super(...arguments);
670
+ this.status = 401;
671
+ }
672
+ };
673
+ __name(_UnauthorizedException, "UnauthorizedException");
674
+ UnauthorizedException = _UnauthorizedException;
675
+ _PaymentRequiredException = class _PaymentRequiredException extends ResponseException {
676
+ constructor() {
677
+ super(...arguments);
678
+ this.status = 402;
679
+ }
680
+ };
681
+ __name(_PaymentRequiredException, "PaymentRequiredException");
682
+ PaymentRequiredException = _PaymentRequiredException;
683
+ _ForbiddenException = class _ForbiddenException extends ResponseException {
684
+ constructor() {
685
+ super(...arguments);
686
+ this.status = 403;
687
+ }
688
+ };
689
+ __name(_ForbiddenException, "ForbiddenException");
690
+ ForbiddenException = _ForbiddenException;
691
+ _NotFoundException = class _NotFoundException extends ResponseException {
692
+ constructor() {
693
+ super(...arguments);
694
+ this.status = 404;
695
+ }
696
+ };
697
+ __name(_NotFoundException, "NotFoundException");
698
+ NotFoundException = _NotFoundException;
699
+ _MethodNotAllowedException = class _MethodNotAllowedException extends ResponseException {
700
+ constructor() {
701
+ super(...arguments);
702
+ this.status = 405;
703
+ }
704
+ };
705
+ __name(_MethodNotAllowedException, "MethodNotAllowedException");
706
+ MethodNotAllowedException = _MethodNotAllowedException;
707
+ _NotAcceptableException = class _NotAcceptableException extends ResponseException {
708
+ constructor() {
709
+ super(...arguments);
710
+ this.status = 406;
711
+ }
712
+ };
713
+ __name(_NotAcceptableException, "NotAcceptableException");
714
+ NotAcceptableException = _NotAcceptableException;
715
+ _RequestTimeoutException = class _RequestTimeoutException extends ResponseException {
716
+ constructor() {
717
+ super(...arguments);
718
+ this.status = 408;
719
+ }
720
+ };
721
+ __name(_RequestTimeoutException, "RequestTimeoutException");
722
+ RequestTimeoutException = _RequestTimeoutException;
723
+ _ConflictException = class _ConflictException extends ResponseException {
724
+ constructor() {
725
+ super(...arguments);
726
+ this.status = 409;
727
+ }
728
+ };
729
+ __name(_ConflictException, "ConflictException");
730
+ ConflictException = _ConflictException;
731
+ _UpgradeRequiredException = class _UpgradeRequiredException extends ResponseException {
732
+ constructor() {
733
+ super(...arguments);
734
+ this.status = 426;
735
+ }
736
+ };
737
+ __name(_UpgradeRequiredException, "UpgradeRequiredException");
738
+ UpgradeRequiredException = _UpgradeRequiredException;
739
+ _TooManyRequestsException = class _TooManyRequestsException extends ResponseException {
740
+ constructor() {
741
+ super(...arguments);
742
+ this.status = 429;
743
+ }
744
+ };
745
+ __name(_TooManyRequestsException, "TooManyRequestsException");
746
+ TooManyRequestsException = _TooManyRequestsException;
747
+ _InternalServerException = class _InternalServerException extends ResponseException {
748
+ constructor() {
749
+ super(...arguments);
750
+ this.status = 500;
751
+ }
752
+ };
753
+ __name(_InternalServerException, "InternalServerException");
754
+ InternalServerException = _InternalServerException;
755
+ _NotImplementedException = class _NotImplementedException extends ResponseException {
756
+ constructor() {
757
+ super(...arguments);
758
+ this.status = 501;
759
+ }
760
+ };
761
+ __name(_NotImplementedException, "NotImplementedException");
762
+ NotImplementedException = _NotImplementedException;
763
+ _BadGatewayException = class _BadGatewayException extends ResponseException {
764
+ constructor() {
765
+ super(...arguments);
766
+ this.status = 502;
767
+ }
768
+ };
769
+ __name(_BadGatewayException, "BadGatewayException");
770
+ BadGatewayException = _BadGatewayException;
771
+ _ServiceUnavailableException = class _ServiceUnavailableException extends ResponseException {
772
+ constructor() {
773
+ super(...arguments);
774
+ this.status = 503;
775
+ }
776
+ };
777
+ __name(_ServiceUnavailableException, "ServiceUnavailableException");
778
+ ServiceUnavailableException = _ServiceUnavailableException;
779
+ _GatewayTimeoutException = class _GatewayTimeoutException extends ResponseException {
780
+ constructor() {
781
+ super(...arguments);
782
+ this.status = 504;
783
+ }
784
+ };
785
+ __name(_GatewayTimeoutException, "GatewayTimeoutException");
786
+ GatewayTimeoutException = _GatewayTimeoutException;
787
+ _HttpVersionNotSupportedException = class _HttpVersionNotSupportedException extends ResponseException {
788
+ constructor() {
789
+ super(...arguments);
790
+ this.status = 505;
791
+ }
792
+ };
793
+ __name(_HttpVersionNotSupportedException, "HttpVersionNotSupportedException");
794
+ HttpVersionNotSupportedException = _HttpVersionNotSupportedException;
795
+ _VariantAlsoNegotiatesException = class _VariantAlsoNegotiatesException extends ResponseException {
796
+ constructor() {
797
+ super(...arguments);
798
+ this.status = 506;
799
+ }
800
+ };
801
+ __name(_VariantAlsoNegotiatesException, "VariantAlsoNegotiatesException");
802
+ VariantAlsoNegotiatesException = _VariantAlsoNegotiatesException;
803
+ _InsufficientStorageException = class _InsufficientStorageException extends ResponseException {
804
+ constructor() {
805
+ super(...arguments);
806
+ this.status = 507;
807
+ }
808
+ };
809
+ __name(_InsufficientStorageException, "InsufficientStorageException");
810
+ InsufficientStorageException = _InsufficientStorageException;
811
+ _LoopDetectedException = class _LoopDetectedException extends ResponseException {
812
+ constructor() {
813
+ super(...arguments);
814
+ this.status = 508;
815
+ }
816
+ };
817
+ __name(_LoopDetectedException, "LoopDetectedException");
818
+ LoopDetectedException = _LoopDetectedException;
819
+ _NotExtendedException = class _NotExtendedException extends ResponseException {
820
+ constructor() {
821
+ super(...arguments);
822
+ this.status = 510;
823
+ }
824
+ };
825
+ __name(_NotExtendedException, "NotExtendedException");
826
+ NotExtendedException = _NotExtendedException;
827
+ _NetworkAuthenticationRequiredException = class _NetworkAuthenticationRequiredException extends ResponseException {
828
+ constructor() {
829
+ super(...arguments);
830
+ this.status = 511;
831
+ }
832
+ };
833
+ __name(_NetworkAuthenticationRequiredException, "NetworkAuthenticationRequiredException");
834
+ NetworkAuthenticationRequiredException = _NetworkAuthenticationRequiredException;
835
+ _NetworkConnectTimeoutException = class _NetworkConnectTimeoutException extends ResponseException {
836
+ constructor() {
837
+ super(...arguments);
838
+ this.status = 599;
839
+ }
840
+ };
841
+ __name(_NetworkConnectTimeoutException, "NetworkConnectTimeoutException");
842
+ NetworkConnectTimeoutException = _NetworkConnectTimeoutException;
843
+ }
844
+ });
974
845
 
975
846
  // src/request.ts
976
- var import_reflect_metadata3 = require("reflect-metadata");
977
- var _Request = class _Request {
978
- constructor(event, senderId, id, method, path2, body) {
979
- __publicField(this, "event");
980
- __publicField(this, "senderId");
981
- __publicField(this, "id");
982
- __publicField(this, "method");
983
- __publicField(this, "path");
984
- __publicField(this, "body");
985
- __publicField(this, "context", RootInjector.createScope());
986
- __publicField(this, "params", {});
987
- this.event = event;
988
- this.senderId = senderId;
989
- this.id = id;
990
- this.method = method;
991
- this.path = path2;
992
- this.body = body;
993
- this.path = path2.replace(/^\/|\/$/g, "");
994
- }
995
- };
996
- __name(_Request, "Request");
997
- var Request = _Request;
998
- var RENDERER_EVENT_TYPE = "noxus:event";
999
847
  function createRendererEventMessage(event, payload) {
1000
848
  return {
1001
849
  type: RENDERER_EVENT_TYPE,
@@ -1003,7 +851,6 @@ function createRendererEventMessage(event, payload) {
1003
851
  payload
1004
852
  };
1005
853
  }
1006
- __name(createRendererEventMessage, "createRendererEventMessage");
1007
854
  function isRendererEventMessage(value) {
1008
855
  if (value === null || typeof value !== "object") {
1009
856
  return false;
@@ -1011,572 +858,528 @@ function isRendererEventMessage(value) {
1011
858
  const possibleMessage = value;
1012
859
  return possibleMessage.type === RENDERER_EVENT_TYPE && typeof possibleMessage.event === "string";
1013
860
  }
1014
- __name(isRendererEventMessage, "isRendererEventMessage");
861
+ var _Request, Request, RENDERER_EVENT_TYPE;
862
+ var init_request = __esm({
863
+ "src/request.ts"() {
864
+ "use strict";
865
+ init_app_injector();
866
+ _Request = class _Request {
867
+ constructor(event, senderId, id, method, path2, body) {
868
+ this.event = event;
869
+ this.senderId = senderId;
870
+ this.id = id;
871
+ this.method = method;
872
+ this.path = path2;
873
+ this.body = body;
874
+ this.context = RootInjector.createScope();
875
+ this.params = {};
876
+ this.path = path2.replace(/^\/|\/$/g, "");
877
+ }
878
+ };
879
+ __name(_Request, "Request");
880
+ Request = _Request;
881
+ RENDERER_EVENT_TYPE = "noxus:event";
882
+ __name(createRendererEventMessage, "createRendererEventMessage");
883
+ __name(isRendererEventMessage, "isRendererEventMessage");
884
+ }
885
+ });
1015
886
 
1016
887
  // src/utils/radix-tree.ts
1017
- var _a;
1018
- var RadixNode = (_a = class {
1019
- /**
1020
- * Creates a new RadixNode.
1021
- * @param segment - The segment of the path this node represents.
1022
- */
1023
- constructor(segment) {
1024
- __publicField(this, "segment");
1025
- __publicField(this, "children", []);
1026
- __publicField(this, "value");
1027
- __publicField(this, "isParam");
1028
- __publicField(this, "paramName");
1029
- this.segment = segment;
1030
- this.isParam = segment.startsWith(":");
1031
- if (this.isParam) {
1032
- this.paramName = segment.slice(1);
1033
- }
1034
- }
1035
- /**
1036
- * Matches a child node against a given segment.
1037
- * This method checks if the segment matches any of the children nodes.
1038
- * @param segment - The segment to match against the children of this node.
1039
- * @returns A child node that matches the segment, or undefined if no match is found.
1040
- */
1041
- matchChild(segment) {
1042
- for (const child of this.children) {
1043
- if (child.isParam || segment.startsWith(child.segment)) return child;
1044
- }
1045
- return void 0;
1046
- }
1047
- /**
1048
- * Finds a child node that matches the segment exactly.
1049
- * This method checks if there is a child node that matches the segment exactly.
1050
- * @param segment - The segment to find an exact match for among the children of this node.
1051
- * @returns A child node that matches the segment exactly, or undefined if no match is found.
1052
- */
1053
- findExactChild(segment) {
1054
- return this.children.find((c) => c.segment === segment);
1055
- }
1056
- /**
1057
- * Adds a child node to this node's children.
1058
- * This method adds a new child node to the list of children for this node.
1059
- * @param node - The child node to add to this node's children.
1060
- */
1061
- addChild(node) {
1062
- this.children.push(node);
1063
- }
1064
- }, __name(_a, "RadixNode"), _a);
1065
- var _RadixTree = class _RadixTree {
1066
- constructor() {
1067
- __publicField(this, "root", new RadixNode(""));
1068
- }
1069
- /**
1070
- * Inserts a path and its associated value into the Radix Tree.
1071
- * This method normalizes the path and inserts it into the tree, associating it with
1072
- * @param path - The path to insert into the tree.
1073
- * @param value - The value to associate with the path.
1074
- */
1075
- insert(path2, value) {
1076
- const segments = this.normalize(path2);
1077
- this.insertRecursive(this.root, segments, value);
1078
- }
1079
- /**
1080
- * Recursively inserts a path into the Radix Tree.
1081
- * This method traverses the tree and inserts the segments of the path, creating new nodes
1082
- * @param node - The node to start inserting from.
1083
- * @param segments - The segments of the path to insert.
1084
- * @param value - The value to associate with the path.
1085
- */
1086
- insertRecursive(node, segments, value) {
1087
- if (segments.length === 0) {
1088
- node.value = value;
1089
- return;
1090
- }
1091
- const segment = segments[0] ?? "";
1092
- let child = node.children.find((c) => c.isParam === segment.startsWith(":") && (c.isParam || c.segment === segment));
1093
- if (!child) {
1094
- child = new RadixNode(segment);
1095
- node.addChild(child);
1096
- }
1097
- this.insertRecursive(child, segments.slice(1), value);
1098
- }
1099
- /**
1100
- * Searches for a path in the Radix Tree.
1101
- * This method normalizes the path and searches for it in the tree, returning the node
1102
- * @param path - The path to search for in the Radix Tree.
1103
- * @returns An ISearchResult containing the node and parameters if a match is found, otherwise undefined.
1104
- */
1105
- search(path2) {
1106
- const segments = this.normalize(path2);
1107
- return this.searchRecursive(this.root, segments, {});
1108
- }
1109
- /**
1110
- * Recursively searches for a path in the Radix Tree.
1111
- * This method traverses the tree and searches for the segments of the path, collecting parameters
1112
- * @param node - The node to start searching from.
1113
- * @param segments - The segments of the path to search for.
1114
- * @param params - The parameters collected during the search.
1115
- * @returns An ISearchResult containing the node and parameters if a match is found, otherwise undefined.
1116
- */
1117
- searchRecursive(node, segments, params) {
1118
- if (segments.length === 0) {
1119
- if (node.value !== void 0) {
1120
- return {
1121
- node,
1122
- params
1123
- };
888
+ var _RadixNode, RadixNode, _RadixTree, RadixTree;
889
+ var init_radix_tree = __esm({
890
+ "src/utils/radix-tree.ts"() {
891
+ "use strict";
892
+ _RadixNode = class _RadixNode {
893
+ /**
894
+ * Creates a new RadixNode.
895
+ * @param segment - The segment of the path this node represents.
896
+ */
897
+ constructor(segment) {
898
+ this.children = [];
899
+ this.segment = segment;
900
+ this.isParam = segment.startsWith(":");
901
+ if (this.isParam) {
902
+ this.paramName = segment.slice(1);
903
+ }
1124
904
  }
1125
- return void 0;
1126
- }
1127
- const [segment, ...rest] = segments;
1128
- for (const child of node.children) {
1129
- if (child.isParam) {
1130
- const paramName = child.paramName;
1131
- const childParams = {
1132
- ...params,
1133
- [paramName]: segment ?? ""
1134
- };
1135
- if (rest.length === 0) {
1136
- return {
1137
- node: child,
1138
- params: childParams
1139
- };
905
+ /**
906
+ * Matches a child node against a given segment.
907
+ * This method checks if the segment matches any of the children nodes.
908
+ * @param segment - The segment to match against the children of this node.
909
+ * @returns A child node that matches the segment, or undefined if no match is found.
910
+ */
911
+ matchChild(segment) {
912
+ for (const child of this.children) {
913
+ if (child.isParam || segment.startsWith(child.segment))
914
+ return child;
1140
915
  }
1141
- const result = this.searchRecursive(child, rest, childParams);
1142
- if (result) return result;
1143
- } else if (segment === child.segment) {
1144
- if (rest.length === 0) {
1145
- return {
1146
- node: child,
1147
- params
1148
- };
916
+ return void 0;
917
+ }
918
+ /**
919
+ * Finds a child node that matches the segment exactly.
920
+ * This method checks if there is a child node that matches the segment exactly.
921
+ * @param segment - The segment to find an exact match for among the children of this node.
922
+ * @returns A child node that matches the segment exactly, or undefined if no match is found.
923
+ */
924
+ findExactChild(segment) {
925
+ return this.children.find((c) => c.segment === segment);
926
+ }
927
+ /**
928
+ * Adds a child node to this node's children.
929
+ * This method adds a new child node to the list of children for this node.
930
+ * @param node - The child node to add to this node's children.
931
+ */
932
+ addChild(node) {
933
+ this.children.push(node);
934
+ }
935
+ };
936
+ __name(_RadixNode, "RadixNode");
937
+ RadixNode = _RadixNode;
938
+ _RadixTree = class _RadixTree {
939
+ constructor() {
940
+ this.root = new RadixNode("");
941
+ }
942
+ /**
943
+ * Inserts a path and its associated value into the Radix Tree.
944
+ * This method normalizes the path and inserts it into the tree, associating it with
945
+ * @param path - The path to insert into the tree.
946
+ * @param value - The value to associate with the path.
947
+ */
948
+ insert(path2, value) {
949
+ const segments = this.normalize(path2);
950
+ this.insertRecursive(this.root, segments, value);
951
+ }
952
+ /**
953
+ * Recursively inserts a path into the Radix Tree.
954
+ * This method traverses the tree and inserts the segments of the path, creating new nodes
955
+ * @param node - The node to start inserting from.
956
+ * @param segments - The segments of the path to insert.
957
+ * @param value - The value to associate with the path.
958
+ */
959
+ insertRecursive(node, segments, value) {
960
+ if (segments.length === 0) {
961
+ node.value = value;
962
+ return;
963
+ }
964
+ const segment = segments[0] ?? "";
965
+ let child = node.children.find(
966
+ (c) => c.isParam === segment.startsWith(":") && (c.isParam || c.segment === segment)
967
+ );
968
+ if (!child) {
969
+ child = new RadixNode(segment);
970
+ node.addChild(child);
1149
971
  }
1150
- const result = this.searchRecursive(child, rest, params);
1151
- if (result) return result;
972
+ this.insertRecursive(child, segments.slice(1), value);
1152
973
  }
1153
- }
1154
- return void 0;
1155
- }
1156
- /**
1157
- * Normalizes a path into an array of segments.
1158
- * This method removes leading and trailing slashes, splits the path by slashes, and
1159
- * @param path - The path to normalize.
1160
- * @returns An array of normalized path segments.
1161
- */
1162
- normalize(path2) {
1163
- const segments = path2.replace(/^\/+|\/+$/g, "").split("/").filter(Boolean);
1164
- return [
1165
- "",
1166
- ...segments
1167
- ];
974
+ /**
975
+ * Searches for a path in the Radix Tree.
976
+ * This method normalizes the path and searches for it in the tree, returning the node
977
+ * @param path - The path to search for in the Radix Tree.
978
+ * @returns An ISearchResult containing the node and parameters if a match is found, otherwise undefined.
979
+ */
980
+ search(path2) {
981
+ const segments = this.normalize(path2);
982
+ return this.searchRecursive(this.root, segments, {});
983
+ }
984
+ /**
985
+ * Recursively searches for a path in the Radix Tree.
986
+ * This method traverses the tree and searches for the segments of the path, collecting parameters
987
+ * @param node - The node to start searching from.
988
+ * @param segments - The segments of the path to search for.
989
+ * @param params - The parameters collected during the search.
990
+ * @returns An ISearchResult containing the node and parameters if a match is found, otherwise undefined.
991
+ */
992
+ searchRecursive(node, segments, params) {
993
+ if (segments.length === 0) {
994
+ if (node.value !== void 0) {
995
+ return {
996
+ node,
997
+ params
998
+ };
999
+ }
1000
+ return void 0;
1001
+ }
1002
+ const [segment, ...rest] = segments;
1003
+ for (const child of node.children) {
1004
+ if (child.isParam) {
1005
+ const paramName = child.paramName;
1006
+ const childParams = {
1007
+ ...params,
1008
+ [paramName]: segment ?? ""
1009
+ };
1010
+ if (rest.length === 0) {
1011
+ return {
1012
+ node: child,
1013
+ params: childParams
1014
+ };
1015
+ }
1016
+ const result = this.searchRecursive(child, rest, childParams);
1017
+ if (result)
1018
+ return result;
1019
+ } else if (segment === child.segment) {
1020
+ if (rest.length === 0) {
1021
+ return {
1022
+ node: child,
1023
+ params
1024
+ };
1025
+ }
1026
+ const result = this.searchRecursive(child, rest, params);
1027
+ if (result)
1028
+ return result;
1029
+ }
1030
+ }
1031
+ return void 0;
1032
+ }
1033
+ /**
1034
+ * Normalizes a path into an array of segments.
1035
+ * This method removes leading and trailing slashes, splits the path by slashes, and
1036
+ * @param path - The path to normalize.
1037
+ * @returns An array of normalized path segments.
1038
+ */
1039
+ normalize(path2) {
1040
+ const segments = path2.replace(/^\/+|\/+$/g, "").split("/").filter(Boolean);
1041
+ return ["", ...segments];
1042
+ }
1043
+ };
1044
+ __name(_RadixTree, "RadixTree");
1045
+ RadixTree = _RadixTree;
1168
1046
  }
1169
- };
1170
- __name(_RadixTree, "RadixTree");
1171
- var RadixTree = _RadixTree;
1047
+ });
1172
1048
 
1173
1049
  // src/router.ts
1174
- function _ts_decorate(decorators, target, key, desc) {
1175
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1176
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1177
- 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;
1178
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1179
- }
1180
- __name(_ts_decorate, "_ts_decorate");
1181
- var ATOMIC_HTTP_METHODS = /* @__PURE__ */ new Set([
1182
- "GET",
1183
- "POST",
1184
- "PUT",
1185
- "PATCH",
1186
- "DELETE"
1187
- ]);
1188
- function isAtomicHttpMethod(method) {
1189
- return typeof method === "string" && ATOMIC_HTTP_METHODS.has(method);
1190
- }
1191
- __name(isAtomicHttpMethod, "isAtomicHttpMethod");
1192
- var _Router = class _Router {
1193
- constructor() {
1194
- __publicField(this, "routes", new RadixTree());
1195
- __publicField(this, "rootMiddlewares", []);
1196
- }
1197
- /**
1198
- * Registers a controller class with the router.
1199
- * This method extracts the route metadata from the controller class and registers it in the routing tree.
1200
- * It also handles the guards and middlewares associated with the controller.
1201
- * @param controllerClass - The controller class to register.
1202
- */
1203
- registerController(controllerClass) {
1204
- const controllerMeta = getControllerMetadata(controllerClass);
1205
- const controllerGuards = getGuardForController(controllerClass.name);
1206
- const controllerMiddlewares = getMiddlewaresForController(controllerClass.name);
1207
- if (!controllerMeta) throw new Error(`Missing @Controller decorator on ${controllerClass.name}`);
1208
- const routeMetadata = getRouteMetadata(controllerClass);
1209
- for (const def of routeMetadata) {
1210
- const fullPath = `${controllerMeta.path}/${def.path}`.replace(/\/+/g, "/");
1211
- const routeGuards = getGuardForControllerAction(controllerClass.name, def.handler);
1212
- const routeMiddlewares = getMiddlewaresForControllerAction(controllerClass.name, def.handler);
1213
- const guards = /* @__PURE__ */ new Set([
1214
- ...controllerGuards,
1215
- ...routeGuards
1216
- ]);
1217
- const middlewares2 = /* @__PURE__ */ new Set([
1218
- ...controllerMiddlewares,
1219
- ...routeMiddlewares
1220
- ]);
1221
- const routeDef = {
1222
- method: def.method,
1223
- path: fullPath,
1224
- controller: controllerClass,
1225
- handler: def.handler,
1226
- guards: [
1227
- ...guards
1228
- ],
1229
- middlewares: [
1230
- ...middlewares2
1231
- ]
1232
- };
1233
- this.routes.insert(fullPath + "/" + def.method, routeDef);
1234
- const hasActionGuards = routeDef.guards.length > 0;
1235
- const actionGuardsInfo = hasActionGuards ? "<" + routeDef.guards.map((g) => g.name).join("|") + ">" : "";
1236
- Logger.log(`Mapped {${routeDef.method} /${fullPath}}${actionGuardsInfo} route`);
1237
- }
1238
- const hasCtrlGuards = controllerMeta.guards.length > 0;
1239
- const controllerGuardsInfo = hasCtrlGuards ? "<" + controllerMeta.guards.map((g) => g.name).join("|") + ">" : "";
1240
- Logger.log(`Mapped ${controllerClass.name}${controllerGuardsInfo} controller's routes`);
1241
- return this;
1242
- }
1243
- /**
1244
- * Defines a middleware for the root of the application.
1245
- * This method allows you to register a middleware that will be applied to all requests
1246
- * to the application, regardless of the controller or action.
1247
- * @param middleware - The middleware class to register.
1248
- */
1249
- defineRootMiddleware(middleware) {
1250
- this.rootMiddlewares.push(middleware);
1251
- return this;
1252
- }
1253
- /**
1254
- * Shuts down the message channel for a specific sender ID.
1255
- * This method closes the IPC channel for the specified sender ID and
1256
- * removes it from the messagePorts map.
1257
- * @param channelSenderId - The ID of the sender channel to shut down.
1258
- */
1259
- async handle(request) {
1260
- if (request.method === "BATCH") {
1261
- return this.handleBatch(request);
1262
- }
1263
- return this.handleAtomic(request);
1264
- }
1265
- async handleAtomic(request) {
1266
- Logger.comment(`> ${request.method} /${request.path}`);
1267
- const t0 = performance.now();
1268
- const response = {
1269
- requestId: request.id,
1270
- status: 200,
1271
- body: null
1272
- };
1273
- let isCritical = false;
1274
- try {
1275
- const routeDef = this.findRoute(request);
1276
- await this.resolveController(request, response, routeDef);
1277
- if (response.status > 400) {
1278
- throw new ResponseException(response.status, response.error);
1279
- }
1280
- } catch (error) {
1281
- response.body = void 0;
1282
- if (error instanceof ResponseException) {
1283
- response.status = error.status;
1284
- response.error = error.message;
1285
- response.stack = error.stack;
1286
- } else if (error instanceof Error) {
1287
- isCritical = true;
1288
- response.status = 500;
1289
- response.error = error.message || "Internal Server Error";
1290
- response.stack = error.stack || "No stack trace available";
1291
- } else {
1292
- isCritical = true;
1293
- response.status = 500;
1294
- response.error = "Unknown error occurred";
1295
- response.stack = "No stack trace available";
1296
- }
1297
- } finally {
1298
- const t1 = performance.now();
1299
- const message = `< ${response.status} ${request.method} /${request.path} ${Logger.colors.yellow}${Math.round(t1 - t0)}ms${Logger.colors.initial}`;
1300
- if (response.status < 400) {
1301
- Logger.log(message);
1302
- } else if (response.status < 500) {
1303
- Logger.warn(message);
1304
- } else {
1305
- if (isCritical) {
1306
- Logger.critical(message);
1307
- } else {
1308
- Logger.error(message);
1309
- }
1050
+ var router_exports = {};
1051
+ __export(router_exports, {
1052
+ Router: () => Router
1053
+ });
1054
+ var Router;
1055
+ var init_router = __esm({
1056
+ "src/router.ts"() {
1057
+ "use strict";
1058
+ init_controller_decorator();
1059
+ init_injectable_decorator();
1060
+ init_method_decorator();
1061
+ init_injector_explorer();
1062
+ init_exceptions();
1063
+ init_request();
1064
+ init_logger();
1065
+ init_radix_tree();
1066
+ Router = class {
1067
+ constructor() {
1068
+ this.routes = new RadixTree();
1069
+ this.rootMiddlewares = [];
1070
+ this.lazyRoutes = /* @__PURE__ */ new Map();
1310
1071
  }
1311
- if (response.error !== void 0) {
1312
- if (isCritical) {
1313
- Logger.critical(response.error);
1314
- } else {
1315
- Logger.error(response.error);
1072
+ // -------------------------------------------------------------------------
1073
+ // Registration
1074
+ // -------------------------------------------------------------------------
1075
+ registerController(controllerClass, pathPrefix, routeGuards = [], routeMiddlewares = []) {
1076
+ const meta = getControllerMetadata(controllerClass);
1077
+ if (!meta) {
1078
+ throw new Error(`[Noxus] Missing @Controller decorator on ${controllerClass.name}`);
1316
1079
  }
1317
- if (response.stack !== void 0) {
1318
- Logger.errorStack(response.stack);
1080
+ const routeMeta = getRouteMetadata(controllerClass);
1081
+ for (const def of routeMeta) {
1082
+ const fullPath = `${pathPrefix}/${def.path}`.replace(/\/+/g, "/").replace(/\/$/, "") || "/";
1083
+ const guards = [.../* @__PURE__ */ new Set([...routeGuards, ...def.guards])];
1084
+ const middlewares = [.../* @__PURE__ */ new Set([...routeMiddlewares, ...def.middlewares])];
1085
+ const routeDef = {
1086
+ method: def.method,
1087
+ path: fullPath,
1088
+ controller: controllerClass,
1089
+ handler: def.handler,
1090
+ guards,
1091
+ middlewares
1092
+ };
1093
+ this.routes.insert(fullPath + "/" + def.method, routeDef);
1094
+ const guardInfo = guards.length ? `<${guards.map((g) => g.name).join("|")}>` : "";
1095
+ Logger.log(`Mapped {${def.method} /${fullPath}}${guardInfo} route`);
1319
1096
  }
1097
+ const ctrlGuardInfo = routeGuards.length ? `<${routeGuards.map((g) => g.name).join("|")}>` : "";
1098
+ Logger.log(`Mapped ${controllerClass.name}${ctrlGuardInfo} controller's routes`);
1099
+ return this;
1320
1100
  }
1321
- return response;
1322
- }
1323
- }
1324
- async handleBatch(request) {
1325
- Logger.comment(`> ${request.method} /${request.path}`);
1326
- const t0 = performance.now();
1327
- const response = {
1328
- requestId: request.id,
1329
- status: 200,
1330
- body: {
1331
- responses: []
1101
+ registerLazyRoute(pathPrefix, load, guards = [], middlewares = []) {
1102
+ const normalized = pathPrefix.replace(/^\/+|\/+$/g, "");
1103
+ this.lazyRoutes.set(normalized, { load, guards, middlewares, loading: null, loaded: false });
1104
+ Logger.log(`Registered lazy route prefix {${normalized}}`);
1105
+ return this;
1332
1106
  }
1333
- };
1334
- let isCritical = false;
1335
- try {
1336
- const payload = this.normalizeBatchPayload(request.body);
1337
- const batchPromises = payload.requests.map((item, index) => {
1338
- const subRequestId = item.requestId ?? `${request.id}:${index}`;
1339
- const atomicRequest = new Request(request.event, request.senderId, subRequestId, item.method, item.path, item.body);
1340
- return this.handleAtomic(atomicRequest);
1341
- });
1342
- response.body.responses = await Promise.all(batchPromises);
1343
- } catch (error) {
1344
- response.body = void 0;
1345
- if (error instanceof ResponseException) {
1346
- response.status = error.status;
1347
- response.error = error.message;
1348
- response.stack = error.stack;
1349
- } else if (error instanceof Error) {
1350
- isCritical = true;
1351
- response.status = 500;
1352
- response.error = error.message || "Internal Server Error";
1353
- response.stack = error.stack || "No stack trace available";
1354
- } else {
1355
- isCritical = true;
1356
- response.status = 500;
1357
- response.error = "Unknown error occurred";
1358
- response.stack = "No stack trace available";
1359
- }
1360
- } finally {
1361
- const t1 = performance.now();
1362
- const message = `< ${response.status} ${request.method} /${request.path} ${Logger.colors.yellow}${Math.round(t1 - t0)}ms${Logger.colors.initial}`;
1363
- if (response.status < 400) {
1364
- Logger.log(message);
1365
- } else if (response.status < 500) {
1366
- Logger.warn(message);
1367
- } else {
1368
- if (isCritical) {
1369
- Logger.critical(message);
1370
- } else {
1371
- Logger.error(message);
1107
+ defineRootMiddleware(middleware) {
1108
+ this.rootMiddlewares.push(middleware);
1109
+ return this;
1110
+ }
1111
+ // -------------------------------------------------------------------------
1112
+ // Request handling
1113
+ // -------------------------------------------------------------------------
1114
+ async handle(request) {
1115
+ return request.method === "BATCH" ? this.handleBatch(request) : this.handleAtomic(request);
1116
+ }
1117
+ async handleAtomic(request) {
1118
+ Logger.comment(`> ${request.method} /${request.path}`);
1119
+ const t0 = performance.now();
1120
+ const response = { requestId: request.id, status: 200, body: null };
1121
+ let isCritical = false;
1122
+ try {
1123
+ const routeDef = await this.findRoute(request);
1124
+ await this.resolveController(request, response, routeDef);
1125
+ if (response.status >= 400) throw new ResponseException(response.status, response.error);
1126
+ } catch (error) {
1127
+ this.fillErrorResponse(response, error, (c) => {
1128
+ isCritical = c;
1129
+ });
1130
+ } finally {
1131
+ this.logResponse(request, response, performance.now() - t0, isCritical);
1132
+ return response;
1372
1133
  }
1373
1134
  }
1374
- if (response.error !== void 0) {
1375
- if (isCritical) {
1376
- Logger.critical(response.error);
1377
- } else {
1378
- Logger.error(response.error);
1135
+ async handleBatch(request) {
1136
+ Logger.comment(`> ${request.method} /${request.path}`);
1137
+ const t0 = performance.now();
1138
+ const response = {
1139
+ requestId: request.id,
1140
+ status: 200,
1141
+ body: { responses: [] }
1142
+ };
1143
+ let isCritical = false;
1144
+ try {
1145
+ const payload = this.normalizeBatchPayload(request.body);
1146
+ response.body.responses = await Promise.all(
1147
+ payload.requests.map((item, i) => {
1148
+ const id = item.requestId ?? `${request.id}:${i}`;
1149
+ return this.handleAtomic(new Request(request.event, request.senderId, id, item.method, item.path, item.body));
1150
+ })
1151
+ );
1152
+ } catch (error) {
1153
+ this.fillErrorResponse(response, error, (c) => {
1154
+ isCritical = c;
1155
+ });
1156
+ } finally {
1157
+ this.logResponse(request, response, performance.now() - t0, isCritical);
1158
+ return response;
1379
1159
  }
1380
- if (response.stack !== void 0) {
1381
- Logger.errorStack(response.stack);
1160
+ }
1161
+ // -------------------------------------------------------------------------
1162
+ // Route resolution
1163
+ // -------------------------------------------------------------------------
1164
+ tryFindRoute(request) {
1165
+ const matched = this.routes.search(request.path);
1166
+ if (!matched?.node || matched.node.children.length === 0) return void 0;
1167
+ return matched.node.findExactChild(request.method)?.value;
1168
+ }
1169
+ async findRoute(request) {
1170
+ const direct = this.tryFindRoute(request);
1171
+ if (direct) return direct;
1172
+ await this.tryLoadLazyRoute(request.path);
1173
+ const afterLazy = this.tryFindRoute(request);
1174
+ if (afterLazy) return afterLazy;
1175
+ throw new NotFoundException(`No route matches ${request.method} ${request.path}`);
1176
+ }
1177
+ async tryLoadLazyRoute(requestPath) {
1178
+ const firstSegment = requestPath.replace(/^\/+/, "").split("/")[0] ?? "";
1179
+ for (const [prefix, entry] of this.lazyRoutes) {
1180
+ if (entry.loaded) continue;
1181
+ const normalized = requestPath.replace(/^\/+/, "");
1182
+ if (normalized === prefix || normalized.startsWith(prefix + "/") || firstSegment === prefix) {
1183
+ if (!entry.loading) entry.loading = this.loadLazyModule(prefix, entry);
1184
+ await entry.loading;
1185
+ return;
1186
+ }
1382
1187
  }
1383
1188
  }
1384
- return response;
1385
- }
1386
- }
1387
- normalizeBatchPayload(body) {
1388
- if (body === null || typeof body !== "object") {
1389
- throw new BadRequestException("Batch payload must be an object containing a requests array.");
1390
- }
1391
- const possiblePayload = body;
1392
- const { requests } = possiblePayload;
1393
- if (!Array.isArray(requests)) {
1394
- throw new BadRequestException("Batch payload must define a requests array.");
1395
- }
1396
- const normalizedRequests = requests.map((entry, index) => this.normalizeBatchItem(entry, index));
1397
- return {
1398
- requests: normalizedRequests
1399
- };
1400
- }
1401
- normalizeBatchItem(entry, index) {
1402
- if (entry === null || typeof entry !== "object") {
1403
- throw new BadRequestException(`Batch request at index ${index} must be an object.`);
1404
- }
1405
- const { requestId, path: path2, method, body } = entry;
1406
- if (requestId !== void 0 && typeof requestId !== "string") {
1407
- throw new BadRequestException(`Batch request at index ${index} has an invalid requestId.`);
1408
- }
1409
- if (typeof path2 !== "string" || path2.length === 0) {
1410
- throw new BadRequestException(`Batch request at index ${index} must define a non-empty path.`);
1411
- }
1412
- if (typeof method !== "string") {
1413
- throw new BadRequestException(`Batch request at index ${index} must define an HTTP method.`);
1414
- }
1415
- const normalizedMethod = method.toUpperCase();
1416
- if (!isAtomicHttpMethod(normalizedMethod)) {
1417
- throw new BadRequestException(`Batch request at index ${index} uses the unsupported method ${method}.`);
1418
- }
1419
- return {
1420
- requestId,
1421
- path: path2,
1422
- method: normalizedMethod,
1423
- body
1424
- };
1425
- }
1426
- /**
1427
- * Finds the route definition for a given request.
1428
- * This method searches the routing tree for a matching route based on the request's path and method.
1429
- * If no matching route is found, it throws a NotFoundException.
1430
- * @param request - The Request object containing the method and path to search for.
1431
- * @returns The IRouteDefinition for the matched route.
1432
- */
1433
- findRoute(request) {
1434
- const matchedRoutes = this.routes.search(request.path);
1435
- if (matchedRoutes?.node === void 0 || matchedRoutes.node.children.length === 0) {
1436
- throw new NotFoundException(`No route matches ${request.method} ${request.path}`);
1437
- }
1438
- const routeDef = matchedRoutes.node.findExactChild(request.method);
1439
- if (routeDef?.value === void 0) {
1440
- throw new MethodNotAllowedException(`Method Not Allowed for ${request.method} ${request.path}`);
1441
- }
1442
- return routeDef.value;
1443
- }
1444
- /**
1445
- * Resolves the controller for a given route definition.
1446
- * This method creates an instance of the controller class and prepares the request parameters.
1447
- * It also runs the request pipeline, which includes executing middlewares and guards.
1448
- * @param request - The Request object containing the request data.
1449
- * @param response - The IResponse object to populate with the response data.
1450
- * @param routeDef - The IRouteDefinition for the matched route.
1451
- * @return A Promise that resolves when the controller action has been executed.
1452
- * @throws UnauthorizedException if the request is not authorized by the guards.
1453
- */
1454
- async resolveController(request, response, routeDef) {
1455
- const controllerInstance = request.context.resolve(routeDef.controller);
1456
- Object.assign(request.params, this.extractParams(request.path, routeDef.path));
1457
- await this.runRequestPipeline(request, response, routeDef, controllerInstance);
1458
- }
1459
- /**
1460
- * Runs the request pipeline for a given request.
1461
- * This method executes the middlewares and guards associated with the route,
1462
- * and finally calls the controller action.
1463
- * @param request - The Request object containing the request data.
1464
- * @param response - The IResponse object to populate with the response data.
1465
- * @param routeDef - The IRouteDefinition for the matched route.
1466
- * @param controllerInstance - The instance of the controller class.
1467
- * @return A Promise that resolves when the request pipeline has been executed.
1468
- * @throws ResponseException if the response status is not successful.
1469
- */
1470
- async runRequestPipeline(request, response, routeDef, controllerInstance) {
1471
- const middlewares2 = [
1472
- .../* @__PURE__ */ new Set([
1473
- ...this.rootMiddlewares,
1474
- ...routeDef.middlewares
1475
- ])
1476
- ];
1477
- const middlewareMaxIndex = middlewares2.length - 1;
1478
- const guardsMaxIndex = middlewareMaxIndex + routeDef.guards.length;
1479
- let index = -1;
1480
- const dispatch = /* @__PURE__ */ __name(async (i) => {
1481
- if (i <= index) throw new Error("next() called multiple times");
1482
- index = i;
1483
- if (i <= middlewareMaxIndex) {
1484
- const nextFn = dispatch.bind(null, i + 1);
1485
- await this.runMiddleware(request, response, nextFn, middlewares2[i]);
1486
- if (response.status >= 400) {
1487
- throw new ResponseException(response.status, response.error);
1189
+ async loadLazyModule(prefix, entry) {
1190
+ const t0 = performance.now();
1191
+ InjectorExplorer.beginAccumulate();
1192
+ await entry.load?.();
1193
+ entry.loading = null;
1194
+ entry.load = null;
1195
+ InjectorExplorer.flushAccumulated(entry.guards, entry.middlewares, prefix);
1196
+ entry.loaded = true;
1197
+ Logger.info(`Lazy-loaded module for prefix {${prefix}} in ${Math.round(performance.now() - t0)}ms`);
1198
+ }
1199
+ // -------------------------------------------------------------------------
1200
+ // Pipeline
1201
+ // -------------------------------------------------------------------------
1202
+ async resolveController(request, response, routeDef) {
1203
+ const instance = request.context.resolve(routeDef.controller);
1204
+ Object.assign(request.params, this.extractParams(request.path, routeDef.path));
1205
+ await this.runPipeline(request, response, routeDef, instance);
1206
+ }
1207
+ async runPipeline(request, response, routeDef, controllerInstance) {
1208
+ const middlewares = [.../* @__PURE__ */ new Set([...this.rootMiddlewares, ...routeDef.middlewares])];
1209
+ const mwMax = middlewares.length - 1;
1210
+ const guardMax = mwMax + routeDef.guards.length;
1211
+ let index = -1;
1212
+ const dispatch = /* @__PURE__ */ __name(async (i) => {
1213
+ if (i <= index) throw new Error("next() called multiple times");
1214
+ index = i;
1215
+ if (i <= mwMax) {
1216
+ await this.runMiddleware(request, response, dispatch.bind(null, i + 1), middlewares[i]);
1217
+ if (response.status >= 400) throw new ResponseException(response.status, response.error);
1218
+ return;
1219
+ }
1220
+ if (i <= guardMax) {
1221
+ await this.runGuard(request, routeDef.guards[i - middlewares.length]);
1222
+ await dispatch(i + 1);
1223
+ return;
1224
+ }
1225
+ const action = controllerInstance[routeDef.handler];
1226
+ response.body = await action.call(controllerInstance, request, response);
1227
+ if (response.body === void 0) response.body = {};
1228
+ }, "dispatch");
1229
+ await dispatch(0);
1230
+ }
1231
+ async runMiddleware(request, response, next, middleware) {
1232
+ await middleware(request, response, next);
1233
+ }
1234
+ async runGuard(request, guard) {
1235
+ if (!await guard(request)) {
1236
+ throw new UnauthorizedException(`Unauthorized for ${request.method} ${request.path}`);
1488
1237
  }
1489
- return;
1490
1238
  }
1491
- if (i <= guardsMaxIndex) {
1492
- const guardIndex = i - middlewares2.length;
1493
- const guardType = routeDef.guards[guardIndex];
1494
- await this.runGuard(request, guardType);
1495
- await dispatch(i + 1);
1496
- return;
1239
+ // -------------------------------------------------------------------------
1240
+ // Utilities
1241
+ // -------------------------------------------------------------------------
1242
+ extractParams(actual, template) {
1243
+ const aParts = actual.split("/");
1244
+ const tParts = template.split("/");
1245
+ const params = {};
1246
+ tParts.forEach((part, i) => {
1247
+ if (part.startsWith(":")) params[part.slice(1)] = aParts[i] ?? "";
1248
+ });
1249
+ return params;
1497
1250
  }
1498
- const action = controllerInstance[routeDef.handler];
1499
- response.body = await action.call(controllerInstance, request, response);
1500
- if (response.body === void 0) {
1501
- response.body = {};
1251
+ normalizeBatchPayload(body) {
1252
+ if (body === null || typeof body !== "object") {
1253
+ throw new BadRequestException("Batch payload must be an object containing a requests array.");
1254
+ }
1255
+ const { requests } = body;
1256
+ if (!Array.isArray(requests)) throw new BadRequestException("Batch payload must define a requests array.");
1257
+ return { requests: requests.map((e, i) => this.normalizeBatchItem(e, i)) };
1502
1258
  }
1503
- }, "dispatch");
1504
- await dispatch(0);
1505
- }
1506
- /**
1507
- * Runs a middleware function in the request pipeline.
1508
- * This method creates an instance of the middleware and invokes its `invoke` method,
1509
- * passing the request, response, and next function.
1510
- * @param request - The Request object containing the request data.
1511
- * @param response - The IResponse object to populate with the response data.
1512
- * @param next - The NextFunction to call to continue the middleware chain.
1513
- * @param middlewareType - The type of the middleware to run.
1514
- * @return A Promise that resolves when the middleware has been executed.
1515
- */
1516
- async runMiddleware(request, response, next, middlewareType) {
1517
- const middleware = request.context.resolve(middlewareType);
1518
- await middleware.invoke(request, response, next);
1519
- }
1520
- /**
1521
- * Runs a guard to check if the request is authorized.
1522
- * This method creates an instance of the guard and calls its `canActivate` method.
1523
- * If the guard returns false, it throws an UnauthorizedException.
1524
- * @param request - The Request object containing the request data.
1525
- * @param guardType - The type of the guard to run.
1526
- * @return A Promise that resolves if the guard allows the request, or throws an UnauthorizedException if not.
1527
- * @throws UnauthorizedException if the guard denies access to the request.
1528
- */
1529
- async runGuard(request, guardType) {
1530
- const guard = request.context.resolve(guardType);
1531
- const allowed = await guard.canActivate(request);
1532
- if (!allowed) throw new UnauthorizedException(`Unauthorized for ${request.method} ${request.path}`);
1533
- }
1534
- /**
1535
- * Extracts parameters from the actual request path based on the template path.
1536
- * This method splits the actual path and the template path into segments,
1537
- * then maps the segments to parameters based on the template.
1538
- * @param actual - The actual request path.
1539
- * @param template - The template path to extract parameters from.
1540
- * @returns An object containing the extracted parameters.
1541
- */
1542
- extractParams(actual, template) {
1543
- const aParts = actual.split("/");
1544
- const tParts = template.split("/");
1545
- const params = {};
1546
- tParts.forEach((part, i) => {
1547
- if (part.startsWith(":")) {
1548
- params[part.slice(1)] = aParts[i] ?? "";
1259
+ normalizeBatchItem(entry, index) {
1260
+ if (entry === null || typeof entry !== "object") throw new BadRequestException(`Batch request at index ${index} must be an object.`);
1261
+ const { requestId, path: path2, method, body } = entry;
1262
+ if (requestId !== void 0 && typeof requestId !== "string") throw new BadRequestException(`Batch request at index ${index} has an invalid requestId.`);
1263
+ if (typeof path2 !== "string" || !path2.length) throw new BadRequestException(`Batch request at index ${index} must define a non-empty path.`);
1264
+ if (typeof method !== "string") throw new BadRequestException(`Batch request at index ${index} must define an HTTP method.`);
1265
+ const normalized = method.toUpperCase();
1266
+ if (!isAtomicHttpMethod(normalized)) throw new BadRequestException(`Batch request at index ${index} uses unsupported method ${method}.`);
1267
+ return { requestId, path: path2, method: normalized, body };
1549
1268
  }
1550
- });
1551
- return params;
1269
+ fillErrorResponse(response, error, setCritical) {
1270
+ response.body = void 0;
1271
+ if (error instanceof ResponseException) {
1272
+ response.status = error.status;
1273
+ response.error = error.message;
1274
+ response.stack = error.stack;
1275
+ } else if (error instanceof Error) {
1276
+ setCritical(true);
1277
+ response.status = 500;
1278
+ response.error = error.message || "Internal Server Error";
1279
+ response.stack = error.stack;
1280
+ } else {
1281
+ setCritical(true);
1282
+ response.status = 500;
1283
+ response.error = "Unknown error occurred";
1284
+ }
1285
+ }
1286
+ logResponse(request, response, ms, isCritical) {
1287
+ const msg = `< ${response.status} ${request.method} /${request.path} ${Logger.colors.yellow}${Math.round(ms)}ms${Logger.colors.initial}`;
1288
+ if (response.status < 400) Logger.log(msg);
1289
+ else if (response.status < 500) Logger.warn(msg);
1290
+ else isCritical ? Logger.critical(msg) : Logger.error(msg);
1291
+ if (response.error) {
1292
+ isCritical ? Logger.critical(response.error) : Logger.error(response.error);
1293
+ if (response.stack) Logger.errorStack(response.stack);
1294
+ }
1295
+ }
1296
+ };
1297
+ __name(Router, "Router");
1298
+ Router = __decorateClass([
1299
+ Injectable({ lifetime: "singleton" })
1300
+ ], Router);
1552
1301
  }
1553
- };
1554
- __name(_Router, "Router");
1555
- var Router = _Router;
1556
- Router = _ts_decorate([
1557
- Injectable("singleton")
1558
- ], Router);
1302
+ });
1303
+
1304
+ // src/main.ts
1305
+ var main_exports = {};
1306
+ __export(main_exports, {
1307
+ AppInjector: () => AppInjector,
1308
+ BadGatewayException: () => BadGatewayException,
1309
+ BadRequestException: () => BadRequestException,
1310
+ ConflictException: () => ConflictException,
1311
+ Controller: () => Controller,
1312
+ Delete: () => Delete,
1313
+ ForbiddenException: () => ForbiddenException,
1314
+ ForwardReference: () => ForwardReference,
1315
+ GatewayTimeoutException: () => GatewayTimeoutException,
1316
+ Get: () => Get,
1317
+ HttpVersionNotSupportedException: () => HttpVersionNotSupportedException,
1318
+ Injectable: () => Injectable,
1319
+ InsufficientStorageException: () => InsufficientStorageException,
1320
+ InternalServerException: () => InternalServerException,
1321
+ Logger: () => Logger,
1322
+ LoopDetectedException: () => LoopDetectedException,
1323
+ MethodNotAllowedException: () => MethodNotAllowedException,
1324
+ NetworkAuthenticationRequiredException: () => NetworkAuthenticationRequiredException,
1325
+ NetworkConnectTimeoutException: () => NetworkConnectTimeoutException,
1326
+ NotAcceptableException: () => NotAcceptableException,
1327
+ NotExtendedException: () => NotExtendedException,
1328
+ NotFoundException: () => NotFoundException,
1329
+ NotImplementedException: () => NotImplementedException,
1330
+ NoxApp: () => NoxApp,
1331
+ NoxSocket: () => NoxSocket,
1332
+ Patch: () => Patch,
1333
+ PaymentRequiredException: () => PaymentRequiredException,
1334
+ Post: () => Post,
1335
+ Put: () => Put,
1336
+ RENDERER_EVENT_TYPE: () => RENDERER_EVENT_TYPE,
1337
+ Request: () => Request,
1338
+ RequestTimeoutException: () => RequestTimeoutException,
1339
+ ResponseException: () => ResponseException,
1340
+ RootInjector: () => RootInjector,
1341
+ Router: () => Router,
1342
+ ServiceUnavailableException: () => ServiceUnavailableException,
1343
+ Token: () => Token,
1344
+ TooManyRequestsException: () => TooManyRequestsException,
1345
+ UnauthorizedException: () => UnauthorizedException,
1346
+ UpgradeRequiredException: () => UpgradeRequiredException,
1347
+ VariantAlsoNegotiatesException: () => VariantAlsoNegotiatesException,
1348
+ WindowManager: () => WindowManager,
1349
+ bootstrapApplication: () => bootstrapApplication,
1350
+ createRendererEventMessage: () => createRendererEventMessage,
1351
+ defineRoutes: () => defineRoutes,
1352
+ forwardRef: () => forwardRef,
1353
+ getControllerMetadata: () => getControllerMetadata,
1354
+ getRouteMetadata: () => getRouteMetadata,
1355
+ inject: () => inject,
1356
+ isAtomicHttpMethod: () => isAtomicHttpMethod,
1357
+ isRendererEventMessage: () => isRendererEventMessage,
1358
+ token: () => token
1359
+ });
1360
+ module.exports = __toCommonJS(main_exports);
1361
+ init_app_injector();
1362
+ init_token();
1363
+ init_router();
1559
1364
 
1560
1365
  // src/app.ts
1561
- var import_main = require("electron/main");
1366
+ var import_main2 = require("electron/main");
1367
+ init_injectable_decorator();
1368
+ init_app_injector();
1369
+ init_injector_explorer();
1370
+ init_request();
1371
+ init_router();
1562
1372
 
1563
1373
  // src/socket.ts
1564
- function _ts_decorate2(decorators, target, key, desc) {
1565
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1566
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1567
- 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;
1568
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1569
- }
1570
- __name(_ts_decorate2, "_ts_decorate");
1571
- var _NoxSocket = class _NoxSocket {
1374
+ init_injectable_decorator();
1375
+ init_request();
1376
+ init_logger();
1377
+ var NoxSocket = class {
1572
1378
  constructor() {
1573
- __publicField(this, "channels", /* @__PURE__ */ new Map());
1379
+ this.channels = /* @__PURE__ */ new Map();
1574
1380
  }
1575
1381
  register(senderId, requestChannel, socketChannel) {
1576
- this.channels.set(senderId, {
1577
- request: requestChannel,
1578
- socket: socketChannel
1579
- });
1382
+ this.channels.set(senderId, { request: requestChannel, socket: socketChannel });
1580
1383
  }
1581
1384
  get(senderId) {
1582
1385
  return this.channels.get(senderId);
@@ -1585,9 +1388,7 @@ var _NoxSocket = class _NoxSocket {
1585
1388
  this.channels.delete(senderId);
1586
1389
  }
1587
1390
  getSenderIds() {
1588
- return [
1589
- ...this.channels.keys()
1590
- ];
1391
+ return [...this.channels.keys()];
1591
1392
  }
1592
1393
  emit(eventName, payload, targetSenderIds) {
1593
1394
  const normalizedEvent = eventName.trim();
@@ -1612,39 +1413,196 @@ var _NoxSocket = class _NoxSocket {
1612
1413
  return delivered;
1613
1414
  }
1614
1415
  emitToRenderer(senderId, eventName, payload) {
1615
- return this.emit(eventName, payload, [
1616
- senderId
1617
- ]) > 0;
1416
+ return this.emit(eventName, payload, [senderId]) > 0;
1618
1417
  }
1619
1418
  };
1620
- __name(_NoxSocket, "NoxSocket");
1621
- var NoxSocket = _NoxSocket;
1622
- NoxSocket = _ts_decorate2([
1623
- Injectable("singleton")
1419
+ __name(NoxSocket, "NoxSocket");
1420
+ NoxSocket = __decorateClass([
1421
+ Injectable({ lifetime: "singleton" })
1624
1422
  ], NoxSocket);
1625
1423
 
1626
1424
  // src/app.ts
1627
- function _ts_decorate3(decorators, target, key, desc) {
1628
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1629
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1630
- 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;
1631
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1632
- }
1633
- __name(_ts_decorate3, "_ts_decorate");
1634
- function _ts_metadata(k, v) {
1635
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1636
- }
1637
- __name(_ts_metadata, "_ts_metadata");
1638
- var _NoxApp = class _NoxApp {
1639
- constructor(router, socket) {
1640
- __publicField(this, "router");
1641
- __publicField(this, "socket");
1642
- __publicField(this, "app");
1643
- __publicField(this, "mainWindow");
1644
- /**
1645
- *
1646
- */
1647
- __publicField(this, "onRendererMessage", /* @__PURE__ */ __name(async (event) => {
1425
+ init_logger();
1426
+
1427
+ // src/window/window-manager.ts
1428
+ var import_main = require("electron/main");
1429
+ init_injectable_decorator();
1430
+ init_logger();
1431
+ var WindowManager = class {
1432
+ constructor() {
1433
+ this._windows = /* @__PURE__ */ new Map();
1434
+ }
1435
+ // -------------------------------------------------------------------------
1436
+ // Creation
1437
+ // -------------------------------------------------------------------------
1438
+ /**
1439
+ * Creates a BrowserWindow, optionally performs an animated expand to the
1440
+ * work area, and registers it in the manager.
1441
+ *
1442
+ * If expandToWorkArea is true:
1443
+ * 1. The window is created at the given initial size (defaults to 600×600, centered).
1444
+ * 2. An animated setBounds expands it to the full work area.
1445
+ * 3. The returned promise resolves only after the animation, so callers
1446
+ * can safely call win.loadFile() without the viewbox freeze.
1447
+ *
1448
+ * @param config Window configuration.
1449
+ * @param isMain Mark this window as the main window (accessible via getMain()).
1450
+ */
1451
+ async create(config, isMain = false) {
1452
+ const {
1453
+ expandToWorkArea = false,
1454
+ expandAnimationDuration = 600,
1455
+ ...bwOptions
1456
+ } = config;
1457
+ const win = new import_main.BrowserWindow({ show: false, ...bwOptions });
1458
+ this._register(win, isMain);
1459
+ if (expandToWorkArea) {
1460
+ await this._expandToWorkArea(win, expandAnimationDuration);
1461
+ }
1462
+ win.once("ready-to-show", () => win.show());
1463
+ Logger.log(`[WindowManager] Created window #${win.id}${isMain ? " (main)" : ""}`);
1464
+ return win;
1465
+ }
1466
+ /**
1467
+ * Creates the initial "splash" window that is shown immediately after
1468
+ * app.whenReady(). It is displayed instantly (show: true, no preload
1469
+ * loading) and then expanded to the work area with animation.
1470
+ *
1471
+ * After the animation completes you can call win.loadFile() without
1472
+ * experiencing the viewbox freeze.
1473
+ *
1474
+ * This is the recommended way to get pixels on screen as fast as possible.
1475
+ *
1476
+ * @example
1477
+ * const win = await wm.createSplash({
1478
+ * webPreferences: { preload: path.join(__dirname, 'preload.js') }
1479
+ * });
1480
+ * win.loadFile('index.html');
1481
+ */
1482
+ async createSplash(options = {}) {
1483
+ const { animationDuration = 600, ...bwOptions } = options;
1484
+ const win = new import_main.BrowserWindow({
1485
+ width: 600,
1486
+ height: 600,
1487
+ center: true,
1488
+ frame: false,
1489
+ show: true,
1490
+ ...bwOptions
1491
+ });
1492
+ this._register(win, true);
1493
+ Logger.log(`[WindowManager] Splash window #${win.id} created`);
1494
+ await this._expandToWorkArea(win, animationDuration);
1495
+ return win;
1496
+ }
1497
+ // -------------------------------------------------------------------------
1498
+ // Accessors
1499
+ // -------------------------------------------------------------------------
1500
+ /** Returns all currently open windows. */
1501
+ getAll() {
1502
+ return [...this._windows.values()];
1503
+ }
1504
+ /** Returns the window designated as main, or undefined. */
1505
+ getMain() {
1506
+ return this._mainWindowId !== void 0 ? this._windows.get(this._mainWindowId) : void 0;
1507
+ }
1508
+ /** Returns a window by its Electron id, or undefined. */
1509
+ getById(id) {
1510
+ return this._windows.get(id);
1511
+ }
1512
+ /** Returns the number of open windows. */
1513
+ get count() {
1514
+ return this._windows.size;
1515
+ }
1516
+ // -------------------------------------------------------------------------
1517
+ // Actions
1518
+ // -------------------------------------------------------------------------
1519
+ /** Closes and destroys a window by id. */
1520
+ close(id) {
1521
+ const win = this._windows.get(id);
1522
+ if (!win) {
1523
+ Logger.warn(`[WindowManager] Window #${id} not found`);
1524
+ return;
1525
+ }
1526
+ win.destroy();
1527
+ }
1528
+ /** Closes all windows. */
1529
+ closeAll() {
1530
+ for (const win of this._windows.values()) {
1531
+ win.destroy();
1532
+ }
1533
+ }
1534
+ /**
1535
+ * Sends a message to a specific window via webContents.send.
1536
+ * @param id Target window id.
1537
+ * @param channel IPC channel name.
1538
+ * @param args Payload.
1539
+ */
1540
+ send(id, channel, ...args) {
1541
+ const win = this._windows.get(id);
1542
+ if (!win || win.isDestroyed()) {
1543
+ Logger.warn(`[WindowManager] Cannot send to window #${id}: not found or destroyed`);
1544
+ return;
1545
+ }
1546
+ win.webContents.send(channel, ...args);
1547
+ }
1548
+ /**
1549
+ * Broadcasts a message to all open windows.
1550
+ */
1551
+ broadcast(channel, ...args) {
1552
+ for (const win of this._windows.values()) {
1553
+ if (!win.isDestroyed()) win.webContents.send(channel, ...args);
1554
+ }
1555
+ }
1556
+ // -------------------------------------------------------------------------
1557
+ // Private
1558
+ // -------------------------------------------------------------------------
1559
+ _register(win, isMain) {
1560
+ this._windows.set(win.id, win);
1561
+ if (isMain && this._mainWindowId === void 0) {
1562
+ this._mainWindowId = win.id;
1563
+ }
1564
+ win.once("closed", () => {
1565
+ this._windows.delete(win.id);
1566
+ if (this._mainWindowId === win.id) this._mainWindowId = void 0;
1567
+ Logger.log(`[WindowManager] Window #${win.id} closed`);
1568
+ });
1569
+ }
1570
+ /**
1571
+ * Animates the window to the full work area of the primary display.
1572
+ * Resolves only after the animation is complete, so that content loaded
1573
+ * afterward gets the correct surface size (no viewbox freeze).
1574
+ */
1575
+ _expandToWorkArea(win, animationDuration) {
1576
+ return new Promise((resolve) => {
1577
+ const { x, y, width, height } = import_main.screen.getPrimaryDisplay().workArea;
1578
+ win.setBounds({ x, y, width, height }, true);
1579
+ let resolved = false;
1580
+ const done = /* @__PURE__ */ __name(() => {
1581
+ if (resolved) return;
1582
+ resolved = true;
1583
+ win.removeListener("resize", done);
1584
+ resolve();
1585
+ }, "done");
1586
+ win.once("resize", done);
1587
+ setTimeout(done, animationDuration + 100);
1588
+ });
1589
+ }
1590
+ };
1591
+ __name(WindowManager, "WindowManager");
1592
+ WindowManager = __decorateClass([
1593
+ Injectable({ lifetime: "singleton" })
1594
+ ], WindowManager);
1595
+
1596
+ // src/app.ts
1597
+ var NoxApp = class {
1598
+ constructor() {
1599
+ this.router = inject(Router);
1600
+ this.socket = inject(NoxSocket);
1601
+ this.windowManager = inject(WindowManager);
1602
+ // -------------------------------------------------------------------------
1603
+ // IPC
1604
+ // -------------------------------------------------------------------------
1605
+ this.onRendererMessage = /* @__PURE__ */ __name(async (event) => {
1648
1606
  const { senderId, requestId, path: path2, method, body } = event.data;
1649
1607
  const channels = this.socket.get(senderId);
1650
1608
  if (!channels) {
@@ -1660,69 +1618,108 @@ var _NoxApp = class _NoxApp {
1660
1618
  requestId,
1661
1619
  status: 500,
1662
1620
  body: null,
1663
- error: err.message || "Internal Server Error"
1621
+ error: err instanceof Error ? err.message : "Internal Server Error"
1664
1622
  };
1665
1623
  channels.request.port1.postMessage(response);
1666
1624
  }
1667
- }, "onRendererMessage"));
1668
- this.router = router;
1669
- this.socket = socket;
1625
+ }, "onRendererMessage");
1670
1626
  }
1671
- /**
1672
- * Initializes the NoxApp instance.
1673
- * This method sets up the IPC communication, registers event listeners,
1674
- * and prepares the application for use.
1675
- */
1627
+ // -------------------------------------------------------------------------
1628
+ // Initialisation
1629
+ // -------------------------------------------------------------------------
1676
1630
  async init() {
1677
- import_main.ipcMain.on("gimme-my-port", this.giveTheRendererAPort.bind(this));
1678
- import_main.app.once("activate", this.onAppActivated.bind(this));
1679
- import_main.app.once("window-all-closed", this.onAllWindowsClosed.bind(this));
1631
+ import_main2.ipcMain.on("gimme-my-port", this.giveTheRendererAPort.bind(this));
1632
+ import_main2.app.once("activate", this.onAppActivated.bind(this));
1633
+ import_main2.app.once("window-all-closed", this.onAllWindowsClosed.bind(this));
1680
1634
  console.log("");
1681
1635
  return this;
1682
1636
  }
1637
+ // -------------------------------------------------------------------------
1638
+ // Public API
1639
+ // -------------------------------------------------------------------------
1640
+ /**
1641
+ * Registers a lazy route. The file behind this prefix is dynamically
1642
+ * imported on the first IPC request that targets it.
1643
+ *
1644
+ * The import function should NOT statically reference heavy modules —
1645
+ * the whole point is to defer their loading.
1646
+ *
1647
+ * @example
1648
+ * noxApp.lazy('auth', () => import('./modules/auth/auth.controller.js'));
1649
+ * noxApp.lazy('reporting', () => import('./modules/reporting/index.js'));
1650
+ */
1651
+ lazy(pathPrefix, load, guards = [], middlewares = []) {
1652
+ this.router.registerLazyRoute(pathPrefix, load, guards, middlewares);
1653
+ return this;
1654
+ }
1655
+ /**
1656
+ * Eagerly loads a set of modules (controllers + services) before start().
1657
+ * Use this for modules that provide services needed by your IApp.onReady().
1658
+ *
1659
+ * All imports run in parallel; DI is flushed with the two-phase guarantee.
1660
+ */
1661
+ async load(importFns) {
1662
+ InjectorExplorer.beginAccumulate();
1663
+ await Promise.all(importFns.map((fn) => fn()));
1664
+ InjectorExplorer.flushAccumulated();
1665
+ return this;
1666
+ }
1667
+ /**
1668
+ * Registers a global middleware applied to every route.
1669
+ */
1670
+ use(middleware) {
1671
+ this.router.defineRootMiddleware(middleware);
1672
+ return this;
1673
+ }
1674
+ /**
1675
+ * Sets the application service (implements IApp) that receives lifecycle events.
1676
+ * @param appClass - Class decorated with @Injectable that implements IApp.
1677
+ */
1678
+ configure(appClass) {
1679
+ this.appService = inject(appClass);
1680
+ return this;
1681
+ }
1683
1682
  /**
1684
- * Handles the request from the renderer process.
1685
- * This method creates a Request object from the IPC event data,
1686
- * processes it through the Router, and sends the response back
1687
- * to the renderer process using the MessageChannel.
1683
+ * Calls IApp.onReady(). Should be called after configure() and any lazy()
1684
+ * registrations are set up.
1688
1685
  */
1686
+ start() {
1687
+ this.appService?.onReady();
1688
+ return this;
1689
+ }
1689
1690
  giveTheRendererAPort(event) {
1690
1691
  const senderId = event.sender.id;
1691
1692
  if (this.socket.get(senderId)) {
1692
1693
  this.shutdownChannel(senderId);
1693
1694
  }
1694
- const requestChannel = new import_main.MessageChannelMain();
1695
- const socketChannel = new import_main.MessageChannelMain();
1695
+ const requestChannel = new import_main2.MessageChannelMain();
1696
+ const socketChannel = new import_main2.MessageChannelMain();
1696
1697
  requestChannel.port1.on("message", this.onRendererMessage);
1697
1698
  requestChannel.port1.start();
1698
1699
  socketChannel.port1.start();
1700
+ event.sender.once("destroyed", () => this.shutdownChannel(senderId));
1699
1701
  this.socket.register(senderId, requestChannel, socketChannel);
1700
- event.sender.postMessage("port", {
1701
- senderId
1702
- }, [
1703
- requestChannel.port2,
1704
- socketChannel.port2
1705
- ]);
1702
+ event.sender.postMessage("port", { senderId }, [requestChannel.port2, socketChannel.port2]);
1706
1703
  }
1707
- /**
1708
- * MacOS specific behavior.
1709
- */
1704
+ // -------------------------------------------------------------------------
1705
+ // Lifecycle
1706
+ // -------------------------------------------------------------------------
1710
1707
  onAppActivated() {
1711
- if (process.platform === "darwin" && import_main.BrowserWindow.getAllWindows().length === 0) {
1712
- this.app?.onActivated();
1708
+ if (process.platform === "darwin" && import_main2.BrowserWindow.getAllWindows().length === 0) {
1709
+ this.appService?.onActivated();
1713
1710
  }
1714
1711
  }
1715
- /**
1716
- * Shuts down the message channel for a specific sender ID.
1717
- * This method closes the IPC channel for the specified sender ID and
1718
- * removes it from the messagePorts map.
1719
- * @param channelSenderId - The ID of the sender channel to shut down.
1720
- * @param remove - Whether to remove the channel from the messagePorts map.
1721
- */
1712
+ async onAllWindowsClosed() {
1713
+ for (const senderId of this.socket.getSenderIds()) {
1714
+ this.shutdownChannel(senderId);
1715
+ }
1716
+ Logger.info("All windows closed, shutting down application...");
1717
+ await this.appService?.dispose();
1718
+ if (process.platform !== "darwin") import_main2.app.quit();
1719
+ }
1722
1720
  shutdownChannel(channelSenderId) {
1723
1721
  const channels = this.socket.get(channelSenderId);
1724
1722
  if (!channels) {
1725
- Logger.warn(`No message channel found for sender ID: ${channelSenderId}`);
1726
1723
  return;
1727
1724
  }
1728
1725
  channels.request.port1.off("message", this.onRendererMessage);
@@ -1732,459 +1729,67 @@ var _NoxApp = class _NoxApp {
1732
1729
  channels.socket.port2.close();
1733
1730
  this.socket.unregister(channelSenderId);
1734
1731
  }
1735
- /**
1736
- * Handles the application shutdown process.
1737
- * This method is called when all windows are closed, and it cleans up the message channels
1738
- */
1739
- async onAllWindowsClosed() {
1740
- for (const senderId of this.socket.getSenderIds()) {
1741
- this.shutdownChannel(senderId);
1742
- }
1743
- Logger.info("All windows closed, shutting down application...");
1744
- await this.app?.dispose();
1745
- if (process.platform !== "darwin") {
1746
- import_main.app.quit();
1747
- }
1748
- }
1749
- // ---
1750
- /**
1751
- * Sets the main BrowserWindow that was created early by bootstrapApplication.
1752
- * This window will be passed to IApp.onReady when start() is called.
1753
- * @param window - The BrowserWindow created during bootstrap.
1754
- */
1755
- setMainWindow(window2) {
1756
- this.mainWindow = window2;
1757
- }
1758
- /**
1759
- * Configures the NoxApp instance with the provided application class.
1760
- * This method allows you to set the application class that will handle lifecycle events.
1761
- * @param app - The application class to configure.
1762
- * @returns NoxApp instance for method chaining.
1763
- */
1764
- configure(app3) {
1765
- this.app = inject(app3);
1766
- return this;
1767
- }
1768
- /**
1769
- * Registers a middleware for the root of the application.
1770
- * This method allows you to define a middleware that will be applied to all requests
1771
- * @param middleware - The middleware class to register.
1772
- * @returns NoxApp instance for method chaining.
1773
- */
1774
- use(middleware) {
1775
- this.router.defineRootMiddleware(middleware);
1776
- return this;
1777
- }
1778
- /**
1779
- * Should be called after the bootstrapApplication function is called.
1780
- * Passes the early-created BrowserWindow (if any) to the configured IApp service.
1781
- * @returns NoxApp instance for method chaining.
1782
- */
1783
- start() {
1784
- this.app?.onReady(this.mainWindow);
1785
- return this;
1786
- }
1787
1732
  };
1788
- __name(_NoxApp, "NoxApp");
1789
- var NoxApp = _NoxApp;
1790
- NoxApp = _ts_decorate3([
1791
- Injectable("singleton"),
1792
- _ts_metadata("design:type", Function),
1793
- _ts_metadata("design:paramtypes", [
1794
- typeof Router === "undefined" ? Object : Router,
1795
- typeof NoxSocket === "undefined" ? Object : NoxSocket
1796
- ])
1733
+ __name(NoxApp, "NoxApp");
1734
+ NoxApp = __decorateClass([
1735
+ Injectable({ lifetime: "singleton", deps: [Router, NoxSocket, WindowManager] })
1797
1736
  ], NoxApp);
1798
1737
 
1799
1738
  // src/bootstrap.ts
1800
- var import_main2 = require("electron/main");
1801
- async function bootstrapApplication(rootModule, options) {
1802
- if (!getModuleMetadata(rootModule)) {
1803
- throw new Error(`Root module must be decorated with @Module`);
1804
- }
1805
- await import_main2.app.whenReady();
1806
- let mainWindow;
1807
- if (options?.window) {
1808
- mainWindow = new import_main2.BrowserWindow(options.window);
1809
- }
1810
- InjectorExplorer.processPending();
1739
+ var import_main3 = require("electron/main");
1740
+ init_app_injector();
1741
+ init_injector_explorer();
1742
+ async function bootstrapApplication(config = {}) {
1743
+ await import_main3.app.whenReady();
1744
+ const overrides = /* @__PURE__ */ new Map();
1745
+ for (const { token: token2, useValue } of config.singletons ?? []) {
1746
+ overrides.set(token2, useValue);
1747
+ RootInjector.singletons.set(token2, useValue);
1748
+ }
1749
+ InjectorExplorer.processPending(overrides);
1811
1750
  const noxApp = inject(NoxApp);
1812
- if (mainWindow) {
1813
- noxApp.setMainWindow(mainWindow);
1751
+ if (config.routes?.length) {
1752
+ for (const route of config.routes) {
1753
+ noxApp.lazy(route.path, route.load, route.guards, route.middlewares);
1754
+ }
1755
+ }
1756
+ if (config.eagerLoad?.length) {
1757
+ await noxApp.load(config.eagerLoad);
1814
1758
  }
1815
1759
  await noxApp.init();
1816
1760
  return noxApp;
1817
1761
  }
1818
1762
  __name(bootstrapApplication, "bootstrapApplication");
1819
1763
 
1820
- // src/preload-bridge.ts
1821
- var import_renderer = require("electron/renderer");
1822
- var DEFAULT_EXPOSE_NAME = "noxus";
1823
- var DEFAULT_INIT_EVENT = "init-port";
1824
- var DEFAULT_REQUEST_CHANNEL = "gimme-my-port";
1825
- var DEFAULT_RESPONSE_CHANNEL = "port";
1826
- function exposeNoxusBridge(options = {}) {
1827
- const { exposeAs = DEFAULT_EXPOSE_NAME, initMessageType = DEFAULT_INIT_EVENT, requestChannel = DEFAULT_REQUEST_CHANNEL, responseChannel = DEFAULT_RESPONSE_CHANNEL, targetWindow = window } = options;
1828
- const api = {
1829
- requestPort: /* @__PURE__ */ __name(() => {
1830
- import_renderer.ipcRenderer.send(requestChannel);
1831
- import_renderer.ipcRenderer.once(responseChannel, (event, message) => {
1832
- const ports = (event.ports ?? []).filter((port) => port !== void 0);
1833
- if (ports.length === 0) {
1834
- console.error("[Noxus] No MessagePort received from main process.");
1835
- return;
1836
- }
1837
- for (const port of ports) {
1838
- try {
1839
- port.start();
1840
- } catch (error) {
1841
- console.error("[Noxus] Failed to start MessagePort.", error);
1842
- }
1843
- }
1844
- targetWindow.postMessage({
1845
- type: initMessageType,
1846
- senderId: message?.senderId
1847
- }, "*", ports);
1848
- });
1849
- }, "requestPort")
1850
- };
1851
- import_renderer.contextBridge.exposeInMainWorld(exposeAs, api);
1852
- return api;
1853
- }
1854
- __name(exposeNoxusBridge, "exposeNoxusBridge");
1855
-
1856
- // src/renderer-events.ts
1857
- var _RendererEventRegistry = class _RendererEventRegistry {
1858
- constructor() {
1859
- __publicField(this, "listeners", /* @__PURE__ */ new Map());
1860
- }
1861
- /**
1862
- *
1863
- */
1864
- subscribe(eventName, handler) {
1865
- const normalizedEventName = eventName.trim();
1866
- if (normalizedEventName.length === 0) {
1867
- throw new Error("Renderer event name must be a non-empty string.");
1868
- }
1869
- const handlers = this.listeners.get(normalizedEventName) ?? /* @__PURE__ */ new Set();
1870
- handlers.add(handler);
1871
- this.listeners.set(normalizedEventName, handlers);
1872
- return {
1873
- unsubscribe: /* @__PURE__ */ __name(() => this.unsubscribe(normalizedEventName, handler), "unsubscribe")
1874
- };
1875
- }
1876
- /**
1877
- *
1878
- */
1879
- unsubscribe(eventName, handler) {
1880
- const handlers = this.listeners.get(eventName);
1881
- if (!handlers) {
1882
- return;
1883
- }
1884
- handlers.delete(handler);
1885
- if (handlers.size === 0) {
1886
- this.listeners.delete(eventName);
1887
- }
1888
- }
1889
- /**
1890
- *
1891
- */
1892
- clear(eventName) {
1893
- if (eventName) {
1894
- this.listeners.delete(eventName);
1895
- return;
1896
- }
1897
- this.listeners.clear();
1898
- }
1899
- /**
1900
- *
1901
- */
1902
- dispatch(message) {
1903
- const handlers = this.listeners.get(message.event);
1904
- if (!handlers || handlers.size === 0) {
1905
- return;
1906
- }
1907
- handlers.forEach((handler) => {
1908
- try {
1909
- handler(message.payload);
1910
- } catch (error) {
1911
- console.error(`[Noxus] Renderer event handler for "${message.event}" threw an error.`, error);
1912
- }
1913
- });
1914
- }
1915
- /**
1916
- *
1917
- */
1918
- tryDispatchFromMessageEvent(event) {
1919
- if (!isRendererEventMessage(event.data)) {
1920
- return false;
1921
- }
1922
- this.dispatch(event.data);
1923
- return true;
1924
- }
1925
- /**
1926
- *
1927
- */
1928
- hasHandlers(eventName) {
1929
- const handlers = this.listeners.get(eventName);
1930
- return !!handlers && handlers.size > 0;
1931
- }
1932
- };
1933
- __name(_RendererEventRegistry, "RendererEventRegistry");
1934
- var RendererEventRegistry = _RendererEventRegistry;
1764
+ // src/main.ts
1765
+ init_exceptions();
1766
+ init_controller_decorator();
1767
+ init_injectable_decorator();
1768
+ init_method_decorator();
1769
+ init_logger();
1770
+ init_forward_ref();
1771
+ init_request();
1935
1772
 
1936
- // src/renderer-client.ts
1937
- var DEFAULT_INIT_EVENT2 = "init-port";
1938
- var DEFAULT_BRIDGE_NAMES = [
1939
- "noxus",
1940
- "ipcRenderer"
1941
- ];
1942
- function defaultRequestId() {
1943
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
1944
- return crypto.randomUUID();
1945
- }
1946
- return `${Date.now().toString(16)}-${Math.floor(Math.random() * 1e8).toString(16)}`;
1947
- }
1948
- __name(defaultRequestId, "defaultRequestId");
1949
- function normalizeBridgeNames(preferred) {
1950
- const names = [];
1951
- const add = /* @__PURE__ */ __name((name) => {
1952
- if (!name) return;
1953
- if (!names.includes(name)) {
1954
- names.push(name);
1955
- }
1956
- }, "add");
1957
- if (Array.isArray(preferred)) {
1958
- for (const name of preferred) {
1959
- add(name);
1960
- }
1961
- } else {
1962
- add(preferred);
1963
- }
1964
- for (const fallback of DEFAULT_BRIDGE_NAMES) {
1965
- add(fallback);
1966
- }
1967
- return names;
1968
- }
1969
- __name(normalizeBridgeNames, "normalizeBridgeNames");
1970
- function resolveBridgeFromWindow(windowRef, preferred) {
1971
- const names = normalizeBridgeNames(preferred);
1972
- const globalRef = windowRef;
1973
- if (!globalRef) {
1974
- return null;
1975
- }
1976
- for (const name of names) {
1977
- const candidate = globalRef[name];
1978
- if (candidate && typeof candidate.requestPort === "function") {
1979
- return candidate;
1980
- }
1981
- }
1982
- return null;
1773
+ // src/routes.ts
1774
+ function defineRoutes(routes) {
1775
+ const paths = routes.map((r) => r.path.replace(/^\/+|\/+$/g, ""));
1776
+ const duplicates = paths.filter((p, i) => paths.indexOf(p) !== i);
1777
+ if (duplicates.length > 0) {
1778
+ throw new Error(
1779
+ `[Noxus] Duplicate route prefixes detected: ${[...new Set(duplicates)].map((d) => `"${d}"`).join(", ")}`
1780
+ );
1781
+ }
1782
+ return routes.map((r) => ({
1783
+ ...r,
1784
+ path: r.path.replace(/^\/+|\/+$/g, "")
1785
+ }));
1983
1786
  }
1984
- __name(resolveBridgeFromWindow, "resolveBridgeFromWindow");
1985
- var _NoxRendererClient = class _NoxRendererClient {
1986
- constructor(options = {}) {
1987
- __publicField(this, "events", new RendererEventRegistry());
1988
- __publicField(this, "pendingRequests", /* @__PURE__ */ new Map());
1989
- __publicField(this, "requestPort");
1990
- __publicField(this, "socketPort");
1991
- __publicField(this, "senderId");
1992
- __publicField(this, "bridge");
1993
- __publicField(this, "initMessageType");
1994
- __publicField(this, "windowRef");
1995
- __publicField(this, "generateRequestId");
1996
- __publicField(this, "isReady", false);
1997
- __publicField(this, "setupPromise");
1998
- __publicField(this, "setupResolve");
1999
- __publicField(this, "setupReject");
2000
- __publicField(this, "onWindowMessage", /* @__PURE__ */ __name((event) => {
2001
- if (event.data?.type !== this.initMessageType) {
2002
- return;
2003
- }
2004
- if (!Array.isArray(event.ports) || event.ports.length < 2) {
2005
- const error = new Error("[Noxus] Renderer expected two MessagePorts (request + socket).");
2006
- console.error(error);
2007
- this.setupReject?.(error);
2008
- this.resetSetupState();
2009
- return;
2010
- }
2011
- this.windowRef.removeEventListener("message", this.onWindowMessage);
2012
- this.requestPort = event.ports[0];
2013
- this.socketPort = event.ports[1];
2014
- this.senderId = event.data.senderId;
2015
- if (this.requestPort === void 0 || this.socketPort === void 0) {
2016
- const error = new Error("[Noxus] Renderer failed to receive valid MessagePorts.");
2017
- console.error(error);
2018
- this.setupReject?.(error);
2019
- this.resetSetupState();
2020
- return;
2021
- }
2022
- this.attachRequestPort(this.requestPort);
2023
- this.attachSocketPort(this.socketPort);
2024
- this.isReady = true;
2025
- this.setupResolve?.();
2026
- this.resetSetupState(true);
2027
- }, "onWindowMessage"));
2028
- __publicField(this, "onSocketMessage", /* @__PURE__ */ __name((event) => {
2029
- if (this.events.tryDispatchFromMessageEvent(event)) {
2030
- return;
2031
- }
2032
- console.warn("[Noxus] Received a socket message that is not a renderer event payload.", event.data);
2033
- }, "onSocketMessage"));
2034
- __publicField(this, "onRequestMessage", /* @__PURE__ */ __name((event) => {
2035
- if (this.events.tryDispatchFromMessageEvent(event)) {
2036
- return;
2037
- }
2038
- const response = event.data;
2039
- if (!response || typeof response.requestId !== "string") {
2040
- console.error("[Noxus] Renderer received an invalid response payload.", response);
2041
- return;
2042
- }
2043
- const pending = this.pendingRequests.get(response.requestId);
2044
- if (!pending) {
2045
- console.error(`[Noxus] No pending handler found for request ${response.requestId}.`);
2046
- return;
2047
- }
2048
- this.pendingRequests.delete(response.requestId);
2049
- this.onRequestCompleted(pending, response);
2050
- if (response.status >= 400) {
2051
- pending.reject(response);
2052
- return;
2053
- }
2054
- pending.resolve(response.body);
2055
- }, "onRequestMessage"));
2056
- this.windowRef = options.windowRef ?? window;
2057
- const resolvedBridge = options.bridge ?? resolveBridgeFromWindow(this.windowRef, options.bridgeName);
2058
- this.bridge = resolvedBridge ?? null;
2059
- this.initMessageType = options.initMessageType ?? DEFAULT_INIT_EVENT2;
2060
- this.generateRequestId = options.generateRequestId ?? defaultRequestId;
2061
- }
2062
- async setup() {
2063
- if (this.isReady) {
2064
- return Promise.resolve();
2065
- }
2066
- if (this.setupPromise) {
2067
- return this.setupPromise;
2068
- }
2069
- if (!this.bridge || typeof this.bridge.requestPort !== "function") {
2070
- throw new Error("[Noxus] Renderer bridge is missing requestPort().");
2071
- }
2072
- this.setupPromise = new Promise((resolve, reject) => {
2073
- this.setupResolve = resolve;
2074
- this.setupReject = reject;
2075
- });
2076
- this.windowRef.addEventListener("message", this.onWindowMessage);
2077
- this.bridge.requestPort();
2078
- return this.setupPromise;
2079
- }
2080
- dispose() {
2081
- this.windowRef.removeEventListener("message", this.onWindowMessage);
2082
- this.requestPort?.close();
2083
- this.socketPort?.close();
2084
- this.requestPort = void 0;
2085
- this.socketPort = void 0;
2086
- this.senderId = void 0;
2087
- this.isReady = false;
2088
- this.pendingRequests.clear();
2089
- }
2090
- async request(request) {
2091
- const senderId = this.senderId;
2092
- const requestId = this.generateRequestId();
2093
- if (senderId === void 0) {
2094
- return Promise.reject(this.createErrorResponse(requestId, "MessagePort is not available"));
2095
- }
2096
- const readinessError = this.validateReady(requestId);
2097
- if (readinessError) {
2098
- return Promise.reject(readinessError);
2099
- }
2100
- const message = {
2101
- requestId,
2102
- senderId,
2103
- ...request
2104
- };
2105
- return new Promise((resolve, reject) => {
2106
- const pending = {
2107
- resolve,
2108
- reject: /* @__PURE__ */ __name((response) => reject(response), "reject"),
2109
- request: message,
2110
- submittedAt: Date.now()
2111
- };
2112
- this.pendingRequests.set(message.requestId, pending);
2113
- this.requestPort.postMessage(message);
2114
- });
2115
- }
2116
- async batch(requests) {
2117
- return this.request({
2118
- method: "BATCH",
2119
- path: "",
2120
- body: {
2121
- requests
2122
- }
2123
- });
2124
- }
2125
- getSenderId() {
2126
- return this.senderId;
2127
- }
2128
- onRequestCompleted(pending, response) {
2129
- if (typeof console.groupCollapsed === "function") {
2130
- console.groupCollapsed(`${response.status} ${pending.request.method} /${pending.request.path}`);
2131
- }
2132
- if (response.error) {
2133
- console.error("error message:", response.error);
2134
- }
2135
- if (response.body !== void 0) {
2136
- console.info("response:", response.body);
2137
- }
2138
- console.info("request:", pending.request);
2139
- console.info(`Request duration: ${Date.now() - pending.submittedAt} ms`);
2140
- if (typeof console.groupCollapsed === "function") {
2141
- console.groupEnd();
2142
- }
2143
- }
2144
- attachRequestPort(port) {
2145
- port.onmessage = this.onRequestMessage;
2146
- port.start();
2147
- }
2148
- attachSocketPort(port) {
2149
- port.onmessage = this.onSocketMessage;
2150
- port.start();
2151
- }
2152
- validateReady(requestId) {
2153
- if (!this.isElectronEnvironment()) {
2154
- return this.createErrorResponse(requestId, "Not running in Electron environment");
2155
- }
2156
- if (!this.requestPort) {
2157
- return this.createErrorResponse(requestId, "MessagePort is not available");
2158
- }
2159
- return void 0;
2160
- }
2161
- createErrorResponse(requestId, message) {
2162
- return {
2163
- status: 500,
2164
- requestId,
2165
- error: message
2166
- };
2167
- }
2168
- resetSetupState(success = false) {
2169
- if (!success) {
2170
- this.setupPromise = void 0;
2171
- }
2172
- this.setupResolve = void 0;
2173
- this.setupReject = void 0;
2174
- }
2175
- isElectronEnvironment() {
2176
- return typeof window !== "undefined" && /Electron/.test(window.navigator.userAgent);
2177
- }
2178
- };
2179
- __name(_NoxRendererClient, "NoxRendererClient");
2180
- var NoxRendererClient = _NoxRendererClient;
1787
+ __name(defineRoutes, "defineRoutes");
2181
1788
  // Annotate the CommonJS export names for ESM import in node:
2182
1789
  0 && (module.exports = {
2183
1790
  AppInjector,
2184
- Authorize,
2185
1791
  BadGatewayException,
2186
1792
  BadRequestException,
2187
- CONTROLLER_METADATA_KEY,
2188
1793
  ConflictException,
2189
1794
  Controller,
2190
1795
  Delete,
@@ -2193,17 +1798,12 @@ var NoxRendererClient = _NoxRendererClient;
2193
1798
  GatewayTimeoutException,
2194
1799
  Get,
2195
1800
  HttpVersionNotSupportedException,
2196
- INJECTABLE_METADATA_KEY,
2197
- INJECT_METADATA_KEY,
2198
- Inject,
2199
1801
  Injectable,
2200
1802
  InsufficientStorageException,
2201
1803
  InternalServerException,
2202
1804
  Logger,
2203
1805
  LoopDetectedException,
2204
- MODULE_METADATA_KEY,
2205
1806
  MethodNotAllowedException,
2206
- Module,
2207
1807
  NetworkAuthenticationRequiredException,
2208
1808
  NetworkConnectTimeoutException,
2209
1809
  NotAcceptableException,
@@ -2211,45 +1811,45 @@ var NoxRendererClient = _NoxRendererClient;
2211
1811
  NotFoundException,
2212
1812
  NotImplementedException,
2213
1813
  NoxApp,
2214
- NoxRendererClient,
2215
1814
  NoxSocket,
2216
1815
  Patch,
2217
1816
  PaymentRequiredException,
2218
1817
  Post,
2219
1818
  Put,
2220
1819
  RENDERER_EVENT_TYPE,
2221
- ROUTE_METADATA_KEY,
2222
- RendererEventRegistry,
2223
1820
  Request,
2224
1821
  RequestTimeoutException,
2225
1822
  ResponseException,
2226
1823
  RootInjector,
2227
1824
  Router,
2228
1825
  ServiceUnavailableException,
1826
+ Token,
2229
1827
  TooManyRequestsException,
2230
1828
  UnauthorizedException,
2231
1829
  UpgradeRequiredException,
2232
- UseMiddlewares,
2233
1830
  VariantAlsoNegotiatesException,
1831
+ WindowManager,
2234
1832
  bootstrapApplication,
2235
1833
  createRendererEventMessage,
2236
- exposeNoxusBridge,
1834
+ defineRoutes,
2237
1835
  forwardRef,
2238
1836
  getControllerMetadata,
2239
- getGuardForController,
2240
- getGuardForControllerAction,
2241
- getInjectableMetadata,
2242
- getMiddlewaresForController,
2243
- getMiddlewaresForControllerAction,
2244
- getModuleMetadata,
2245
1837
  getRouteMetadata,
2246
- hasInjectableMetadata,
2247
1838
  inject,
2248
- isRendererEventMessage
1839
+ isAtomicHttpMethod,
1840
+ isRendererEventMessage,
1841
+ token
2249
1842
  });
2250
1843
  /**
2251
1844
  * @copyright 2025 NoxFly
2252
1845
  * @license MIT
2253
1846
  * @author NoxFly
2254
1847
  */
1848
+ /**
1849
+ * @copyright 2025 NoxFly
1850
+ * @license MIT
1851
+ * @author NoxFly
1852
+ *
1853
+ * Entry point for Electron main-process consumers.
1854
+ */
2255
1855
  //# sourceMappingURL=main.js.map