@forinda/kickjs 0.1.4 → 0.2.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 CHANGED
@@ -6,6 +6,9 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
8
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
9
12
  var __export = (target, all) => {
10
13
  for (var name in all)
11
14
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -28,337 +31,428 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
31
  ));
29
32
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
33
 
34
+ // src/cli/utils/config-loader.ts
35
+ async function loadKickConfig(cwd) {
36
+ const workingDir = cwd || process.cwd();
37
+ for (const configFileName of CONFIG_FILE_NAMES) {
38
+ const configPath = import_node_path.default.resolve(workingDir, configFileName);
39
+ if ((0, import_node_fs.existsSync)(configPath)) {
40
+ try {
41
+ const configModule = await import(configPath);
42
+ const config = configModule.default || configModule;
43
+ return {
44
+ ...config,
45
+ configPath
46
+ };
47
+ } catch (error) {
48
+ console.warn(`\u26A0\uFE0F Failed to load config from ${configPath}:`, error);
49
+ }
50
+ }
51
+ }
52
+ return getDefaultConfig();
53
+ }
54
+ function getDefaultConfig() {
55
+ return {
56
+ app: {
57
+ name: "KickJS App",
58
+ port: 3e3,
59
+ host: "localhost",
60
+ prefix: "",
61
+ env: "development"
62
+ },
63
+ dev: {
64
+ port: 3e3,
65
+ host: "localhost",
66
+ entry: "src/index.ts",
67
+ watch: true,
68
+ env: {
69
+ NODE_ENV: "development"
70
+ }
71
+ },
72
+ start: {
73
+ port: 3e3,
74
+ host: "0.0.0.0",
75
+ entry: "dist/index.js",
76
+ env: {
77
+ NODE_ENV: "production"
78
+ }
79
+ },
80
+ structure: {
81
+ domainRoot: "src/domains",
82
+ domainFolders: [
83
+ "controllers",
84
+ "services",
85
+ "domain"
86
+ ],
87
+ defaultDomain: "app"
88
+ },
89
+ generators: {
90
+ controllerRoot: "src/domains/app/controllers"
91
+ },
92
+ commands: []
93
+ };
94
+ }
95
+ function getAppConfig(config, overrides = {}) {
96
+ return {
97
+ ...getDefaultConfig().app,
98
+ ...config.app,
99
+ ...overrides
100
+ };
101
+ }
102
+ var import_node_fs, import_node_path, CONFIG_FILE_NAMES;
103
+ var init_config_loader = __esm({
104
+ "src/cli/utils/config-loader.ts"() {
105
+ "use strict";
106
+ import_node_fs = require("fs");
107
+ import_node_path = __toESM(require("path"));
108
+ CONFIG_FILE_NAMES = [
109
+ "kick.config.ts",
110
+ "kick.config.js",
111
+ "kick.config.mjs",
112
+ "kickjs.config.ts",
113
+ "kickjs.config.js",
114
+ "kickjs.config.mjs"
115
+ ];
116
+ __name(loadKickConfig, "loadKickConfig");
117
+ __name(getDefaultConfig, "getDefaultConfig");
118
+ __name(getAppConfig, "getAppConfig");
119
+ }
120
+ });
121
+
122
+ // src/core/utils/app-config.ts
123
+ var app_config_exports = {};
124
+ __export(app_config_exports, {
125
+ getConfigFromEnv: () => getConfigFromEnv,
126
+ loadAppConfig: () => loadAppConfig
127
+ });
128
+ async function loadAppConfig(overrides = {}) {
129
+ const kickConfig = await loadKickConfig();
130
+ return getAppConfig(kickConfig, overrides);
131
+ }
132
+ function getConfigFromEnv() {
133
+ return {
134
+ port: process.env.PORT ? parseInt(process.env.PORT) : void 0,
135
+ host: process.env.HOST || void 0,
136
+ env: process.env.NODE_ENV || void 0
137
+ };
138
+ }
139
+ var init_app_config = __esm({
140
+ "src/core/utils/app-config.ts"() {
141
+ "use strict";
142
+ init_config_loader();
143
+ __name(loadAppConfig, "loadAppConfig");
144
+ __name(getConfigFromEnv, "getConfigFromEnv");
145
+ }
146
+ });
147
+
31
148
  // src/index.ts
32
149
  var index_exports = {};
33
150
  __export(index_exports, {
34
- AppDiagnostics: () => AppDiagnostics,
35
- AppError: () => AppError,
36
- BaseController: () => BaseController,
37
- Controller: () => Controller,
38
- Delete: () => Delete,
39
- DeleteController: () => DeleteController,
40
- Get: () => Get,
41
- GetController: () => GetController,
42
- HttpVerbController: () => HttpVerbController,
43
- Inject: () => Inject,
44
- Injectable: () => Injectable,
45
- MultiInject: () => MultiInject,
46
- Named: () => Named,
47
- Optional: () => Optional,
48
- Patch: () => Patch,
49
- PatchController: () => PatchController,
50
- Post: () => Post,
51
- PostController: () => PostController,
52
- Put: () => Put,
53
- PutController: () => PutController,
54
- RequestTracker: () => RequestTracker,
55
- TYPES: () => TYPES,
56
- Tagged: () => Tagged,
57
- Unmanaged: () => Unmanaged,
58
- bootstrap: () => bootstrap,
59
- configureApp: () => configureApp,
60
- createApp: () => createApp,
61
- createError: () => createError,
151
+ AutoBind: () => AutoBind,
152
+ BaseKickMiddleware: () => BaseKickMiddleware,
153
+ BaseKickPlugin: () => BaseKickPlugin,
154
+ KICK_CONTROLLER_METADATA_KEYS: () => KICK_CONTROLLER_METADATA_KEYS,
155
+ KICK_MODULE_KEYS: () => KICK_MODULE_KEYS,
156
+ KickApp: () => KickApp,
157
+ KickController: () => KickController,
158
+ KickDelete: () => KickDelete,
159
+ KickGet: () => KickGet,
160
+ KickInject: () => KickInject,
161
+ KickInjectable: () => KickInjectable,
162
+ KickMiddleware: () => KickMiddleware,
163
+ KickPatch: () => KickPatch,
164
+ KickPost: () => KickPost,
165
+ KickPut: () => KickPut,
166
+ RouteMapper: () => RouteMapper,
167
+ bindClassMethods: () => bindClassMethods,
168
+ combineRoutePaths: () => combineRoutePaths,
169
+ createKickApp: () => createKickApp,
170
+ createKickAppWithConfig: () => createKickAppWithConfig,
62
171
  createKickConfig: () => createKickConfig,
63
- discoverControllersFromFilesystem: () => discoverControllersFromFilesystem,
64
- getAppConfig: () => getAppConfig,
65
- isAppError: () => isAppError,
66
- listRegisteredControllers: () => listRegisteredControllers,
67
- registerController: () => registerController,
68
- resetAppConfig: () => resetAppConfig,
69
- resetControllerRegistry: () => resetControllerRegistry,
70
- resolveConfig: () => resolveConfig
172
+ createModule: () => createModule,
173
+ defineAppConfig: () => defineAppConfig,
174
+ defineDevConfig: () => defineDevConfig,
175
+ defineStartConfig: () => defineStartConfig,
176
+ getConfigFromEnv: () => getConfigFromEnv,
177
+ getMiddlewareMetadata: () => getMiddlewareMetadata,
178
+ isKickMiddleware: () => isKickMiddleware,
179
+ loadAppConfig: () => loadAppConfig,
180
+ mapController: () => mapController,
181
+ normalizeRoutePath: () => normalizeRoutePath
71
182
  });
72
183
  module.exports = __toCommonJS(index_exports);
73
184
 
74
- // src/decorators/http.ts
185
+ // src/core/index.ts
75
186
  var import_reflect_metadata = require("reflect-metadata");
76
- var CONTROLLER_KEY = Symbol("core:controller");
77
- var ROUTES_KEY = Symbol("core:routes");
78
- var controllerRegistry = /* @__PURE__ */ new Set();
79
- function Controller(pathOrOptions = "/") {
80
- const options = normalizeControllerOptions(pathOrOptions);
81
- return function(target) {
82
- Reflect.defineMetadata(CONTROLLER_KEY, {
83
- basePath: options.path,
84
- tags: options.tags
85
- }, target);
86
- if (!Reflect.hasMetadata(ROUTES_KEY, target)) {
87
- Reflect.defineMetadata(ROUTES_KEY, [], target);
88
- }
89
- if (options.autoRegister !== false) {
90
- controllerRegistry.add(target);
91
- }
92
- };
93
- }
94
- __name(Controller, "Controller");
95
- function Get(path3, ...middlewares) {
96
- return createRouteDecorator("get")(path3, ...middlewares);
97
- }
98
- __name(Get, "Get");
99
- function Post(path3, ...middlewares) {
100
- return createRouteDecorator("post")(path3, ...middlewares);
101
- }
102
- __name(Post, "Post");
103
- function Put(path3, ...middlewares) {
104
- return createRouteDecorator("put")(path3, ...middlewares);
105
- }
106
- __name(Put, "Put");
107
- function Patch(path3, ...middlewares) {
108
- return createRouteDecorator("patch")(path3, ...middlewares);
109
- }
110
- __name(Patch, "Patch");
111
- function Delete(path3, ...middlewares) {
112
- return createRouteDecorator("delete")(path3, ...middlewares);
113
- }
114
- __name(Delete, "Delete");
115
- function listRegisteredControllers() {
116
- return Array.from(controllerRegistry);
117
- }
118
- __name(listRegisteredControllers, "listRegisteredControllers");
119
- function registerController(controller) {
120
- controllerRegistry.add(controller);
121
- }
122
- __name(registerController, "registerController");
123
- function resetControllerRegistry() {
124
- controllerRegistry.clear();
125
- }
126
- __name(resetControllerRegistry, "resetControllerRegistry");
127
- var DecoratorMetadata = {
128
- CONTROLLER_KEY,
129
- ROUTES_KEY
187
+
188
+ // src/core/constants/di-keys.ts
189
+ var KICK_MODULE_KEYS = {
190
+ KickControllerType: Symbol.for("Kick:ControllerType"),
191
+ KickMiddlewareType: Symbol.for("Kick:MiddlewareType")
130
192
  };
131
- function createRouteDecorator(method) {
132
- return (pathOrOptions, ...middlewares) => function(target, propertyKey) {
133
- const controller = target.constructor;
134
- const routes = Reflect.getMetadata(ROUTES_KEY, controller) ?? [];
135
- const normalized = normalizeRouteOptions(pathOrOptions, middlewares);
136
- routes.push({
137
- method,
138
- path: normalized.path,
139
- propertyKey,
140
- middlewares: normalized.middlewares,
141
- validation: normalized.validation
142
- });
143
- Reflect.defineMetadata(ROUTES_KEY, routes, controller);
144
- };
145
- }
146
- __name(createRouteDecorator, "createRouteDecorator");
147
- function normalizeControllerOptions(pathOrOptions) {
148
- if (typeof pathOrOptions === "string") {
149
- return {
150
- path: normalizePath(pathOrOptions),
151
- autoRegister: true,
152
- tags: []
193
+ var KICK_CONTROLLER_METADATA_KEYS = {
194
+ path: Symbol.for("Kick:controller:path"),
195
+ options: Symbol.for("Kick:controller:options"),
196
+ routes: Symbol.for("Kick:controller:routes"),
197
+ middlewares: Symbol.for("Kick:controller:middlewares"),
198
+ middlewareOptions: Symbol.for("Kick:middleware:options"),
199
+ isMiddleware: Symbol.for("Kick:middleware:isMiddleware")
200
+ };
201
+
202
+ // src/core/decorators/route.ts
203
+ function createKickRoute(createOptions) {
204
+ return function(path2, options = {}) {
205
+ return function(target, propertyKey, descriptor) {
206
+ if (typeof descriptor.value !== "function") {
207
+ throw new Error("[KickRoute] Decorator can only be applied to methods.");
208
+ }
209
+ const routeMetadata = {
210
+ path: path2,
211
+ method: createOptions.method,
212
+ handlerName: propertyKey,
213
+ handler: descriptor.value,
214
+ middlewares: options.middlewares ?? []
215
+ };
216
+ const existingRoutes = Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.routes, target.constructor) || [];
217
+ existingRoutes.push(routeMetadata);
218
+ Reflect.defineMetadata(KICK_CONTROLLER_METADATA_KEYS.routes, existingRoutes, target.constructor);
153
219
  };
154
- }
155
- return {
156
- path: normalizePath(pathOrOptions.path ?? "/"),
157
- autoRegister: pathOrOptions.autoRegister ?? true,
158
- tags: pathOrOptions.tags ?? []
159
220
  };
160
221
  }
161
- __name(normalizeControllerOptions, "normalizeControllerOptions");
162
- function normalizeRouteOptions(pathOrOptions, extraMiddlewares) {
163
- const base = normalizeRouteOptionObject(pathOrOptions);
164
- const middlewares = [
165
- ...base.middlewares ?? [],
166
- ...extraMiddlewares
167
- ];
168
- return {
169
- path: normalizeRoutePath(base.path ?? "/"),
170
- middlewares,
171
- validation: base.validate
222
+ __name(createKickRoute, "createKickRoute");
223
+ function KickGet(path2, options) {
224
+ return createKickRoute({
225
+ method: "GET"
226
+ })(path2, options);
227
+ }
228
+ __name(KickGet, "KickGet");
229
+ function KickPost(path2, options) {
230
+ return createKickRoute({
231
+ method: "POST"
232
+ })(path2, options);
233
+ }
234
+ __name(KickPost, "KickPost");
235
+ function KickPut(path2, options) {
236
+ return createKickRoute({
237
+ method: "PUT"
238
+ })(path2, options);
239
+ }
240
+ __name(KickPut, "KickPut");
241
+ function KickPatch(path2, options) {
242
+ return createKickRoute({
243
+ method: "PATCH"
244
+ })(path2, options);
245
+ }
246
+ __name(KickPatch, "KickPatch");
247
+ function KickDelete(path2, options) {
248
+ return createKickRoute({
249
+ method: "DELETE"
250
+ })(path2, options);
251
+ }
252
+ __name(KickDelete, "KickDelete");
253
+
254
+ // src/core/decorators/controller.ts
255
+ var import_inversify = require("inversify");
256
+
257
+ // src/core/utils/bind-class-methods.ts
258
+ function bindClassMethods(instance) {
259
+ const proto = Object.getPrototypeOf(instance);
260
+ const methods = Object.getOwnPropertyNames(proto).filter((prop) => typeof instance[prop] === "function" && prop !== "constructor");
261
+ methods.forEach((method) => {
262
+ instance[method] = instance[method].bind(instance);
263
+ });
264
+ }
265
+ __name(bindClassMethods, "bindClassMethods");
266
+
267
+ // src/core/decorators/controller.ts
268
+ function KickController(path2, options) {
269
+ return function(target) {
270
+ (0, import_inversify.decorate)((0, import_inversify.injectable)("Request"), target);
271
+ bindClassMethods(target.prototype);
272
+ Reflect.defineMetadata(KICK_CONTROLLER_METADATA_KEYS.path, path2, target);
273
+ Reflect.defineMetadata(KICK_CONTROLLER_METADATA_KEYS.options, options || {}, target);
172
274
  };
173
275
  }
174
- __name(normalizeRouteOptions, "normalizeRouteOptions");
175
- function normalizeRouteOptionObject(pathOrOptions) {
176
- if (typeof pathOrOptions === "string") {
177
- return {
178
- path: pathOrOptions
179
- };
180
- }
181
- if (typeof pathOrOptions === "object" && pathOrOptions !== null) {
182
- return {
183
- ...pathOrOptions
276
+ __name(KickController, "KickController");
277
+
278
+ // src/core/decorators/auto-bind.ts
279
+ function AutoBind(target) {
280
+ bindClassMethods(target.prototype);
281
+ }
282
+ __name(AutoBind, "AutoBind");
283
+
284
+ // src/core/decorators/middleware.ts
285
+ var import_inversify2 = require("inversify");
286
+ function KickMiddleware(options = {}) {
287
+ return function(target) {
288
+ AutoBind(target);
289
+ (0, import_inversify2.decorate)((0, import_inversify2.injectable)(), target);
290
+ const middlewareMetadata = {
291
+ name: options.name || target.name,
292
+ priority: options.priority || 0,
293
+ global: options.global || false,
294
+ tags: options.tags || [],
295
+ className: target.name
184
296
  };
185
- }
186
- return {};
297
+ Reflect.defineMetadata(KICK_CONTROLLER_METADATA_KEYS.middlewareOptions, middlewareMetadata, target);
298
+ Reflect.defineMetadata(KICK_CONTROLLER_METADATA_KEYS.isMiddleware, true, target);
299
+ };
187
300
  }
188
- __name(normalizeRouteOptionObject, "normalizeRouteOptionObject");
189
- function normalizePath(path3) {
190
- if (!path3 || path3 === "/") {
191
- return "/";
192
- }
193
- const withLeading = path3.startsWith("/") ? path3 : `/${path3}`;
194
- return withLeading.endsWith("/") && withLeading !== "/" ? withLeading.slice(0, -1) : withLeading;
301
+ __name(KickMiddleware, "KickMiddleware");
302
+ function isKickMiddleware(target) {
303
+ return Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.isMiddleware, target) === true;
195
304
  }
196
- __name(normalizePath, "normalizePath");
197
- function normalizeRoutePath(path3) {
198
- if (!path3 || path3 === "/") {
199
- return "";
200
- }
201
- const cleaned = path3.startsWith("/") ? path3.slice(1) : path3;
202
- return cleaned.endsWith("/") ? cleaned.slice(0, -1) : cleaned;
305
+ __name(isKickMiddleware, "isKickMiddleware");
306
+ function getMiddlewareMetadata(target) {
307
+ return Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.middlewareOptions, target);
203
308
  }
204
- __name(normalizeRoutePath, "normalizeRoutePath");
309
+ __name(getMiddlewareMetadata, "getMiddlewareMetadata");
205
310
 
206
- // src/utils/errors.ts
207
- var AppError = class extends Error {
208
- static {
209
- __name(this, "AppError");
311
+ // src/core/utils/normalize-route-path.ts
312
+ function normalizeRoutePath(path2) {
313
+ if (typeof path2 !== "string") {
314
+ throw new Error("Invalid path type");
210
315
  }
211
- code;
212
- status;
213
- details;
214
- constructor(code, message, options = {}) {
215
- super(message);
216
- this.code = code;
217
- this.status = options.status;
218
- this.details = options.details;
219
- if (options.cause) {
220
- this.cause = options.cause;
221
- }
222
- this.name = "AppError";
316
+ if (!path2.startsWith("/")) {
317
+ path2 = `/${path2}`;
223
318
  }
224
- };
225
- function createError(code, message, options = {}) {
226
- return new AppError(code, message, options);
319
+ if (path2.endsWith("/")) {
320
+ path2 = path2.slice(0, -1);
321
+ }
322
+ return path2;
227
323
  }
228
- __name(createError, "createError");
229
- function isAppError(error) {
230
- return error instanceof AppError;
324
+ __name(normalizeRoutePath, "normalizeRoutePath");
325
+ function combineRoutePaths(basePath, routePath) {
326
+ const base = basePath === "" ? "" : basePath.replace(/\/$/, "");
327
+ const route = routePath === "" ? "" : routePath;
328
+ const full = `${base}${route}`;
329
+ return normalizeRoutePath(full === "" ? "/" : full);
231
330
  }
232
- __name(isAppError, "isAppError");
331
+ __name(combineRoutePaths, "combineRoutePaths");
233
332
 
234
- // src/core/request-tracker.ts
235
- var import_node_crypto2 = require("crypto");
333
+ // src/core/utils/controller-mapper.ts
334
+ function mapController(controller) {
335
+ const basePath = Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.path, controller.constructor) || "";
336
+ const routes = Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.routes, controller.constructor) || [];
337
+ const baseOptions = Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.options, controller.constructor) || {};
338
+ return routes.map((route) => ({
339
+ ...route,
340
+ path: combineRoutePaths(basePath, route.path),
341
+ middlewares: [
342
+ ...baseOptions.middlewares || [],
343
+ ...route.middlewares || []
344
+ ]
345
+ }));
346
+ }
347
+ __name(mapController, "mapController");
236
348
 
237
- // src/utils/injection.ts
238
- var import_inversify = require("inversify");
239
- function Injectable() {
240
- return (0, import_inversify.injectable)();
241
- }
242
- __name(Injectable, "Injectable");
243
- function Inject(identifier) {
244
- return (0, import_inversify.inject)(identifier);
245
- }
246
- __name(Inject, "Inject");
247
- function Optional() {
248
- return (0, import_inversify.optional)();
249
- }
250
- __name(Optional, "Optional");
251
- function MultiInject(identifier) {
252
- return (0, import_inversify.multiInject)(identifier);
253
- }
254
- __name(MultiInject, "MultiInject");
255
- function Named(name) {
256
- return (0, import_inversify.named)(name);
257
- }
258
- __name(Named, "Named");
259
- function Tagged(metadataKey, metadataValue) {
260
- return (0, import_inversify.tagged)(metadataKey, metadataValue);
261
- }
262
- __name(Tagged, "Tagged");
263
- function Unmanaged() {
264
- return (0, import_inversify.unmanaged)();
265
- }
266
- __name(Unmanaged, "Unmanaged");
349
+ // src/core/utils/di.ts
350
+ var import_inversify3 = require("inversify");
351
+ var KickInject = import_inversify3.inject;
352
+ var KickInjectable = import_inversify3.injectable;
267
353
 
268
- // src/utils/reactive.ts
269
- var import_node_crypto = require("crypto");
270
- var ReactiveRegistry2 = class {
354
+ // src/core/utils/route-mapper.ts
355
+ var RouteMapper = class _RouteMapper {
271
356
  static {
272
- __name(this, "ReactiveRegistry");
273
- }
274
- stores = /* @__PURE__ */ new Map();
275
- register(store) {
276
- this.stores.set(store.id, store);
357
+ __name(this, "RouteMapper");
277
358
  }
278
- unregister(id) {
279
- this.stores.delete(id);
359
+ /**
360
+ * Creates a contextual handler that injects request context into controller methods
361
+ * @param controller - The controller instance
362
+ * @param route - The route metadata
363
+ * @param prefix - Optional prefix to prepend to route paths
364
+ * @returns Express-compatible handler function
365
+ */
366
+ static createContextualHandler(controller, route, prefix = "") {
367
+ return (req, res, next) => {
368
+ const requestId = `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
369
+ const requestContext = {
370
+ req,
371
+ res,
372
+ next,
373
+ meta: {
374
+ routePath: _RouteMapper.buildRoutePath(prefix, route.path),
375
+ method: route.method,
376
+ controllerName: controller.constructor.name,
377
+ handlerName: route.handlerName,
378
+ startTime: Date.now(),
379
+ requestId
380
+ }
381
+ };
382
+ try {
383
+ const result = route.handler.call(controller, requestContext);
384
+ if (result instanceof Promise) {
385
+ result.catch((error) => {
386
+ console.error(`[${controller.constructor.name}:${route.handlerName}] Error:`, error);
387
+ if (!res.headersSent) {
388
+ res.status(500).json({
389
+ error: "Internal Server Error",
390
+ requestId: requestContext.meta.requestId
391
+ });
392
+ }
393
+ });
394
+ }
395
+ return result;
396
+ } catch (error) {
397
+ console.error(`[${controller.constructor.name}:${route.handlerName}] Error:`, error);
398
+ if (!res.headersSent) {
399
+ res.status(500).json({
400
+ error: "Internal Server Error",
401
+ requestId: requestContext.meta.requestId
402
+ });
403
+ }
404
+ }
405
+ };
280
406
  }
281
- get(id) {
282
- return this.stores.get(id);
407
+ /**
408
+ * Builds the full route path by combining prefix and route path
409
+ * @param prefix - The prefix to prepend
410
+ * @param routePath - The route path
411
+ * @returns Combined route path
412
+ */
413
+ static buildRoutePath(prefix, routePath) {
414
+ const normalizedPrefix = prefix.replace(/\/+$/, "");
415
+ const normalizedRoutePath = routePath.startsWith("/") ? routePath : `/${routePath}`;
416
+ if (!normalizedPrefix) {
417
+ return normalizedRoutePath;
418
+ }
419
+ return combineRoutePaths(normalizedPrefix, normalizedRoutePath);
283
420
  }
284
- list() {
285
- return Array.from(this.stores.values()).map((store) => ({
286
- id: store.id,
287
- label: store.label,
288
- snapshot: store.snapshot(),
289
- history: store.history()
421
+ /**
422
+ * Maps a controller to its routes with optional prefix
423
+ * @param controller - The controller instance
424
+ * @param routes - The route metadata array
425
+ * @param prefix - Optional prefix to prepend to all routes
426
+ * @returns Array of mapped route information
427
+ */
428
+ static mapControllerRoutes(controller, routes, prefix = "") {
429
+ return routes.map((route) => ({
430
+ ...route,
431
+ fullPath: _RouteMapper.buildRoutePath(prefix, route.path),
432
+ handler: _RouteMapper.createContextualHandler(controller, route, prefix),
433
+ controllerName: controller.constructor.name
290
434
  }));
291
435
  }
436
+ /**
437
+ * Logs route registration information
438
+ * @param method - HTTP method
439
+ * @param path - Route path
440
+ * @param handlerName - Handler method name
441
+ * @param controllerName - Controller class name
442
+ * @param prefix - Optional prefix used
443
+ */
444
+ static logRouteRegistration(method, path2, handlerName, controllerName, prefix) {
445
+ const _prefixInfo = prefix ? ` [prefix: ${prefix}]` : "";
446
+ }
292
447
  };
293
- function createReactive(initial, options = {}) {
294
- const listeners = /* @__PURE__ */ new Set();
295
- const target = {
296
- ...initial
297
- };
298
- const history = [];
299
- const historyEnabled = options.trackHistory ?? true;
300
- const maxHistory = options.maxHistory ?? 100;
301
- const reactiveId = options.id ?? (0, import_node_crypto.randomUUID)();
302
- const proxy = new Proxy(target, {
303
- set(current, prop, value) {
304
- if (typeof prop === "symbol") {
305
- return Reflect.set(current, prop, value);
306
- }
307
- const typedProp = prop;
308
- const previous = current[typedProp];
309
- const didChange = previous !== value;
310
- const result = Reflect.set(current, typedProp, value);
311
- if (didChange) {
312
- const change = {
313
- property: typedProp,
314
- value,
315
- previous,
316
- timestamp: Date.now()
317
- };
318
- if (historyEnabled) {
319
- history.push(change);
320
- if (history.length > maxHistory) {
321
- history.shift();
322
- }
323
- }
324
- listeners.forEach((listener) => listener(proxy, change));
325
- }
326
- return result;
327
- }
328
- });
329
- const store = {
330
- id: reactiveId,
331
- label: options.label,
332
- state: proxy,
333
- watch(watcher) {
334
- listeners.add(watcher);
335
- return () => listeners.delete(watcher);
336
- },
337
- snapshot() {
338
- return structuredClone(target);
339
- },
340
- history() {
341
- return historyEnabled ? [
342
- ...history
343
- ] : [];
344
- }
345
- };
346
- options.registry?.register(store);
347
- return store;
348
- }
349
- __name(createReactive, "createReactive");
350
448
 
351
- // src/shared/types.ts
352
- var TYPES = {
353
- AppState: Symbol.for("kick:AppState"),
354
- Config: Symbol.for("kick:Config"),
355
- Diagnostics: Symbol.for("kick:Diagnostics"),
356
- Logger: Symbol.for("kick:Logger"),
357
- StateRegistry: Symbol.for("kick:StateRegistry"),
358
- RequestTracker: Symbol.for("kick:RequestTracker")
359
- };
449
+ // src/core/utils/index.ts
450
+ init_app_config();
360
451
 
361
- // src/core/request-tracker.ts
452
+ // src/core/app/index.ts
453
+ var import_http = require("http");
454
+ var import_events = require("events");
455
+ var import_inversify4 = require("inversify");
362
456
  function _ts_decorate(decorators, target, key, desc) {
363
457
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
364
458
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -370,1459 +464,420 @@ function _ts_metadata(k, v) {
370
464
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
371
465
  }
372
466
  __name(_ts_metadata, "_ts_metadata");
373
- function _ts_param(paramIndex, decorator) {
374
- return function(target, key) {
375
- decorator(target, key, paramIndex);
376
- };
377
- }
378
- __name(_ts_param, "_ts_param");
379
- var RequestTracker = class {
467
+ var KickApp = class extends import_events.EventEmitter {
380
468
  static {
381
- __name(this, "RequestTracker");
469
+ __name(this, "KickApp");
382
470
  }
383
- registry;
471
+ context;
472
+ name;
473
+ prefix;
384
474
  config;
385
- logger;
386
- constructor(registry, config, logger) {
387
- this.registry = registry;
475
+ container;
476
+ _isInitialized = false;
477
+ _state = {};
478
+ constructor(context, name = "KickApp", prefix = "", config) {
479
+ super();
480
+ this.context = context;
481
+ this.name = name;
482
+ this.prefix = prefix;
388
483
  this.config = config;
389
- this.logger = logger;
390
- }
391
- middleware() {
392
- return (req, res, next) => {
393
- const id = (0, import_node_crypto2.randomUUID)();
394
- const requestState = createReactive({
395
- id,
396
- method: req.method,
397
- path: req.originalUrl ?? req.url,
398
- startedAt: Date.now(),
399
- logs: [],
400
- metadata: {}
401
- }, {
402
- id,
403
- label: `request:${req.method} ${req.originalUrl ?? req.url}`,
404
- registry: this.registry,
405
- trackHistory: this.config.telemetry.trackReactiveHistory,
406
- maxHistory: this.config.telemetry.requestHistoryLimit
407
- });
408
- res.locals.requestState = requestState;
409
- req.on("error", (error) => {
410
- this.recordError(res, error);
411
- });
412
- res.on("finish", () => {
413
- this.finalise(res);
414
- });
415
- res.on("close", () => {
416
- this.finalise(res);
417
- });
418
- res.on("error", (error) => {
419
- this.recordError(res, error);
420
- });
421
- next();
422
- };
423
- }
424
- get(res) {
425
- return res.locals.requestState;
426
- }
427
- log(res, message, level = "info", metadata) {
428
- const store = this.get(res);
429
- if (!store) {
430
- return;
431
- }
432
- const entry = {
433
- timestamp: Date.now(),
434
- level,
435
- message,
436
- metadata
437
- };
438
- store.state.logs = [
439
- ...store.state.logs,
440
- entry
441
- ];
442
- this.dispatchLog(level, `[${store.state.method} ${store.state.path}] ${message}`, {
443
- requestId: store.state.id,
444
- ...metadata
484
+ this.container = new import_inversify4.Container({
485
+ autobind: true
445
486
  });
446
- }
447
- mergeMetadata(res, patch) {
448
- const store = this.get(res);
449
- if (!store) {
450
- return;
451
- }
452
- store.state.metadata = {
453
- ...store.state.metadata,
454
- ...patch
455
- };
456
- }
457
- recordResponse(res, status, payload) {
458
- const store = this.get(res);
459
- if (!store) {
460
- return;
461
- }
462
- store.state.status = status;
463
- store.state.response = payload;
464
- }
465
- recordError(res, error) {
466
- const store = this.get(res);
467
- if (!store) {
468
- return;
469
- }
470
- const errorMessage = error instanceof Error ? error.message : String(error);
471
- store.state.error = errorMessage;
472
- if (isAppError(error)) {
473
- store.state.errorCode = error.code;
474
- this.mergeMetadata(res, {
475
- errorCode: error.code,
476
- errorDetails: error.details
477
- });
478
- }
479
- this.log(res, errorMessage, "error", {
480
- errorCode: isAppError(error) ? error.code : void 0
487
+ this.emit("created", {
488
+ name: this.name,
489
+ prefix: this.prefix,
490
+ config: this.config
481
491
  });
482
492
  }
483
- finalise(res) {
484
- const store = this.get(res);
485
- if (!store) {
486
- return;
487
- }
488
- store.state.status = res.statusCode;
489
- store.state.endedAt = Date.now();
490
- store.state.durationMs = store.state.endedAt - store.state.startedAt;
491
- this.dispatchLog("debug", `Request completed with ${res.statusCode}`, {
492
- requestId: store.state.id,
493
- durationMs: store.state.durationMs
494
- });
495
- }
496
- dispatchLog(level, message, metadata) {
497
- switch (level) {
498
- case "debug":
499
- this.logger.debug(message, metadata);
500
- break;
501
- case "info":
502
- this.logger.info(message, metadata);
503
- break;
504
- case "warn":
505
- this.logger.warn(message, metadata);
506
- break;
507
- case "error":
508
- this.logger.error(message, metadata);
509
- break;
510
- }
493
+ get isInitialized() {
494
+ return this._isInitialized;
511
495
  }
512
- };
513
- RequestTracker = _ts_decorate([
514
- Injectable(),
515
- _ts_param(0, Inject(TYPES.StateRegistry)),
516
- _ts_param(1, Inject(TYPES.Config)),
517
- _ts_param(2, Inject(TYPES.Logger)),
518
- _ts_metadata("design:type", Function),
519
- _ts_metadata("design:paramtypes", [
520
- typeof ReactiveRegistry === "undefined" ? Object : ReactiveRegistry,
521
- typeof ResolvedAppConfig === "undefined" ? Object : ResolvedAppConfig,
522
- typeof AppLogger === "undefined" ? Object : AppLogger
523
- ])
524
- ], RequestTracker);
525
-
526
- // src/core/base-controller.ts
527
- function _ts_decorate2(decorators, target, key, desc) {
528
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
529
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
530
- 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;
531
- return c > 3 && r && Object.defineProperty(target, key, r), r;
532
- }
533
- __name(_ts_decorate2, "_ts_decorate");
534
- function _ts_metadata2(k, v) {
535
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
536
- }
537
- __name(_ts_metadata2, "_ts_metadata");
538
- var BaseController = class {
539
- static {
540
- __name(this, "BaseController");
541
- }
542
- injectedTracker;
543
- runtimeTracker;
544
- ok(res, payload) {
545
- return this.respond(res, 200, payload);
546
- }
547
- created(res, payload) {
548
- return this.respond(res, 201, payload);
549
- }
550
- accepted(res, payload) {
551
- return this.respond(res, 202, payload);
552
- }
553
- noContent(res) {
554
- return this.respond(res, 204);
555
- }
556
- respond(res, status, payload) {
557
- const tracker = this.ensureTracker();
558
- tracker.recordResponse(res, status, payload);
559
- if (payload === void 0) {
560
- res.status(status).end();
561
- } else {
562
- res.status(status).json(payload);
496
+ get controllers() {
497
+ try {
498
+ return this.container.getAll(KICK_MODULE_KEYS.KickControllerType);
499
+ } catch {
500
+ return [];
563
501
  }
564
- return res;
565
502
  }
566
- logDebug(res, message, metadata) {
567
- const tracker = this.ensureTracker();
568
- tracker.log(res, `[${this.controllerId()}] ${message}`, "debug", metadata);
569
- }
570
- logInfo(res, message, metadata) {
571
- const tracker = this.ensureTracker();
572
- tracker.log(res, `[${this.controllerId()}] ${message}`, "info", metadata);
573
- }
574
- logWarn(res, message, metadata) {
575
- const tracker = this.ensureTracker();
576
- tracker.log(res, `[${this.controllerId()}] ${message}`, "warn", metadata);
577
- }
578
- logError(res, message, metadata) {
579
- const tracker = this.ensureTracker();
580
- tracker.log(res, `[${this.controllerId()}] ${message}`, "error", metadata);
581
- }
582
- mergeRequestMetadata(res, patch) {
583
- const tracker = this.ensureTracker();
584
- const current = tracker.get(res)?.state.metadata[this.controllerId()];
585
- const currentRecord = typeof current === "object" && current !== null ? current : {};
586
- const namespacedPatch = {
587
- [this.controllerId()]: {
588
- ...currentRecord,
589
- ...patch
590
- }
503
+ get state() {
504
+ return {
505
+ ...this._state
591
506
  };
592
- tracker.mergeMetadata(res, namespacedPatch);
593
507
  }
594
- getRequestState(res) {
595
- return this.ensureTracker().get(res)?.state;
596
- }
597
- fail(code, message, options) {
598
- throw createError(code, message, options);
508
+ setState(key, value) {
509
+ const oldValue = this._state[key];
510
+ this._state[key] = value;
511
+ this.emit("state:changed", {
512
+ key,
513
+ value,
514
+ oldValue
515
+ });
516
+ this.emit(`state:${key}`, {
517
+ value,
518
+ oldValue
519
+ });
599
520
  }
600
- attachRequestTracker(tracker) {
601
- this.runtimeTracker = tracker;
521
+ getState(key) {
522
+ return this._state[key];
602
523
  }
603
- ensureTracker() {
604
- if (this.runtimeTracker) {
605
- return this.runtimeTracker;
606
- }
607
- if (this.injectedTracker) {
608
- this.runtimeTracker = this.injectedTracker;
609
- return this.runtimeTracker;
610
- }
611
- throw createError("TRACKER_MISSING", "RequestTracker is not available on this controller");
524
+ onStateChange(key, listener) {
525
+ this.on(`state:${key}`, listener);
612
526
  }
613
- };
614
- _ts_decorate2([
615
- Inject(TYPES.RequestTracker),
616
- _ts_metadata2("design:type", typeof RequestTracker === "undefined" ? Object : RequestTracker)
617
- ], BaseController.prototype, "injectedTracker", void 0);
618
- BaseController = _ts_decorate2([
619
- Injectable()
620
- ], BaseController);
621
-
622
- // src/core/http-controllers.ts
623
- var VERB_CONTROLLER_SYMBOL = Symbol.for("kick:core:verb-controller");
624
- var HttpVerbController = class extends BaseController {
625
- static {
626
- __name(this, "HttpVerbController");
527
+ offStateChange(key, listener) {
528
+ this.off(`state:${key}`, listener);
627
529
  }
628
530
  /**
629
- * Return the HTTP method associated with this controller. Static so discovery can consume it
630
- * without instantiating the controller (which would require container dependencies).
631
- */
632
- static method() {
633
- throw new Error("HttpVerbController.method() must be implemented by subclasses");
531
+ * Get a configuration value by key path (supports nested access like 'database.host')
532
+ */
533
+ getConfig(key) {
534
+ if (!this.config) return void 0;
535
+ if (!key) return this.config;
536
+ return key.split(".").reduce((obj, k) => obj?.[k], this.config);
634
537
  }
635
- /** HTTP method instance mirror for convenience in handlers/tests. */
636
- httpMethod = this.constructor.method();
637
538
  /**
638
- * Optional static override for the route path. When provided, discovery will use this value
639
- * instead of deriving the path from the file-system location.
640
- */
641
- static route;
642
- /**
643
- * Optional static tags collection. These map to the controller metadata and can be used by
644
- * diagnostics tooling.
645
- */
646
- static tags;
647
- controllerId() {
648
- return this.constructor.name;
649
- }
650
- };
651
- Object.defineProperty(HttpVerbController, VERB_CONTROLLER_SYMBOL, {
652
- value: true,
653
- enumerable: false,
654
- configurable: false,
655
- writable: false
656
- });
657
- var GetController = class extends HttpVerbController {
658
- static {
659
- __name(this, "GetController");
660
- }
661
- static method() {
662
- return "get";
663
- }
664
- };
665
- var PostController = class extends HttpVerbController {
666
- static {
667
- __name(this, "PostController");
668
- }
669
- static method() {
670
- return "post";
671
- }
672
- };
673
- var PutController = class extends HttpVerbController {
674
- static {
675
- __name(this, "PutController");
676
- }
677
- static method() {
678
- return "put";
539
+ * Check if a configuration key exists
540
+ */
541
+ hasConfig(key) {
542
+ return this.getConfig(key) !== void 0;
679
543
  }
680
- };
681
- var PatchController = class extends HttpVerbController {
682
- static {
683
- __name(this, "PatchController");
684
- }
685
- static method() {
686
- return "patch";
687
- }
688
- };
689
- var DeleteController = class extends HttpVerbController {
690
- static {
691
- __name(this, "DeleteController");
692
- }
693
- static method() {
694
- return "delete";
695
- }
696
- };
697
- function isVerbController(constructor) {
698
- if (typeof constructor !== "function") {
699
- return false;
700
- }
701
- return Boolean(constructor[VERB_CONTROLLER_SYMBOL]);
702
- }
703
- __name(isVerbController, "isVerbController");
704
-
705
- // src/core/controller-discovery.ts
706
- var import_node_fs = require("fs");
707
- var import_node_path = __toESM(require("path"));
708
- var import_reflect_metadata2 = require("reflect-metadata");
709
- var HTTP_METHODS = [
710
- "get",
711
- "post",
712
- "put",
713
- "patch",
714
- "delete"
715
- ];
716
- var tsNodeRegistered = false;
717
- function discoverControllersFromFilesystem(config) {
718
- if (!config.enabled) {
719
- return [];
720
- }
721
- const discovered = [];
722
- const seen = /* @__PURE__ */ new Map();
723
- const resolvedRoots = config.roots.map((root) => import_node_path.default.isAbsolute(root) ? root : import_node_path.default.join(process.cwd(), root));
724
- resolvedRoots.forEach((root) => {
725
- if (!safeExistsSync(root)) {
726
- return;
727
- }
728
- traverseDirectory(root, root, [], config, (filePath, dirSegments) => {
729
- const discovery = interpretControllerFile(root, filePath, dirSegments, config);
730
- if (!discovery) {
731
- return;
732
- }
733
- const key = `${discovery.method}:${discovery.route}`;
734
- if (seen.has(key)) {
735
- throw createError("ROUTE_CONFLICT", `Duplicate discovered route for [${discovery.method.toUpperCase()}] ${discovery.route}`, {
736
- details: {
737
- existing: seen.get(key),
738
- duplicate: filePath
739
- }
740
- });
741
- }
742
- seen.set(key, filePath);
743
- annotateController(discovery.controller, discovery.route, discovery.method, discovery.tags);
744
- if (config.registerGlobally) {
745
- registerController(discovery.controller);
746
- }
747
- discovered.push(discovery);
748
- });
749
- });
750
- return discovered;
751
- }
752
- __name(discoverControllersFromFilesystem, "discoverControllersFromFilesystem");
753
- function traverseDirectory(root, directory, segments, config, onFile) {
754
- const entries = (0, import_node_fs.readdirSync)(directory, {
755
- withFileTypes: true
756
- });
757
- entries.forEach((entry) => {
758
- if (shouldIgnore(entry.name, config)) {
759
- return;
760
- }
761
- const entryPath = import_node_path.default.join(directory, entry.name);
762
- if (entry.isDirectory()) {
763
- traverseDirectory(root, entryPath, [
764
- ...segments,
765
- entry.name
766
- ], config, onFile);
767
- return;
768
- }
769
- if (!entry.isFile()) {
770
- return;
771
- }
772
- onFile(entryPath, segments);
773
- });
774
- }
775
- __name(traverseDirectory, "traverseDirectory");
776
- function interpretControllerFile(root, filePath, dirSegments, config) {
777
- const ext = import_node_path.default.extname(filePath);
778
- if (!config.extensions.includes(ext)) {
779
- return void 0;
780
- }
781
- const relative = import_node_path.default.relative(root, filePath);
782
- const fileName = import_node_path.default.basename(relative, ext);
783
- const normalized = stripSuffix(fileName, config.suffix);
784
- const { slug, method } = extractSlugAndMethod(normalized, config);
785
- if (!slug || !method) {
786
- if (config.enforceStructure) {
787
- throw createError("INVALID_CONTROLLER_STRUCTURE", `Controller file ${relative} must follow <name>.<verb>${config.suffix}${ext}`);
544
+ /**
545
+ * Get config value with fallback
546
+ */
547
+ getConfigOrDefault(key, defaultValue) {
548
+ const value = this.getConfig(key);
549
+ return value !== void 0 ? value : defaultValue;
550
+ }
551
+ loadPlugin(plugins) {
552
+ if (!Array.isArray(plugins)) {
553
+ plugins = [
554
+ plugins
555
+ ];
788
556
  }
789
- return void 0;
790
- }
791
- const controllerConstructor = loadController(filePath);
792
- if (!controllerConstructor) {
793
- return void 0;
794
- }
795
- if (!isVerbController(controllerConstructor)) {
796
- throw createError("INVALID_VERB_CONTROLLER", `Discovered controller ${controllerConstructor.name || filePath} must extend HttpVerbController.`);
797
- }
798
- const VerbController = controllerConstructor;
799
- const methodFromClass = VerbController.method();
800
- if (methodFromClass !== method) {
801
- throw createError("VERB_MISMATCH", `Controller ${VerbController.name} declares ${methodFromClass.toUpperCase()} but file name enforces ${method.toUpperCase()}.`, {
802
- details: {
803
- filePath
804
- }
557
+ plugins.forEach((plugin) => {
558
+ plugin.install(this.context);
559
+ this.emit("plugin:loaded", {
560
+ plugin
561
+ });
805
562
  });
563
+ return this;
806
564
  }
807
- const derivedSegments = buildRouteSegments(dirSegments, slug, config);
808
- const baseSegments = toSegments(config.baseRoute);
809
- const override = config.allowStaticRoutes ? extractStaticRoute(VerbController) : void 0;
810
- const overrideSegments = override ? toSegments(override.startsWith("/") ? override : joinSegments([
811
- ...baseSegments,
812
- override
813
- ])) : void 0;
814
- const finalSegments = overrideSegments ?? [
815
- ...baseSegments,
816
- ...derivedSegments
817
- ];
818
- const route = normalizeRoute(finalSegments);
819
- const tags = buildTags(VerbController, dirSegments, config);
820
- return {
821
- controller: controllerConstructor,
822
- filePath,
823
- route,
824
- method,
825
- tags
826
- };
827
- }
828
- __name(interpretControllerFile, "interpretControllerFile");
829
- function buildTags(controller, dirSegments, config) {
830
- const staticTags = Array.isArray(controller.tags) ? controller.tags : [];
831
- if (!config.tagsFromDirectories) {
832
- return [
833
- ...new Set(staticTags)
834
- ];
835
- }
836
- const derived = dirSegments.filter(Boolean).map((segment) => segment.replace(/[^A-Za-z0-9]/g, "-").toLowerCase());
837
- return [
838
- .../* @__PURE__ */ new Set([
839
- ...staticTags,
840
- ...derived
841
- ])
842
- ];
843
- }
844
- __name(buildTags, "buildTags");
845
- function extractStaticRoute(controller) {
846
- const route = controller.route;
847
- if (!route) {
848
- return void 0;
849
- }
850
- return route;
851
- }
852
- __name(extractStaticRoute, "extractStaticRoute");
853
- function buildRouteSegments(dirSegments, slugSegments, config) {
854
- const directoryParts = dirSegments.flatMap((segment) => interpretSegment(segment, false));
855
- const slugParts = slugSegments.flatMap((segment, index) => interpretSegment(segment, true, index === slugSegments.length - 1));
856
- const segments = [
857
- ...directoryParts,
858
- ...slugParts
859
- ];
860
- if (segments.length === 0) {
861
- return [
862
- "/"
863
- ];
864
- }
865
- return segments;
866
- }
867
- __name(buildRouteSegments, "buildRouteSegments");
868
- function interpretSegment(segment, fromFile, isLastFilePart = false) {
869
- if (!segment) {
870
- return [];
871
- }
872
- if (segment === "index" && fromFile && isLastFilePart) {
873
- return [];
874
- }
875
- const dynamic = segment.match(/^\[(\.\.\.)?(.+)]$/);
876
- if (dynamic) {
877
- const [, spread, name] = dynamic;
878
- if (spread) {
879
- return [
880
- `:${name}*`
565
+ registerMiddleware(middleware) {
566
+ if (!Array.isArray(middleware)) {
567
+ middleware = [
568
+ middleware
881
569
  ];
882
570
  }
883
- return [
884
- `:${name}`
885
- ];
886
- }
887
- return [
888
- segment
889
- ];
890
- }
891
- __name(interpretSegment, "interpretSegment");
892
- function normalizeRoute(segments) {
893
- const filtered = segments.flat().map((segment) => segment.trim()).filter((segment) => segment && segment !== "/");
894
- if (filtered.length === 0) {
895
- return "/";
896
- }
897
- return `/${filtered.join("/")}`.replace(/\/+/g, "/");
898
- }
899
- __name(normalizeRoute, "normalizeRoute");
900
- function stripSuffix(fileName, suffix) {
901
- if (!suffix) {
902
- return fileName;
903
- }
904
- return fileName.endsWith(suffix) ? fileName.slice(0, -suffix.length) : fileName;
905
- }
906
- __name(stripSuffix, "stripSuffix");
907
- function extractSlugAndMethod(fileName, config) {
908
- const parts = fileName.split(".").filter(Boolean);
909
- if (parts.length === 0) {
910
- return {
911
- slug: void 0,
912
- method: void 0
913
- };
914
- }
915
- const potentialMethod = parts[parts.length - 1].toLowerCase();
916
- if (!HTTP_METHODS.includes(potentialMethod)) {
917
- return {
918
- slug: void 0,
919
- method: void 0
920
- };
921
- }
922
- const slugString = fileName.slice(0, fileName.length - potentialMethod.length - 1);
923
- const slugSegments = slugString ? slugString.split(config.segmentSeparator).filter(Boolean) : [
924
- "index"
925
- ];
926
- return {
927
- slug: slugSegments,
928
- method: potentialMethod
929
- };
930
- }
931
- __name(extractSlugAndMethod, "extractSlugAndMethod");
932
- function loadController(filePath) {
933
- const ext = import_node_path.default.extname(filePath);
934
- if (ext === ".ts" || ext === ".tsx") {
935
- ensureTsNode();
936
- }
937
- const required = require(filePath);
938
- const exported = required?.default ?? required?.Controller ?? pickFirstConstructor(required);
939
- if (typeof exported !== "function") {
940
- return void 0;
941
- }
942
- return exported;
943
- }
944
- __name(loadController, "loadController");
945
- function pickFirstConstructor(exportsObject) {
946
- if (!exportsObject || typeof exportsObject !== "object") {
947
- return void 0;
948
- }
949
- return Object.values(exportsObject).find((value) => typeof value === "function");
950
- }
951
- __name(pickFirstConstructor, "pickFirstConstructor");
952
- function ensureTsNode() {
953
- if (tsNodeRegistered) {
954
- return;
955
- }
956
- try {
957
- require("ts-node/register");
958
- tsNodeRegistered = true;
959
- } catch (error) {
960
- throw createError("TS_NODE_REQUIRED", "Unable to load TypeScript controllers. Install ts-node or run with a TS-aware runner.");
961
- }
962
- }
963
- __name(ensureTsNode, "ensureTsNode");
964
- function shouldIgnore(name, config) {
965
- if (!name) {
966
- return true;
967
- }
968
- if (name.startsWith(".")) {
969
- return true;
970
- }
971
- return config.ignore.includes(name);
972
- }
973
- __name(shouldIgnore, "shouldIgnore");
974
- function safeExistsSync(target) {
975
- try {
976
- const stats = (0, import_node_fs.statSync)(target);
977
- return stats.isDirectory();
978
- } catch (error) {
979
- return false;
980
- }
981
- }
982
- __name(safeExistsSync, "safeExistsSync");
983
- function toSegments(value) {
984
- if (!value || value === "/") {
985
- return [];
986
- }
987
- return value.split("/").map((segment) => segment.trim()).filter(Boolean);
988
- }
989
- __name(toSegments, "toSegments");
990
- function joinSegments(segments) {
991
- return segments.filter(Boolean).join("/");
992
- }
993
- __name(joinSegments, "joinSegments");
994
- function annotateController(controller, route, method, tags) {
995
- const basePath = route === "/" ? "/" : route;
996
- Reflect.defineMetadata(DecoratorMetadata.CONTROLLER_KEY, {
997
- basePath,
998
- tags
999
- }, controller);
1000
- const handleKey = "handle";
1001
- const descriptor = controller.prototype?.[handleKey];
1002
- if (typeof descriptor !== "function") {
1003
- throw createError("INVALID_CONTROLLER_HANDLER", `Controller ${controller.name || "[anonymous]"} must implement a handle method.`);
1004
- }
1005
- const routes = [
1006
- {
1007
- method,
1008
- path: "",
1009
- propertyKey: handleKey,
1010
- middlewares: []
1011
- }
1012
- ];
1013
- Reflect.defineMetadata(DecoratorMetadata.ROUTES_KEY, routes, controller);
1014
- }
1015
- __name(annotateController, "annotateController");
1016
-
1017
- // src/core/diagnostics.ts
1018
- function _ts_decorate3(decorators, target, key, desc) {
1019
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1020
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1021
- 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;
1022
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1023
- }
1024
- __name(_ts_decorate3, "_ts_decorate");
1025
- function _ts_metadata3(k, v) {
1026
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1027
- }
1028
- __name(_ts_metadata3, "_ts_metadata");
1029
- function _ts_param2(paramIndex, decorator) {
1030
- return function(target, key) {
1031
- decorator(target, key, paramIndex);
1032
- };
1033
- }
1034
- __name(_ts_param2, "_ts_param");
1035
- var AppDiagnostics = class {
1036
- static {
1037
- __name(this, "AppDiagnostics");
1038
- }
1039
- registry;
1040
- config;
1041
- constructor(registry, config) {
1042
- this.registry = registry;
1043
- this.config = config;
1044
- }
1045
- settings() {
1046
- return this.config;
1047
- }
1048
- stores() {
1049
- return this.registry.list().map((entry) => ({
1050
- id: entry.id,
1051
- label: entry.label,
1052
- snapshot: entry.snapshot,
1053
- history: entry.history
1054
- }));
1055
- }
1056
- requests() {
1057
- return this.registry.list().filter((entry) => entry.label?.startsWith("request:")).map((entry) => entry.snapshot);
1058
- }
1059
- };
1060
- AppDiagnostics = _ts_decorate3([
1061
- Injectable(),
1062
- _ts_param2(0, Inject(TYPES.StateRegistry)),
1063
- _ts_param2(1, Inject(TYPES.Config)),
1064
- _ts_metadata3("design:type", Function),
1065
- _ts_metadata3("design:paramtypes", [
1066
- typeof ReactiveRegistry2 === "undefined" ? Object : ReactiveRegistry2,
1067
- typeof ResolvedAppConfig === "undefined" ? Object : ResolvedAppConfig
1068
- ])
1069
- ], AppDiagnostics);
1070
-
1071
- // src/core/application.ts
1072
- var import_reflect_metadata4 = require("reflect-metadata");
1073
- var import_express = __toESM(require("express"));
1074
-
1075
- // src/core/server.ts
1076
- var import_node_crypto3 = require("crypto");
1077
- var import_reflect_metadata3 = require("reflect-metadata");
1078
- var appRouteRegistry = /* @__PURE__ */ new WeakMap();
1079
- function registerControllers(app, container, options = {}) {
1080
- const controllers = options.controllers ?? listRegisteredControllers();
1081
- const prefix = options.prefix ?? "";
1082
- const requestTracker = container.get(TYPES.RequestTracker);
1083
- controllers.forEach((ControllerClass) => {
1084
- ensureInjectable(ControllerClass);
1085
- const controllerMetadata = Reflect.getMetadata(DecoratorMetadata.CONTROLLER_KEY, ControllerClass);
1086
- if (!controllerMetadata) {
1087
- return;
1088
- }
1089
- if (!container.isBound(ControllerClass)) {
1090
- container.bind(ControllerClass).toSelf().inSingletonScope();
1091
- }
1092
- const instance = container.get(ControllerClass);
1093
- attachRequestTracker(instance, requestTracker);
1094
- const routes = Reflect.getMetadata(DecoratorMetadata.ROUTES_KEY, ControllerClass) ?? [];
1095
- routes.forEach((route) => {
1096
- const handler = instance[route.propertyKey];
1097
- if (typeof handler !== "function") {
1098
- throw new Error(`Route handler ${String(route.propertyKey)} on ${ControllerClass.name} is not a function`);
1099
- }
1100
- const fullPath = buildRoutePath(prefix, controllerMetadata.basePath, route.path);
1101
- const routeHash = registerRouteSignature(app, route.method, fullPath, ControllerClass.name, route.propertyKey);
1102
- const boundHandler = handler.bind(instance);
1103
- const validationMiddleware = buildValidationMiddleware(route.validation);
1104
- const routeMetadataMiddleware = /* @__PURE__ */ __name((_req, res, next) => {
1105
- requestTracker.mergeMetadata(res, {
1106
- route: fullPath,
1107
- method: route.method.toUpperCase(),
1108
- routeHash
1109
- });
1110
- next();
1111
- }, "routeMetadataMiddleware");
1112
- const pipeline = [
1113
- routeMetadataMiddleware,
1114
- ...validationMiddleware,
1115
- ...route.middlewares
1116
- ];
1117
- app[route.method](fullPath, ...pipeline, async (req, res, next) => {
1118
- try {
1119
- const result = await Promise.resolve(boundHandler(req, res, next));
1120
- if (result !== void 0 && !res.headersSent) {
1121
- res.json(result);
1122
- }
1123
- } catch (error) {
1124
- next(error);
1125
- }
1126
- });
571
+ const sortedMiddleware = middleware.sort((a, b) => {
572
+ const metadataA = Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.middlewareOptions, a.constructor) || {
573
+ priority: 0
574
+ };
575
+ const metadataB = Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.middlewareOptions, b.constructor) || {
576
+ priority: 0
577
+ };
578
+ return metadataA.priority - metadataB.priority;
1127
579
  });
1128
- });
1129
- }
1130
- __name(registerControllers, "registerControllers");
1131
- function ensureInjectable(constructor) {
1132
- if (!Reflect.hasOwnMetadata("inversify:paramtypes", constructor)) {
1133
- Injectable()(constructor);
1134
- }
1135
- }
1136
- __name(ensureInjectable, "ensureInjectable");
1137
- function attachRequestTracker(instance, tracker) {
1138
- const attach = instance.attachRequestTracker;
1139
- if (typeof attach !== "function") {
1140
- return;
1141
- }
1142
- attach.call(instance, tracker);
1143
- }
1144
- __name(attachRequestTracker, "attachRequestTracker");
1145
- function buildRoutePath(prefix, basePath, routePath) {
1146
- const segments = [
1147
- ...toSegments2(prefix),
1148
- ...toSegments2(basePath),
1149
- ...toSegments2(routePath)
1150
- ];
1151
- if (segments.length === 0) {
1152
- return "/";
1153
- }
1154
- return `/${segments.join("/")}`;
1155
- }
1156
- __name(buildRoutePath, "buildRoutePath");
1157
- function toSegments2(segment) {
1158
- if (!segment || segment === "/") {
1159
- return [];
1160
- }
1161
- const trimmed = segment.replace(/^\/+|\/+$/g, "");
1162
- return trimmed ? [
1163
- trimmed
1164
- ] : [];
1165
- }
1166
- __name(toSegments2, "toSegments");
1167
- function registerRouteSignature(app, method, path3, controllerName, propertyKey) {
1168
- let registry = appRouteRegistry.get(app);
1169
- if (!registry) {
1170
- registry = /* @__PURE__ */ new Set();
1171
- appRouteRegistry.set(app, registry);
1172
- }
1173
- const normalized = `${method.toLowerCase()}:${path3.toLowerCase()}`;
1174
- const hash = (0, import_node_crypto3.createHash)("sha256").update(normalized).digest("hex");
1175
- if (registry.has(hash)) {
1176
- throw createError("ROUTE_CONFLICT", `Duplicate route detected for [${method.toUpperCase()}] ${path3}`, {
1177
- details: {
1178
- controller: controllerName,
1179
- handler: String(propertyKey)
580
+ this.context.middlewares.push(...sortedMiddleware);
581
+ sortedMiddleware.forEach((mw) => {
582
+ const metadata = Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.middlewareOptions, mw.constructor);
583
+ if (metadata) {
584
+ this.emit("middleware:registered:detailed", {
585
+ middleware: mw,
586
+ metadata,
587
+ className: mw.constructor.name
588
+ });
589
+ } else {
590
+ console.log(`[KickApp]: Registered global middleware: ${mw.constructor.name}`);
1180
591
  }
1181
592
  });
593
+ this.emit("middleware:registered", {
594
+ count: sortedMiddleware.length
595
+ });
596
+ return this;
1182
597
  }
1183
- registry.add(hash);
1184
- return hash;
1185
- }
1186
- __name(registerRouteSignature, "registerRouteSignature");
1187
- function buildValidationMiddleware(validation) {
1188
- if (!validation) {
1189
- return [];
598
+ mountMiddlewares() {
599
+ this.context.middlewares.forEach((middleware) => {
600
+ this.context.app.use(middleware.use);
601
+ });
602
+ this.emit("middlewares:mounted", {
603
+ count: this.context.middlewares.length
604
+ });
605
+ return this;
1190
606
  }
1191
- const middleware = /* @__PURE__ */ __name((req, _res, next) => {
607
+ loadModules(modules) {
608
+ modules.forEach((module2) => {
609
+ module2.install(this.container);
610
+ this.emit("module:loaded", {
611
+ module: module2.name
612
+ });
613
+ });
614
+ this.extractMiddlewaresFromContainer();
615
+ this.mapControllers();
616
+ this._isInitialized = true;
617
+ this.setState("isInitialized", true);
618
+ this.setState("modulesCount", modules.length);
619
+ this.emit("initialized", this.getStats());
620
+ return this;
621
+ }
622
+ extractMiddlewaresFromContainer() {
1192
623
  try {
1193
- if (validation.params) {
1194
- req.params = runSchema(validation.params, req.params, "params");
1195
- }
1196
- if (validation.query) {
1197
- req.query = runSchema(validation.query, req.query, "query");
624
+ const middlewares = this.container.getAll(KICK_MODULE_KEYS.KickMiddlewareType);
625
+ if (middlewares.length > 0) {
626
+ this.registerMiddleware(middlewares);
1198
627
  }
1199
- if (validation.body) {
1200
- req.body = runSchema(validation.body, req.body, "body");
1201
- }
1202
- next();
1203
- } catch (error) {
1204
- next(error);
1205
- }
1206
- }, "middleware");
1207
- return [
1208
- middleware
1209
- ];
1210
- }
1211
- __name(buildValidationMiddleware, "buildValidationMiddleware");
1212
- function runSchema(schema, value, target) {
1213
- if (isZodSchema(schema)) {
1214
- if (typeof schema.safeParse === "function") {
1215
- const result = schema.safeParse(value);
1216
- if (!result.success) {
1217
- const issues = Array.isArray(result.error?.issues) ? result.error.issues.map((issue) => issue.message) : [
1218
- result.error.message
1219
- ].filter(Boolean);
1220
- throw validationError(target, issues);
1221
- }
1222
- return result.data;
628
+ } catch {
629
+ console.warn("[KickApp]: No middlewares found in DI container");
1223
630
  }
631
+ }
632
+ mapControllers() {
1224
633
  try {
1225
- return schema.parse(value);
634
+ const controllers = this.container.getAll(KICK_MODULE_KEYS.KickControllerType);
635
+ let routeCount = 0;
636
+ controllers.forEach((controller) => {
637
+ const routes = mapController(controller);
638
+ const mappedRoutes = RouteMapper.mapControllerRoutes(controller, routes, this.prefix);
639
+ mappedRoutes.forEach((mappedRoute) => {
640
+ const expressMethod = mappedRoute.method.toLowerCase();
641
+ if (typeof this.context.app[expressMethod] === "function") {
642
+ RouteMapper.logRouteRegistration(mappedRoute.method, mappedRoute.fullPath, mappedRoute.handlerName, mappedRoute.controllerName, this.prefix || void 0);
643
+ this.context.app[expressMethod](mappedRoute.fullPath, mappedRoute.handler);
644
+ this.context.requestHandlers[`${mappedRoute.method}:${mappedRoute.fullPath}`] = {
645
+ ...mappedRoute,
646
+ path: mappedRoute.fullPath
647
+ };
648
+ this.emit("route:registered", {
649
+ method: mappedRoute.method,
650
+ path: mappedRoute.fullPath,
651
+ handler: mappedRoute.handlerName,
652
+ controller: mappedRoute.controllerName,
653
+ prefix: this.prefix
654
+ });
655
+ routeCount++;
656
+ }
657
+ });
658
+ this.emit("controller:mapped", {
659
+ controller: controller.constructor.name,
660
+ routeCount: mappedRoutes.length,
661
+ prefix: this.prefix
662
+ });
663
+ });
664
+ this.setState("controllersCount", controllers.length);
665
+ this.setState("routesCount", routeCount);
666
+ this.setState("routePrefix", this.prefix);
1226
667
  } catch (error) {
1227
- const issues = extractErrorMessages(error);
1228
- throw validationError(target, issues);
1229
- }
1230
- }
1231
- if (isJoiSchema(schema)) {
1232
- const { error, value: validated } = schema.validate(value, {
1233
- abortEarly: false,
1234
- stripUnknown: true
1235
- });
1236
- if (error) {
1237
- throw validationError(target, error.details?.map((detail) => detail.message));
1238
- }
1239
- return validated;
1240
- }
1241
- throw createError("VALIDATION_UNSUPPORTED", "Unsupported validation schema provided", {
1242
- details: {
1243
- target
1244
- }
1245
- });
1246
- }
1247
- __name(runSchema, "runSchema");
1248
- function isZodSchema(schema) {
1249
- if (typeof schema !== "object" || schema === null) {
1250
- return false;
1251
- }
1252
- return typeof schema.safeParse === "function" || typeof schema.parse === "function";
1253
- }
1254
- __name(isZodSchema, "isZodSchema");
1255
- function isJoiSchema(schema) {
1256
- if (typeof schema !== "object" || schema === null) {
1257
- return false;
1258
- }
1259
- return typeof schema.validate === "function";
1260
- }
1261
- __name(isJoiSchema, "isJoiSchema");
1262
- function validationError(target, issues) {
1263
- return createError("VALIDATION_ERROR", `Invalid ${target}`, {
1264
- status: 400,
1265
- details: {
1266
- target,
1267
- issues: issues?.filter((issue) => Boolean(issue))
668
+ this.emit("error", {
669
+ type: "controller-mapping",
670
+ error
671
+ });
1268
672
  }
1269
- });
1270
- }
1271
- __name(validationError, "validationError");
1272
- function extractErrorMessages(error) {
1273
- if (!error) {
1274
- return [];
1275
673
  }
1276
- if (Array.isArray(error.issues)) {
1277
- return error.issues.map((issue) => issue.message);
674
+ getContainer() {
675
+ return this.container;
1278
676
  }
1279
- if (error instanceof Error && error.message) {
1280
- return [
1281
- error.message
1282
- ];
1283
- }
1284
- return [
1285
- String(error)
1286
- ];
1287
- }
1288
- __name(extractErrorMessages, "extractErrorMessages");
1289
-
1290
- // src/infrastructure/container.ts
1291
- var import_inversify2 = require("inversify");
1292
-
1293
- // src/utils/logger.ts
1294
- var LEVEL_WEIGHT = {
1295
- debug: 10,
1296
- info: 20,
1297
- warn: 30,
1298
- error: 40
1299
- };
1300
- var ConsoleLogger = class {
1301
- static {
1302
- __name(this, "ConsoleLogger");
1303
- }
1304
- level;
1305
- constructor(level = "info") {
1306
- this.level = level;
1307
- }
1308
- debug(message, metadata) {
1309
- this.log("debug", message, metadata);
1310
- }
1311
- info(message, metadata) {
1312
- this.log("info", message, metadata);
1313
- }
1314
- warn(message, metadata) {
1315
- this.log("warn", message, metadata);
677
+ getStats() {
678
+ return {
679
+ name: this.name,
680
+ isInitialized: this._isInitialized,
681
+ controllersCount: this.controllers.length,
682
+ middlewaresCount: this.context.middlewares.length,
683
+ routes: Object.keys(this.context.requestHandlers),
684
+ routesCount: Object.keys(this.context.requestHandlers).length,
685
+ state: this.state
686
+ };
1316
687
  }
1317
- error(message, metadata) {
1318
- this.log("error", message, metadata);
688
+ addErrorHandler(handler) {
689
+ this.on("error", handler);
1319
690
  }
1320
- log(level, message, metadata) {
1321
- if (!this.shouldLog(level)) {
1322
- return;
1323
- }
1324
- const payload = metadata ? [
1325
- message,
1326
- metadata
1327
- ] : [
1328
- message
1329
- ];
1330
- switch (level) {
1331
- case "debug":
1332
- console.debug(...payload);
1333
- break;
1334
- case "info":
1335
- console.info(...payload);
1336
- break;
1337
- case "warn":
1338
- console.warn(...payload);
1339
- break;
1340
- case "error":
1341
- console.error(...payload);
1342
- break;
1343
- }
691
+ handleError(error, context) {
692
+ this.emit("error", {
693
+ error,
694
+ context,
695
+ timestamp: Date.now()
696
+ });
1344
697
  }
1345
- shouldLog(level) {
1346
- return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[this.level];
698
+ addRequestInterceptor(interceptor) {
699
+ this.context.app.use((req, res, next) => {
700
+ try {
701
+ interceptor(req, res, next);
702
+ } catch (error) {
703
+ this.handleError(error, {
704
+ req: req.url,
705
+ method: req.method
706
+ });
707
+ next(error);
708
+ }
709
+ });
1347
710
  }
1348
711
  };
1349
- function createLogger(config = {}) {
1350
- return new ConsoleLogger(config.level);
1351
- }
1352
- __name(createLogger, "createLogger");
1353
-
1354
- // src/infrastructure/container.ts
1355
- function buildContainer(resolvedConfig) {
1356
- const container = new import_inversify2.Container({
1357
- defaultScope: "Singleton"
712
+ KickApp = _ts_decorate([
713
+ AutoBind,
714
+ _ts_metadata("design:type", Function),
715
+ _ts_metadata("design:paramtypes", [
716
+ typeof KickApplicationContext === "undefined" ? Object : KickApplicationContext,
717
+ String,
718
+ String,
719
+ typeof KickAppConfig === "undefined" ? Object : KickAppConfig
720
+ ])
721
+ ], KickApp);
722
+ function createKickApp(options) {
723
+ const appContext = {
724
+ requestHandlers: {},
725
+ middlewares: [],
726
+ app: options.app
727
+ };
728
+ const kickApp = new KickApp(appContext, options.name || "KickApp", options.prefix || "", options.config);
729
+ if (kickApp.config) {
730
+ }
731
+ if (options.plugins) {
732
+ kickApp.loadPlugin(options.plugins);
733
+ }
734
+ if (options.globalMiddlewares) {
735
+ kickApp.registerMiddleware(options.globalMiddlewares);
736
+ }
737
+ kickApp.loadModules(options.modules);
738
+ kickApp.mountMiddlewares();
739
+ const server = (0, import_http.createServer)(kickApp.context.app);
740
+ const kickServer = {
741
+ // Server methods
742
+ listen: server.listen.bind(server),
743
+ close: server.close.bind(server),
744
+ address: server.address.bind(server),
745
+ getConnections: server.getConnections.bind(server),
746
+ on: server.on.bind(server),
747
+ off: server.off.bind(server),
748
+ emit: server.emit.bind(server),
749
+ // KickApp instance and methods
750
+ kickApp,
751
+ app: kickApp.context.app,
752
+ // Convenience methods
753
+ getStats: /* @__PURE__ */ __name(() => kickApp.getStats(), "getStats"),
754
+ getState: /* @__PURE__ */ __name(() => kickApp.state, "getState"),
755
+ setState: /* @__PURE__ */ __name((key, value) => kickApp.setState(key, value), "setState"),
756
+ onStateChange: /* @__PURE__ */ __name((key, listener) => kickApp.onStateChange(key, listener), "onStateChange"),
757
+ onKickEvent: /* @__PURE__ */ __name((event, listener) => kickApp.on(event, listener), "onKickEvent"),
758
+ offKickEvent: /* @__PURE__ */ __name((event, listener) => kickApp.off(event, listener), "offKickEvent"),
759
+ emitKickEvent: /* @__PURE__ */ __name((event, data) => kickApp.emit(event, data), "emitKickEvent"),
760
+ addErrorHandler: /* @__PURE__ */ __name((handler) => kickApp.addErrorHandler(handler), "addErrorHandler"),
761
+ handleError: /* @__PURE__ */ __name((error, context) => kickApp.handleError(error, context), "handleError")
762
+ };
763
+ kickServer.addErrorHandler((errorData) => {
764
+ console.error(`[Server:${kickApp.name}] Unhandled error:`, errorData);
1358
765
  });
1359
- const registry = new ReactiveRegistry2();
1360
- container.bind(TYPES.StateRegistry).toConstantValue(registry);
1361
- container.bind(TYPES.Config).toConstantValue(resolvedConfig);
1362
- container.bind(TYPES.Logger).toConstantValue(createLogger(resolvedConfig.logging));
1363
- const appState = createReactive({
1364
- bootedAt: Date.now(),
1365
- metadata: {}
1366
- }, {
1367
- id: "app:state",
1368
- label: "application:state",
1369
- registry,
1370
- trackHistory: resolvedConfig.telemetry.trackReactiveHistory,
1371
- maxHistory: resolvedConfig.telemetry.requestHistoryLimit
766
+ return kickServer;
767
+ }
768
+ __name(createKickApp, "createKickApp");
769
+ async function createKickAppWithConfig(options) {
770
+ const { loadAppConfig: loadAppConfig2, getConfigFromEnv: getConfigFromEnv2 } = await Promise.resolve().then(() => (init_app_config(), app_config_exports));
771
+ const envConfig = getConfigFromEnv2();
772
+ const appConfig = await loadAppConfig2({
773
+ ...envConfig,
774
+ ...options.configOverrides
1372
775
  });
1373
- container.bind(TYPES.AppState).toConstantValue(appState);
1374
- container.bind(TYPES.RequestTracker).to(RequestTracker).inSingletonScope();
1375
- container.bind(TYPES.Diagnostics).to(AppDiagnostics).inSingletonScope();
1376
- return container;
776
+ const appOptions = {
777
+ ...options,
778
+ name: options.name || appConfig.name,
779
+ prefix: options.prefix || appConfig.prefix,
780
+ config: appConfig
781
+ };
782
+ return createKickApp(appOptions);
1377
783
  }
1378
- __name(buildContainer, "buildContainer");
784
+ __name(createKickAppWithConfig, "createKickAppWithConfig");
1379
785
 
1380
- // src/utils/env.ts
1381
- var import_node_fs2 = require("fs");
1382
- var import_node_path2 = __toESM(require("path"));
1383
- function parseEnv(content) {
1384
- const result = {};
1385
- const lines = content.split(/\r?\n/);
1386
- for (const line of lines) {
1387
- if (!line || line.trim().startsWith("#")) {
1388
- continue;
1389
- }
1390
- const match = line.match(/^(\w[\w\d_\.]*)\s*=\s*(.*)$/);
1391
- if (!match) {
1392
- continue;
1393
- }
1394
- const [, key, rawValue] = match;
1395
- const value = rawValue.trim().replace(/^['"]|['"]$/g, "");
1396
- result[key] = value;
1397
- }
1398
- return result;
1399
- }
1400
- __name(parseEnv, "parseEnv");
1401
- function loadEnvFiles(files) {
1402
- for (const file of files) {
1403
- if (!file) {
1404
- continue;
1405
- }
1406
- const filePath = import_node_path2.default.isAbsolute(file) ? file : import_node_path2.default.join(process.cwd(), file);
1407
- try {
1408
- const content = (0, import_node_fs2.readFileSync)(filePath, "utf8");
1409
- const parsed = parseEnv(content);
1410
- for (const [key, value] of Object.entries(parsed)) {
1411
- if (process.env[key] === void 0) {
1412
- process.env[key] = value;
1413
- }
1414
- }
1415
- } catch (error) {
1416
- }
786
+ // src/core/base/base-plugin.ts
787
+ var BaseKickPlugin = class {
788
+ static {
789
+ __name(this, "BaseKickPlugin");
1417
790
  }
1418
- }
1419
- __name(loadEnvFiles, "loadEnvFiles");
1420
-
1421
- // src/shared/config.ts
1422
- var DEFAULT_DISCOVERY_CONFIG = {
1423
- enabled: true,
1424
- roots: [
1425
- "src/domains",
1426
- "src/http"
1427
- ],
1428
- suffix: ".controller",
1429
- extensions: [
1430
- ".ts",
1431
- ".js",
1432
- ".mjs",
1433
- ".cjs"
1434
- ],
1435
- baseRoute: "/",
1436
- segmentSeparator: ".",
1437
- enforceStructure: true,
1438
- registerGlobally: true,
1439
- ignore: [
1440
- "__tests__",
1441
- "__mocks__",
1442
- ".DS_Store"
1443
- ],
1444
- tagsFromDirectories: true,
1445
- allowStaticRoutes: true
1446
791
  };
1447
- var DEFAULT_CONFIG = {
1448
- prefix: "",
1449
- healthEndpoint: "/health",
1450
- logging: {
1451
- level: "info"
1452
- },
1453
- telemetry: {
1454
- trackReactiveHistory: true,
1455
- requestHistoryLimit: 250
1456
- },
1457
- api: {
1458
- discovery: DEFAULT_DISCOVERY_CONFIG
792
+
793
+ // src/core/base/base-middleware.ts
794
+ var BaseKickMiddleware = class {
795
+ static {
796
+ __name(this, "BaseKickMiddleware");
1459
797
  }
1460
798
  };
1461
- var currentConfig = cloneResolvedConfig(DEFAULT_CONFIG);
1462
- function createKickConfig(options = {}) {
1463
- if (options.envFiles !== false) {
1464
- const defaultFiles = [
1465
- ".env"
1466
- ];
1467
- const nodeEnv = process.env.NODE_ENV;
1468
- if (nodeEnv) {
1469
- defaultFiles.push(`.env.${nodeEnv}`);
1470
- }
1471
- defaultFiles.push(".env.local");
1472
- const envFiles = Array.isArray(options.envFiles) ? options.envFiles : defaultFiles;
1473
- loadEnvFiles(envFiles);
1474
- }
1475
- let config = {
1476
- ...options.defaults ?? {}
1477
- };
1478
- if (options.env) {
1479
- for (const [envKey, binding] of Object.entries(options.env)) {
1480
- const rawValue = process.env[envKey];
1481
- if (rawValue === void 0) {
1482
- continue;
1483
- }
1484
- if (typeof binding === "function") {
1485
- const partial = binding(rawValue, process.env);
1486
- config = mergeAppConfigs(config, partial);
1487
- continue;
1488
- }
1489
- if (typeof binding === "string") {
1490
- config = setConfigValue(config, binding, autoCast(rawValue));
1491
- continue;
1492
- }
1493
- const value = binding.transform ? binding.transform(rawValue, process.env) : autoCast(rawValue);
1494
- config = setConfigValue(config, binding.path, value);
1495
- }
1496
- }
1497
- if (options.overrides) {
1498
- const overrides = typeof options.overrides === "function" ? options.overrides(config) : options.overrides;
1499
- config = mergeAppConfigs(config, overrides);
1500
- }
1501
- return config;
1502
- }
1503
- __name(createKickConfig, "createKickConfig");
1504
- function configureApp(config) {
1505
- currentConfig = mergeConfig(currentConfig, config);
1506
- }
1507
- __name(configureApp, "configureApp");
1508
- function getAppConfig() {
1509
- return currentConfig;
1510
- }
1511
- __name(getAppConfig, "getAppConfig");
1512
- function resolveConfig(overrides) {
1513
- if (!overrides) {
1514
- return currentConfig;
1515
- }
1516
- return mergeConfig(currentConfig, overrides);
1517
- }
1518
- __name(resolveConfig, "resolveConfig");
1519
- function resetAppConfig() {
1520
- currentConfig = cloneResolvedConfig(DEFAULT_CONFIG);
1521
- }
1522
- __name(resetAppConfig, "resetAppConfig");
1523
- function mergeConfig(base, overrides) {
1524
- return {
1525
- prefix: overrides.prefix ?? base.prefix,
1526
- healthEndpoint: overrides.healthEndpoint ?? base.healthEndpoint,
1527
- logging: {
1528
- level: overrides.logging?.level ?? base.logging.level
1529
- },
1530
- telemetry: {
1531
- trackReactiveHistory: overrides.telemetry?.trackReactiveHistory ?? base.telemetry.trackReactiveHistory,
1532
- requestHistoryLimit: overrides.telemetry?.requestHistoryLimit ?? base.telemetry.requestHistoryLimit
1533
- },
1534
- api: {
1535
- discovery: mergeDiscoveryConfig(base.api.discovery, overrides.api?.discovery)
1536
- }
1537
- };
1538
- }
1539
- __name(mergeConfig, "mergeConfig");
1540
- function cloneResolvedConfig(config) {
1541
- return {
1542
- prefix: config.prefix,
1543
- healthEndpoint: config.healthEndpoint,
1544
- logging: {
1545
- ...config.logging
1546
- },
1547
- telemetry: {
1548
- ...config.telemetry
1549
- },
1550
- api: {
1551
- discovery: {
1552
- enabled: config.api.discovery.enabled,
1553
- roots: [
1554
- ...config.api.discovery.roots
1555
- ],
1556
- suffix: config.api.discovery.suffix,
1557
- extensions: [
1558
- ...config.api.discovery.extensions
1559
- ],
1560
- baseRoute: config.api.discovery.baseRoute,
1561
- segmentSeparator: config.api.discovery.segmentSeparator,
1562
- enforceStructure: config.api.discovery.enforceStructure,
1563
- registerGlobally: config.api.discovery.registerGlobally,
1564
- ignore: [
1565
- ...config.api.discovery.ignore
1566
- ],
1567
- tagsFromDirectories: config.api.discovery.tagsFromDirectories,
1568
- allowStaticRoutes: config.api.discovery.allowStaticRoutes
1569
- }
1570
- }
1571
- };
1572
- }
1573
- __name(cloneResolvedConfig, "cloneResolvedConfig");
1574
- function mergeDiscoveryConfig(base, overrides) {
1575
- if (!overrides) {
1576
- return {
1577
- ...base,
1578
- roots: [
1579
- ...base.roots
1580
- ],
1581
- extensions: [
1582
- ...base.extensions
1583
- ],
1584
- ignore: [
1585
- ...base.ignore
1586
- ]
1587
- };
1588
- }
1589
- return {
1590
- enabled: overrides.enabled ?? base.enabled,
1591
- roots: overrides.roots ? [
1592
- ...overrides.roots
1593
- ] : [
1594
- ...base.roots
1595
- ],
1596
- suffix: overrides.suffix ?? base.suffix,
1597
- extensions: overrides.extensions ? [
1598
- ...overrides.extensions
1599
- ] : [
1600
- ...base.extensions
1601
- ],
1602
- baseRoute: overrides.baseRoute ?? base.baseRoute,
1603
- segmentSeparator: overrides.segmentSeparator ?? base.segmentSeparator,
1604
- enforceStructure: overrides.enforceStructure ?? base.enforceStructure,
1605
- registerGlobally: overrides.registerGlobally ?? base.registerGlobally,
1606
- ignore: overrides.ignore ? [
1607
- ...overrides.ignore
1608
- ] : [
1609
- ...base.ignore
1610
- ],
1611
- tagsFromDirectories: overrides.tagsFromDirectories ?? base.tagsFromDirectories,
1612
- allowStaticRoutes: overrides.allowStaticRoutes ?? base.allowStaticRoutes
1613
- };
1614
- }
1615
- __name(mergeDiscoveryConfig, "mergeDiscoveryConfig");
1616
- function mergeAppConfigs(base, patch) {
1617
- if (!patch) {
1618
- return base;
1619
- }
1620
- const merged = {
1621
- ...base
1622
- };
1623
- if (patch.prefix !== void 0) {
1624
- merged.prefix = patch.prefix;
1625
- }
1626
- if (patch.healthEndpoint !== void 0) {
1627
- merged.healthEndpoint = patch.healthEndpoint;
1628
- }
1629
- if (patch.logging) {
1630
- merged.logging = {
1631
- ...merged.logging,
1632
- ...patch.logging
1633
- };
1634
- }
1635
- if (patch.telemetry) {
1636
- merged.telemetry = {
1637
- ...merged.telemetry,
1638
- ...patch.telemetry
1639
- };
1640
- }
1641
- if (patch.api?.discovery) {
1642
- merged.api = merged.api ?? {};
1643
- merged.api.discovery = {
1644
- ...merged.api.discovery,
1645
- ...patch.api.discovery
1646
- };
1647
- }
1648
- return merged;
1649
- }
1650
- __name(mergeAppConfigs, "mergeAppConfigs");
1651
- function setConfigValue(config, path3, value) {
1652
- const patch = buildConfigFromPath(path3, value);
1653
- return mergeAppConfigs(config, patch);
1654
- }
1655
- __name(setConfigValue, "setConfigValue");
1656
- function buildConfigFromPath(path3, value) {
1657
- const segments = path3.split(".");
1658
- const result = {};
1659
- let cursor = result;
1660
- segments.forEach((segment, index) => {
1661
- if (index === segments.length - 1) {
1662
- cursor[segment] = value;
1663
- return;
1664
- }
1665
- cursor[segment] = cursor[segment] ? {
1666
- ...cursor[segment]
1667
- } : {};
1668
- cursor = cursor[segment];
1669
- });
1670
- return result;
1671
- }
1672
- __name(buildConfigFromPath, "buildConfigFromPath");
1673
- function autoCast(value) {
1674
- const lower = value.toLowerCase();
1675
- if (lower === "true") {
1676
- return true;
1677
- }
1678
- if (lower === "false") {
1679
- return false;
1680
- }
1681
- const num = Number(value);
1682
- if (!Number.isNaN(num) && `${num}` === value.trim()) {
1683
- return num;
1684
- }
1685
- try {
1686
- if (value.startsWith("{") && value.endsWith("}") || value.startsWith("[") && value.endsWith("]")) {
1687
- return JSON.parse(value);
1688
- }
1689
- } catch (error) {
1690
- }
1691
- return value;
1692
- }
1693
- __name(autoCast, "autoCast");
1694
799
 
1695
- // src/core/application.ts
1696
- function createApp(options = {}) {
1697
- const config = resolveConfig(options.config);
1698
- const container = options.container ?? buildContainer(config);
1699
- options.configureContainer?.(container);
1700
- const app = (0, import_express.default)();
1701
- const requestTracker = container.get(TYPES.RequestTracker);
1702
- const diagnostics = container.get(TYPES.Diagnostics);
1703
- const discoveredControllers = discoverControllersFromFilesystem(config.api.discovery);
1704
- const manualControllers = options.controllers ?? [];
1705
- const controllers = /* @__PURE__ */ new Set();
1706
- manualControllers.forEach((ControllerClass) => controllers.add(ControllerClass));
1707
- discoveredControllers.forEach((entry) => controllers.add(entry.controller));
1708
- const controllersToRegister = controllers.size > 0 ? Array.from(controllers) : void 0;
1709
- app.use(import_express.default.json());
1710
- options.additionalMiddleware?.forEach((middleware) => {
1711
- app.use(middleware);
1712
- });
1713
- app.use(requestTracker.middleware());
1714
- registerControllers(app, container, {
1715
- controllers: controllersToRegister,
1716
- prefix: config.prefix
1717
- });
1718
- if (config.healthEndpoint !== false) {
1719
- app.get(config.healthEndpoint, (_req, res) => {
1720
- res.json({
1721
- status: "ok"
1722
- });
800
+ // src/core/module.ts
801
+ var import_inversify5 = require("inversify");
802
+ var createModule = /* @__PURE__ */ __name((name, options) => {
803
+ const { controllers = [], middlewares = [] } = options;
804
+ const uniqueControllers = new Set(controllers);
805
+ const uniqueMiddlewares = new Set(middlewares);
806
+ const module2 = new import_inversify5.ContainerModule(({ bind }) => {
807
+ uniqueControllers.forEach((controller) => {
808
+ const bindingKey = KICK_MODULE_KEYS.KickControllerType;
809
+ bind(bindingKey).to(controller);
810
+ bind(controller).toSelf();
1723
811
  });
1724
- }
1725
- app.use((err, _req, res, _next) => {
1726
- const appError = isAppError(err) ? err : createError("INTERNAL_ERROR", err instanceof Error ? err.message : "Unexpected error", {
1727
- cause: err,
1728
- status: 500
812
+ uniqueMiddlewares.forEach((middleware) => {
813
+ const bindingKey = KICK_MODULE_KEYS.KickMiddlewareType;
814
+ bind(bindingKey).to(middleware);
815
+ bind(middleware).toSelf();
1729
816
  });
1730
- if (err instanceof Error && err.stack) {
1731
- requestTracker.mergeMetadata(res, {
1732
- errorStack: err.stack
1733
- });
1734
- }
1735
- requestTracker.recordError(res, appError);
1736
- const status = Number.isFinite(appError.status) ? Number(appError.status) : 500;
1737
- const payload = {
1738
- error: {
1739
- code: appError.code,
1740
- message: appError.message
1741
- }
1742
- };
1743
- if (appError.details) {
1744
- payload.error.details = appError.details;
1745
- }
1746
- requestTracker.recordResponse(res, status, payload);
1747
- if (!res.headersSent) {
1748
- res.status(status).json(payload);
1749
- }
1750
817
  });
1751
818
  return {
1752
- app,
1753
- container,
1754
- requestTracker,
1755
- diagnostics,
1756
- config,
1757
- discovery: {
1758
- controllers: discoveredControllers
1759
- }
819
+ /**
820
+ * Installs the module into the provided Inversify container.
821
+ */
822
+ install: /* @__PURE__ */ __name((container) => {
823
+ container.load(module2);
824
+ }, "install"),
825
+ name
1760
826
  };
827
+ }, "createModule");
828
+
829
+ // src/cli/utils/config-helpers.ts
830
+ function createKickConfig(config) {
831
+ return config;
1761
832
  }
1762
- __name(createApp, "createApp");
1763
- async function bootstrap(options = {}) {
1764
- const { app, container, requestTracker, diagnostics, config, discovery } = createApp(options);
1765
- const port = Number(options.port ?? process.env.PORT ?? 3e3);
1766
- const server = app.listen(port, () => {
1767
- console.log(`\u{1F680} Server listening on http://localhost:${port}`);
1768
- });
1769
- const shutdown = /* @__PURE__ */ __name(() => {
1770
- server.close(() => {
1771
- console.log("HTTP server closed");
1772
- });
1773
- }, "shutdown");
1774
- process.once("SIGINT", shutdown);
1775
- process.once("SIGTERM", shutdown);
1776
- return {
1777
- app,
1778
- server,
1779
- container,
1780
- requestTracker,
1781
- diagnostics,
1782
- config,
1783
- discovery,
1784
- shutdown
1785
- };
833
+ __name(createKickConfig, "createKickConfig");
834
+ function defineAppConfig(config) {
835
+ return config;
836
+ }
837
+ __name(defineAppConfig, "defineAppConfig");
838
+ function defineDevConfig(config) {
839
+ return config;
1786
840
  }
1787
- __name(bootstrap, "bootstrap");
841
+ __name(defineDevConfig, "defineDevConfig");
842
+ function defineStartConfig(config) {
843
+ return config;
844
+ }
845
+ __name(defineStartConfig, "defineStartConfig");
846
+
847
+ // src/index.ts
848
+ init_app_config();
1788
849
  // Annotate the CommonJS export names for ESM import in node:
1789
850
  0 && (module.exports = {
1790
- AppDiagnostics,
1791
- AppError,
1792
- BaseController,
1793
- Controller,
1794
- Delete,
1795
- DeleteController,
1796
- Get,
1797
- GetController,
1798
- HttpVerbController,
1799
- Inject,
1800
- Injectable,
1801
- MultiInject,
1802
- Named,
1803
- Optional,
1804
- Patch,
1805
- PatchController,
1806
- Post,
1807
- PostController,
1808
- Put,
1809
- PutController,
1810
- RequestTracker,
1811
- TYPES,
1812
- Tagged,
1813
- Unmanaged,
1814
- bootstrap,
1815
- configureApp,
1816
- createApp,
1817
- createError,
851
+ AutoBind,
852
+ BaseKickMiddleware,
853
+ BaseKickPlugin,
854
+ KICK_CONTROLLER_METADATA_KEYS,
855
+ KICK_MODULE_KEYS,
856
+ KickApp,
857
+ KickController,
858
+ KickDelete,
859
+ KickGet,
860
+ KickInject,
861
+ KickInjectable,
862
+ KickMiddleware,
863
+ KickPatch,
864
+ KickPost,
865
+ KickPut,
866
+ RouteMapper,
867
+ bindClassMethods,
868
+ combineRoutePaths,
869
+ createKickApp,
870
+ createKickAppWithConfig,
1818
871
  createKickConfig,
1819
- discoverControllersFromFilesystem,
1820
- getAppConfig,
1821
- isAppError,
1822
- listRegisteredControllers,
1823
- registerController,
1824
- resetAppConfig,
1825
- resetControllerRegistry,
1826
- resolveConfig
872
+ createModule,
873
+ defineAppConfig,
874
+ defineDevConfig,
875
+ defineStartConfig,
876
+ getConfigFromEnv,
877
+ getMiddlewareMetadata,
878
+ isKickMiddleware,
879
+ loadAppConfig,
880
+ mapController,
881
+ normalizeRoutePath
1827
882
  });
1828
883
  //# sourceMappingURL=index.js.map