@forinda/kickjs 0.1.0 → 0.1.3

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
@@ -36,15 +36,21 @@ __export(index_exports, {
36
36
  BaseController: () => BaseController,
37
37
  Controller: () => Controller,
38
38
  Delete: () => Delete,
39
+ DeleteController: () => DeleteController,
39
40
  Get: () => Get,
41
+ GetController: () => GetController,
42
+ HttpVerbController: () => HttpVerbController,
40
43
  Inject: () => Inject,
41
44
  Injectable: () => Injectable,
42
45
  MultiInject: () => MultiInject,
43
46
  Named: () => Named,
44
47
  Optional: () => Optional,
45
48
  Patch: () => Patch,
49
+ PatchController: () => PatchController,
46
50
  Post: () => Post,
51
+ PostController: () => PostController,
47
52
  Put: () => Put,
53
+ PutController: () => PutController,
48
54
  RequestTracker: () => RequestTracker,
49
55
  TYPES: () => TYPES,
50
56
  Tagged: () => Tagged,
@@ -53,6 +59,8 @@ __export(index_exports, {
53
59
  configureApp: () => configureApp,
54
60
  createApp: () => createApp,
55
61
  createError: () => createError,
62
+ createKickConfig: () => createKickConfig,
63
+ discoverControllersFromFilesystem: () => discoverControllersFromFilesystem,
56
64
  getAppConfig: () => getAppConfig,
57
65
  isAppError: () => isAppError,
58
66
  listRegisteredControllers: () => listRegisteredControllers,
@@ -84,24 +92,24 @@ function Controller(pathOrOptions = "/") {
84
92
  };
85
93
  }
86
94
  __name(Controller, "Controller");
87
- function Get(path, ...middlewares) {
88
- return createRouteDecorator("get")(path, ...middlewares);
95
+ function Get(path3, ...middlewares) {
96
+ return createRouteDecorator("get")(path3, ...middlewares);
89
97
  }
90
98
  __name(Get, "Get");
91
- function Post(path, ...middlewares) {
92
- return createRouteDecorator("post")(path, ...middlewares);
99
+ function Post(path3, ...middlewares) {
100
+ return createRouteDecorator("post")(path3, ...middlewares);
93
101
  }
94
102
  __name(Post, "Post");
95
- function Put(path, ...middlewares) {
96
- return createRouteDecorator("put")(path, ...middlewares);
103
+ function Put(path3, ...middlewares) {
104
+ return createRouteDecorator("put")(path3, ...middlewares);
97
105
  }
98
106
  __name(Put, "Put");
99
- function Patch(path, ...middlewares) {
100
- return createRouteDecorator("patch")(path, ...middlewares);
107
+ function Patch(path3, ...middlewares) {
108
+ return createRouteDecorator("patch")(path3, ...middlewares);
101
109
  }
102
110
  __name(Patch, "Patch");
103
- function Delete(path, ...middlewares) {
104
- return createRouteDecorator("delete")(path, ...middlewares);
111
+ function Delete(path3, ...middlewares) {
112
+ return createRouteDecorator("delete")(path3, ...middlewares);
105
113
  }
106
114
  __name(Delete, "Delete");
107
115
  function listRegisteredControllers() {
@@ -178,19 +186,19 @@ function normalizeRouteOptionObject(pathOrOptions) {
178
186
  return {};
179
187
  }
180
188
  __name(normalizeRouteOptionObject, "normalizeRouteOptionObject");
181
- function normalizePath(path) {
182
- if (!path || path === "/") {
189
+ function normalizePath(path3) {
190
+ if (!path3 || path3 === "/") {
183
191
  return "/";
184
192
  }
185
- const withLeading = path.startsWith("/") ? path : `/${path}`;
193
+ const withLeading = path3.startsWith("/") ? path3 : `/${path3}`;
186
194
  return withLeading.endsWith("/") && withLeading !== "/" ? withLeading.slice(0, -1) : withLeading;
187
195
  }
188
196
  __name(normalizePath, "normalizePath");
189
- function normalizeRoutePath(path) {
190
- if (!path || path === "/") {
197
+ function normalizeRoutePath(path3) {
198
+ if (!path3 || path3 === "/") {
191
199
  return "";
192
200
  }
193
- const cleaned = path.startsWith("/") ? path.slice(1) : path;
201
+ const cleaned = path3.startsWith("/") ? path3.slice(1) : path3;
194
202
  return cleaned.endsWith("/") ? cleaned.slice(0, -1) : cleaned;
195
203
  }
196
204
  __name(normalizeRoutePath, "normalizeRoutePath");
@@ -223,67 +231,6 @@ function isAppError(error) {
223
231
  }
224
232
  __name(isAppError, "isAppError");
225
233
 
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
234
  // src/core/request-tracker.ts
288
235
  var import_node_crypto2 = require("crypto");
289
236
 
@@ -576,7 +523,7 @@ RequestTracker = _ts_decorate([
576
523
  ])
577
524
  ], RequestTracker);
578
525
 
579
- // src/core/diagnostics.ts
526
+ // src/core/base-controller.ts
580
527
  function _ts_decorate2(decorators, target, key, desc) {
581
528
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
582
529
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -588,6 +535,497 @@ function _ts_metadata2(k, v) {
588
535
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
589
536
  }
590
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);
563
+ }
564
+ return res;
565
+ }
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
+ }
591
+ };
592
+ tracker.mergeMetadata(res, namespacedPatch);
593
+ }
594
+ getRequestState(res) {
595
+ return this.ensureTracker().get(res)?.state;
596
+ }
597
+ fail(code, message, options) {
598
+ throw createError(code, message, options);
599
+ }
600
+ attachRequestTracker(tracker) {
601
+ this.runtimeTracker = tracker;
602
+ }
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");
612
+ }
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");
627
+ }
628
+ /**
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");
634
+ }
635
+ /** HTTP method instance mirror for convenience in handlers/tests. */
636
+ httpMethod = this.constructor.method();
637
+ /**
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";
679
+ }
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}`);
788
+ }
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
+ }
805
+ });
806
+ }
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}*`
881
+ ];
882
+ }
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");
591
1029
  function _ts_param2(paramIndex, decorator) {
592
1030
  return function(target, key) {
593
1031
  decorator(target, key, paramIndex);
@@ -619,24 +1057,24 @@ var AppDiagnostics = class {
619
1057
  return this.registry.list().filter((entry) => entry.label?.startsWith("request:")).map((entry) => entry.snapshot);
620
1058
  }
621
1059
  };
622
- AppDiagnostics = _ts_decorate2([
1060
+ AppDiagnostics = _ts_decorate3([
623
1061
  Injectable(),
624
1062
  _ts_param2(0, Inject(TYPES.StateRegistry)),
625
1063
  _ts_param2(1, Inject(TYPES.Config)),
626
- _ts_metadata2("design:type", Function),
627
- _ts_metadata2("design:paramtypes", [
1064
+ _ts_metadata3("design:type", Function),
1065
+ _ts_metadata3("design:paramtypes", [
628
1066
  typeof ReactiveRegistry2 === "undefined" ? Object : ReactiveRegistry2,
629
1067
  typeof ResolvedAppConfig === "undefined" ? Object : ResolvedAppConfig
630
1068
  ])
631
1069
  ], AppDiagnostics);
632
1070
 
633
1071
  // src/core/application.ts
634
- var import_reflect_metadata3 = require("reflect-metadata");
1072
+ var import_reflect_metadata4 = require("reflect-metadata");
635
1073
  var import_express = __toESM(require("express"));
636
1074
 
637
1075
  // src/core/server.ts
638
1076
  var import_node_crypto3 = require("crypto");
639
- var import_reflect_metadata2 = require("reflect-metadata");
1077
+ var import_reflect_metadata3 = require("reflect-metadata");
640
1078
  var appRouteRegistry = /* @__PURE__ */ new WeakMap();
641
1079
  function registerControllers(app, container, options = {}) {
642
1080
  const controllers = options.controllers ?? listRegisteredControllers();
@@ -652,6 +1090,7 @@ function registerControllers(app, container, options = {}) {
652
1090
  container.bind(ControllerClass).toSelf().inSingletonScope();
653
1091
  }
654
1092
  const instance = container.get(ControllerClass);
1093
+ attachRequestTracker(instance, requestTracker);
655
1094
  const routes = Reflect.getMetadata(DecoratorMetadata.ROUTES_KEY, ControllerClass) ?? [];
656
1095
  routes.forEach((route) => {
657
1096
  const handler = instance[route.propertyKey];
@@ -695,11 +1134,19 @@ function ensureInjectable(constructor) {
695
1134
  }
696
1135
  }
697
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");
698
1145
  function buildRoutePath(prefix, basePath, routePath) {
699
1146
  const segments = [
700
- ...toSegments(prefix),
701
- ...toSegments(basePath),
702
- ...toSegments(routePath)
1147
+ ...toSegments2(prefix),
1148
+ ...toSegments2(basePath),
1149
+ ...toSegments2(routePath)
703
1150
  ];
704
1151
  if (segments.length === 0) {
705
1152
  return "/";
@@ -707,7 +1154,7 @@ function buildRoutePath(prefix, basePath, routePath) {
707
1154
  return `/${segments.join("/")}`;
708
1155
  }
709
1156
  __name(buildRoutePath, "buildRoutePath");
710
- function toSegments(segment) {
1157
+ function toSegments2(segment) {
711
1158
  if (!segment || segment === "/") {
712
1159
  return [];
713
1160
  }
@@ -716,17 +1163,17 @@ function toSegments(segment) {
716
1163
  trimmed
717
1164
  ] : [];
718
1165
  }
719
- __name(toSegments, "toSegments");
720
- function registerRouteSignature(app, method, path, controllerName, propertyKey) {
1166
+ __name(toSegments2, "toSegments");
1167
+ function registerRouteSignature(app, method, path3, controllerName, propertyKey) {
721
1168
  let registry = appRouteRegistry.get(app);
722
1169
  if (!registry) {
723
1170
  registry = /* @__PURE__ */ new Set();
724
1171
  appRouteRegistry.set(app, registry);
725
1172
  }
726
- const normalized = `${method.toLowerCase()}:${path.toLowerCase()}`;
1173
+ const normalized = `${method.toLowerCase()}:${path3.toLowerCase()}`;
727
1174
  const hash = (0, import_node_crypto3.createHash)("sha256").update(normalized).digest("hex");
728
1175
  if (registry.has(hash)) {
729
- throw createError("ROUTE_CONFLICT", `Duplicate route detected for [${method.toUpperCase()}] ${path}`, {
1176
+ throw createError("ROUTE_CONFLICT", `Duplicate route detected for [${method.toUpperCase()}] ${path3}`, {
730
1177
  details: {
731
1178
  controller: controllerName,
732
1179
  handler: String(propertyKey)
@@ -930,7 +1377,73 @@ function buildContainer(resolvedConfig) {
930
1377
  }
931
1378
  __name(buildContainer, "buildContainer");
932
1379
 
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
+ }
1417
+ }
1418
+ }
1419
+ __name(loadEnvFiles, "loadEnvFiles");
1420
+
933
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
+ };
934
1447
  var DEFAULT_CONFIG = {
935
1448
  prefix: "",
936
1449
  healthEndpoint: "/health",
@@ -940,11 +1453,54 @@ var DEFAULT_CONFIG = {
940
1453
  telemetry: {
941
1454
  trackReactiveHistory: true,
942
1455
  requestHistoryLimit: 250
1456
+ },
1457
+ api: {
1458
+ discovery: DEFAULT_DISCOVERY_CONFIG
943
1459
  }
944
1460
  };
945
- var currentConfig = {
946
- ...DEFAULT_CONFIG
947
- };
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");
948
1504
  function configureApp(config) {
949
1505
  currentConfig = mergeConfig(currentConfig, config);
950
1506
  }
@@ -961,9 +1517,7 @@ function resolveConfig(overrides) {
961
1517
  }
962
1518
  __name(resolveConfig, "resolveConfig");
963
1519
  function resetAppConfig() {
964
- currentConfig = {
965
- ...DEFAULT_CONFIG
966
- };
1520
+ currentConfig = cloneResolvedConfig(DEFAULT_CONFIG);
967
1521
  }
968
1522
  __name(resetAppConfig, "resetAppConfig");
969
1523
  function mergeConfig(base, overrides) {
@@ -976,10 +1530,167 @@ function mergeConfig(base, overrides) {
976
1530
  telemetry: {
977
1531
  trackReactiveHistory: overrides.telemetry?.trackReactiveHistory ?? base.telemetry.trackReactiveHistory,
978
1532
  requestHistoryLimit: overrides.telemetry?.requestHistoryLimit ?? base.telemetry.requestHistoryLimit
1533
+ },
1534
+ api: {
1535
+ discovery: mergeDiscoveryConfig(base.api.discovery, overrides.api?.discovery)
979
1536
  }
980
1537
  };
981
1538
  }
982
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");
983
1694
 
984
1695
  // src/core/application.ts
985
1696
  function createApp(options = {}) {
@@ -989,13 +1700,19 @@ function createApp(options = {}) {
989
1700
  const app = (0, import_express.default)();
990
1701
  const requestTracker = container.get(TYPES.RequestTracker);
991
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;
992
1709
  app.use(import_express.default.json());
993
1710
  options.additionalMiddleware?.forEach((middleware) => {
994
1711
  app.use(middleware);
995
1712
  });
996
1713
  app.use(requestTracker.middleware());
997
1714
  registerControllers(app, container, {
998
- controllers: options.controllers,
1715
+ controllers: controllersToRegister,
999
1716
  prefix: config.prefix
1000
1717
  });
1001
1718
  if (config.healthEndpoint !== false) {
@@ -1036,12 +1753,15 @@ function createApp(options = {}) {
1036
1753
  container,
1037
1754
  requestTracker,
1038
1755
  diagnostics,
1039
- config
1756
+ config,
1757
+ discovery: {
1758
+ controllers: discoveredControllers
1759
+ }
1040
1760
  };
1041
1761
  }
1042
1762
  __name(createApp, "createApp");
1043
1763
  async function bootstrap(options = {}) {
1044
- const { app, container, requestTracker, diagnostics, config } = createApp(options);
1764
+ const { app, container, requestTracker, diagnostics, config, discovery } = createApp(options);
1045
1765
  const port = Number(options.port ?? process.env.PORT ?? 3e3);
1046
1766
  const server = app.listen(port, () => {
1047
1767
  console.log(`\u{1F680} Server listening on http://localhost:${port}`);
@@ -1060,6 +1780,7 @@ async function bootstrap(options = {}) {
1060
1780
  requestTracker,
1061
1781
  diagnostics,
1062
1782
  config,
1783
+ discovery,
1063
1784
  shutdown
1064
1785
  };
1065
1786
  }
@@ -1071,15 +1792,21 @@ __name(bootstrap, "bootstrap");
1071
1792
  BaseController,
1072
1793
  Controller,
1073
1794
  Delete,
1795
+ DeleteController,
1074
1796
  Get,
1797
+ GetController,
1798
+ HttpVerbController,
1075
1799
  Inject,
1076
1800
  Injectable,
1077
1801
  MultiInject,
1078
1802
  Named,
1079
1803
  Optional,
1080
1804
  Patch,
1805
+ PatchController,
1081
1806
  Post,
1807
+ PostController,
1082
1808
  Put,
1809
+ PutController,
1083
1810
  RequestTracker,
1084
1811
  TYPES,
1085
1812
  Tagged,
@@ -1088,6 +1815,8 @@ __name(bootstrap, "bootstrap");
1088
1815
  configureApp,
1089
1816
  createApp,
1090
1817
  createError,
1818
+ createKickConfig,
1819
+ discoverControllersFromFilesystem,
1091
1820
  getAppConfig,
1092
1821
  isAppError,
1093
1822
  listRegisteredControllers,