@forinda/kickjs 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,1099 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var index_exports = {};
33
+ __export(index_exports, {
34
+ AppDiagnostics: () => AppDiagnostics,
35
+ AppError: () => AppError,
36
+ BaseController: () => BaseController,
37
+ Controller: () => Controller,
38
+ Delete: () => Delete,
39
+ Get: () => Get,
40
+ Inject: () => Inject,
41
+ Injectable: () => Injectable,
42
+ MultiInject: () => MultiInject,
43
+ Named: () => Named,
44
+ Optional: () => Optional,
45
+ Patch: () => Patch,
46
+ Post: () => Post,
47
+ Put: () => Put,
48
+ RequestTracker: () => RequestTracker,
49
+ TYPES: () => TYPES,
50
+ Tagged: () => Tagged,
51
+ Unmanaged: () => Unmanaged,
52
+ bootstrap: () => bootstrap,
53
+ configureApp: () => configureApp,
54
+ createApp: () => createApp,
55
+ createError: () => createError,
56
+ getAppConfig: () => getAppConfig,
57
+ isAppError: () => isAppError,
58
+ listRegisteredControllers: () => listRegisteredControllers,
59
+ registerController: () => registerController,
60
+ resetAppConfig: () => resetAppConfig,
61
+ resetControllerRegistry: () => resetControllerRegistry,
62
+ resolveConfig: () => resolveConfig
63
+ });
64
+ module.exports = __toCommonJS(index_exports);
65
+
66
+ // src/decorators/http.ts
67
+ var import_reflect_metadata = require("reflect-metadata");
68
+ var CONTROLLER_KEY = Symbol("core:controller");
69
+ var ROUTES_KEY = Symbol("core:routes");
70
+ var controllerRegistry = /* @__PURE__ */ new Set();
71
+ function Controller(pathOrOptions = "/") {
72
+ const options = normalizeControllerOptions(pathOrOptions);
73
+ return function(target) {
74
+ Reflect.defineMetadata(CONTROLLER_KEY, {
75
+ basePath: options.path,
76
+ tags: options.tags
77
+ }, target);
78
+ if (!Reflect.hasMetadata(ROUTES_KEY, target)) {
79
+ Reflect.defineMetadata(ROUTES_KEY, [], target);
80
+ }
81
+ if (options.autoRegister !== false) {
82
+ controllerRegistry.add(target);
83
+ }
84
+ };
85
+ }
86
+ __name(Controller, "Controller");
87
+ function Get(path, ...middlewares) {
88
+ return createRouteDecorator("get")(path, ...middlewares);
89
+ }
90
+ __name(Get, "Get");
91
+ function Post(path, ...middlewares) {
92
+ return createRouteDecorator("post")(path, ...middlewares);
93
+ }
94
+ __name(Post, "Post");
95
+ function Put(path, ...middlewares) {
96
+ return createRouteDecorator("put")(path, ...middlewares);
97
+ }
98
+ __name(Put, "Put");
99
+ function Patch(path, ...middlewares) {
100
+ return createRouteDecorator("patch")(path, ...middlewares);
101
+ }
102
+ __name(Patch, "Patch");
103
+ function Delete(path, ...middlewares) {
104
+ return createRouteDecorator("delete")(path, ...middlewares);
105
+ }
106
+ __name(Delete, "Delete");
107
+ function listRegisteredControllers() {
108
+ return Array.from(controllerRegistry);
109
+ }
110
+ __name(listRegisteredControllers, "listRegisteredControllers");
111
+ function registerController(controller) {
112
+ controllerRegistry.add(controller);
113
+ }
114
+ __name(registerController, "registerController");
115
+ function resetControllerRegistry() {
116
+ controllerRegistry.clear();
117
+ }
118
+ __name(resetControllerRegistry, "resetControllerRegistry");
119
+ var DecoratorMetadata = {
120
+ CONTROLLER_KEY,
121
+ ROUTES_KEY
122
+ };
123
+ function createRouteDecorator(method) {
124
+ return (pathOrOptions, ...middlewares) => function(target, propertyKey) {
125
+ const controller = target.constructor;
126
+ const routes = Reflect.getMetadata(ROUTES_KEY, controller) ?? [];
127
+ const normalized = normalizeRouteOptions(pathOrOptions, middlewares);
128
+ routes.push({
129
+ method,
130
+ path: normalized.path,
131
+ propertyKey,
132
+ middlewares: normalized.middlewares,
133
+ validation: normalized.validation
134
+ });
135
+ Reflect.defineMetadata(ROUTES_KEY, routes, controller);
136
+ };
137
+ }
138
+ __name(createRouteDecorator, "createRouteDecorator");
139
+ function normalizeControllerOptions(pathOrOptions) {
140
+ if (typeof pathOrOptions === "string") {
141
+ return {
142
+ path: normalizePath(pathOrOptions),
143
+ autoRegister: true,
144
+ tags: []
145
+ };
146
+ }
147
+ return {
148
+ path: normalizePath(pathOrOptions.path ?? "/"),
149
+ autoRegister: pathOrOptions.autoRegister ?? true,
150
+ tags: pathOrOptions.tags ?? []
151
+ };
152
+ }
153
+ __name(normalizeControllerOptions, "normalizeControllerOptions");
154
+ function normalizeRouteOptions(pathOrOptions, extraMiddlewares) {
155
+ const base = normalizeRouteOptionObject(pathOrOptions);
156
+ const middlewares = [
157
+ ...base.middlewares ?? [],
158
+ ...extraMiddlewares
159
+ ];
160
+ return {
161
+ path: normalizeRoutePath(base.path ?? "/"),
162
+ middlewares,
163
+ validation: base.validate
164
+ };
165
+ }
166
+ __name(normalizeRouteOptions, "normalizeRouteOptions");
167
+ function normalizeRouteOptionObject(pathOrOptions) {
168
+ if (typeof pathOrOptions === "string") {
169
+ return {
170
+ path: pathOrOptions
171
+ };
172
+ }
173
+ if (typeof pathOrOptions === "object" && pathOrOptions !== null) {
174
+ return {
175
+ ...pathOrOptions
176
+ };
177
+ }
178
+ return {};
179
+ }
180
+ __name(normalizeRouteOptionObject, "normalizeRouteOptionObject");
181
+ function normalizePath(path) {
182
+ if (!path || path === "/") {
183
+ return "/";
184
+ }
185
+ const withLeading = path.startsWith("/") ? path : `/${path}`;
186
+ return withLeading.endsWith("/") && withLeading !== "/" ? withLeading.slice(0, -1) : withLeading;
187
+ }
188
+ __name(normalizePath, "normalizePath");
189
+ function normalizeRoutePath(path) {
190
+ if (!path || path === "/") {
191
+ return "";
192
+ }
193
+ const cleaned = path.startsWith("/") ? path.slice(1) : path;
194
+ return cleaned.endsWith("/") ? cleaned.slice(0, -1) : cleaned;
195
+ }
196
+ __name(normalizeRoutePath, "normalizeRoutePath");
197
+
198
+ // src/utils/errors.ts
199
+ var AppError = class extends Error {
200
+ static {
201
+ __name(this, "AppError");
202
+ }
203
+ code;
204
+ status;
205
+ details;
206
+ constructor(code, message, options = {}) {
207
+ super(message);
208
+ this.code = code;
209
+ this.status = options.status;
210
+ this.details = options.details;
211
+ if (options.cause) {
212
+ this.cause = options.cause;
213
+ }
214
+ this.name = "AppError";
215
+ }
216
+ };
217
+ function createError(code, message, options = {}) {
218
+ return new AppError(code, message, options);
219
+ }
220
+ __name(createError, "createError");
221
+ function isAppError(error) {
222
+ return error instanceof AppError;
223
+ }
224
+ __name(isAppError, "isAppError");
225
+
226
+ // src/core/base-controller.ts
227
+ var BaseController = class {
228
+ static {
229
+ __name(this, "BaseController");
230
+ }
231
+ requestTracker;
232
+ constructor(requestTracker) {
233
+ this.requestTracker = requestTracker;
234
+ }
235
+ ok(res, payload) {
236
+ return this.respond(res, 200, payload);
237
+ }
238
+ created(res, payload) {
239
+ return this.respond(res, 201, payload);
240
+ }
241
+ accepted(res, payload) {
242
+ return this.respond(res, 202, payload);
243
+ }
244
+ noContent(res) {
245
+ return this.respond(res, 204);
246
+ }
247
+ respond(res, status, payload) {
248
+ this.requestTracker.recordResponse(res, status, payload);
249
+ if (payload === void 0) {
250
+ res.status(status).end();
251
+ } else {
252
+ res.status(status).json(payload);
253
+ }
254
+ return res;
255
+ }
256
+ logDebug(res, message, metadata) {
257
+ this.requestTracker.log(res, `[${this.controllerId()}] ${message}`, "debug", metadata);
258
+ }
259
+ logInfo(res, message, metadata) {
260
+ this.requestTracker.log(res, `[${this.controllerId()}] ${message}`, "info", metadata);
261
+ }
262
+ logWarn(res, message, metadata) {
263
+ this.requestTracker.log(res, `[${this.controllerId()}] ${message}`, "warn", metadata);
264
+ }
265
+ logError(res, message, metadata) {
266
+ this.requestTracker.log(res, `[${this.controllerId()}] ${message}`, "error", metadata);
267
+ }
268
+ mergeRequestMetadata(res, patch) {
269
+ const current = this.requestTracker.get(res)?.state.metadata[this.controllerId()];
270
+ const currentRecord = typeof current === "object" && current !== null ? current : {};
271
+ const namespacedPatch = {
272
+ [this.controllerId()]: {
273
+ ...currentRecord,
274
+ ...patch
275
+ }
276
+ };
277
+ this.requestTracker.mergeMetadata(res, namespacedPatch);
278
+ }
279
+ getRequestState(res) {
280
+ return this.requestTracker.get(res)?.state;
281
+ }
282
+ fail(code, message, options) {
283
+ throw createError(code, message, options);
284
+ }
285
+ };
286
+
287
+ // src/core/request-tracker.ts
288
+ var import_node_crypto2 = require("crypto");
289
+
290
+ // src/utils/injection.ts
291
+ var import_inversify = require("inversify");
292
+ function Injectable() {
293
+ return (0, import_inversify.injectable)();
294
+ }
295
+ __name(Injectable, "Injectable");
296
+ function Inject(identifier) {
297
+ return (0, import_inversify.inject)(identifier);
298
+ }
299
+ __name(Inject, "Inject");
300
+ function Optional() {
301
+ return (0, import_inversify.optional)();
302
+ }
303
+ __name(Optional, "Optional");
304
+ function MultiInject(identifier) {
305
+ return (0, import_inversify.multiInject)(identifier);
306
+ }
307
+ __name(MultiInject, "MultiInject");
308
+ function Named(name) {
309
+ return (0, import_inversify.named)(name);
310
+ }
311
+ __name(Named, "Named");
312
+ function Tagged(metadataKey, metadataValue) {
313
+ return (0, import_inversify.tagged)(metadataKey, metadataValue);
314
+ }
315
+ __name(Tagged, "Tagged");
316
+ function Unmanaged() {
317
+ return (0, import_inversify.unmanaged)();
318
+ }
319
+ __name(Unmanaged, "Unmanaged");
320
+
321
+ // src/utils/reactive.ts
322
+ var import_node_crypto = require("crypto");
323
+ var ReactiveRegistry2 = class {
324
+ static {
325
+ __name(this, "ReactiveRegistry");
326
+ }
327
+ stores = /* @__PURE__ */ new Map();
328
+ register(store) {
329
+ this.stores.set(store.id, store);
330
+ }
331
+ unregister(id) {
332
+ this.stores.delete(id);
333
+ }
334
+ get(id) {
335
+ return this.stores.get(id);
336
+ }
337
+ list() {
338
+ return Array.from(this.stores.values()).map((store) => ({
339
+ id: store.id,
340
+ label: store.label,
341
+ snapshot: store.snapshot(),
342
+ history: store.history()
343
+ }));
344
+ }
345
+ };
346
+ function createReactive(initial, options = {}) {
347
+ const listeners = /* @__PURE__ */ new Set();
348
+ const target = {
349
+ ...initial
350
+ };
351
+ const history = [];
352
+ const historyEnabled = options.trackHistory ?? true;
353
+ const maxHistory = options.maxHistory ?? 100;
354
+ const reactiveId = options.id ?? (0, import_node_crypto.randomUUID)();
355
+ const proxy = new Proxy(target, {
356
+ set(current, prop, value) {
357
+ if (typeof prop === "symbol") {
358
+ return Reflect.set(current, prop, value);
359
+ }
360
+ const typedProp = prop;
361
+ const previous = current[typedProp];
362
+ const didChange = previous !== value;
363
+ const result = Reflect.set(current, typedProp, value);
364
+ if (didChange) {
365
+ const change = {
366
+ property: typedProp,
367
+ value,
368
+ previous,
369
+ timestamp: Date.now()
370
+ };
371
+ if (historyEnabled) {
372
+ history.push(change);
373
+ if (history.length > maxHistory) {
374
+ history.shift();
375
+ }
376
+ }
377
+ listeners.forEach((listener) => listener(proxy, change));
378
+ }
379
+ return result;
380
+ }
381
+ });
382
+ const store = {
383
+ id: reactiveId,
384
+ label: options.label,
385
+ state: proxy,
386
+ watch(watcher) {
387
+ listeners.add(watcher);
388
+ return () => listeners.delete(watcher);
389
+ },
390
+ snapshot() {
391
+ return structuredClone(target);
392
+ },
393
+ history() {
394
+ return historyEnabled ? [
395
+ ...history
396
+ ] : [];
397
+ }
398
+ };
399
+ options.registry?.register(store);
400
+ return store;
401
+ }
402
+ __name(createReactive, "createReactive");
403
+
404
+ // src/shared/types.ts
405
+ var TYPES = {
406
+ AppState: Symbol.for("kick:AppState"),
407
+ Config: Symbol.for("kick:Config"),
408
+ Diagnostics: Symbol.for("kick:Diagnostics"),
409
+ Logger: Symbol.for("kick:Logger"),
410
+ StateRegistry: Symbol.for("kick:StateRegistry"),
411
+ RequestTracker: Symbol.for("kick:RequestTracker")
412
+ };
413
+
414
+ // src/core/request-tracker.ts
415
+ function _ts_decorate(decorators, target, key, desc) {
416
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
417
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
418
+ 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;
419
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
420
+ }
421
+ __name(_ts_decorate, "_ts_decorate");
422
+ function _ts_metadata(k, v) {
423
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
424
+ }
425
+ __name(_ts_metadata, "_ts_metadata");
426
+ function _ts_param(paramIndex, decorator) {
427
+ return function(target, key) {
428
+ decorator(target, key, paramIndex);
429
+ };
430
+ }
431
+ __name(_ts_param, "_ts_param");
432
+ var RequestTracker = class {
433
+ static {
434
+ __name(this, "RequestTracker");
435
+ }
436
+ registry;
437
+ config;
438
+ logger;
439
+ constructor(registry, config, logger) {
440
+ this.registry = registry;
441
+ this.config = config;
442
+ this.logger = logger;
443
+ }
444
+ middleware() {
445
+ return (req, res, next) => {
446
+ const id = (0, import_node_crypto2.randomUUID)();
447
+ const requestState = createReactive({
448
+ id,
449
+ method: req.method,
450
+ path: req.originalUrl ?? req.url,
451
+ startedAt: Date.now(),
452
+ logs: [],
453
+ metadata: {}
454
+ }, {
455
+ id,
456
+ label: `request:${req.method} ${req.originalUrl ?? req.url}`,
457
+ registry: this.registry,
458
+ trackHistory: this.config.telemetry.trackReactiveHistory,
459
+ maxHistory: this.config.telemetry.requestHistoryLimit
460
+ });
461
+ res.locals.requestState = requestState;
462
+ req.on("error", (error) => {
463
+ this.recordError(res, error);
464
+ });
465
+ res.on("finish", () => {
466
+ this.finalise(res);
467
+ });
468
+ res.on("close", () => {
469
+ this.finalise(res);
470
+ });
471
+ res.on("error", (error) => {
472
+ this.recordError(res, error);
473
+ });
474
+ next();
475
+ };
476
+ }
477
+ get(res) {
478
+ return res.locals.requestState;
479
+ }
480
+ log(res, message, level = "info", metadata) {
481
+ const store = this.get(res);
482
+ if (!store) {
483
+ return;
484
+ }
485
+ const entry = {
486
+ timestamp: Date.now(),
487
+ level,
488
+ message,
489
+ metadata
490
+ };
491
+ store.state.logs = [
492
+ ...store.state.logs,
493
+ entry
494
+ ];
495
+ this.dispatchLog(level, `[${store.state.method} ${store.state.path}] ${message}`, {
496
+ requestId: store.state.id,
497
+ ...metadata
498
+ });
499
+ }
500
+ mergeMetadata(res, patch) {
501
+ const store = this.get(res);
502
+ if (!store) {
503
+ return;
504
+ }
505
+ store.state.metadata = {
506
+ ...store.state.metadata,
507
+ ...patch
508
+ };
509
+ }
510
+ recordResponse(res, status, payload) {
511
+ const store = this.get(res);
512
+ if (!store) {
513
+ return;
514
+ }
515
+ store.state.status = status;
516
+ store.state.response = payload;
517
+ }
518
+ recordError(res, error) {
519
+ const store = this.get(res);
520
+ if (!store) {
521
+ return;
522
+ }
523
+ const errorMessage = error instanceof Error ? error.message : String(error);
524
+ store.state.error = errorMessage;
525
+ if (isAppError(error)) {
526
+ store.state.errorCode = error.code;
527
+ this.mergeMetadata(res, {
528
+ errorCode: error.code,
529
+ errorDetails: error.details
530
+ });
531
+ }
532
+ this.log(res, errorMessage, "error", {
533
+ errorCode: isAppError(error) ? error.code : void 0
534
+ });
535
+ }
536
+ finalise(res) {
537
+ const store = this.get(res);
538
+ if (!store) {
539
+ return;
540
+ }
541
+ store.state.status = res.statusCode;
542
+ store.state.endedAt = Date.now();
543
+ store.state.durationMs = store.state.endedAt - store.state.startedAt;
544
+ this.dispatchLog("debug", `Request completed with ${res.statusCode}`, {
545
+ requestId: store.state.id,
546
+ durationMs: store.state.durationMs
547
+ });
548
+ }
549
+ dispatchLog(level, message, metadata) {
550
+ switch (level) {
551
+ case "debug":
552
+ this.logger.debug(message, metadata);
553
+ break;
554
+ case "info":
555
+ this.logger.info(message, metadata);
556
+ break;
557
+ case "warn":
558
+ this.logger.warn(message, metadata);
559
+ break;
560
+ case "error":
561
+ this.logger.error(message, metadata);
562
+ break;
563
+ }
564
+ }
565
+ };
566
+ RequestTracker = _ts_decorate([
567
+ Injectable(),
568
+ _ts_param(0, Inject(TYPES.StateRegistry)),
569
+ _ts_param(1, Inject(TYPES.Config)),
570
+ _ts_param(2, Inject(TYPES.Logger)),
571
+ _ts_metadata("design:type", Function),
572
+ _ts_metadata("design:paramtypes", [
573
+ typeof ReactiveRegistry === "undefined" ? Object : ReactiveRegistry,
574
+ typeof ResolvedAppConfig === "undefined" ? Object : ResolvedAppConfig,
575
+ typeof AppLogger === "undefined" ? Object : AppLogger
576
+ ])
577
+ ], RequestTracker);
578
+
579
+ // src/core/diagnostics.ts
580
+ function _ts_decorate2(decorators, target, key, desc) {
581
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
582
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
583
+ 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;
584
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
585
+ }
586
+ __name(_ts_decorate2, "_ts_decorate");
587
+ function _ts_metadata2(k, v) {
588
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
589
+ }
590
+ __name(_ts_metadata2, "_ts_metadata");
591
+ function _ts_param2(paramIndex, decorator) {
592
+ return function(target, key) {
593
+ decorator(target, key, paramIndex);
594
+ };
595
+ }
596
+ __name(_ts_param2, "_ts_param");
597
+ var AppDiagnostics = class {
598
+ static {
599
+ __name(this, "AppDiagnostics");
600
+ }
601
+ registry;
602
+ config;
603
+ constructor(registry, config) {
604
+ this.registry = registry;
605
+ this.config = config;
606
+ }
607
+ settings() {
608
+ return this.config;
609
+ }
610
+ stores() {
611
+ return this.registry.list().map((entry) => ({
612
+ id: entry.id,
613
+ label: entry.label,
614
+ snapshot: entry.snapshot,
615
+ history: entry.history
616
+ }));
617
+ }
618
+ requests() {
619
+ return this.registry.list().filter((entry) => entry.label?.startsWith("request:")).map((entry) => entry.snapshot);
620
+ }
621
+ };
622
+ AppDiagnostics = _ts_decorate2([
623
+ Injectable(),
624
+ _ts_param2(0, Inject(TYPES.StateRegistry)),
625
+ _ts_param2(1, Inject(TYPES.Config)),
626
+ _ts_metadata2("design:type", Function),
627
+ _ts_metadata2("design:paramtypes", [
628
+ typeof ReactiveRegistry2 === "undefined" ? Object : ReactiveRegistry2,
629
+ typeof ResolvedAppConfig === "undefined" ? Object : ResolvedAppConfig
630
+ ])
631
+ ], AppDiagnostics);
632
+
633
+ // src/core/application.ts
634
+ var import_reflect_metadata3 = require("reflect-metadata");
635
+ var import_express = __toESM(require("express"));
636
+
637
+ // src/core/server.ts
638
+ var import_node_crypto3 = require("crypto");
639
+ var import_reflect_metadata2 = require("reflect-metadata");
640
+ var appRouteRegistry = /* @__PURE__ */ new WeakMap();
641
+ function registerControllers(app, container, options = {}) {
642
+ const controllers = options.controllers ?? listRegisteredControllers();
643
+ const prefix = options.prefix ?? "";
644
+ const requestTracker = container.get(TYPES.RequestTracker);
645
+ controllers.forEach((ControllerClass) => {
646
+ ensureInjectable(ControllerClass);
647
+ const controllerMetadata = Reflect.getMetadata(DecoratorMetadata.CONTROLLER_KEY, ControllerClass);
648
+ if (!controllerMetadata) {
649
+ return;
650
+ }
651
+ if (!container.isBound(ControllerClass)) {
652
+ container.bind(ControllerClass).toSelf().inSingletonScope();
653
+ }
654
+ const instance = container.get(ControllerClass);
655
+ const routes = Reflect.getMetadata(DecoratorMetadata.ROUTES_KEY, ControllerClass) ?? [];
656
+ routes.forEach((route) => {
657
+ const handler = instance[route.propertyKey];
658
+ if (typeof handler !== "function") {
659
+ throw new Error(`Route handler ${String(route.propertyKey)} on ${ControllerClass.name} is not a function`);
660
+ }
661
+ const fullPath = buildRoutePath(prefix, controllerMetadata.basePath, route.path);
662
+ const routeHash = registerRouteSignature(app, route.method, fullPath, ControllerClass.name, route.propertyKey);
663
+ const boundHandler = handler.bind(instance);
664
+ const validationMiddleware = buildValidationMiddleware(route.validation);
665
+ const routeMetadataMiddleware = /* @__PURE__ */ __name((_req, res, next) => {
666
+ requestTracker.mergeMetadata(res, {
667
+ route: fullPath,
668
+ method: route.method.toUpperCase(),
669
+ routeHash
670
+ });
671
+ next();
672
+ }, "routeMetadataMiddleware");
673
+ const pipeline = [
674
+ routeMetadataMiddleware,
675
+ ...validationMiddleware,
676
+ ...route.middlewares
677
+ ];
678
+ app[route.method](fullPath, ...pipeline, async (req, res, next) => {
679
+ try {
680
+ const result = await Promise.resolve(boundHandler(req, res, next));
681
+ if (result !== void 0 && !res.headersSent) {
682
+ res.json(result);
683
+ }
684
+ } catch (error) {
685
+ next(error);
686
+ }
687
+ });
688
+ });
689
+ });
690
+ }
691
+ __name(registerControllers, "registerControllers");
692
+ function ensureInjectable(constructor) {
693
+ if (!Reflect.hasOwnMetadata("inversify:paramtypes", constructor)) {
694
+ Injectable()(constructor);
695
+ }
696
+ }
697
+ __name(ensureInjectable, "ensureInjectable");
698
+ function buildRoutePath(prefix, basePath, routePath) {
699
+ const segments = [
700
+ ...toSegments(prefix),
701
+ ...toSegments(basePath),
702
+ ...toSegments(routePath)
703
+ ];
704
+ if (segments.length === 0) {
705
+ return "/";
706
+ }
707
+ return `/${segments.join("/")}`;
708
+ }
709
+ __name(buildRoutePath, "buildRoutePath");
710
+ function toSegments(segment) {
711
+ if (!segment || segment === "/") {
712
+ return [];
713
+ }
714
+ const trimmed = segment.replace(/^\/+|\/+$/g, "");
715
+ return trimmed ? [
716
+ trimmed
717
+ ] : [];
718
+ }
719
+ __name(toSegments, "toSegments");
720
+ function registerRouteSignature(app, method, path, controllerName, propertyKey) {
721
+ let registry = appRouteRegistry.get(app);
722
+ if (!registry) {
723
+ registry = /* @__PURE__ */ new Set();
724
+ appRouteRegistry.set(app, registry);
725
+ }
726
+ const normalized = `${method.toLowerCase()}:${path.toLowerCase()}`;
727
+ const hash = (0, import_node_crypto3.createHash)("sha256").update(normalized).digest("hex");
728
+ if (registry.has(hash)) {
729
+ throw createError("ROUTE_CONFLICT", `Duplicate route detected for [${method.toUpperCase()}] ${path}`, {
730
+ details: {
731
+ controller: controllerName,
732
+ handler: String(propertyKey)
733
+ }
734
+ });
735
+ }
736
+ registry.add(hash);
737
+ return hash;
738
+ }
739
+ __name(registerRouteSignature, "registerRouteSignature");
740
+ function buildValidationMiddleware(validation) {
741
+ if (!validation) {
742
+ return [];
743
+ }
744
+ const middleware = /* @__PURE__ */ __name((req, _res, next) => {
745
+ try {
746
+ if (validation.params) {
747
+ req.params = runSchema(validation.params, req.params, "params");
748
+ }
749
+ if (validation.query) {
750
+ req.query = runSchema(validation.query, req.query, "query");
751
+ }
752
+ if (validation.body) {
753
+ req.body = runSchema(validation.body, req.body, "body");
754
+ }
755
+ next();
756
+ } catch (error) {
757
+ next(error);
758
+ }
759
+ }, "middleware");
760
+ return [
761
+ middleware
762
+ ];
763
+ }
764
+ __name(buildValidationMiddleware, "buildValidationMiddleware");
765
+ function runSchema(schema, value, target) {
766
+ if (isZodSchema(schema)) {
767
+ if (typeof schema.safeParse === "function") {
768
+ const result = schema.safeParse(value);
769
+ if (!result.success) {
770
+ const issues = Array.isArray(result.error?.issues) ? result.error.issues.map((issue) => issue.message) : [
771
+ result.error.message
772
+ ].filter(Boolean);
773
+ throw validationError(target, issues);
774
+ }
775
+ return result.data;
776
+ }
777
+ try {
778
+ return schema.parse(value);
779
+ } catch (error) {
780
+ const issues = extractErrorMessages(error);
781
+ throw validationError(target, issues);
782
+ }
783
+ }
784
+ if (isJoiSchema(schema)) {
785
+ const { error, value: validated } = schema.validate(value, {
786
+ abortEarly: false,
787
+ stripUnknown: true
788
+ });
789
+ if (error) {
790
+ throw validationError(target, error.details?.map((detail) => detail.message));
791
+ }
792
+ return validated;
793
+ }
794
+ throw createError("VALIDATION_UNSUPPORTED", "Unsupported validation schema provided", {
795
+ details: {
796
+ target
797
+ }
798
+ });
799
+ }
800
+ __name(runSchema, "runSchema");
801
+ function isZodSchema(schema) {
802
+ if (typeof schema !== "object" || schema === null) {
803
+ return false;
804
+ }
805
+ return typeof schema.safeParse === "function" || typeof schema.parse === "function";
806
+ }
807
+ __name(isZodSchema, "isZodSchema");
808
+ function isJoiSchema(schema) {
809
+ if (typeof schema !== "object" || schema === null) {
810
+ return false;
811
+ }
812
+ return typeof schema.validate === "function";
813
+ }
814
+ __name(isJoiSchema, "isJoiSchema");
815
+ function validationError(target, issues) {
816
+ return createError("VALIDATION_ERROR", `Invalid ${target}`, {
817
+ status: 400,
818
+ details: {
819
+ target,
820
+ issues: issues?.filter((issue) => Boolean(issue))
821
+ }
822
+ });
823
+ }
824
+ __name(validationError, "validationError");
825
+ function extractErrorMessages(error) {
826
+ if (!error) {
827
+ return [];
828
+ }
829
+ if (Array.isArray(error.issues)) {
830
+ return error.issues.map((issue) => issue.message);
831
+ }
832
+ if (error instanceof Error && error.message) {
833
+ return [
834
+ error.message
835
+ ];
836
+ }
837
+ return [
838
+ String(error)
839
+ ];
840
+ }
841
+ __name(extractErrorMessages, "extractErrorMessages");
842
+
843
+ // src/infrastructure/container.ts
844
+ var import_inversify2 = require("inversify");
845
+
846
+ // src/utils/logger.ts
847
+ var LEVEL_WEIGHT = {
848
+ debug: 10,
849
+ info: 20,
850
+ warn: 30,
851
+ error: 40
852
+ };
853
+ var ConsoleLogger = class {
854
+ static {
855
+ __name(this, "ConsoleLogger");
856
+ }
857
+ level;
858
+ constructor(level = "info") {
859
+ this.level = level;
860
+ }
861
+ debug(message, metadata) {
862
+ this.log("debug", message, metadata);
863
+ }
864
+ info(message, metadata) {
865
+ this.log("info", message, metadata);
866
+ }
867
+ warn(message, metadata) {
868
+ this.log("warn", message, metadata);
869
+ }
870
+ error(message, metadata) {
871
+ this.log("error", message, metadata);
872
+ }
873
+ log(level, message, metadata) {
874
+ if (!this.shouldLog(level)) {
875
+ return;
876
+ }
877
+ const payload = metadata ? [
878
+ message,
879
+ metadata
880
+ ] : [
881
+ message
882
+ ];
883
+ switch (level) {
884
+ case "debug":
885
+ console.debug(...payload);
886
+ break;
887
+ case "info":
888
+ console.info(...payload);
889
+ break;
890
+ case "warn":
891
+ console.warn(...payload);
892
+ break;
893
+ case "error":
894
+ console.error(...payload);
895
+ break;
896
+ }
897
+ }
898
+ shouldLog(level) {
899
+ return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[this.level];
900
+ }
901
+ };
902
+ function createLogger(config = {}) {
903
+ return new ConsoleLogger(config.level);
904
+ }
905
+ __name(createLogger, "createLogger");
906
+
907
+ // src/infrastructure/container.ts
908
+ function buildContainer(resolvedConfig) {
909
+ const container = new import_inversify2.Container({
910
+ defaultScope: "Singleton"
911
+ });
912
+ const registry = new ReactiveRegistry2();
913
+ container.bind(TYPES.StateRegistry).toConstantValue(registry);
914
+ container.bind(TYPES.Config).toConstantValue(resolvedConfig);
915
+ container.bind(TYPES.Logger).toConstantValue(createLogger(resolvedConfig.logging));
916
+ const appState = createReactive({
917
+ bootedAt: Date.now(),
918
+ metadata: {}
919
+ }, {
920
+ id: "app:state",
921
+ label: "application:state",
922
+ registry,
923
+ trackHistory: resolvedConfig.telemetry.trackReactiveHistory,
924
+ maxHistory: resolvedConfig.telemetry.requestHistoryLimit
925
+ });
926
+ container.bind(TYPES.AppState).toConstantValue(appState);
927
+ container.bind(TYPES.RequestTracker).to(RequestTracker).inSingletonScope();
928
+ container.bind(TYPES.Diagnostics).to(AppDiagnostics).inSingletonScope();
929
+ return container;
930
+ }
931
+ __name(buildContainer, "buildContainer");
932
+
933
+ // src/shared/config.ts
934
+ var DEFAULT_CONFIG = {
935
+ prefix: "",
936
+ healthEndpoint: "/health",
937
+ logging: {
938
+ level: "info"
939
+ },
940
+ telemetry: {
941
+ trackReactiveHistory: true,
942
+ requestHistoryLimit: 250
943
+ }
944
+ };
945
+ var currentConfig = {
946
+ ...DEFAULT_CONFIG
947
+ };
948
+ function configureApp(config) {
949
+ currentConfig = mergeConfig(currentConfig, config);
950
+ }
951
+ __name(configureApp, "configureApp");
952
+ function getAppConfig() {
953
+ return currentConfig;
954
+ }
955
+ __name(getAppConfig, "getAppConfig");
956
+ function resolveConfig(overrides) {
957
+ if (!overrides) {
958
+ return currentConfig;
959
+ }
960
+ return mergeConfig(currentConfig, overrides);
961
+ }
962
+ __name(resolveConfig, "resolveConfig");
963
+ function resetAppConfig() {
964
+ currentConfig = {
965
+ ...DEFAULT_CONFIG
966
+ };
967
+ }
968
+ __name(resetAppConfig, "resetAppConfig");
969
+ function mergeConfig(base, overrides) {
970
+ return {
971
+ prefix: overrides.prefix ?? base.prefix,
972
+ healthEndpoint: overrides.healthEndpoint ?? base.healthEndpoint,
973
+ logging: {
974
+ level: overrides.logging?.level ?? base.logging.level
975
+ },
976
+ telemetry: {
977
+ trackReactiveHistory: overrides.telemetry?.trackReactiveHistory ?? base.telemetry.trackReactiveHistory,
978
+ requestHistoryLimit: overrides.telemetry?.requestHistoryLimit ?? base.telemetry.requestHistoryLimit
979
+ }
980
+ };
981
+ }
982
+ __name(mergeConfig, "mergeConfig");
983
+
984
+ // src/core/application.ts
985
+ function createApp(options = {}) {
986
+ const config = resolveConfig(options.config);
987
+ const container = options.container ?? buildContainer(config);
988
+ options.configureContainer?.(container);
989
+ const app = (0, import_express.default)();
990
+ const requestTracker = container.get(TYPES.RequestTracker);
991
+ const diagnostics = container.get(TYPES.Diagnostics);
992
+ app.use(import_express.default.json());
993
+ options.additionalMiddleware?.forEach((middleware) => {
994
+ app.use(middleware);
995
+ });
996
+ app.use(requestTracker.middleware());
997
+ registerControllers(app, container, {
998
+ controllers: options.controllers,
999
+ prefix: config.prefix
1000
+ });
1001
+ if (config.healthEndpoint !== false) {
1002
+ app.get(config.healthEndpoint, (_req, res) => {
1003
+ res.json({
1004
+ status: "ok"
1005
+ });
1006
+ });
1007
+ }
1008
+ app.use((err, _req, res, _next) => {
1009
+ const appError = isAppError(err) ? err : createError("INTERNAL_ERROR", err instanceof Error ? err.message : "Unexpected error", {
1010
+ cause: err,
1011
+ status: 500
1012
+ });
1013
+ if (err instanceof Error && err.stack) {
1014
+ requestTracker.mergeMetadata(res, {
1015
+ errorStack: err.stack
1016
+ });
1017
+ }
1018
+ requestTracker.recordError(res, appError);
1019
+ const status = Number.isFinite(appError.status) ? Number(appError.status) : 500;
1020
+ const payload = {
1021
+ error: {
1022
+ code: appError.code,
1023
+ message: appError.message
1024
+ }
1025
+ };
1026
+ if (appError.details) {
1027
+ payload.error.details = appError.details;
1028
+ }
1029
+ requestTracker.recordResponse(res, status, payload);
1030
+ if (!res.headersSent) {
1031
+ res.status(status).json(payload);
1032
+ }
1033
+ });
1034
+ return {
1035
+ app,
1036
+ container,
1037
+ requestTracker,
1038
+ diagnostics,
1039
+ config
1040
+ };
1041
+ }
1042
+ __name(createApp, "createApp");
1043
+ async function bootstrap(options = {}) {
1044
+ const { app, container, requestTracker, diagnostics, config } = createApp(options);
1045
+ const port = Number(options.port ?? process.env.PORT ?? 3e3);
1046
+ const server = app.listen(port, () => {
1047
+ console.log(`\u{1F680} Server listening on http://localhost:${port}`);
1048
+ });
1049
+ const shutdown = /* @__PURE__ */ __name(() => {
1050
+ server.close(() => {
1051
+ console.log("HTTP server closed");
1052
+ });
1053
+ }, "shutdown");
1054
+ process.once("SIGINT", shutdown);
1055
+ process.once("SIGTERM", shutdown);
1056
+ return {
1057
+ app,
1058
+ server,
1059
+ container,
1060
+ requestTracker,
1061
+ diagnostics,
1062
+ config,
1063
+ shutdown
1064
+ };
1065
+ }
1066
+ __name(bootstrap, "bootstrap");
1067
+ // Annotate the CommonJS export names for ESM import in node:
1068
+ 0 && (module.exports = {
1069
+ AppDiagnostics,
1070
+ AppError,
1071
+ BaseController,
1072
+ Controller,
1073
+ Delete,
1074
+ Get,
1075
+ Inject,
1076
+ Injectable,
1077
+ MultiInject,
1078
+ Named,
1079
+ Optional,
1080
+ Patch,
1081
+ Post,
1082
+ Put,
1083
+ RequestTracker,
1084
+ TYPES,
1085
+ Tagged,
1086
+ Unmanaged,
1087
+ bootstrap,
1088
+ configureApp,
1089
+ createApp,
1090
+ createError,
1091
+ getAppConfig,
1092
+ isAppError,
1093
+ listRegisteredControllers,
1094
+ registerController,
1095
+ resetAppConfig,
1096
+ resetControllerRegistry,
1097
+ resolveConfig
1098
+ });
1099
+ //# sourceMappingURL=index.js.map